Помогите со скетчем
- Войдите на сайт для отправки комментариев
Втр, 10/05/2016 - 10:31
Сделал часы на WS2811 и Arduino nano. На готовом прототипе стоит датчик освещенности для автоматической регулировки яркости день-ночь (к примеру днем яркость 255, ночь 100), но столкнулся с проблемой слабой чуствительности датчика. В солнечный день отробатывает нормально, но в пасмурную погоду для него ночь. Помогите с кодом (в Arduiono еще не очень разбираюся). На борту имеются часы реального времени DS3231, можно ли регулировать яркость в зависивимостри от времени раз с датчиком такая беда (в интервале допустим с 8.00-22.00 на выходе иметь яркость 255, а с 22.00-8.00 яркость 100). Вот мой скетч
#include <DS3231RTC.h>
#include <Time.h>
#include <Wire.h>
#include "FastLED.h"
#define NUM_LEDS 29 // Number of LED controles (remember I have 3 leds / controler
#define COLOR_ORDER BRG // Define color order for your strip
#define DATA_PIN 6 // Data pin for led comunication
CRGB leds[NUM_LEDS]; // Define LEDs strip
byte digits[10][7] = {{0,1,1,1,1,1,1}, // Digit 0
{0,1,0,0,0,0,1}, // Digit 1
{1,1,1,0,1,1,0}, // Digit 2
{1,1,1,0,0,1,1}, // Digit 3
{1,1,0,1,0,0,1}, // Digit 4
{1,0,1,1,0,1,1}, // Digit 5
{1,0,1,1,1,1,1}, // Digit 6
{0,1,1,0,0,0,1}, // Digit 7
{1,1,1,1,1,1,1}, // Digit 8
{1,1,1,1,0,1,1}}; // Digit 9 | 2D Array for numbers on 7 segment
bool Dot = true; //Dot state
bool DST = false; //DST state
int last_digit = 0;//long ledColor = CRGB::DarkOrchid; // Color used (in hex)
long ledColor = CRGB::MediumVioletRed;
long ColorTable[16] = {
CRGB::Amethyst,
CRGB::Aqua,
CRGB::Blue,
CRGB::Chartreuse,
CRGB::DarkGreen,
CRGB::DarkMagenta,
CRGB::DarkOrange,
CRGB::DeepPink,
CRGB::Fuchsia,
CRGB::Gold,
CRGB::GreenYellow,
CRGB::LightCoral,
CRGB::Tomato,
CRGB::Salmon,
CRGB::Red,
CRGB::Orchid};
void setup(){
// Serial.begin(9600);
// Wire.begin();
LEDS.addLeds<WS2811, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS); // Set LED strip type
LEDS.setBrightness(255); // Set initial brightness
pinMode(2, INPUT_PULLUP); // Define DST adjust button pin
pinMode(4, INPUT_PULLUP); // Define Minutes adjust button pin
pinMode(5, INPUT_PULLUP); // Define Hours adjust button pin
}
// Get time in a single number, if hours will be a single digit then time will be displayed 155 instead of 0155
int GetTime(){
tmElements_t Now;
RTC.read(Now);
//time_t Now = RTC.Now();// Getting the current Time and storing it into a DateTime object
int hour=Now.Hour;
int minutes=Now.Minute;
int second =Now.Second;
if (second % 2==0) {Dot = false;}
else {Dot = true;};
return (hour*100+minutes);
};
// Check Light sensor and set brightness accordingly
void BrightnessCheck(){
const byte sensorPin = 3; // light sensor pin
const byte brightnessLow = 100; // Low brightness value
const byte brightnessHigh = 255; // High brightness value
int sensorValue = digitalRead(sensorPin); // Read sensor
if (sensorValue == 0) {LEDS.setBrightness(brightnessHigh);}
else {LEDS.setBrightness(brightnessLow);}
};
// Convert time to array needet for display
void TimeToArray(){
int Now = GetTime(); // Get time
int cursor = 29;
// Serial.print("Time is: ");Serial.println(Now);
if (DST){ // if DST is true then add one hour
Now+=100;
// Serial.print("DST is ON, time set to : ");Serial.println(Now);
};
if (Dot){leds[14]=ledColor;}
else {leds[14]=0x000000;
};
for(int i=1;i<=4;i++){
int digit = Now % 10; // get last digit in time
if (i==1){
// Serial.print("Digit 4 is : ");Serial.print(digit);Serial.print(" ");
cursor =22;
for(int k=0; k<=6;k++){
// Serial.print(digits[digit][k]);
if (digits[digit][k]== 1){leds[cursor]=ledColor;}
else if (digits[digit][k]==0){leds[cursor]=0x000000;};
cursor ++;
};
Serial.println();
if (digit != last_digit)
{ fadefonction();
ledColor = ColorTable[random(16)];
}
last_digit = digit;
}// fin if
else if (i==2){
// Serial.print("Digit 3 is : ");Serial.print(digit);Serial.print(" ");
cursor -=14;
for(int k=0; k<=6;k++){
// Serial.print(digits[digit][k]);
if (digits[digit][k]== 1){leds[cursor]=ledColor;}
else if (digits[digit][k]==0){leds[cursor]=0x000000;};
cursor ++;
};
// Serial.println();
}
else if (i==3){
// Serial.print("Digit 2 is : ");Serial.print(digit);Serial.print(" ");
cursor =7;
for(int k=0; k<=6;k++){
// Serial.print(digits[digit][k]);
if (digits[digit][k]== 1){leds[cursor]=ledColor;}
else if (digits[digit][k]==0){leds[cursor]=0x000000;};
cursor ++;
};
// Serial.println();
}
else if (i==4){
// Serial.print("Digit1 is : ");Serial.print(digit);Serial.print(" ");
cursor =0;
for(int k=0; k<=6;k++){
// Serial.print(digits[digit][k]);
if (digits[digit][k]== 1){leds[cursor]=ledColor;}
else if (digits[digit][k]==0){leds[cursor]=0x000000;};
cursor ++;
};
// Serial.println();
}
Now /= 10;
};
};
void DSTcheck(){
int buttonDST = digitalRead(2);
// Serial.print("DST is: ");Serial.println(DST);
if (buttonDST == LOW){
if (DST){
DST=false;
// Serial.print("Switching DST to: ");Serial.println(DST);
}
else if (!DST){
DST=true;
// Serial.print("Switching DST to: ");Serial.println(DST);
};
delay(500);
};
}
void TimeAdjust(){
int buttonH = digitalRead(5);
int buttonM = digitalRead(4);
if (buttonH == LOW || buttonM == LOW){
delay(500);
tmElements_t Now;
RTC.read(Now);
int hour=Now.Hour;
int minutes=Now.Minute;
int second =Now.Second;
if (buttonH == LOW){
if (Now.Hour== 23){Now.Hour=0;}
else {Now.Hour += 1;};
}else {
if (Now.Minute== 59){Now.Minute=0;}
else {Now.Minute += 1;};
};
RTC.write(Now);
}
}
void fadeall() {
for(int m = 0; m < NUM_LEDS; m++) {
leds[m].nscale8(250);
}
}
void fadefonction () {
static uint8_t hue = 0;
// First slide the led in one direction
for(int i = 0; i < NUM_LEDS; i++) {
// Set the i'th led to red
leds[i] = CHSV(hue++, 255, 255);
// Show the leds
FastLED.show();
// now that we've shown the leds, reset the i'th led to black
// leds[i] = CRGB::Black;
fadeall();
// Wait a little bit before we loop around and do it again
delay(10);
}
// Now go in the other direction.
for(int i = (NUM_LEDS)-1; i >= 0; i--) {
// Set the i'th led to red
leds[i] = CHSV(hue++, 255, 255);
// Show the leds
FastLED.show();
// now that we've shown the leds, reset the i'th led to black
// leds[i] = CRGB::Black;
fadeall();
// Wait a little bit before we loop around and do it again
delay(10);
}
}
void loop() // Main loop
{
BrightnessCheck(); // Check brightness
DSTcheck(); // Check DST
TimeAdjust(); // Check to se if time is geting modified
TimeToArray(); // Get leds array with required configuration
FastLED.show(); // Display leds array
}
Не знаю кто у вас там работает датчиком,
но для начала попробуйте увеличить в 10 -100 раз резистор подключенный к датчику.
на датчике есть подстроечный потенцометр но толку от него ноль, да и хочу отказаться от него вообще, пусть лучше програмно регулруется.
Не ясно какой датчик у вас стоит, но скорее всего у вас там обычный делитель напряжения. Попробуйте подключите его к аналоговому входу, и читайте значения с него - выводите значения в сериал для отладки и поймете где вам нужно включать, а где отключать. Вы сейчас считываете значения напряжения с цифрового пина, если оно больше 3 Вольт то темно, если меньше то светло.
датчик стоит http://ru.aliexpress.com/item/Free-shipping-3-3-5V-Input-Light-Light-Sensor-Sensor-Photodiode-Module-for-Arduino-Raspberry-pi/32471300405.html?spm=2114.30010708.3.137.x44a6d&ws_ab_test=searchweb201556_0,searchweb201602_3_10037_10017_10034_10021_507_10033_10022_10032_10020_10018_10019,searchweb201603_2&btsid=508173ba-a78e-49d0-9f14-9fa62c97c32a такой есть и цифра и аналоговый выхода, ну допустим перекину на аналог там понимаю можно плавно регулировать в зависимости от освещения, а не как на цифре либо 0 либо 1
Там есть есть выход A0 - это скорее всего аналоговый выход. Посмотрите тестером, что с него приходит, в зависимости от уровня освещенности. И если это он, меняйте уровень подсветки плавно.
Ваша платка создана для ленивых, там компаратором порог выставляется.
Попробуйте простой фоторезистор ( а не фотодиод ).
И, естественно, на аналоговый вход.
Сможете увидеть плавное изменение освещённости.
зацепиться на A0 к примеру и попробовать прогнать что то типо этого
01 const int analogPin = 0; 02 03 void setup() { 04 Serial.begin(9600); 05 } 06 07 void loop() { 08 int mn = 1024; 09 int mx = 0; 10 for (int i=0; i < 10000; ++i) { 11 int val = analogRead(analogPin); 12 mn = min(mn, val); 13 mx = max(mx, val); 14 } 15 Serial.print("m="); 16 Serial.print(mn); 17 Serial.print(" M="); 18 Serial.print(mx); 19 Serial.print(" D="); 20 Serial.print(mx-mn); 21 Serial.println(); 22 }то что диод заметил уже когда получил плату, в оригинальном проекте с которого собирал часы была та же плата на фоторезисторе, вероятно поэтому у него все норм а я с диодом налип
зацепиться на A0 к примеру и попробовать прогнать что то типо этого
01 const int analogPin = 0; 02 03 void setup() { 04 Serial.begin(9600); 05 } 06 07 void loop() { 08 int mn = 1024; 09 int mx = 0; 10 for (int i=0; i < 10000; ++i) { 11 int val = analogRead(analogPin); 12 mn = min(mn, val); 13 mx = max(mx, val); 14 } 15 Serial.print("m="); 16 Serial.print(mn); 17 Serial.print(" M="); 18 Serial.print(mx); 19 Serial.print(" D="); 20 Serial.print(mx-mn); 21 Serial.println(); 22 }Можно так, m и M главное не попутать :-) Хотя мнемонически правильно.
Только analogPin = 0; на analogPin = A0; надо
сегодня получил вот такой http://ru.aliexpress.com/item/5Pcs-Photosensitive-brightness-resistance-sensor-module-Light-intensity-detect-New-Free-Shipping/1625377263.html?spm=2114.30010708.3.1.3xY0hb&ws_ab_test=searchweb201556_0,searchweb201602_3_10037_10017_10034_10021_507_10033_10022_10032_10020_10018_10019,searchweb201603_2&btsid=03a5b058-d097-40c3-a480-bfd2234a028b на нем только цифровой, но он на фоторезисторе. Только analogPin = 0; на analogPin = A0; надо тоесть с АО датчика на А0 Arduino? я так и хотел )) завтра на работе попробую как новый будет работать (дома проводов нет), если новый нормально будет пахать то тупо поменяю. если нет, то буду мучить аналог =)
надо тоесть с АО датчика на А0 Arduino? я так и хотел )) завтра на работе попробую как новый будет работать (дома проводов нет), если новый нормально будет пахать то тупо поменяю. если нет, то буду мучить аналог =)
Нет, вы меня не так поняли.
Номера аналоговых пинов вводят с буквами (A0,A1). Вы переменную analogPin кладете значение 0, а надо A0. AnalogRead(0) - вас IDE поправит. Но правильнее AnalogRead(A0).
DigitalRead(0)
DigitalRead(A0) - чтение с разных портов.
Вас понял чпасибо что поправили
Сегодня проверил новый датчик на резисторе он на много адекватнее, похоже буду менять на него. Сегодня не смогу дел много, завтра заменю отпишусь как работает.
Вам не нужен (совсем не нужен) аналоговый вход.
Судя по фото у вас выходной сигнал с компаратра. Вроде с 393-его.....
Для снятия аналоговог сигнала нужен его выход, а у вас его нет.
Вот на этих есть: https://uge-one.com/index.php?route=product/product&product_id=847
Или возьмите его с платы сами.
В точке соединения фото и обычного резистора.
на новом датчике аналогового выхода нет, а на старом есть. но новый вроде и на цифре нормуль работает. то ли на первом из за диода такие траблы, есть еще подозрение на подстроечный патенцометр. завтра воткну новый датчик посмотрю как будет, а так как часы все равно разберу можно и с аналоговым поиграться (так хоть что то новое узнаю =))
поставил новый датчик работает отлично, чуствительность хорошо регулируется. а со старым буду на работе играться, попробую с аналогом по эксперементировать =)
мои часики цифровые на ленте ws2811 (семисегментные индикаторы), видел пару видосов с аналоговыми часами на ws2812b думаю такой проектик замутить (завалялось 4м такой =) 60диодов на метр как раз на часы), ни кому не попадался такой проект с нормальным описанием, а то мои поиски пока ни к чему не привели =)
поставил новый датчик работает отлично, чуствительность хорошо регулируется. а со старым буду на работе играться, попробую с аналогом по эксперементировать =)
Вам виднее.
Регулируйте порог компаратора потенциометром.
Вместо того чтобы измерять освещённость.
На здоровье.
поигрался с аналоговым входом, все работает. но переделывать не буду, на новом датчике замечательно все работает. возник другой вопрос: сделал led табло под небольшие часы на диодах ws2812b с размером одной цифры 3*5 диоды спаяны в следующем порядке 5 6 13 18 19 26 32 33 40 45 46 53 4 12 17 25 31 39 44 52 3 7 11 16 20 24 27 30 34 38 43 47 51 2 10 15 23 29 37 42 50 1 8 9 14 21 22 28 35 36 41 48 49 попытался переделать скетч под такие цифры в виде:
byte digits[10][13] = { {1,1,1,1,1,1,0,1,1,1,1,1,1}, // Digit 0 {0,0,0,0,0,0,0,0,1,1,1,1,1}, // Digit 1 {1,1,1,0,1,1,1,1,1,0,1,1,1}, // Digit 2 {1,0,1,0,1,1,1,1,1,1,1,1,1}, // Digit 3 {0,0,1,1,1,1,1,0,1,1,1,1,1}, // Digit 4 {1,0,1,1,1,1,1,1,1,1,1,0,1}, // Digit 5 {1,1,1,1,1,1,1,1,1,1,1,0,1}, // Digit 6 {0,0,0,0,0,1,0,0,1,1,1,1,1}, // Digit 7 {1,1,1,1,1,1,1,1,1,1,1,1,1}, // Digit 8 {1,0,1,1,1,1,1,1,1,1,1,1,1}}; // Digit 9в оригинальном скетче на цифру было использовано больше диодов (21 диод), но при опросе в мониторе СОМ порта выдает цыфры как были прописаны до изменения тоесть 13моих символов+8 не понятно от куда взятых. К примеру Digit 4 is : 1110111110111******** = 2, соответственно на табло вместо времени черти что. Куда копать? Вот измененный мною скетч
#include <DS3232RTC.h> #include <Time.h> #include <Wire.h> #include <FastLED.h> #define NUM_LEDS 53 // 5 by segment + 6 in the middle #define LED_TYPE WS2812 #define COLOR_ORDER GRB // Define color order for your strip #define BRIGHTNESS 150 #define LED_PIN 5 // Data pin for led comunication CRGB leds[NUM_LEDS]; // Define LEDs strip byte digits[10][13] = { {1,1,1,1,1,1,0,1,1,1,1,1,1}, // Digit 0 {0,0,0,0,0,0,0,0,1,1,1,1,1}, // Digit 1 {1,1,1,0,1,1,1,1,1,0,1,1,1}, // Digit 2 {1,0,1,0,1,1,1,1,1,1,1,1,1}, // Digit 3 {0,0,1,1,1,1,1,0,1,1,1,1,1}, // Digit 4 {1,0,1,1,1,1,1,1,1,1,1,0,1}, // Digit 5 {1,1,1,1,1,1,1,1,1,1,1,0,1}, // Digit 6 {0,0,0,0,0,1,0,0,1,1,1,1,1}, // Digit 7 {1,1,1,1,1,1,1,1,1,1,1,1,1}, // Digit 8 {1,0,1,1,1,1,1,1,1,1,1,1,1}}; // Digit 9 | 2D Array for numbers on 7 segment byte firstdigit[2][5] = { {0,0,0,0,0}, // Digit 0 first number {1,1,1,1,1}}; // Digit 1 first number | 2D Array for numbers on 7 segment bool Dot = true; //Dot state bool DST = false; //DST state int last_digit = 0; //long ledColor = CRGB::DarkOrchid; // Color used (in hex) long ledColor = CRGB::MediumVioletRed; long ColorTable[16] = { CRGB::Amethyst, CRGB::Aqua, CRGB::Blue, CRGB::Chartreuse, CRGB::DarkGreen, CRGB::DarkMagenta, CRGB::DarkOrange, CRGB::DeepPink, CRGB::Fuchsia, CRGB::Gold, CRGB::GreenYellow, CRGB::LightCoral, CRGB::Tomato, CRGB::Salmon, CRGB::Red, CRGB::Orchid}; void setup(){ Serial.begin(9600); Wire.begin(); FastLED.addLeds<WS2812B, LED_PIN, RGB>(leds, NUM_LEDS); //FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip ); FastLED.setBrightness( BRIGHTNESS ); //pinMode(6, INPUT_PULLUP); // Define DST adjust button pin pinMode(4, INPUT_PULLUP); // Define Minutes adjust button pin pinMode(2, INPUT_PULLUP); // Define Hours adjust button pin } // Check Light sensor and set brightness accordingly void BrightnessCheck(){ const byte sensorPin = 3; // light sensor pin const byte brightnessLow = 75; // Low brightness value const byte brightnessHigh = 100; // High brightness value int sensorValue = digitalRead(sensorPin); // Read sensor if (sensorValue == 0) { Serial.println("Brightness High"); LEDS.setBrightness(brightnessHigh); } else { Serial.println("Brightness Low"); LEDS.setBrightness(brightnessLow); } }; // Get time in a single number int GetTime(){ tmElements_t Now; RTC.read(Now); //time_t Now = RTC.Now();// Getting the current Time and storing it into a DateTime object int hour=Now.Hour; int minutes=Now.Minute; int second =Now.Second; if (second % 2==0) { Dot = false; } else { Dot = true; }; return (hour*100+minutes); }; void DSTcheck(){ int buttonDST = digitalRead(2); Serial.print("DST is: "); Serial.println(DST); if (buttonDST == LOW){ if (DST){ DST=false; Serial.print("Switching DST to: "); Serial.println(DST); } else if (!DST){ DST=true; Serial.print("Switching DST to: "); Serial.println(DST); }; delay(500); }; } // Convert time to array needet for display void TimeToArray(){ int Now = GetTime(); // Get time int cursor = 53; //116 Serial.print("Time is: "); Serial.println(Now); if (Dot){ leds[25]=ledColor; leds[26]=ledColor; leds[27]=ledColor; leds[28]=ledColor; leds[29]=ledColor; //leds[48]=ledColor; } else { leds[25]=0x000000; leds[26]=0x000000; leds[27]=0x000000; leds[28]=0x000000; leds[29]=0x000000; //leds[48]=0x000000; }; for(int i=1;i<=4;i++){ int digit = Now % 10; // get last digit in time if (i==1){ cursor =40; //82 Serial.print("Digit 4 is : "); Serial.print(digit); Serial.print(", the array is : "); for(int k=0; k<=20;k++){ Serial.print(digits[digit][k]); if (digits[digit][k]== 1){ leds[cursor]=ledColor; } else if (digits[digit][k]==0){ leds[cursor]=0x000000; }; cursor ++; }; // fin for Serial.println(); if (digit != last_digit) { fadefonction(); ledColor = ColorTable[random(16)]; } last_digit = digit; }// fin if else if (i==2){ cursor =27; Serial.print("Digit 3 is : "); Serial.print(digit); Serial.print(", the array is : "); for(int k=0; k<=20;k++){ Serial.print(digits[digit][k]); if (digits[digit][k]== 1){ leds[cursor]=ledColor; } else if (digits[digit][k]==0){ leds[cursor]=0x000000; }; cursor ++; }; Serial.println(); } else if (i==3){ cursor =13; Serial.print("Digit 2 is : "); Serial.print(digit); Serial.print(", the array is : "); for(int k=0; k<=20;k++){ Serial.print(digits[digit][k]); if (digits[digit][k]== 1){ leds[cursor]=ledColor; } else if (digits[digit][k]==0){ leds[cursor]=0x000000; }; cursor ++; }; Serial.println(); } else if (i==4){ cursor =0; Serial.print("Digit 1 is : "); Serial.print(digit); Serial.print(", the array is : "); for(int k=0; k<=20;k++){ Serial.print(digits[digit][k]); if (digits[digit][k]== 1){ leds[cursor]=ledColor; } else if (digits[digit][k]==0){ leds[cursor]=0x000000; }; cursor ++; }; // Serial.println(); }; Now /= 10; }; }; void TimeAdjust(){ int buttonH = digitalRead(5); int buttonM = digitalRead(4); if (buttonH == LOW || buttonM == LOW){ delay(500); tmElements_t Now; RTC.read(Now); int hour=Now.Hour; int minutes=Now.Minute; if (buttonH == LOW){ if (Now.Hour== 24){ Now.Hour=1; } else { Now.Hour += 1; }; } else { if (Now.Minute== 59){ Now.Minute=0; } else { Now.Minute += 1; }; }; RTC.write(Now); } } void fadeall() { for(int m = 0; m < NUM_LEDS; m++) { leds[m].nscale8(250); } } void fadefonction () { static uint8_t hue = 0; // First slide the led in one direction for(int i = 0; i < NUM_LEDS; i++) { // Set the i'th led to red leds[i] = CHSV(hue++, 255, 255); // Show the leds FastLED.show(); // now that we've shown the leds, reset the i'th led to black // leds[i] = CRGB::Black; fadeall(); // Wait a little bit before we loop around and do it again delay(10); } // Now go in the other direction. for(int i = (NUM_LEDS)-1; i >= 0; i--) { // Set the i'th led to red leds[i] = CHSV(hue++, 255, 255); // Show the leds FastLED.show(); // now that we've shown the leds, reset the i'th led to black // leds[i] = CRGB::Black; fadeall(); // Wait a little bit before we loop around and do it again delay(10); } } void loop() // Main loop { /*BrightnessCheck(); // Check brightness DSTcheck(); // Check DST TimeAdjust(); // Check to se if time is geting modified*/ TimeToArray(); // Get leds array with required configuration FastLED.show(); // Display leds array float t = RTC.temperature(); float celsius = t / 4.0; Serial.println(); Serial.print("Temp is : "); Serial.print(celsius); Serial.println(); }в оригинальном скетче на цифру было использовано больше диодов (21 диод), но при опросе в мониторе СОМ порта выдает цыфры как были прописаны до изменения тоесть 13моих символов+8 не понятно от куда взятых. К примеру Digit 4 is : 1110111110111******** = 2, соответственно на табло вместо времени черти что. Куда копать? Вот измененный мною скетч
for(int k=0; k<=20;k++){ // строка 268 Serial.print(digits[digit][k]); // строка 269 if (digits[digit][k]== 1){тут вывод массива до от 0 до 20 включительно (т.е. 21 знак) сделайте for(int k=0; k < 13;k++)
Для каждой цифры надо поправить.
спс за ответ. а вот здесь к примеру
cursor =40; //82 Serial.print("Digit 4 is : "); Serial.print(digit); Serial.print(", the array is : "); for(int k=0; k<=20;k++){ Serial.print(digits[digit][k]); if (digits[digit][k]== 1){ leds[cursor]=ledColor; } else if (digits[digit][k]==0){ leds[cursor]=0x000000; }; cursor ++;я правильно понял cursor =40 это начало 4й цифры? и где прописываются точки которые межджу часами и минутами?
Курсор указывает на текущий номер диода от нуля.
Код для точки :
141intcursor = 53;//116142143Serial.print("Time is: ");144Serial.println(Now);145146if(Dot){147leds[25]=ledColor;148leds[26]=ledColor;149leds[27]=ledColor;150leds[28]=ledColor;151leds[29]=ledColor;152//leds[48]=ledColor;153}154155else{156157leds[25]=0x000000;158leds[26]=0x000000;159leds[27]=0x000000;160leds[28]=0x000000;161leds[29]=0x000000;162//leds[48]=0x000000;163164};тоесть в моем случае с одной точкой (27 по счету) нужно
Мне кажется от нуля, будет leds[26]=0x000000;
а я от единички считаю ))) УПС да вникать и вникать ))
а это что такое что за массив и с чем его едят
byte firstdigit[2][5] = { {0,0,0,0,0}, // Digit 0 first number {1,1,1,1,1}}; // Digit 1 first number | 2D Array for numbers on 7 segmentчем он отличается от
byte digits[10][13] = { {1,1,1,1,1,1,0,1,1,1,1,1,1}, // Digit 0 {0,0,0,0,0,0,0,0,1,1,1,1,1}, // Digit 1Это знает только автор скетча, в коде я не нашел использования данного массива.
Что то связанное с первой цифрой в 12 часовом формате.
спс огромное за помощь завтра попробую, посмотрим что получится ))
Как оказалось ключевое слово здесь включительно =) сделайте for(int k=0; k < 13;k++) соответственно не прокатило т.к. это уже 14. Обмазговав полученые от вас знания пришел к тому что, ноль мы тоже считаем за единицу (что я тоже изночально не учел), поставил 12 все завелось. Добавил вторую точку. Сегодня всячески пытался вставить в скетч код для измерения и вывода температуры с модуля DS3231RTC, что-то не получилось =) Весь день мозговал чуть моск не лопнул. Не просветите в этом вопросе? Ковыряя другие скетчи где измеряется и выводится температура пришел к выводу, что нужно добавить еще один символ в виде буквы "С", его туда же прописывать куда и цыфры? аля
byte digits[10][13] = { {1,1,1,1,1,1,0,1,1,1,1,1,1}, // Digit 0 {0,0,0,0,0,0,0,0,1,1,1,1,1}, // Digit 1 {1,1,1,0,1,1,1,1,1,0,1,1,1}, // Digit 2 {1,0,1,0,1,1,1,1,1,1,1,1,1}, // Digit 3 {0,0,1,1,1,1,1,0,1,1,1,1,1}, // Digit 4 {1,0,1,1,1,1,1,1,1,1,1,0,1}, // Digit 5 {1,1,1,1,1,1,1,1,1,1,1,0,1}, // Digit 6 {0,0,0,0,0,1,0,0,1,1,1,1,1}, // Digit 7 {1,1,1,1,1,1,1,1,1,1,1,1,1}, // Digit 8 {1,0,1,1,1,1,1,1,1,1,1,1,1}}; // Digit 9 {1,1,1,1,1,1,0,1,1,0,0,0,1}}; // Digit Сfor(int k=0; k < 13;k++) вы точно так написали ? или все же так: for(int k=0; k <= 13;k++)
bytedigits[10][13] - он у вас не ругается на размерность ?Вы говорите ему 10 массивов по 13 значений, а сами указываете 11 по 13, причем еще с неправильным синтаксисом в конце.вот так мне кажется будет лучше01bytedigits[11][13] = {02{1,1,1,1,1,1,0,1,1,1,1,1,1},// Digit 003{0,0,0,0,0,0,0,0,1,1,1,1,1},// Digit 104{1,1,1,0,1,1,1,1,1,0,1,1,1},// Digit 205{1,0,1,0,1,1,1,1,1,1,1,1,1},// Digit 306{0,0,1,1,1,1,1,0,1,1,1,1,1},// Digit 407{1,0,1,1,1,1,1,1,1,1,1,0,1},// Digit 508{1,1,1,1,1,1,1,1,1,1,1,0,1},// Digit 609{0,0,0,0,0,1,0,0,1,1,1,1,1},// Digit 710{1,1,1,1,1,1,1,1,1,1,1,1,1},// Digit 811{1,0,1,1,1,1,1,1,1,1,1,1,1},// Digit 912{1,1,1,1,1,1,0,1,1,0,0,0,1}};// Digit Сс этим for(int k=0; k < 13;k++) сейчас не скажу (не обратил вниманияч) скетч на работе. с [11][13] это тоже понятно я просто про
{1,1,1,1,1,1,0,1,1,0,0,0,1}};// Digit Си туда ли его воткнуть поэтому 10 13 было =) нашел вот скетч похожих часов, из него сегодня пытался безуспешно выдрать все что связано с температуруй =) не ткнете носом, что конкретно мне понадобиться для чтения и вывода температуры на табло =)#include <DS3232RTC.h> #include <Time.h> #include <Wire.h> #include <FastLED.h> //#include <IRremote.h> #define NUM_LEDS 86 //3*7*4 +2 Number of LED controles (remember I have 3 leds / controler #define LED_TYPE WS2812 //#define COLOR_ORDER BRG // Define color order for your strip #define BRIGHTNESS_DEFAULT 180 #define LED_PIN 5 // Data pin for led comunication char incoming_command = 'H'; int brightness = 0; int auto_brightness = 1; //brightness int photocellPin = 0; // the cell and 10K pulldown are connected to a0 int photocellReading; // the analog reading from the analog resis int led_on = 1; //LEDS COLORS volatile boolean animate = true; volatile long animation_change_timeout; unsigned long previousMillis = 0; // will store last time LED was updated const long interval = 5000; // interval for printing Temp and date CRGB leds[NUM_LEDS]; // Define LEDs strip // 10 digit :0...10, each digit is composed of 7 segments of 3 leds byte digits[10][21] = { { 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } , // Digit 0 { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 } , // Digit 1 { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0 } , // Digit 2 { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 } , // Digit 3 { 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1 } , // Digit 4 { 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1 } , // Digit 5 { 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } , // Digit 6 { 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 } , // Digit 7 { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } , // Digit 8 { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1 } }; // Digit 9 | 2D Array for numbers on 7 segment // Digit 1 first number | 2D Array for numbers on 7 segment bool Dot = true; //Dot state bool DST = false; //DST state int last_digit = 0; //long ledColor = CRGB::DarkOrchid; // Color used (in hex) long ledColor = CRGB::MediumVioletRed; //Random colors i picked up long ColorTable[16] = { CRGB::Amethyst, CRGB::Aqua, CRGB::Blue, CRGB::Chartreuse, CRGB::DarkGreen, CRGB::DarkMagenta, CRGB::DarkOrange, CRGB::DeepPink, CRGB::Fuchsia, CRGB::Gold, CRGB::GreenYellow, CRGB::LightCoral, CRGB::Tomato, CRGB::Salmon, CRGB::Red, CRGB::Orchid }; void setup() { Serial.begin(9600); Wire.begin(); FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS); // FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip ); FastLED.setBrightness( BRIGHTNESS_DEFAULT ); } // Check Light sensor and set brightness accordingly void BrightnessCheck() { photocellReading = analogRead(photocellPin); const byte brightnessLow = 30; // Low brightness value const byte brightnessHigh = 100; // High brightness value //you can choose between auto or manual brightness if (auto_brightness ) { if (photocellReading > 100) { FastLED.setBrightness( brightnessHigh ); } else if (photocellReading < 100) { FastLED.setBrightness( brightnessLow); } } }; // Get time in a single number int GetTime() { tmElements_t Now; RTC.read(Now); //time_t Now = RTC.Now();// Getting the current Time and storing it into a DateTime object int hour = Now.Hour; int minutes = Now.Minute; int second = Now.Second; //use this to blink your dots every second if (second % 2 == 0) { Dot = false; } else { Dot = true; }; //it is easy to manipulate 2150 rather than hours = 10 minutes = 50 return (hour * 100 + minutes); }; //function to print day and month int DayMonth() { tmElements_t Now; RTC.read(Now); int day = Now.Day; int month = Now.Month; return (day * 100 + month); } // not used yet void DSTcheck() { int buttonDST = digitalRead(2); Serial.print("DST is: "); Serial.println(DST); if (buttonDST == LOW) { if (DST) { DST = false; Serial.print("Switching DST to: "); Serial.println(DST); } else if (!DST) { DST = true; Serial.print("Switching DST to: "); Serial.println(DST); }; delay(500); }; } // Convert time to array needet for display void TimeToArray() { int Now = GetTime(); // Get time int cursor = 86; // //Serial.print("Time is: "); //Serial.println(Now); if (Dot) { leds[42] = ledColor; leds[43] = ledColor; } else { leds[42] = 0x000000; leds[43] = 0x000000; }; for (int i = 1; i <= 4; i++) { int digit = Now % 10; // get last digit in time if (i == 1) { cursor = 65; //Serial.print("Digit 4 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 20; k++) { //Serial.print(digits[digit][k]); if (digits[digit][k] == 1) { leds[cursor] = ledColor; } else if (digits[digit][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; // fin for // Serial.println(); if (digit != last_digit) { fadefonction(); ledColor = ColorTable[random(16)]; } last_digit = digit; }// fin if else if (i == 2) { cursor = 44; //Serial.print("Digit 3 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 20; k++) { //Serial.print(digits[digit][k]); if (digits[digit][k] == 1) { leds[cursor] = ledColor; } else if (digits[digit][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; // Serial.println(); } else if (i == 3) { cursor = 21; //Serial.print("Digit 2 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 20; k++) { //Serial.print(digits[digit][k]); if (digits[digit][k] == 1) { leds[cursor] = ledColor; } else if (digits[digit][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; //Serial.println(); } else if (i == 4) { cursor = 0; //Serial.print("Digit 1 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 20; k++) { //Serial.print(digits[digit][k]); if (digits[digit][k] == 1) { leds[cursor] = ledColor; } else if (digits[digit][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; // Serial.println(); }; Now /= 10; }; }; // Convert date to array needet for display void DateToArray() { FastLED.clear(); unsigned long currentMillis = millis(); while (millis() - currentMillis < interval) { FastLED.show(); int Now = DayMonth(); // Get time int cursor = 86; //116 //Serial.print("Time is: "); //Serial.println(Now); for (int i = 1; i <= 4; i++) { int digit = Now % 10; // get last digit in time if (i == 1) { cursor = 65; //82 //Serial.print("Digit 4 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 20; k++) { //Serial.print(digits[digit][k]); if (digits[digit][k] == 1) { leds[cursor] = ledColor; } else if (digits[digit][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; // fin for // Serial.println(); }// fin if else if (i == 2) { cursor = 44; //Serial.print("Digit 3 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 20; k++) { //Serial.print(digits[digit][k]); if (digits[digit][k] == 1) { leds[cursor] = ledColor; } else if (digits[digit][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; // Serial.println(); } else if (i == 3) { cursor = 21; //Serial.print("Digit 2 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 20; k++) { //Serial.print(digits[digit][k]); if (digits[digit][k] == 1) { leds[cursor] = ledColor; } else if (digits[digit][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; //Serial.println(); } else if (i == 4) { cursor = 0; //Serial.print("Digit 1 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 20; k++) { //Serial.print(digits[digit][k]); if (digits[digit][k] == 1) { leds[cursor] = ledColor; } else if (digits[digit][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; // Serial.println(); }; Now /= 10; }; } }; //not used yet void TimeAdjust() { int buttonH = digitalRead(5); int buttonM = digitalRead(4); if (buttonH == LOW || buttonM == LOW) { delay(500); tmElements_t Now; RTC.read(Now); int hour = Now.Hour; int minutes = Now.Minute; if (buttonH == LOW) { if (Now.Hour == 24) { Now.Hour = 1; } else { Now.Hour += 1; }; } else { if (Now.Minute == 59) { Now.Minute = 0; } else { Now.Minute += 1; }; }; RTC.write(Now); } } /* coool effect function*/ void fadeall() { for (int m = 0; m < NUM_LEDS; m++) { leds[m].nscale8(250); } } void fadefonction () { static uint8_t hue = 0; // First slide the led in one direction for (int i = 0; i < NUM_LEDS; i++) { // Set the i'th led to red leds[i] = CHSV(hue++, 255, 255); // Show the leds FastLED.show(); // now that we've shown the leds, reset the i'th led to black // leds[i] = CRGB::Black; fadeall(); // Wait a little bit before we loop around and do it again delay(10); } // Now go in the other direction. for (int i = (NUM_LEDS) - 1; i >= 0; i--) { // Set the i'th led to red leds[i] = CHSV(hue++, 255, 255); // Show the leds FastLED.show(); // now that we've shown the leds, reset the i'th led to black // leds[i] = CRGB::Black; fadeall(); // Wait a little bit before we loop around and do it again delay(10); } } /******IR check**** Check the command on the serial port sent by the other arduino depending on the button pressed */ void IR_Check() { if (Serial.available() > 0) { // read the incoming byte: incoming_command = Serial.read(); unsigned long startTime = 0; switch (incoming_command) { //colors case 'R' : //Serial.println("RED"); ledColor = CRGB::Red; break; case 'B' : ledColor = CRGB::Blue; break; case 'G' : ledColor = CRGB::Green; break; case 'W' : ledColor = CRGB::White; break; case 'I' : ledColor = CRGB::OrangeRed; break; case 'J' : ledColor = CRGB::GreenYellow; break; case 'K' : ledColor = CRGB::MediumSlateBlue; break; case 'L' : ledColor = CRGB::Pink; break; case 'M' : ledColor = CRGB::DarkOrange; break; case 'N' : ledColor = CRGB::Aqua; break; case 'P' : ledColor = CRGB::DarkSlateBlue; break; case 'Q' : ledColor = CRGB::LightPink; break; case 'S' : ledColor = CRGB::LightSalmon; break; case 'U' : ledColor = CRGB::LightSeaGreen; break; case 'V' : ledColor = CRGB::Purple; break; case 'X' : ledColor = CRGB::Yellow; break; case 'Y' : ledColor = CRGB::Teal; break; case 'Z' : ledColor = CRGB::PaleVioletRed; break; case '*' : ledColor = CRGB::PaleTurquoise; break; case 'F' : //pick a random color but not working yet ledColor = CRGB( random8(), 100, 50); break; case '+' : //brighter brightness += 10; if (brightness > 255) brightness = 255; FastLED.setBrightness( brightness ); auto_brightness = 0; break; case '-' : brightness -= 10; if (brightness < 10) brightness = 10; FastLED.setBrightness( brightness ); auto_brightness = 0; break; case 'O' : //auto brightness if (led_on) { brightness = 0; led_on = 0; } else { brightness = BRIGHTNESS_DEFAULT ; led_on = 1; } FastLED.setBrightness( brightness ); break; case 'T' : //Temp Temp(); break; case 'a' : //Date DateToArray(); break; case 'A' : auto_brightness = 1; break; default: break; //Serial.println("error"); }//switch // say what you got: //Serial.print("I received: "); //Serial.println(incoming_command); } /* if (irrecv.decode(&results)) { Serial.println(results.value, HEX); switch(results.value) { case 0xFF1AE5 : Serial.println("RED"); ledColor = CRGB::Red; break; default: Serial.println("error"); } irrecv.resume(); // Receive the next value } */ }; //print the internal temperature void Temp() { FastLED.clear(); int cursor = 21; //65 float t = RTC.temperature(); int celsius = t / 4.0; Serial.print(celsius); unsigned long currentMillis = millis(); while (millis() - currentMillis < interval) { FastLED.show(); int cursor = 21; //65 float t = RTC.temperature(); int celsius = t / 4.0; for (int i = 1; i <= 2; i++) { int digit = celsius % 10; // get last digit in time Serial.print("digit"); Serial.println(digit); if (i == 1) { //Serial.print("Digit 4 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 20; k++) { //Serial.print(digits[digit][k]); if (digits[digit][k] == 1) { leds[cursor] = ledColor; } else if (digits[digit][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; // fin for FastLED.show(); }// fin if else if (i == 2) { cursor = 0; //Serial.print("Digit 3 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 20; k++) { //Serial.print(digits[digit][k]); if (digits[digit][k] == 1) { leds[cursor] = ledColor; } else if (digits[digit][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; // Serial.println(); } celsius /= 10; FastLED.show(); } for (int m = 44; m < 56; m++) { leds[m] = ledColor; } for (int m = 72; m < 83; m++) { leds[m] = ledColor; } FastLED.show(); //check_for_input(); }//fin while animate }; //not used yet void check_for_input() { if (animation_change_timeout > 100) { if (Serial.available() > 0) { // read the incoming byte: incoming_command = Serial.read(); // say what you got: Serial.print("I received: "); Serial.println(incoming_command); animate = false; } } } void loop() // Main loop { BrightnessCheck(); // Check brightness TimeToArray(); // Get leds array with required configuration IR_Check(); FastLED.show(); // Display leds array }Сами напросились :-), строка 793 вашего скетча, функция вывода температуры.
793//print the internal temperature794voidTemp()оно или лишнего зацепил )) я так понимаю это вывод температуры, а где чтение датчика? чтение часов нашел, а температуры нихт )) и почему только две цыфры "Digit 4 is : " "Digit 3 is : " а куда и как мне воткнуть мои цельсии "С" ))
793 //print the internal temperature 794 void Temp() 795 { 796 FastLED.clear(); 797 int cursor = 21; //65 798 float t = RTC.temperature(); 799 int celsius = t / 4.0; 800 Serial.print(celsius); 801 802 803 unsigned long currentMillis = millis(); 804 while (millis() - currentMillis < interval) { 805 FastLED.show(); 806 int cursor = 21; //65 807 float t = RTC.temperature(); 808 int celsius = t / 4.0; 809 for (int i = 1; i <= 2; i++) { 810 811 int digit = celsius % 10; // get last digit in time 812 Serial.print("digit"); 813 Serial.println(digit); 814 if (i == 1) { 815 816 817 818 //Serial.print("Digit 4 is : "); 819 //Serial.print(digit); 820 //Serial.print(", the array is : "); 821 822 for (int k = 0; k <= 20; k++) { 823 824 //Serial.print(digits[digit][k]); 825 826 if (digits[digit][k] == 1) { 827 leds[cursor] = ledColor; 828 } 829 830 else if (digits[digit][k] == 0) { 831 leds[cursor] = 0x000000; 832 }; 833 834 cursor ++; 835 836 }; // fin for 837 838 FastLED.show(); 839 840 }// fin if 841 842 else if (i == 2) { 843 844 cursor = 0; 845 846 //Serial.print("Digit 3 is : "); 847 //Serial.print(digit); 848 //Serial.print(", the array is : "); 849 850 for (int k = 0; k <= 20; k++) { 851 852 //Serial.print(digits[digit][k]); 853 854 if (digits[digit][k] == 1) { 855 leds[cursor] = ledColor; 856 } 857 858 else if (digits[digit][k] == 0) { 859 leds[cursor] = 0x000000; 860 }; 861 862 cursor ++; 863 864 }; 865 866 // Serial.println(); 867 } 868 869 celsius /= 10; 870 FastLED.show(); 871 } 872 for (int m = 44; m < 56; m++) { 873 leds[m] = ledColor; 874 } 875 for (int m = 72; m < 83; m++) { 876 leds[m] = ledColor; 877 } 878 FastLED.show();это у меня так for(int k=0; k < =13;k++), в чем отличие k<=13 k<13. типо тут k<=13 меньше или равно 13 тоесть с нулем 14, а k<13 меньше 13 тоесть 12+0=13 так что ли понимать =)
12+0=13 да математика отдыхает, кому расскажи что 12+0=13 не поверят же =) почему счет с нуля где логика? 0 это же ничего =)
1.Оно, на счет лишнего не уверен. (возможно внутри что-то есть).
2,
floatt = RTC.temperature(); - 99,99 - это опрос датчика (значения надо делить на 4 (точность до 1/4 градуса)),дробную часть можно отбросить приведением к int
intcelsius = t / 4.0;3. Поэтому и цифры 2, больше не требуется(если у вас часы не в жидком азоте и в духовку ставить не собираетесь).Дробная часть баловство, но если очень хочется то....Как показываются цифры вы не разобрались ? cursor нужно установить в начало участка для отображения, а дальше вместо digits указать 10.
Задача: Необходимо разметить участок дороги в 10 км, сколько нам понадобится столбиков, если ставиить их через 1 км.
ну сотые не нужны и даже десятые думаю тоже, планируется на первые две цыфры выводить саму температуру на третий символ градуса верхние четыре сегмента и на четвертый "C". А что отвечает за вывод "C" ну и символа градусов где их прописывать?
Вкратце объясняю суть работы скетча.
У вас лента N диодов.
Каждый диод упраляется через массив.
leds[25]=ledColor; //-- означает зажечь 26 диод (25 от нуля) цветомledColor. например:long ledColor = CRGB::MediumVioletRed; fоr(diod = 0; diod < N; diod++) leds[diod]=ledColor; // включаем диоды от 0 до N (т.е. в нашем случае всю ленту из N диодов.)fоr(diod = 0; diod < N; diod++) leds[diod]=0x000000; // выключаем диоды от 0 до N (т.е. в нашем случае всю ленту из N диодов.)fоr(diod = 13; diod < 26; diod++) leds[diod]=ledColor; // включаем вторую ячейку диоды от 14 до 27 (т.е. в если на цифру 13 диодов то зажгется вторая ячейка)//перейдем к нашим баранам, пример выше с небольшим усложнением
cursor =13; // начинаем от этого диода(14 по порядку) for(int k=0; k < 13;k++){ // if (digits[digit][k]== 1){leds[cursor]=ledColor;} // если значение в массиве digits в строке digit(тут нет s) в столбце k содержит еденицу, то диод с индексом cursor зажигаем else if (digits[digit][k]==0){leds[cursor]=0x000000;}; // иначе если значение 0 тушим диод с индексом cursor cursor ++; // увеличиваем индекс диода };// если значение digit будет 10 - то будет отработана строка 11 в массиве digits , а там у вас должна быть буква "С"
мда уж пока читал моск медленно начал закипать =) сегодня занимался сборкой корпуса завтра начну опыты с температурой правда не совсем все понятно, потыкаюсь может что соображу =))
тут дописываем
byte digits[12][13] = { {1,1,1,1,1,1,0,1,1,1,1,1,1}, // Digit 0 {0,0,0,0,0,0,0,0,1,1,1,1,1}, // Digit 1 {1,1,1,0,1,1,1,1,1,0,1,1,1}, // Digit 2 {1,0,1,0,1,1,1,1,1,1,1,1,1}, // Digit 3 {0,0,1,1,1,1,1,0,1,1,1,1,1}, // Digit 4 {1,0,1,1,1,1,1,1,1,1,1,0,1}, // Digit 5 {1,1,1,1,1,1,1,1,1,1,1,0,1}, // Digit 6 {0,0,0,0,0,1,0,0,1,1,1,1,1}, // Digit 7 {1,1,1,1,1,1,1,1,1,1,1,1,1}, // Digit 8 {1,0,1,1,1,1,1,1,1,1,1,1,1}, // Digit 9 {0,0,1,1,1,1,1,0,0,0,1,1,1}, // Digit ° {1,1,1,1,1,1,0,1,1,0,0,0,1}}; // Digit Cтемпература будет иметь вид 35°С
вроде как я понял что то такое должно получиться
//print the internal temperature void Temp() { FastLED.clear(); int cursor = 0; //54 float t = RTC.temperature(); int celsius = t / 4.0; Serial.print(celsius); unsigned long currentMillis = millis(); while (millis() - currentMillis < interval) { FastLED.show(); int cursor = 0; //54 float t = RTC.temperature(); int celsius = t / 4.0; for (int i = 1; i <= 2; i++) { int digit = celsius % 10; // get last digit in time Serial.print("digit"); Serial.println(digit); if (i == 1) { cursor =41; //Serial.print("Digit 4 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 12; k++) { //Serial.print(digits[digit][k]); if (digits[12][k] == 1) { leds[cursor] = ledColor; } else if (digits[12][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; // fin for FastLED.show(); }// fin if else if (i == 2) { cursor = 28; //Serial.print("Digit 3 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 12; k++) { //Serial.print(digits[digit][k]); if (digits[11][k] == 1) { leds[cursor] = ledColor; } else if (digits[11][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; cursor =13; //Serial.print("Digit 2 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 12; k++) { //Serial.print(digits[digit][k]); if (digits[digit][k] == 1) { leds[cursor] = ledColor; } else if (digits[digit][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; cursor =0; //Serial.print("Digit 1 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 12; k++) { //Serial.print(digits[digit][k]); if (digits[digit][k] == 1) { leds[cursor] = ledColor; } else if (digits[digit][k] == 0) { leds[cursor] = 0x000000; }; cursor ++; }; // Serial.println(); } celsius /= 10; FastLED.show();только не знаю значение digit туда прописал или нет? вот к примеру Digit 12
cursor =41; //Serial.print("Digit 4 is : "); //Serial.print(digit); //Serial.print(", the array is : "); for (int k = 0; k <= 12; k++) { //Serial.print(digits[digit][k]); if (digits[12][k] == 1) { leds[cursor] = ledColor; } else if (digits[12][k] == 0) { leds[cursor] = 0x000000; };и еще куда прописывается время через которое будет отображаться температура и продолжительнось отображения тут?
unsignedlongcurrentMillis = millis();11while(millis() - currentMillis < interval)что то я совсем запутался в этих библиотеках =) проводил эксперементы с температурой и на библиотеках завис. вот скетч чаов https://yadi.sk/d/WO3whksssBDPC , компилится с этой библиотекой https://yadi.sk/d/x70i61QGsBDP4. С этой библиотекой https://yadi.sk/d/4w9MEf6usBDNw компилится не хочет, но на ней (в отличии от первой) хотя бы пример термометра запустить удалось, а на первой даже пример измерения температуры не захотел работать. вопрос как быть? можно ли их как то объединить? =)
сегодня опять проводил эксперементы, понял что бибиотеки можно не объединять а просто прописать при необходимости их в скетче и о чуду все будет оке =) добавил в скетч следующее для опроса температуры с RTC
#include "Wire.h" #define DS3232_I2C_ADDRESS 0x68 void setup() { Wire.begin(); Serial.begin(9600); } void loop() { byte tempMSB, tempLSB, temp; float temperature; Wire.beginTransmission(DS3232_I2C_ADDRESS); Wire.write(0x11); // move register pointer to first temperature register Wire.endTransmission(); Wire.requestFrom(DS3232_I2C_ADDRESS, 2); tempMSB = Wire.read(); tempLSB = Wire.read() >> 6; temperature = tempMSB + (0.25*tempLSB); Serial.print(" Temperature (C): "); Serial.println(temperature); delay(2000); }с опросом теперь все ок, в мониторе порта есть темпер (и работает с родной библиотекой на которой компилил скетч часов). как мне теперь этот темпер вывести на мои часы? вот полный скетч того что сейчас есть
#include <DS3231RTC.h> #include <Time.h> #include <Wire.h> #include "FastLED.h" #define NUM_LEDS 54 // Number of LED controles (remember I have 3 leds / controler #define COLOR_ORDER BRG // Define color order for your strip #define DATA_PIN 6 // Data pin for led comunication #define DS3232_I2C_ADDRESS 0x68 CRGB leds[NUM_LEDS]; // Define LEDs strip byte digits[12][13] = { {1,1,1,1,1,1,0,1,1,1,1,1,1}, // Digit 0 {0,0,0,0,0,0,0,0,1,1,1,1,1}, // Digit 1 {1,1,1,0,1,1,1,1,1,0,1,1,1}, // Digit 2 {1,0,1,0,1,1,1,1,1,1,1,1,1}, // Digit 3 {0,0,1,1,1,0,1,0,1,1,1,1,1}, // Digit 4 {1,0,1,1,1,1,1,1,1,1,1,0,1}, // Digit 5 {1,1,1,1,1,1,1,1,1,1,1,0,1}, // Digit 6 {0,0,0,0,1,1,0,0,1,1,1,1,1}, // Digit 7 {1,1,1,1,1,1,1,1,1,1,1,1,1}, // Digit 8 {1,0,1,1,1,1,1,1,1,1,1,1,1}, // Digit 9 {0,0,1,1,1,1,1,0,0,0,1,1,1}, // Digit ° {1,1,1,1,1,1,0,1,1,0,0,0,1}}; // Digit C bool Dot = true; //Dot state bool DST = false; //DST state int last_digit = 0;//long ledColor = CRGB::DarkOrchid; // Color used (in hex) long ledColor = CRGB::Lime; long ColorTable[16] = { CRGB::Orange, CRGB::Aqua, CRGB::Gold, CRGB::Red, CRGB::Yellow, CRGB::Cyan, CRGB::Orange, CRGB::Lime, CRGB::Pink, CRGB::Red, CRGB::Orange, CRGB::Tomato, CRGB::Aqua, CRGB::Orange, CRGB::Lime, CRGB::Yellow}; void setup(){ Serial.begin(9600); Wire.begin(); LEDS.addLeds<WS2812, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS); // Set LED strip type LEDS.setBrightness(255); // Set initial brightness pinMode(2, INPUT_PULLUP); // Define DST adjust button pin pinMode(4, INPUT_PULLUP); // Define Minutes adjust button pin pinMode(5, INPUT_PULLUP); // Define Hours adjust button pin } // Get time in a single number, if hours will be a single digit then time will be displayed 155 instead of 0155 int GetTime(){ tmElements_t Now; RTC.read(Now); //time_t Now = RTC.Now();// Getting the current Time and storing it into a DateTime object int hour=Now.Hour; int minutes=Now.Minute; int second =Now.Second; if (second % 2==0) {Dot = false;} else {Dot = true;}; return (hour*100+minutes); }; // Check Light sensor and set brightness accordingly void BrightnessCheck(){ const byte sensorPin = 3; // light sensor pin const byte brightnessLow = 30; // Low brightness value const byte brightnessHigh = 220; // High brightness value int sensorValue = digitalRead(sensorPin); // Read sensor if (sensorValue == 0) {LEDS.setBrightness(brightnessHigh);} else {LEDS.setBrightness(brightnessLow);} }; // Convert time to array needet for display void TimeToArray(){ int Now = GetTime(); // Get time int cursor = 54; // Serial.print("Time is: ");Serial.println(Now); if (DST){ // if DST is true then add one hour Now+=100; // Serial.print("DST is ON, time set to : ");Serial.println(Now); }; if (Dot){leds[26]=ledColor; leds[27]=ledColor;} else {leds[26]=0x000000; leds[27]=0x000000; }; for(int i=1;i<=4;i++){ int digit = Now % 10; // get last digit in time if (i==1){ // Serial.print("Digit 4 is : ");Serial.print(digit);Serial.print(" "); cursor =41; for(int k=0; k<=12;k++){ // Serial.print(digits[digit][k]); if (digits[digit][k]== 1){leds[cursor]=ledColor;} else if (digits[digit][k]==0){leds[cursor]=0x000000;}; cursor ++; }; Serial.println(); if (digit != last_digit) { fadefonction(); ledColor = ColorTable[random(16)]; } last_digit = digit; }// fin if else if (i==2){ // Serial.print("Digit 3 is : ");Serial.print(digit);Serial.print(" "); cursor =28; for(int k=0; k<=12;k++){ // Serial.print(digits[digit][k]); if (digits[digit][k]== 1){leds[cursor]=ledColor;} else if (digits[digit][k]==0){leds[cursor]=0x000000;}; cursor ++; }; // Serial.println(); } else if (i==3){ // Serial.print("Digit 2 is : ");Serial.print(digit);Serial.print(" "); cursor =13; for(int k=0; k<=12;k++){ // Serial.print(digits[digit][k]); if (digits[digit][k]== 1){leds[cursor]=ledColor;} else if (digits[digit][k]==0){leds[cursor]=0x000000;}; cursor ++; }; // Serial.println(); } else if (i==4){ // Serial.print("Digit1 is : ");Serial.print(digit);Serial.print(" "); cursor =0; for(int k=0; k<=12;k++){ // Serial.print(digits[digit][k]); if (digits[digit][k]== 1){leds[cursor]=ledColor;} else if (digits[digit][k]==0){leds[cursor]=0x000000;}; cursor ++; }; // Serial.println(); } Now /= 10; }; }; void DSTcheck(){ int buttonDST = digitalRead(2); // Serial.print("DST is: ");Serial.println(DST); if (buttonDST == LOW){ if (DST){ DST=false; // Serial.print("Switching DST to: ");Serial.println(DST); } else if (!DST){ DST=true; // Serial.print("Switching DST to: ");Serial.println(DST); }; delay(500); }; } void TimeAdjust(){ int buttonH = digitalRead(5); int buttonM = digitalRead(4); if (buttonH == LOW || buttonM == LOW){ delay(500); tmElements_t Now; RTC.read(Now); int hour=Now.Hour; int minutes=Now.Minute; int second =Now.Second; if (buttonH == LOW){ if (Now.Hour== 23){Now.Hour=0;} else {Now.Hour += 1;}; }else { if (Now.Minute== 59){Now.Minute=0;} else {Now.Minute += 1;}; }; RTC.write(Now); } } void fadeall() { for(int m = 0; m < NUM_LEDS; m++) { leds[m].nscale8(250); } } void fadefonction () { static uint8_t hue = 0; // First slide the led in one direction for(int i = 0; i < NUM_LEDS; i++) { // Set the i'th led to red leds[i] = CHSV(hue++, 255, 255); // Show the leds FastLED.show(); // now that we've shown the leds, reset the i'th led to black // leds[i] = CRGB::Black; fadeall(); // Wait a little bit before we loop around and do it again delay(10); } // Now go in the other direction. for(int i = (NUM_LEDS)-1; i >= 0; i--) { // Set the i'th led to red leds[i] = CHSV(hue++, 255, 255); // Show the leds FastLED.show(); // now that we've shown the leds, reset the i'th led to black // leds[i] = CRGB::Black; fadeall(); // Wait a little bit before we loop around and do it again delay(10); } } void loop() // Main loop { byte tempMSB, tempLSB, temp; float temperature; Wire.beginTransmission(DS3232_I2C_ADDRESS); Wire.write(0x11); // move register pointer to first temperature register Wire.endTransmission(); Wire.requestFrom(DS3232_I2C_ADDRESS, 2); tempMSB = Wire.read(); tempLSB = Wire.read() >> 6; temperature = tempMSB + (0.25*tempLSB); Serial.print(" Temperature (C): "); Serial.println(temperature); delay(10); BrightnessCheck(); // Check brightness DSTcheck(); // Check DST TimeAdjust(); // Check to se if time is geting modified TimeToArray(); // Get leds array with required configuration FastLED.show(); // Display leds array }Народ помогите разобратся
Решил на базе Ардуино Уно сделать контроллер влажности и температуры в комнате. Приобрел датчик DHT-11( знаю по характеристикам не очень. но для комнаты пойдет),скачал скетч но немного не рабочий не могу разобратся почему. Пробовал исправить но не могу понять что исправлять и как?
Народ помогите разобратся
скачал скетч но немного не рабочий
А если подробнее? что пишет в сириале? Что конкретно немного не работает? Он не ругается когда инт с фроатом сравнивает? и Выкладывайте код как подобается через кнопочку code...
Да, ещё, если датчик без платки то нужно сопротивление ставить туда, у Вас стоит?
В строке DHT dht(DHTPIN, DHTTYPE);
Тоже наверное важно, там в зависимости от вашего микропроцессора надо ставить значение 6 - 30, в Вашем случае, наверное 6
// Initialize DHT sensor for normal 16mhz Arduino
Пишет вот что:
Процессор Mega 328P AU в cmd-корпус (DDcduino uno)
pop UP и Mr.Privet сорри не врублюсь как написать кому ответил.
Пробывал
// Initialize DHT sensor for normal 16mhz Arduino