void loop() {
PubNub_BASE_CLIENT *client;
Serial.println("waiting for a message (subscribe)");
PubSubClient *pclient = PubNub.subscribe("uvindex"); // Subscribe to the UV index channel for values.
if (!pclient) {
Serial.println("subscription error");
delay(1000);
return;
}
String message;
while (pclient->wait_for_data()) {
char c = pclient->read();
//Serial.print(c);
message = message+String(c); // Append to string.
}
pclient->stop();
// Get UV index value.
if(message.indexOf("uvindex") > 0) { // Ensure the message contains the UV index (prevents a unexpected message from turning off the led).
uvindex = message.substring(19, message.length() - 4).toInt(); // Remove characters before and after value.
};
// Set the color of the led based on the UV index.
if ((uvindex >= 0) && (uvindex < 1)) { // None 0 Off
analogWrite(rled, 0);
analogWrite(gled, 0);
analogWrite(bled, 0);
} else if ((uvindex >= 1) && (uvindex < 3)) { // Low 1-2 Green
analogWrite(rled, 0);
analogWrite(gled, 255);
analogWrite(bled, 0);
} else if ((uvindex >= 3) && (uvindex < 6)) { // Moderate 3-5 Yellow
analogWrite(rled, 255);
analogWrite(gled, 255);
analogWrite(bled, 0);
} else if ((uvindex >= 6) && (uvindex < 8)) { // High 6-7 Orange
analogWrite(rled, 255);
analogWrite(gled, 120);
analogWrite(bled, 0);
} else if ((uvindex >= 8) && (uvindex < 11)) { // Very High 8-10 Red
analogWrite(rled, 255);
analogWrite(gled, 0);
analogWrite(bled, 0);
} else if (uvindex >= 11) { // Extreme 11+ Purple
analogWrite(rled, 85);
analogWrite(gled, 0);
analogWrite(bled, 85);
};
Serial.print("UV Index: ");
Serial.print(uvindex);
Serial.println();
delay(5000);
}
#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>
const static char ssid[] = "Sensor Network";
const static char pass[] = "sens0rpassw0rd";
int rled = 14; // The PWM pins the LED is attached to.
int gled = 12;
int bled = 15;
int uvindex = 0;
以上是关于c_cpp UV Index Indicator订阅PubNub并使用颜色显示UV索引值。博文的代码片段。在这里查看项目:https:/的主要内容,如果未能解决你的问题,请参考以下文章