Skip to content

Instantly share code, notes, and snippets.

@electricimp
Last active December 23, 2015 22:59
Show Gist options
  • Save electricimp/6706939 to your computer and use it in GitHub Desktop.
Save electricimp/6706939 to your computer and use it in GitHub Desktop.
Basic imp <--> Arduino code example
server.log("Device Started");
function arduinoData()
{
// Read the UART for data sent by Arduino to indicate
// the state of its LED.
local b = arduino.read();
while(b != -1)
{
// As long as UART read value is not -1, we're getting data
local state = "Unknown";
if (b == 0x10) state = "Off";
if (b == 0x11) state = "On"
server.log("LED: " + state);
b = arduino.read();
}
}
function blink(state)
{
// Write state (1 or 0) to the Arduino
server.log("Setting LED to: " + state);
arduino.write(state);
imp.wakeup(1.0, function(){blink(1 - state);});
}
// Alias UART to which Arduino is connected
arduino <- hardware.uart57;
arduino.configure(9600, 8, PARITY_NONE, 1, NO_CTSRTS, arduinoData);
// Start blinking
blink(1);
// Arduino device code
int led = 13; // LED pin number
void setup()
{
Serial.begin(9600); // Configure serial
pinMode(led, OUTPUT); // Configure LED pin
digitalWrite(led, 0); // Turn LED off
}
void loop()
{
int b = 0;
// If there's data available
if (Serial.available () > 0)
{
// Read a byte
b = Serial.read();
if (b == 0x00)
{
digitalWrite(led, LOW);
Serial.write(0x10);
}
else if (b == 0x01)
{
digitalWrite(led, HIGH);
Serial.write(0x11);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment