Create a gist now

Instantly share code, notes, and snippets.

@matthewphilyaw /I2C.c Secret
Last active Aug 29, 2015

What would you like to do?
i2c between erlang ale on raspberry pi and teensduino
#include <Wire.h>
const int iPin = 11;
const int dPin = 13;
void setup() {
Wire.begin(4); // join i2c bus with address #4
Wire.onReceive(receiveEvent); // register event
pinMode(iPin, OUTPUT);
pinMode(dPin, OUTPUT);
debugLed(2, 500);
Serial.begin(9600);
}
void debugLed(int times, int d) {
digitalWrite(dPin, LOW);
delay(100);
while (times-- > 0) {
digitalWrite(dPin, HIGH);
delay(d);
digitalWrite(dPin, LOW);
delay(d);
}
digitalWrite(dPin, LOW);
}
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 (0 < Wire.available()) {
Serial.print("found: ");
Serial.println(Wire.available());
int c = Wire.read();
if (c == 0x01) {
digitalWrite(iPin, HIGH);
digitalWrite(dPin, LOW);
}
else if (c == 0xff) {
digitalWrite(iPin, LOW);
digitalWrite(dPin, HIGH);
}
Serial.println(c);
}
}
%% running make shell in the erlang_Ale root brings up a shell
%% start the i2c supervisor
i2c_sup:start_link([{i2c1, "/dev/i2c-1"}]).
%% using a named fun to create an infinite loop effectively bouncing between the two leds.
D = fun Blink(on) ->
i2c:write(i2c1, 16#04, { 1 }),
timer:sleep(500),
Blink(off);
Blink(off) ->
i2c:write(i2c1, 16#04, { 255 }),
timer:sleep(500),
Blink(on)
end.
%% set it in motion
D(on).
Owner

matthewphilyaw commented May 27, 2014

First file is an arduino sketch for the teensyduino v2.0 board. It's modified (well basically completely gutted) version of the slave_received example for the arduino.

I'm only sending one byte, but obviously the leds will not make much sense if multiple bytes are sent, but the serial data will be fine.

The second file is what would be typed into the erlang shell on the raspberry pi, I copied it from what I typed and just cleaned it up and formatted it nicer.

This basically demonstrates communication between the PI and the teensyduino via I2C. The raspberry pi is powering the teensduino as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment