Ребята, конкретный вопрос, как с помощью запроса if узнать что датчик тупо отлетел и данные в нем не считываются, ну знаете, в серийник он выводит эту надпись non когда перестает его читать, подскажите мне рабочий код условия, гугл тупит...
Что за датчик? Если датчик имеет самодиагностику, то неисправность индицируется либо через показания, либо специальным запросом. Если самодиагностики нет, то применяются другие методы. К примеру, дифференциальный. Когда показания изменяются быстрее, чем это возможно физически. Но это совсем не if.
Код (C++): /* Reading a serial ASCII-encoded string. This sketch demonstrates the Serial parseInt() function. It looks for an ASCII string of comma-separated values. It parses them into ints, and uses those to fade an RGB LED. Circuit: Common-Cathode RGB LED wired like so: - red anode: digital pin 3 through 220 ohm resistor - green anode: digital pin 5 through 220 ohm resistor - blue anode: digital pin 6 through 220 ohm resistor - cathode: GND created 13 Apr 2012 by Tom Igoe modified 14 Mar 2016 by Arturo Guadalupi This example code is in the public domain. https://www.arduino.cc/en/Tutorial/BuiltInExamples/ReadASCIIString */ // pins for the LEDs: const int redPin = 3; const int greenPin = 5; const int bluePin = 6; void setup() { // initialize serial: Serial.begin(9600); // make the pins outputs: pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); } void loop() { // if there's any serial available, read it: while (Serial.available() > 0) { // look for the next valid integer in the incoming serial stream: int red = Serial.parseInt(); // do it again: int green = Serial.parseInt(); // do it again: int blue = Serial.parseInt(); // look for the newline. That's the end of your sentence: if (Serial.read() == '\n') { // constrain the values to 0 - 255 and invert // if you're using a common-cathode LED, just use "constrain(color, 0, 255);" red = 255 - constrain(red, 0, 255); green = 255 - constrain(green, 0, 255); blue = 255 - constrain(blue, 0, 255); // fade the red, green, and blue legs of the LED: analogWrite(redPin, red); analogWrite(greenPin, green); analogWrite(bluePin, blue); // print the three numbers in one string as hexadecimal: Serial.print(red, HEX); Serial.print(green, HEX); Serial.println(blue, HEX); } } }
В профессиональной схемотехнике разрабатывают диагностические обвязки в том числе квазианалоговых входов - на предмет выявления обрыва, кз на минус или плюс, перегруз и т.д. По дешмански это на мультиплексорах к одному из аналоговому входу микроконтроллера - дальше в ПО просто считывается напряжение.
Найди биб-ку от АдыФрукт для DHT11/DHT22 и посмотри в примерах как писать код. В основном, пальчиками, осмысленно тыкая в нужные кнопки.
вывод уарта (Tx) на вход(Rx) и мониторьте - по мне нормальное решение для Вас - это если не надо куда отправлять по уарт-интерфейсу
Я с этими датчиками не сталкивался. Они сильно из бюджетной группы, ждать от них каких то вменяемых показаний точно не стоит. NaN - это "Not a Number" Используемый вами код и соответственно библиотеки вы не выложили. Поэтому первая ссылка в google предлагает следующую проверку: Код (C++): #include "DHT.h" #define DHTPIN 2 // modify to the pin we connected // Uncomment whatever type you're using! //#define DHTTYPE DHT11 // DHT 11 //#define DHTTYPE DHT22 // DHT 22 (AM2302) #define DHTTYPE DHT21 // DHT 21 (AM2301) // Connect pin 1 (on the left) of the sensor to +5V // Connect pin 2 of the sensor to whatever your DHTPIN is // Connect pin 4 (on the right) of the sensor to GROUND // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); Serial.println("DHTxx test!"); dht.begin(); } void loop() { // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float h = dht.readHumidity(); float t = dht.readTemperature(); // check if returns are valid, if they are NaN (not a number) then something went wrong! if (isnan(t) || isnan(h)) { Serial.println("Failed to read from DHT"); } else { Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(t); Serial.println(" *C"); } } То есть код будет звучать так: Код (C++): if (isnan(t) || isnan(h)) { Serial.println("Failed to read from DHT"); } else { //....... }
Ну если Google или Яндекс не доступен, или не получается составить правильный поисковый запрос, то есть раздел "Закажу проект". Там есть заинтересованные пользователи, которые готовы за вознаграждение написать код по любому ТЗ пользователя.