1 | /*
|
---|
2 | Spacebrew String
|
---|
3 |
|
---|
4 | Demonstrates how to create a sketch that sends and receives strings
|
---|
5 | to and from Spacebrew. Every time string data is received it
|
---|
6 | is output to the Serial monitor.
|
---|
7 |
|
---|
8 | Make sure that your Y炭n is connected to the internet for this example
|
---|
9 | to function properly.
|
---|
10 |
|
---|
11 | The circuit:
|
---|
12 | - No circuit required
|
---|
13 |
|
---|
14 | created 2013
|
---|
15 | by Julio Terra
|
---|
16 |
|
---|
17 | This example code is in the public domain.
|
---|
18 |
|
---|
19 | More information about Spacebrew is available at:
|
---|
20 | http://spacebrew.cc/
|
---|
21 |
|
---|
22 | */
|
---|
23 |
|
---|
24 | #include <Bridge.h>
|
---|
25 | #include <SpacebrewYun.h>
|
---|
26 |
|
---|
27 | // create a variable of type SpacebrewYun and initialize it with the constructor
|
---|
28 | SpacebrewYun sb = SpacebrewYun("spacebrewYun Strings", "String sender and receiver");
|
---|
29 |
|
---|
30 | // create variables to manage interval between each time we send a string
|
---|
31 | long last_time = 0;
|
---|
32 | int interval = 2000;
|
---|
33 |
|
---|
34 | void setup() {
|
---|
35 |
|
---|
36 | // start the serial port
|
---|
37 | Serial.begin(57600);
|
---|
38 |
|
---|
39 | // for debugging, wait until a serial console is connected
|
---|
40 | delay(4000);
|
---|
41 | while (!Serial) { ; }
|
---|
42 |
|
---|
43 | // start-up the bridge
|
---|
44 | Bridge.begin();
|
---|
45 |
|
---|
46 | // configure the spacebrew object to print status messages to serial
|
---|
47 | sb.verbose(true);
|
---|
48 |
|
---|
49 | // configure the spacebrew publisher and subscriber
|
---|
50 | sb.addPublish("speak", "string");
|
---|
51 | sb.addSubscribe("listen", "string");
|
---|
52 |
|
---|
53 | // register the string message handler method
|
---|
54 | sb.onStringMessage(handleString);
|
---|
55 |
|
---|
56 | // connect to cloud spacebrew server at "sandbox.spacebrew.cc"
|
---|
57 | sb.connect("sandbox.spacebrew.cc");
|
---|
58 | }
|
---|
59 |
|
---|
60 |
|
---|
61 | void loop() {
|
---|
62 | // monitor spacebrew connection for new data
|
---|
63 | sb.monitor();
|
---|
64 |
|
---|
65 | // connected to spacebrew then send a string every 2 seconds
|
---|
66 | if ( sb.connected() ) {
|
---|
67 |
|
---|
68 | // check if it is time to send a new message
|
---|
69 | if ( (millis() - last_time) > interval ) {
|
---|
70 | sb.send("speak", "is anybody out there?");
|
---|
71 | last_time = millis();
|
---|
72 | }
|
---|
73 | }
|
---|
74 | }
|
---|
75 |
|
---|
76 | // handler method that is called whenever a new string message is received
|
---|
77 | void handleString (String route, String value) {
|
---|
78 | // print the message that was received
|
---|
79 | Serial.print("From ");
|
---|
80 | Serial.print(route);
|
---|
81 | Serial.print(", received msg: ");
|
---|
82 | Serial.println(value);
|
---|
83 | }
|
---|
84 |
|
---|