Нужна помощь в управлени светодиодами в часах
- Войдите на сайт для отправки комментариев
Пт, 03/04/2020 - 11:55
Здравствуйте. Сделал часы семи-сегментные на светодиодах WS2812. Проект не мой а иностранного человека. Часы работают. Решил разделить цвета символов. Часы одним цветом, а вот соответственно минуты другим. Но понять как это сделать не понимаю. Подскажите пожалуйста. Заранее спасибо
Вот исходный код управления цветом:
void displaySegments(int startindex, int number) {
byte numbers[ ] = { 0b00111111, // 0 0b00000110, // 1 0b01011011, // 2 0b01001111, // 3 0b01100110, // 4 0b01101101, // 5 0b01111101, // 6 0b00000111, // 7 0b01111111, // 8 0b01101111, // 9 0b01100011, // º 10 0b00111001, // C(elcius) 11 0b01011100, // º lower 12 0b00000000, // Empty 13 0b01110001, // F(ahrenheit) 14 };
for (int i = 0; i < 7; i++) { LEDs[i + startindex] = ((numbers[number] & 1 << i) == 1 << i) ? (colorMODE == 0 ? colorCRGB : colorCHSV) : colorOFF; } }
И где тут часы, а где минуты?
Если нужны минуты с часами я могу скинуть весь скетч на почту вам. Тут вроде как не вижу как приложить файл.
Но в самом скетче цвет привязывается к сегментам только в том фрагменте, который выложен выше
не надо почту - просто вставьте весь код точно так же, как вы вставили отрывок выше
Но для начала я бы советовал вам внимательно прочитать огромную тему про точно такие же часы буквально на пару сообщений ниже вашего в форуме:
http://arduino.ru/forum/programmirovanie/bolshie-nastennye-chasy-na-arduino
Значит пройдитесь двумя циклами раздельно по часам и по минутам. В каждом цикле будет присваивать свой цвет цифрам через LEDs[i]
Дак если я сделаю два одинаковых цикла, заменив только цвет в них. То так и будет. Что часы сначала одним цветом будут а по второму циклу будут все сегменты перекрашиваться в другой цвет
неправильно поняли. Первым циклом задайте цвет только первой и второй цифре, вторым - третьей и четвертой
Про указанные вами часы, я читал. Там скетч другой.
Выкладываю скетч у меня
#include <DHT.h> #include <DHT_U.h> #include <FastLED.h> #include <Wire.h> #include "RTClib.h" #include <SoftwareSerial.h> #include "Timer.h" #define DHTPIN 12 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); #define NUM_LEDS 30 #define DATA_PIN 6 CRGB LEDs[NUM_LEDS]; SoftwareSerial BTserial(8, 9); RTC_DS3231 rtc; Timer t1; Timer t2; Timer t3; String btBuffer; CRGB colorCRGB = CRGB::Blue; // Change this if you want another default color, for example CRGB::Red CHSV colorCHSV = CHSV(150, 255, 255); // Green (95, 255, 255); бело-голубой (140, 255, 255); голуюой (160, 255, 255); CRGB colorOFF = CRGB(0,0,0); // Color of the segments that are 'disabled'. You can also set it to CRGB::Black volatile int colorMODE = 1; // 0=CRGB, 1=CHSV, 2=Constant Color Changing pattern volatile int mode = 0; // 0=Clock, 1=Temperature, 2=Humidity, 3=Scoreboard, 4=Time counter volatile int scoreLeft = 0; volatile int scoreRight = 0; volatile long timerValue = 0; volatile int timerRunning = 0; #define blinkDots 1 // Set this to 1 if you want the dots to blink in clock mode, set it to value 0 to disable #define hourFormat 24 // Set this to 12 or to 24 hour format #define temperatureMode 'C' // Set this to 'C' for Celcius or 'F' for Fahrenheit void setup () { // Initialize LED strip FastLED.delay(3000); // Check if you're LED strip is a RGB or GRB version (third parameter) FastLED.addLeds<WS2812B, DATA_PIN, GRB>(LEDs, NUM_LEDS); Serial.begin(9600); while (!Serial) { /* Wait until serial is ready */ } BTserial.begin(9600); Serial.println("BTserial started at 9600"); dht.begin(); if (!rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); } if (rtc.lostPower()) { Serial.println("RTC lost power, lets set the time!"); // following line sets the RTC to the date & time this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } t1.every(1000 * 29, refreshDisplay); t2.every(1000, refreshTimer); t3.every(50, updateHue); refreshDisplay(); } void loop () { t1.update(); t2.update(); t3.update(); if (BTserial.available()) { char received = BTserial.read(); btBuffer += received; if (received == '|') { processCommand(); btBuffer = ""; } } } void updateHue() { if (colorMODE != 2) return; colorCHSV.sat = 255; colorCHSV.val = 255; if (colorCHSV.hue >= 255){ colorCHSV.hue = 0; } else { colorCHSV.hue++; } refreshDisplay(); } void refreshDisplay() { switch (mode) { case 0: displayClock(); break; case 1: displayTemperature(); break; case 2: displayHumidity(); break; case 3: displayScoreboard(); break; case 4: // Time counter has it's own timer break; default: break; } } void refreshTimer() { if (mode == 0 && blinkDots == 1) { displayDots(3); } else if (mode == 4 && timerRunning == 1 && timerValue < 6000) { timerValue++; int m1 = (timerValue / 60) / 10 ; int m2 = (timerValue / 60) % 10 ; int s1 = (timerValue % 60) / 10; int s2 = (timerValue % 60) % 10; displaySegments(0, s2); displaySegments(7, s1); displaySegments(16, m2); displaySegments(23, m1); displayDots(0); FastLED.show(); } } void processCommand(){ if (btBuffer.startsWith("RGBD")) { long R = getValue(btBuffer, ',', 1).toInt(); long G = getValue(btBuffer, ',', 2).toInt(); long B = getValue(btBuffer, ',', 3).toInt(); long D = getValue(btBuffer, ',', 4).toInt(); colorCRGB.red = R; colorCRGB.green = G; colorCRGB.blue = B; colorMODE = 0; if (D > 0) FastLED.setBrightness(D); } else if (btBuffer.startsWith("HSVD")) { long H = getValue(btBuffer, ',', 1).toInt(); long S = getValue(btBuffer, ',', 2).toInt(); long V = getValue(btBuffer, ',', 3).toInt(); long D = getValue(btBuffer, ',', 4).toInt(); colorCHSV.hue = H; colorCHSV.sat = S; colorCHSV.val = V; colorMODE = 1; if (D > 0) FastLED.setBrightness(D); } else if (btBuffer.startsWith("RTC")) { long y = getValue(btBuffer, ',', 1).toInt(); long m = getValue(btBuffer, ',', 2).toInt(); long d = getValue(btBuffer, ',', 3).toInt(); long h = getValue(btBuffer, ',', 4).toInt(); long mm = getValue(btBuffer, ',', 5).toInt(); long s = getValue(btBuffer, ',', 6).toInt(); rtc.adjust(DateTime(y, m, d, h, mm, s)); Serial.println("DateTime set"); } else if (btBuffer.startsWith("CLOCK")) { mode = 0; } else if (btBuffer.startsWith("TEMPERATURE")) { mode = 1; } else if (btBuffer.startsWith("HUMIDITY")) { mode = 2; } else if (btBuffer.startsWith("SCOREBOARD")) { scoreLeft = getValue(btBuffer, ',', 1).toInt(); scoreRight = getValue(btBuffer, ',', 2).toInt(); mode = 3; } else if (btBuffer.startsWith("STARTTIMER")) { timerValue = 0; timerRunning = 1; mode = 4; } else if (btBuffer.startsWith("STOPTIMER")) { timerRunning = 0; mode = 4; } else if (btBuffer.startsWith("CHANGINGPATTERN")) { colorMODE = 2; } refreshDisplay(); } void displayClock() { DateTime now = rtc.now(); int h = now.hour(); if (hourFormat == 12 && h > 12) h = h - 12; int hl = (h / 10) == 0 ? 13 : (h / 10); int hr = h % 10; int ml = now.minute() / 10; int mr = now.minute() % 10; displaySegments(0, mr); displaySegments(7, ml); displaySegments(16, hr); displaySegments(23, hl); displayDots(0); FastLED.show(); } void displayTemperature() { float tmp = dht.readTemperature(temperatureMode == 'F' ? true : false); if (isnan(tmp)) { Serial.println("Failed to read from DHT sensor!"); } else { int tmp1 = tmp / 10; int tmp2 = ((int)tmp) % 10; displaySegments(23, tmp1); displaySegments(16, tmp2); displaySegments(7, 10); displaySegments(0, (temperatureMode == 'F' ? 14 : 11)); displayDots(1); FastLED.show(); } } void displayHumidity() { float hum = dht.readHumidity(); if (isnan(hum)) { Serial.println("Failed to read from DHT sensor!"); } else { int hum1 = hum / 10; int hum2 = ((int)hum) % 10; displaySegments(23, hum1); displaySegments(16, hum2); displaySegments(7, 10); displaySegments(0, 12); displayDots(1); FastLED.show(); } } void displayScoreboard() { int s1 = scoreLeft % 10; int s2 = scoreLeft / 10; int s3 = scoreRight % 10; int s4 = scoreRight / 10; displaySegments(0, s3); displaySegments(7, s4); displaySegments(16, s1); displaySegments(23, s2); displayDots(2); FastLED.show(); } void displayDots(int dotMode) { // dotMode: 0=Both on, 1=Both Off, 2=Bottom On, 3=Blink switch (dotMode) { case 0: LEDs[14] = colorMODE == 0 ? colorCRGB : colorCHSV; LEDs[15] = colorMODE == 0 ? colorCRGB : colorCHSV; break; case 1: LEDs[14] = colorOFF; LEDs[15] = colorOFF; break; case 2: LEDs[14] = colorOFF; LEDs[15] = colorMODE == 0 ? colorCRGB : colorCHSV; break; case 3: LEDs[14] = (LEDs[14] == colorOFF) ? (colorMODE == 0 ? colorCRGB : colorCHSV) : colorOFF; LEDs[15] = (LEDs[15] == colorOFF) ? (colorMODE == 0 ? colorCRGB : colorCHSV) : colorOFF; FastLED.show(); break; default: break; } } void displaySegments(int startindex, int number) { byte numbers[] = { 0b00111111, // 0 0b00000110, // 1 0b01011011, // 2 0b01001111, // 3 0b01100110, // 4 0b01101101, // 5 0b01111101, // 6 0b00000111, // 7 0b01111111, // 8 0b01101111, // 9 0b01100011, // º 10 0b00111001, // C(elcius) 11 0b01011100, // º lower 12 0b00000000, // Empty 13 0b01110001, // F(ahrenheit) 14 }; for (int i = 0; i < 7; i++) { LEDs[i + startindex] = ((numbers[number] & 1 << i) == 1 << i) ? (colorMODE == 0 ? colorCRGB : colorCHSV) : colorOFF; } } String getValue(String data, char separator, int index) { int found = 0; int strIndex[] = {0, -1}; int maxIndex = data.length()-1; for(int i=0; i<=maxIndex && found<=index; i++){ if(data.charAt(i)==separator || i==maxIndex){ found++; strIndex[0] = strIndex[1]+1; strIndex[1] = (i == maxIndex) ? i+1 : i; } } return found>index ? data.substring(strIndex[0], strIndex[1]) : "";Словами я понимаю. А как в цикле прописать цвет первой и второй. Ведь цикл
for (int i = 0; i < 7; i++)
учитывает только сегменты.
Киньте код если не сложно как это прописать
Заранее спасибо
вставьте код как код!! - так же, как вы вставляли в первом сообщении
Код выложил
это не код. читайте правила. вставьте его нормально.
без этого никакой помощи не будет.
#include <DHT.h> #include <DHT_U.h> #include <FastLED.h> #include <Wire.h> #include "RTClib.h" #include <SoftwareSerial.h> #include "Timer.h" #define DHTPIN 12 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); #define NUM_LEDS 30 #define DATA_PIN 6 CRGB LEDs[NUM_LEDS]; SoftwareSerial BTserial(8, 9); RTC_DS3231 rtc; Timer t1; Timer t2; Timer t3; String btBuffer; CRGB colorCRGB = CRGB::Blue; // Change this if you want another default color, for example CRGB::Red CHSV colorCHSV = CHSV(150, 255, 255); // Green (95, 255, 255); бело-голубой (140, 255, 255); голуюой (160, 255, 255); CRGB colorOFF = CRGB(0,0,0); // Color of the segments that are 'disabled'. You can also set it to CRGB::Black volatile int colorMODE = 1; // 0=CRGB, 1=CHSV, 2=Constant Color Changing pattern volatile int mode = 0; // 0=Clock, 1=Temperature, 2=Humidity, 3=Scoreboard, 4=Time counter volatile int scoreLeft = 0; volatile int scoreRight = 0; volatile long timerValue = 0; volatile int timerRunning = 0; #define blinkDots 1 // Set this to 1 if you want the dots to blink in clock mode, set it to value 0 to disable #define hourFormat 24 // Set this to 12 or to 24 hour format #define temperatureMode 'C' // Set this to 'C' for Celcius or 'F' for Fahrenheit void setup () { // Initialize LED strip FastLED.delay(3000); // Check if you're LED strip is a RGB or GRB version (third parameter) FastLED.addLeds<WS2812B, DATA_PIN, GRB>(LEDs, NUM_LEDS); Serial.begin(9600); while (!Serial) { /* Wait until serial is ready */ } BTserial.begin(9600); Serial.println("BTserial started at 9600"); dht.begin(); if (!rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); } if (rtc.lostPower()) { Serial.println("RTC lost power, lets set the time!"); // following line sets the RTC to the date & time this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } t1.every(1000 * 29, refreshDisplay); t2.every(1000, refreshTimer); t3.every(50, updateHue); refreshDisplay(); } void loop () { t1.update(); t2.update(); t3.update(); if (BTserial.available()) { char received = BTserial.read(); btBuffer += received; if (received == '|') { processCommand(); btBuffer = ""; } } } void updateHue() { if (colorMODE != 2) return; colorCHSV.sat = 255; colorCHSV.val = 255; if (colorCHSV.hue >= 255){ colorCHSV.hue = 0; } else { colorCHSV.hue++; } refreshDisplay(); } void refreshDisplay() { switch (mode) { case 0: displayClock(); break; case 1: displayTemperature(); break; case 2: displayHumidity(); break; case 3: displayScoreboard(); break; case 4: // Time counter has it's own timer break; default: break; } } void refreshTimer() { if (mode == 0 && blinkDots == 1) { displayDots(3); } else if (mode == 4 && timerRunning == 1 && timerValue < 6000) { timerValue++; int m1 = (timerValue / 60) / 10 ; int m2 = (timerValue / 60) % 10 ; int s1 = (timerValue % 60) / 10; int s2 = (timerValue % 60) % 10; displaySegments(0, s2); displaySegments(7, s1); displaySegments(16, m2); displaySegments(23, m1); displayDots(0); FastLED.show(); } } void processCommand(){ if (btBuffer.startsWith("RGBD")) { long R = getValue(btBuffer, ',', 1).toInt(); long G = getValue(btBuffer, ',', 2).toInt(); long B = getValue(btBuffer, ',', 3).toInt(); long D = getValue(btBuffer, ',', 4).toInt(); colorCRGB.red = R; colorCRGB.green = G; colorCRGB.blue = B; colorMODE = 0; if (D > 0) FastLED.setBrightness(D); } else if (btBuffer.startsWith("HSVD")) { long H = getValue(btBuffer, ',', 1).toInt(); long S = getValue(btBuffer, ',', 2).toInt(); long V = getValue(btBuffer, ',', 3).toInt(); long D = getValue(btBuffer, ',', 4).toInt(); colorCHSV.hue = H; colorCHSV.sat = S; colorCHSV.val = V; colorMODE = 1; if (D > 0) FastLED.setBrightness(D); } else if (btBuffer.startsWith("RTC")) { long y = getValue(btBuffer, ',', 1).toInt(); long m = getValue(btBuffer, ',', 2).toInt(); long d = getValue(btBuffer, ',', 3).toInt(); long h = getValue(btBuffer, ',', 4).toInt(); long mm = getValue(btBuffer, ',', 5).toInt(); long s = getValue(btBuffer, ',', 6).toInt(); rtc.adjust(DateTime(y, m, d, h, mm, s)); Serial.println("DateTime set"); } else if (btBuffer.startsWith("CLOCK")) { mode = 0; } else if (btBuffer.startsWith("TEMPERATURE")) { mode = 1; } else if (btBuffer.startsWith("HUMIDITY")) { mode = 2; } else if (btBuffer.startsWith("SCOREBOARD")) { scoreLeft = getValue(btBuffer, ',', 1).toInt(); scoreRight = getValue(btBuffer, ',', 2).toInt(); mode = 3; } else if (btBuffer.startsWith("STARTTIMER")) { timerValue = 0; timerRunning = 1; mode = 4; } else if (btBuffer.startsWith("STOPTIMER")) { timerRunning = 0; mode = 4; } else if (btBuffer.startsWith("CHANGINGPATTERN")) { colorMODE = 2; } refreshDisplay(); } void displayClock() { DateTime now = rtc.now(); int h = now.hour(); if (hourFormat == 12 && h > 12) h = h - 12; int hl = (h / 10) == 0 ? 13 : (h / 10); int hr = h % 10; int ml = now.minute() / 10; int mr = now.minute() % 10; displaySegments(0, mr); displaySegments(7, ml); displaySegments(16, hr); displaySegments(23, hl); displayDots(0); FastLED.show(); } void displayTemperature() { float tmp = dht.readTemperature(temperatureMode == 'F' ? true : false); if (isnan(tmp)) { Serial.println("Failed to read from DHT sensor!"); } else { int tmp1 = tmp / 10; int tmp2 = ((int)tmp) % 10; displaySegments(23, tmp1); displaySegments(16, tmp2); displaySegments(7, 10); displaySegments(0, (temperatureMode == 'F' ? 14 : 11)); displayDots(1); FastLED.show(); } } void displayHumidity() { float hum = dht.readHumidity(); if (isnan(hum)) { Serial.println("Failed to read from DHT sensor!"); } else { int hum1 = hum / 10; int hum2 = ((int)hum) % 10; displaySegments(23, hum1); displaySegments(16, hum2); displaySegments(7, 10); displaySegments(0, 12); displayDots(1); FastLED.show(); } } void displayScoreboard() { int s1 = scoreLeft % 10; int s2 = scoreLeft / 10; int s3 = scoreRight % 10; int s4 = scoreRight / 10; displaySegments(0, s3); displaySegments(7, s4); displaySegments(16, s1); displaySegments(23, s2); displayDots(2); FastLED.show(); } void displayDots(int dotMode) { // dotMode: 0=Both on, 1=Both Off, 2=Bottom On, 3=Blink switch (dotMode) { case 0: LEDs[14] = colorMODE == 0 ? colorCRGB : colorCHSV; LEDs[15] = colorMODE == 0 ? colorCRGB : colorCHSV; break; case 1: LEDs[14] = colorOFF; LEDs[15] = colorOFF; break; case 2: LEDs[14] = colorOFF; LEDs[15] = colorMODE == 0 ? colorCRGB : colorCHSV; break; case 3: LEDs[14] = (LEDs[14] == colorOFF) ? (colorMODE == 0 ? colorCRGB : colorCHSV) : colorOFF; LEDs[15] = (LEDs[15] == colorOFF) ? (colorMODE == 0 ? colorCRGB : colorCHSV) : colorOFF; FastLED.show(); break; default: break; } } void displaySegments(int startindex, int number) { byte numbers[] = { 0b00111111, // 0 0b00000110, // 1 0b01011011, // 2 0b01001111, // 3 0b01100110, // 4 0b01101101, // 5 0b01111101, // 6 0b00000111, // 7 0b01111111, // 8 0b01101111, // 9 0b01100011, // º 10 0b00111001, // C(elcius) 11 0b01011100, // º lower 12 0b00000000, // Empty 13 0b01110001, // F(ahrenheit) 14 }; for (int i = 0; i < 7; i++) { LEDs[i + startindex] = ((numbers[number] & 1 << i) == 1 << i) ? (colorMODE == 0 ? colorCRGB : colorCHSV) : colorOFF; } } String getValue(String data, char separator, int index) { int found = 0; int strIndex[] = {0, -1}; int maxIndex = data.length()-1; for(int i=0; i<=maxIndex && found<=index; i++){ if(data.charAt(i)==separator || i==maxIndex){ found++; strIndex[0] = strIndex[1]+1; strIndex[1] = (i == maxIndex) ? i+1 : i; } } return found>index ? data.substring(strIndex[0], strIndex[1]) : "";Я не понимаю, на что Вы рассчитываете. Часы нужны Вам, а не мне. Какой смысл мне разбираться полдня в коде, который Вы даже не не пытаетесь понять, а потом еще и разжевывать что и где править.
Как так я не пытаюсь? Я пытаюсь и ваш вариант я делал. И увы он не дал результата
for (int i = 0; i < 7; i++) { LEDs[i + startindex] = ((numbers[number] & 1 << i) == 1 << i) ? (colorMODE == 0 ? colorCRGB : colorCHSV) : colorOFF; } for (int i = 0; i < 7; i++) { LEDs[i + startindex] = ((numbers[number] & 1 << i) == 1 << i) ? (colorMODE == 0 ? colorCRGB : colorCHSVChas) : colorOFF; }avr2012 - теперь другое дело, в коде есть номера строк и его можно обсуждать.
Вот, смотрите - в строчках 261-265 у вас выводятся на ленту каждая цифра и разделительные точки - отдельно. Добавьте в параметры процедуры displaySegments() цвет и вызывайте каждую цифру часов со своим цветом. Так вы сможете выводить разными цветами не только часы и минуты но и все четыре цифры сделать оазноцветными
Я спросил - где в этом массиве часы и где минуты? Какие значения переменной i соответствуют тем и другим?
В строках 261-265 выводится информация с приложения по блютузу
тогда 214 -219
Теперь я вас понял. В том то и дело что вроде как нет привязки i к часам и минутам. LEDs[i] учитывает только сегмент каждого элемента
Я согласен с B707 - нужно добавлять в процедуру displaySegments() параметр "цвет". Проблема только в том, что внутри этой процедуры используются два цветовых пространства. Т.е. цвет придётся передавать через union или использовать только одно пространство. За 5 сек это у Вас не получится.
Я согласен с B707 - нужно добавлять в процедуру параметр "цвет". Проблема только в том, что внутри этой процедуры используются два цветовых пространства. Т.е. цвет придётся передавать через union или использовать только одно пространство. За 5 сек это у Вас не получится.
для начала использовать только один ColorМode. а как заработает - думать дальше
Хорошо. Попробую
Посмотрите как тут реализовано управление цветом.
https://github.com/Lightwell-bg/LEDPixelClock
Посмотрите как тут реализовано управление цветом.
https://github.com/Lightwell-bg/LEDPixelClock
посмотрел. Никак не организовано.
Посмотрите как тут реализовано управление цветом.
https://github.com/Lightwell-bg/LEDPixelClock
посмотрел. Никак не организовано.
Вот же функция где цвет можно задать
Вот же функция где цвет можно задать
разве в ней есть возможность задавать разные цвета разным цифрам? - нет.
А ТС спрашивает именно это. А менять цвет подсветки и у него в коде можно....
Вот же функция где цвет можно задать
разве в ней есть возможность задавать разные цвета разным цифрам? - нет.
А ТС спрашивает именно это. А менять цвет подсветки и у него в коде можно....
Так добавить вместо LedColor LedColor[4] и менять на каждой цифре.