1 | /*
|
---|
2 | PubNub sample client
|
---|
3 |
|
---|
4 | This sample client will publish raw (JSON pre-encoded) PubNub messages.
|
---|
5 |
|
---|
6 | Circuit:
|
---|
7 | * Ethernet shield attached to pins 10, 11, 12, 13
|
---|
8 | * (Optional.) Analog sensors on pins A0 to A5.
|
---|
9 | * (Optional.) LED on pin 9 for success indication.
|
---|
10 |
|
---|
11 | created 23 October 2012
|
---|
12 | by Petr Baudis
|
---|
13 |
|
---|
14 | https://github.com/pubnub/pubnub-api/tree/master/arduino
|
---|
15 | This code is in the public domain.
|
---|
16 | */
|
---|
17 |
|
---|
18 | #include <SPI.h>
|
---|
19 | #include <Ethernet.h>
|
---|
20 | #include <PubNub.h>
|
---|
21 |
|
---|
22 | // Some Ethernet shields have a MAC address printed on a sticker on the shield;
|
---|
23 | // fill in that address here, or choose your own at random:
|
---|
24 | byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
|
---|
25 |
|
---|
26 | const int pubLedPin = 9;
|
---|
27 |
|
---|
28 | char pubkey[] = "demo";
|
---|
29 | char subkey[] = "demo";
|
---|
30 | char channel[] = "hello_world";
|
---|
31 |
|
---|
32 | void setup()
|
---|
33 | {
|
---|
34 | pinMode(pubLedPin, OUTPUT);
|
---|
35 | digitalWrite(pubLedPin, LOW);
|
---|
36 |
|
---|
37 | Serial.begin(9600);
|
---|
38 | Serial.println("Serial set up");
|
---|
39 |
|
---|
40 | while (!Ethernet.begin(mac)) {
|
---|
41 | Serial.println("Ethernet setup error");
|
---|
42 | delay(1000);
|
---|
43 | }
|
---|
44 | Serial.println("Ethernet set up");
|
---|
45 |
|
---|
46 | PubNub.begin(pubkey, subkey);
|
---|
47 | Serial.println("PubNub set up");
|
---|
48 | }
|
---|
49 |
|
---|
50 | void flash(int ledPin)
|
---|
51 | {
|
---|
52 | /* Flash LED three times. */
|
---|
53 | for (int i = 0; i < 3; i++) {
|
---|
54 | digitalWrite(ledPin, HIGH);
|
---|
55 | delay(100);
|
---|
56 | digitalWrite(ledPin, LOW);
|
---|
57 | delay(100);
|
---|
58 | }
|
---|
59 | }
|
---|
60 |
|
---|
61 | void loop()
|
---|
62 | {
|
---|
63 | Ethernet.maintain();
|
---|
64 |
|
---|
65 | EthernetClient *client;
|
---|
66 |
|
---|
67 | char msg[64] = "{\"analog\":[";
|
---|
68 | for (int i = 0; i < 6; i++) {
|
---|
69 | sprintf(msg + strlen(msg), "%d", analogRead(i));
|
---|
70 | if (i < 5)
|
---|
71 | strcat(msg, ",");
|
---|
72 | }
|
---|
73 | strcat(msg, "]}");
|
---|
74 |
|
---|
75 | Serial.print("publishing message: ");
|
---|
76 | Serial.println(msg);
|
---|
77 | client = PubNub.publish(channel, msg);
|
---|
78 | if (!client) {
|
---|
79 | Serial.println("publishing error");
|
---|
80 | } else {
|
---|
81 | flash(pubLedPin);
|
---|
82 | client->stop();
|
---|
83 | }
|
---|
84 |
|
---|
85 | delay(5000);
|
---|
86 | }
|
---|