File size: 2,328 Bytes
69c3cbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
  Spacebrew Range

 Demonstrates how to create a sketch that sends and receives analog
 range value to and from Spacebrew. Every time the state of the
 potentiometer (or other analog input component) change a spacebrew
 message is sent. The sketch also accepts analog range messages from
 other Spacebrew apps.

 Make sure that your Yún is connected to the internet for this example
 to function properly.

 The circuit:
 - Potentiometer connected to Yún. Middle pin connected to analog pin A0,
   other pins connected to 5v and GND pins.

 created 2013
 by Julio Terra

 This example code is in the public domain.

 More information about Spacebrew is available at:
 http://spacebrew.cc/

 */

#include <Bridge.h>
#include <SpacebrewYun.h>

// create a variable of type SpacebrewYun and initialize it with the constructor
SpacebrewYun sb = SpacebrewYun("spacebrewYun Range", "Range sender and receiver");

// variable that holds the last potentiometer value
int last_value = 0;

// create variables to manage interval between each time we send a string
void setup() {

  // start the serial port
  SerialUSB.begin(57600);

  // for debugging, wait until a serial console is connected
  delay(4000);
  while (!SerialUSB) {
    ;
  }

  // start-up the bridge
  Bridge.begin();

  // configure the spacebrew object to print status messages to serial
  sb.verbose(true);

  // configure the spacebrew publisher and subscriber
  sb.addPublish("physical pot", "range");
  sb.addSubscribe("virtual pot", "range");

  // register the string message handler method
  sb.onRangeMessage(handleRange);

  // connect to cloud spacebrew server at "sandbox.spacebrew.cc"
  sb.connect("sandbox.spacebrew.cc");
}


void loop() {
  // monitor spacebrew connection for new data
  sb.monitor();

  // connected to spacebrew then send a new value whenever the pot value changes
  if (sb.connected()) {
    int cur_value = analogRead(A0);
    if (last_value != cur_value) {
      sb.send("physical pot", cur_value);
      last_value = cur_value;
    }
  }
}

// handler method that is called whenever a new string message is received
void handleRange(String route, int value) {
  // print the message that was received
  SerialUSB.print("From ");
  SerialUSB.print(route);
  SerialUSB.print(", received msg: ");
  SerialUSB.println(value);
}