Arduino

What is arduino?


  • AVR ATmega microcontroller
  • nice abstraction layer
  • language: C/C++  (no worries!)
  • many I/O
  • USB plug 'n' play
  • Price: $5 - $50

ATmega328 specs



  • 32Kb flash
  • 2Kb RAM
  • 8-bit, 20MHz CPU

Let's begin


Hello world in microcontrollers world

const int ledPin = 13;

void setup() {                
  // initialize the digital pin as an output.
  pinMode(ledPin, OUTPUT);     
}

void loop() {
  digitalWrite(ledPin, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                  // wait for a second
  digitalWrite(ledPin, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                  // wait for a second
}


but...



Using delay stops whole program execution, 
which is something  we don't want.


Solution?

  • measuring elapsed time (not so great)
  • hardware timer interruptions

Corrected code - measuring time


#include "SimpleTimer.h"

const int ledPin = 13;
SimpleTimer timer;

void setup() {
  timer.setInterval(1000, blink);
}

void loop() { 
  timer.run(); 
}

void blink() {
  digitalWrite(ledPin, digitalRead(ledPin) ^ 1); // toggle pin status
}

Corrected code - HW interrupts


#include "TimerOne.h"

const int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW); // reset led state
  Timer1.initialize();
  Timer1.attachInterrupt(blink, 500 * 1000); // 500ms timeout
}

void loop() {}

void blink() {
  digitalWrite(ledPin, digitalRead(ledPin) ^ 1); // toggle pin status
}



Communication


  • Serial port (built-in)
  • Wi-Fi
  • Bluetooth
  • Ethernet

let's do something fancy!



  • two temperature sensors
  • LED with regulated output
  • communication through websockets
  • present temperature on website
  •  ...and control LED from website

Communication flow chart



reading temperature

  • Sensor - DS18B20
  • Protocol - One Wire
#include "TemperatureSensor.h"

TemperatureSensor sensor(2); // setup sensor on pin 2

void setup() {
  sensor.start();
  Serial.begin(9600);
}

void loop() {
  if (sensor.updateTemperature()) {
    Serial.println(sensor.getTemperature());
  }
}

Wiring



regulating led power using PWM


  • what is PWM?

const int ledPin = 11;

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);
  Serial.begin(9600);
  Serial.setTimeout(100);
}

void loop() {
  char input[4];

  if (Serial.available() && Serial.read() == 'P')
    Serial.readBytes(input, 3);

  int pwmValue = atoi(input);
  if (pwmValue > 0) {
    analogWrite(ledPin, pwmValue);
  }
}

Here it comes... node.js


Communication with arduino


 class ArduinoHandler
  serialport = require('serialport')

  constructor: (@device) ->
    @serialPort = new serialport.SerialPort @device,
      baudrate: 115200,
      dataBits: 8,
      parity: 'none',
      stopBits: 1,
      flowControl: false,
      parser: serialport.parsers.readline("\n")

  listen: (onData) ->
    @serialPort.on "open", => @serialPort.on('data', onData)

  send: (data) ->
    @serialPort.write("P#{data}")

@arduinoHandler = new ArduinoHandler('/dev/tty.usbmodem1421')

Getting and emitting temperature data


class Temperature
  history: []

  constructor: (@ioServer, @arduinoHandler) ->
    @arduinoHandler.listen(@update)
    @ioServer.onConnection(@pushHistory)

  update: (data) =>
    [device, temp] = data.split(':')
    @history.push
      device: parseInt(device)
      temp: temp
      date: new Date()
    @pushHistory()

  pushHistory: =>
    @ioServer.emit('change-temp', @history)

regulating led


 class Pwm
  constructor: (@ioServer, @arduinoHandler) ->
    @ioServer.onConnection(@addEventListener)

  addEventListener: (socket) =>
    socket.on('change-pwm', @onChange)

  onChange: (pwm) =>
    @arduinoHandler.send(pwm)

wiring it up together


 class App
  constructor: (@port, @device) ->
    @httpServer = new HttpServer(@port)
    @ioServer = new IoServer(@httpServer.getApp())
    @arduinoHandler = new ArduinoHandler(@device)

    @temperature = new Temperature(@ioServer, @arduinoHandler)
    @pwm = new Pwm(@ioServer, @arduinoHandler)

Client 


      function updatePwm() {
        val = $("#slider").slider('value');
        toPwm = Math.ceil(val * 2.55);
        socket.emit('change-pwm', toPwm)
      }

      $("#slider").slider({
        slide: updatePwm,
        change: updatePwm
      });

      function updateLatestTemperatures(history) {
        $('[data-role=temperature]').each(function(){
          deviceId = $(this).data('id');
          temp = _.chain(history)
                  .where({ device: deviceId }).last().value().temp
          $(this).html(temp)
        })
      }
      
      var socket = io.connect('http://192.168.5.10:3334');
      socket.on('change-temp', updateLatestTemperatures);





what if arduino

is not enough?

raspberry pi

  • Arduino on steroids
  • ARM powered
  • UNIX support - any high level language
  • GPIO
  • HDMI 1080p output
  • Price? $50



questions?

Arduino

By Lucjan Suski

Arduino

  • 574