Skip to content

14. Networking and communications

This week our group assignment was to get 2 of our individual board to network with each other.

Networking a 1614 and 2040 Xiao via I2C

We used a RP2040 based board that sends a character over I2C (will blink builtin LED when send is complete) to the 412 based board that flashes a LED twice when it is received.

Here is the network we are making

You can see the code below for the RP2040 that sends the message

import machine
import utime

led = machine.Pin(25, machine.Pin.OUT)

i2c = machine.I2C(1, scl=machine.Pin(7), sda=machine.Pin(6), freq=400000)
address = 25

while True:
    try:
        # Read 2 bytes of data from the I2C device at the specified address
        print(i2c.scan())
        print(i2c.writeto(address, b'h'))
        led.value(1)
        utime.sleep_ms(1000)
        led.value(0)
        utime.sleep_ms(1000)


    except OSError as e:
        print("Error writting to I2C device: {}".format(e))

    # Wait for 1 second before reading data again
    utime.sleep(1)

here is the 412 …

#define LEDPIN 1

// where the controller should send the message to this device -- can be anywhere from 8 - 127
#define I2CADDRESS 25 // what's funnier than 24?

#include <Wire.h>

// tells us if this 412 received a message over I2C
bool Received = false;
bool fReceived = false;

void setup() {
  pinMode(LEDPIN, OUTPUT);
  Wire.begin(I2CADDRESS); // enable as peripheral at I2CADDRESS -- 25
  Wire.onReceive(readMessage); // function called when a message over I2C is received
  digitalWrite(LEDPIN,LOW); // ensure LED is off at start
}

// read the message
void readMessage(int bytes){
  if(Wire.available()) { // go through each character in the message
    char c = Wire.read(); // read received byte
    received = true; // received a message
  }
}

// main loop
void loop() {
  // message is received from controller
  if(received){
    // blink LED twice
    digitalWrite(LEDPIN, HIGH);
    delay(100);
    digitalWrite(LEDPIN, LOW);
    delay(100);
    digitalWrite(LEDPIN, HIGH);
    delay(100);
    digitalWrite(LEDPIN, LOW);
    received = false;
  }

  delay(100);
  digitalWrite(LEDPIN, LOW); // make sure the LED is off when a message is not received
}

and the video of the communication in action


Last update: June 26, 2023