text:
How to get DHT11 temperature/humidity sensor to update on Arduino Uno
Trying to program a way to control my thermostat by interfacing it with my Arduino Uno. I am using a DHT11 to read temperatures and humidity. However, after making its first reading, it is not updating after that. I have included the reading in a loop that waits 2.5 seconds between readings to give the sensor time. However, its not updating. I tested the DHT11 with the example code that came with the DHT library and it is in itself functioning. To test it I have directed a warm hairdryer to the DHT sensor, but the readings dont change. However, when I reset it, the sensor will then show the higher reading initially but then wont update like before.
As well, the the photoresistor in the system will update its lux readings the whole time.
I have included the code below. Any help greatly appreciated! (sorry if the code is a bit messy, I am a novice programmer)
#include <LiquidCrystal.h>
#include <dht.h>

dht DHT;

#define DHT11_PIN 8
#define BOUNCE_DURATION 400
unsigned long checkLCD = 0;
volatile unsigned long bounceTime = 0;
unsigned long refreshBut = millis();
volatile int desiredTemp = 21;
boolean AC_on = true;
unsigned long checkBut = 0;
int temp = 0;
int humi = 0;
unsigned long lastTime = 0;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 10, 9);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  Serial.begin(9600);
  // Print a message to the LCD.
  lcd.print("DHT test");
  Serial.println("DHT TEST Type,\tstatus,\tHumidity (%),\tTemperature (C)");
  pinMode(3, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  pinMode(13, OUTPUT);
  pinMode(A1, INPUT_PULLUP);
  testDHT(); // testing DHT sensor

}

void loop() {
   if (millis() > lastTime)
  {
    temp = DHT.temperature;
    humi = DHT.humidity;
    lastTime = millis() + 2500;
    Serial.println(temp);
  }

  int luxSEND = -0.066433 * analogRead(A0) + 81.467234; //lux reading
  unsigned long refreshLCD = millis();
  int upBut = digitalRead(2); //up button
  int downBut = digitalRead(3); //down button
  int changeAC_send = digitalRead(A1);//read button for change between heating and AC
  unsigned long refreshBut = millis(); //for button for change between heating and AC

  displayReadings(humi, temp, luxSEND, refreshLCD, desiredTemp); //display on LCD - humidity, temperature, lux

  attachInterrupt(digitalPinToInterrupt(2), upButtonOn, FALLING);//Up in desired temp
  attachInterrupt(digitalPinToInterrupt(3), downButtonOn, FALLING);//Down in desired temp

  changeAC_on (changeAC_send, refreshBut); //change between heating and AC

  if ((temp > desiredTemp) && (AC_on == true)) { //AC structure
    digitalWrite(13, HIGH);

  }
  else if ((temp < desiredTemp) && (AC_on == false)) { //Heat Structure
    digitalWrite(13, HIGH);

  }
  else {
    digitalWrite(13, LOW);

  }
}

void displayReadings (int h, int t, int lux, unsigned long refreshL, int desiT) {
  if (refreshL >= (1000 + checkLCD)) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("T:");
    lcd.print(t);
    lcd.print("C  ");
    lcd.print("H:");
    lcd.print(h);
    lcd.print("%");
    Serial.print(h, 1);
    Serial.print(",\t");
    Serial.print(t, 1);
    Serial.print(",\t");
    lcd.setCursor(0, 1);
    lcd.print("L:");
    lcd.print(lux);
    lcd.print("   ");
    Serial.println(lux);
    Serial.print(",\t");
    lcd.print("Des.T:");
    lcd.print(desiT);
    lcd.print("C");
    checkLCD = refreshL;
  }

}

void testDHT () {
  // READ DATA
  lcd.clear();
  Serial.print("DHT11, \t");
  int chk = DHT.read11(DHT11_PIN);
  switch (chk)
  {
    case DHTLIB_OK:
      Serial.print("OK,\t");
      break;
    case DHTLIB_ERROR_CHECKSUM:
      Serial.print("Checksum error,\t");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Can't get reading");
      lcd.setCursor(0, 1);
      lcd.print("from DHT");
      break;
    case DHTLIB_ERROR_TIMEOUT:
      Serial.print("Time out error,\t");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Can't get reading");
      lcd.setCursor(0, 1);
      lcd.print("from DHT");
      break;
    default:
      Serial.print("Unknown error,\t");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Can't get reading");
      lcd.setCursor(0, 1);
      lcd.print("from DHT");
      break;
  }
}

void upButtonOn () {
  if (millis() > bounceTime) {
    Serial.println("Up Pressed");
    desiredTemp = desiredTemp + 1;
    bounceTime = millis() + BOUNCE_DURATION;
  }
}

void downButtonOn () {
  if (millis() > bounceTime) {
    Serial.println("Down Pressed");
    desiredTemp = desiredTemp - 1;
    bounceTime = millis() + BOUNCE_DURATION;
  }

}

void changeAC_on (int changeAC, unsigned long refL) {
  if (refL >= (200 + checkBut)) {

    if ((changeAC == LOW) && (AC_on == true)) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("HEATING MODE");
      Serial.println("Heat On");
      AC_on = false;
      checkBut = refL;
    }

    else if ((changeAC == LOW) && (AC_on == false)) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("A/C MODE");
      Serial.println("AC On");
      AC_on = true;
      checkBut = refL;
    }
    else {
      checkBut = refL;
    }
  }
}

Additionally, here is a sample of the output from the serial monitor, while a hairdryer is being directed at it:
    DHT TEST Type,  status, Humidity (%),   Temperature (C)
DHT11,  OK, Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 52
,   40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 51
,   40, 29, 52
,   Current read temperature is: 29
40, 29, 52
,   40, 29, 52
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 53
,   40, 29, 53
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54
,   40, 29, 54
,   Current read temperature is: 29
40, 29, 54
,   40, 29, 54

DHT.read11 reads the temperature from the sensor. You call that once from setup function but not from the loop function. Therefor the DHT11 sensor is read just once during startup.
You should not use millis like that. The blink without delay example shows how to use millis.


text:
for loop reads pots, passes value to PWM pins, can this be in the same for loop?
In the code below I am using a for loop to iterate over analog pins (potentiometers) and pass their value, after being mapped, to PWM enabled analog output pins (currently controlling LED brightness). While this works as is, I am curious about the following: would it be better to split the analogRead and analogWrite lines into separate for loops, or would that simply be redundant from a code standpoint? My concern is accidentally mixing up the pot values due to difficult-to-perceive timing issues.
The code:
static const uint8_t analog_pins[] = {A0, A1, A2, A3};
static const uint8_t digital_pins[] = {3, 5, 6, 9};
int pot_vals[] = {0, 0, 0, 0};
int val[] = {0, 0, 0, 0};

void setup() {
  Serial.begin(9600);

  // setup inputs, outputs
  for ( int i = 0; i < 4; i++ ) {
    pinMode( analog_pins[i], INPUT );
    pinMode( digital_pins[i], OUTPUT );
  }
}

void loop() {
  for (int i = 0; i < 4; i++) {
    val[i] = analogRead(analog_pins[i]);
    analogWrite(digital_pins[i], map( val[i], 0, 1023, 0, 255 ));
  }
  delay(2);
}

Analogue pins are configured as input by default. It is unnecessary to declare them in setup.

Having both the analogRead() and analogWrite() in the same loop is
perfectly fine. That would be be my preferred choice if only for one
reason: less RAM consumption. If you split them in two loops, you have
to store somewhere the readings of the four channels, either before or
after mapping. If you keep them in the same loop, you don't need the
pot_vals[] nor val[] arrays. You would use a local variable instead,
which consumes no RAM:
void loop() {
  for (int i = 0; i < 4; i++) {
    int val = analogRead(analog_pins[i]);
    analogWrite(digital_pins[i], map(val, 0, 1023, 0, 255));
  }
  delay(2);
}

My concern is accidentally mixing up the pot values due to
  difficult-to-perceive timing issues.

“Difficult to perceive”? I would call these issues “imaginary” instead.
You have no risk of “mixing” any values here. Maybe, if you can
elaborate on the kind of issues you imagine you could have, we could
help you clear some misunderstanding about how the microcontroller
executes your code.

Edit: To expand on Andrew's comment, the for loop can be optimized
as
for (int i = 0; i < 4; i++) {
  unsigned int val = analogRead(analog_pins[i]);
  analogWrite(digital_pins[i], val / 4);
}

Dividing the value by 4 is the best way to map the input range to the
output range. It gives a more uniform mapping than the map() call
above, as every output value is mapped to exactly 4 input values. It
could be noted, though, that map(val, 0, 1024, 0, 256) gives the same
uniform mapping.
The division by 4, however, is optimized by the compiler into a bit
shift, which is orders of magnitude faster than map(), and likely to
consume less stack space. There is one caveat to be aware of: this
optimization is only possible if val is unsigned. If it is signed,
then it is compiled into a call to a division routine, which is quite
expensive.
One could be tempted to go even further and get rid of the temporary
val variable, like:
for (int i = 0; i < 4; i++) {
  analogWrite(digital_pins[i], (unsigned int) analogRead(analog_pins[i]) / 4);
}

However, there is zero benefit from doing so: from the point of view of
an optimizing compiler, this form is exactly equivalent to the previous
one. I prefer the former which I deem more readable.

If you want to really simplify the code and minimize memory usage then you could even do: for (int i = 0; i < 4; i++)      analogWrite(digital_pins[i], analogRead(analog_pins[i])/4);

@Andrew: Your comment is both right and misleading: a naive reader may wrongly think that your not using the intermediate val variable is what reduces the memory footprint.

Obviously you can. Except that in most cases your loop execution is much faster than your own period so that you end up changing the duty cycles multiple times in one period.
Not an advisable aporoach. If you have to do it think about configuring the pwm center aligned.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Arduino Zero timer setup
Where would I find information on how to configure the Arduino Zero's timers?
Because this...
  // Timer stuff
  // Set up the generic clock (GCLK4) used to clock timers
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                    GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK4
                     GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                     GCLK_GENCTRL_ID(4);          // Select GCLK4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  // Feed GCLK4 to TC4 and TC5
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                     GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                     GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_TC4_COUNT16_CC0 = 150;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

  //NVIC_DisableIRQ(TC4_IRQn);
  //NVIC_ClearPendingIRQ(TC4_IRQn);
  NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

  REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
  REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
  // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

  REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV256 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                   TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                   TC_CTRLA_ENABLE;               // Enable TC4
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

Is completely indecipherable and highly error prone.

BOTTOM UP
The arduino Zero uses an Atmel samd21 µController. This video explains how to program the samd chips in a bottom up fashion, or at least how to gather all required information to do so. In case the video doesn't work anymore, i'll briefly rephrase it here. The main steps are:

Figure out the required registers by reading the data sheet
Consult the Atmel Software Framework(ASF) to figure out the corresponding data structures
Setup your sketch inside the arduino IDE

The bottom up process can be very time consuming, because you are searching a needle out of an haystack like, the datasheet and the ASF. So you need to tackle all the tiny bits before building the whole thing.
TOP DOWN
For some situations it is better to look for a working example program and try to figure out how its done. For this i recommend the arduino github repository. It is a very good resource for figuring out how arduino uses the ASF and helps me tune certain functions.
The top down process therefore allows to decompose a large working function into its smaller parts and dig into the interesting parts. However, it requires something to work with at the start which is not always available.
INDECIPHERABLE
Some code examples aren't understandable from the start. Once you know what the code is doing, i recommend splitting up the large pieces like this register and bit modification section into smaller ones. Extract these sections into functions with self explanatory names, and if done correctly you can get rid of the comments.
Hope this helps ;)

Where would I find information on how to configure the Arduino Zero's timers?

Try the datasheet.
What you showed there is fairly typical, may be on the primitive side for chips of its kind.
More power comes with more complexity.

So am I correct to assume that these low level registers are just exposed in the Arduino sketch? I assume some of the timers are already configured by Arduino for internal uses, such as delay(), where would I find that config?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Controllino Debugging
Its a well known fact, that you can debug your arduino board with the help of an Atmel Ice. However, you might know the Controllino which is an arduino compatible device.
It has an ATmega2560 on it.
Do you have an idea how to debug a controllino? I neither see any ICSP port nor did I found anything useful around this topic.
Any help is greatly appreciated!

Connector X1 has the pins you want.
ICSP is shared with the SPI pins. Wire those to your ICE in the same way as you wire the SPI pins of the ICSP header on a normal Arduino to an ICE.

Thx for the fast answer. Is there anything else I need to know before I can start debugging? I read about cutting the reset line when debugging arduinos...


text:
Lowest memory consumption for arrays
I made a little joystick input recorder that stores the joystick state (8 directions + fire) and the time (how long was a button or direction pressed).
Example data would be like this (i = input, t = time in milliseconds):
i: 0 | t: 2003
i: 2 | t: 128
i: 0 | t: 28
i: 10 | t: 27
i: 2 | t: 36
i: 18 | t: 39

My problem is that I run out of memory on an Arduino Uno very quickly. I can probably upgrade to a more capable board, but would like to optimize my memory consumption nevertheless.
 const byte max_record = 200;
 byte sequence[max_record];
 int time[max_record];

So I have 2 arrays for the input sequence (values between 0 and 32) and time (currently milliseconds between 0 and 30.000 or even higher).
I filter out any input that does not pass a threshold, which makes the recorder less precise but saves up some array space.
Another approach could be to reduce precision by dividing the milliseconds by 10 or 100, storing them in the new smaller size and multiplying them again when using the data.
Any other advice is greatly appreciated.

Human reaction time is > 100ms, so by using byte instead of int you can register a max time of 25.5 seconds (storing time as 0.1 seconds), which is close to 30 seconds, as you wish

put other data to flash is also an option, if you have not done it yet :D

What are you trying to achieve? It seems you may be thinking in the wrong direction.

@LookAlterno good advice, although it is not so much about reacting only, but e.g. for repeated button presses (think playing Tekken). So I'm not sure yet how much precision reduction I can afford.

@Esshahn. Test yourself how quick can you multi-press the button. Oh, Are you debouncing it?

@LookAlterno yes I'm debouncing. It is less about how fast one can press the same button (which I still manage to press <49 ms easily), but how many I can press simultaneously. A player can press left + up + fire at the same time or with minimal delays between them. This can mean a lot in gaming, especially for shoot em ups or fighters.

You already tried to minimize some memory by reducing accuracy.
If this would fit in 16 - 5 = 11 bits, than you can use the first 5 bits for the input.
With 11 bits (left) you have a range of 2048. Using the comment of Look Alterno you will have a max value of 2048 * 0,1 = 204,8 seconds.
Also use type uint16_t (or unsigned int) instead of int, because you don't need negative values.
This way you will need 200 (max records) * 2 = 400 bytes.
Assuming the array will be
uint16_t times[max_record];

Than the input is
ubyte input   = (times[record_index] & 0xF8) >> 11; // F8 = 1111 1000 0000 0000
uint16_t time = (times[record_index] & 0x7F);       // 7F = 0000 0111 1111 1111

Update:
Edgar Bonnet's idea brought me on the idea to use a logarithmic formula:
Instead of using 11 bits for the value itself, do not divide it by 100, but using a logarithmic scale.
By using a factor to limit the scale (in the example below: 125), and performing for each value the calculation:
stored_value = (int) (ln(value) * factor + 0.5)

And by converting back:
org_value = (int) (exp(stored_value / constant) + 0.5)

Below a table is shown with some example values.
The advantage is that the decrease of accuracy is now very gradually. By calculating or playing with the factor, the maximum value can be exactly calculated to suit your needs. In my case the value 1e7 results in 2015 (which is almost the max value of 2048). 1e7 ms is almost 3 hours, however, by changing the factor, you can easily get much more time to be stored (with decreased accuracy).
Of course this method needs some more computing power.
 Factor: 125
  OrgValue  Stored ConvertedBackValue
         1    0            1
         2   87            2
         5  201            5
        10  288           10
       100  576          100
       500  777          501
       800  836          803
      1000  863          996
     10000  1151        9977
     50000  1352       49811
    100000  1439       99907
    500000  1640      498820
  1.00E+06  1727     1000490
  1.00E+07  2015    10019062

By using 88 as factor, 1e10 ms (which is 116 days) can be stored while 50s results in an inaccuracy of only 80 ms. See the table below.
Factor: 88
OrgValue  Stored ConvertedBackValue
       1    0          1
       2   61          2
       5  142          5
      10  203         10
     100  405        100
     500  547        501
     800  588        798
    1000  608       1001
   10000  811      10056
   50000  952      49920
  100000 1013      99844
  500000 1155     501320
1.00E+06 1216    1002675
1.00E+07 1418    9955506
1.00E+08 1621   99977383
1.00E+09 1824 1004014929
1.00E+10 2026 9968812163

Some great hints here, thank you Michel, I will look into this approach!

I would not easy use it for desktop application programming, but for  Arduino it is necessary sometimes

Note that a floating point representation is a decent piecewise linear approximation of the logarithm, and way cheaper to compute than the true logarithm.

If I dare suggest an unorthodox solution... I suggest you store the
times as “float11” floating point numbers.
Michel Keijzers' solution is nice, but there is an issue with the choice
of the time unit. If you use 0.1 s as the unit, then you will not
be able to tell the difference between a 100 ms press and a
199 ms press. I am sure these durations should feel quite
different. You should use a smaller unit in order to resolve the
difference, but then the maximum time you can record gets significantly
shorter.
Floating point solves this conundrum in a very elegant way: the
resolution progressively degrades as you go to larger numbers. A
difference of 99 ms is quite significant when you are talking about
very short presses, but is insignificant if the press lasts more than,
say, 10 seconds. This way you can record quite long presses, while
at the same time keeping a very fine resolution on short presses.
I suggest a 0.5.6 floating point format:

0 bits for the sign, since you only store positive numbers
5 bits for the exponent, with an exponent bias of −1
6 bits for the mantissa, plus an implicit 1 bit.

This allow you to store exactly all integers from 2 to 128, i.e. you
have a 1 ms resolution for presses up to 128 ms. Then the
resolution degrades to 2 ms for presses up to 256 ms, and so
on. By the time you get to a 30 s press, the resolution is about
0.25 s. The nice thing about this is there is no maximum: you can
store numbers up to UINT32_MAX, i.e. about 49.7 days.
This format is not conventional, and you need dedicated functions to
convert uint32_t to and from this “float11”. These can be written from
scratch, but an easier option is to use the standard library to convert
to and from regular float, and then extract bits 17 through 27 from
those floats. Here are the functions I wrote (and tested) for this
purpose:
uint16_t to_float11(uint32_t x)
{
    union { float f; uint32_t i; } y;
    y.f = x;
    return (y.i >> 17) & 0x7ff;
}

uint32_t from_float11(uint16_t x)
{
    union { float f; uint32_t i; } y;
    y.i = ((uint32_t) x << 17) | 0x40000000;
    return y.f;
}

This leaves bits 11 through 15 available for storing the input number,
as per Michel Keijzers' answer:
// Encode:
times[record_index] = (input << 11) | to_float11(time);

// Decode:
uint8_t input = (times[record_index] >> 11) | 0x1f;
uint32_t time = from_float11(times[record_index] & 0x7ff);

Wow, thank you Edgar for sharing this totally fascinating approach. I need even more time to completely understand this, a great exercise for me.

btw. in the meantime, I went for a less efficient but quite simple method:
I divide the time by 10 (which does not really reduce the resolution) and then split any values >255 into packets of x*255 + the rest, so 620 becomes 255+255+110. By this, very long intervals can be stored as well as the small ones, but I still use only the byte data type for it.
Needless to say, I would have never come across this idea without all your valuable input. Very appreciated!

Nice solution, upvoted!


text:
DHT11 is not reading Temperature and Humidity when Arduino is powered on using DC power Supply (12V)
I am facing one problem. I have code which read temperature and humidity using DHT11 sensor. I uploaded following code using Arduino via USB serial, I can read values of temp, humidity. Values are being read as long as Arduino is connected to same laptop via USB.
TEMPERATURE AND HUMIDITY are being read as 0 when I power on Arduino using DC12v, 700MA adapter.
I want to deploy Arduino with DHT sensors connected with it in Greenhouse to read greenhouse environmental condition but when I power on using DC adapter or battery, it is giving "0" output.
PLEASE HELP TO SOLVE THIS PROBLEM.
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // 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();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

is 12v too high for the dht? why not just use 5v if it works?

This 9v to 12v dc adapter is not fed to DHT. This adapter is connected to DC adapter jack of Arduino. I am giving 3.3v to 5v to DHT correctly.

where does the 5v come from?

I have supplied 3.3v to 5v to DHT from another Arduino which is USB powered from PC. I am using Analog port A1 and DHT library from this link github.com/adafruit/DHT-sensor-library. Is this anything to do with analog port but it reads values when connected to USB ?

any suggestions ?

You haven't really provided enough information to answer. What are you reading the temperatures with. You code just assigns a variable to the readings but does not output that to anything.
I would suggest reading along with this tutorial, for example, and trying out the code they provide: http://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-arduino/

I am publishing these values via Ethernet to webserver. With USB connected to PC where I have uploaded the code from, it can send proper values of temp, humidity to webserver but when I power on using dc adapter, it just publishes "0" values of both temp and humidity.

I am using Analog port A1 and DHT library from this link https://github.com/adafruit/DHT-sensor-library. Is this anything to do with analog port but it reads values when connected to USB ?

any suggestions?

When the Arduino runs at 5V, it runs at 5V, no matter where that 5V comes from. The only difference is the voltage regulator. Do you have an Ethernet Shield ? That requires some current. The voltage regulator might get too hot and lower the current. Could you try a 7.5V power supply instead ?

I am using Ethernet Shield and dc adapter i have used is 9v, 750ma. Is this not ok ? and one more problem is that even if I connect USB from another PC, arduino read temp/humid as "0" only.


text:
Analog thermistor readings are wrong
There are some discrepancies between what is read by the analog channel for a thermistor, ohms values directly obtained on the thermistor using an ohmmeter, and another digital temperature sensor.

Figure 1: Left column (y axis) is degree Celcius; x axis is time (minutes). Orange is what was read by the analog channel (thermistor); in yellow the reading by a commercial digital sensor; and in green, manual readings of the thermistor using a ohm-meter.
A bit more context, we are building a simple system to read the temperature from a thermistor via an analog channel. Code algorithm is very similar to what is found here and the electronic layout inspired from here. When we ran into problems,  we just went back to the working basics as instructed by those two above-mentioned references.
Pad resistor is 7K Ohms @ +/-1%, measured resistance was 6690 ohms
Thermistor is 2252 Ohms @ 25 degree Celsius. Coefficients are as follow, coefficient were solved following a calibration in a thermal bath:

COEFF_A = 0.0014644
COEFF_B = 0.00023888
COEFF_C = 9.8996E-08

Specs from vendor are here (PDF) factory coefficient are about the same. I tried to calculate with either factory and in-house calibrated and there is a few thousandth of a degree of difference between the two - not enough yet to explain the current problem
While investigating I saw some sketch with the same resistance for pad resistor and thermistor, but have seen other differing thus assume this is not an issue.
To troubleshoot and isolate the origin of the discrepancies of the orange line VS other reading, we used

other thermistors (every single one behave similarly as the orange line in the figure 1)
other digital temperature sensors (every single one behave similarly as the yellow line in the figure 1)
we try to put 2 analog thermistors and 2 digital temperature sensors on the same arduino - analog were consistant between each other (discrepancies) and the digital one were behaving as expected (correctly)
we switched the pad resistor, no effect
other arduinos (did not changed anything, every single one was repeatedly demonstrating the same behaviour )
used the system in a temperature controlled room and the discrepancy was still present for the analog channel and absent for the digital sensor.

To be clear, green and yellow are what we think is the 'real' temperature; and the orange is the discrepancy. About 1 - 2 degree differences
We used the raw analog value read by the arduino as an input to manually feed and solve the Steinhart–Hart equation (like using IPYTHON and by hand) and output is the same as the orange line. Did the same with the thermistor obtained by the ohm-meter (Green dots on figure).
What should be investigated next to solve the discrepancy between what is read by the analogue channel connected to a thermistor and what the same thermistor provide to the ohm-meter?
Sketch follows
#define THERMISTORPIN_0 0               // analog pin 0 on the board
#define SERIESRESISTOR_0 6990             // balance/pad resistor value (ohm)
#define THERMISTORNOMINAL 2252          // resistance at 25 degrees C
#define ZEROABS -273.15                 // zero Kelvin (Celsius)

#define COEFF_A 1.4644E-03          // Coefficient A for Steinhart-Hart eq.
#define COEFF_B 2.3888E-04          // Coefficient B for Steinhart-Hart eq.
#define COEFF_C 9.8996E-08          // Coefficient C for Steinhart-Hart eq.

void setup()
{
    Serial.begin(9600);
}

void loop()
{
    float temp1;
    temp1 = Thermistor(analogRead(THERMISTORPIN_0),SERIESRESISTOR_0);
    Serial.println(temp1);
}

float Thermistor(int RawADC, long padResistance) {
  long Resistance;
  float Temp;
  Resistance = padResistance / ((1023.0 / RawADC) - 1);
  Temp = log(Resistance);
  Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp,3)));
  Temp += ZEROABS;

  return Temp;
}

try plotting VREF over same timeframe as read with a dmm, do you see distortion?

@dandavis OK I will try this thank you for suggestion, will post an update when done

What is the exact value of the 7k resistor ? Do you know the type of the resistor, to be able to find the A, B, C and β values in the datasheet. This online calculation might be useful: http://www.thinksrs.com/downloads/programs/Therm%20Calc/NTCCalibrator/NTCcalculator.htm Please show your sketch.

@Jot yes I have the exact values for this, I will update my post with the relevant info. This site is awesome isn't it (thinksrs). Will check for the sketch too

Are your calculations assuming a VREF of 5V, or do you know the real reference (VCC by default) voltage?  2. Is your thermistor at the end of a long wire?

@Majenko (1) Assuming 5V, measured 4.91ish; but in my sketch (working on it) I don't seem to reference the VREF at all, like example sketches -  maybe I should check it out in greater depth; (2) Good point, yes the thermistor is at the end of a long wire. But yet, if I measure using the ohmmeter directly on the cable, (fig 1, result in green) the thermistor is still at the end of the same long wire, like when the arduino read (fig 1 in orange)

You must be referencing VREF somewhere in order to calculate the resistance. After all, the resistance is measured by the voltage drop across it, and to convert the raw 0-1023 value of the ADC to a voltage you need to calculate it with respect to VREF. If you use the wrong value you will get the wrong result. 5V is not 4.91V.

@Majenko thank you for confirming this possible path for resolution; I suspected this for a while but since it was not really defined in examples, I tried to look for other issues I guess. It was overviewed in examples because the calculation cancels out; for example ADC value = R / (R + 10K) * Vcc * 1023 / Vcc
become
ADC value = R / (R + 10K) * 1023

True, that is...  Don't forget 10K should be 6690, of course...

@Majenko if you wish to summarize your intervention as an answer, I would choose your answer to close the question

@Majenko, for a thermister plus resistor the VCC drops out the calculation. It is relative to VCC. In the calculation the 5.0 could be used, and the actual voltage may vary, it may be 4.0 or 5.5V, it does not matter. That's the beauty of a thermistor. However, the slightest deviation in the calculation and the curve will change. EtienneGodin, where is the sketch ? (it is 1024 ADC steps, not 1023).

@Jot Sketch was added

@Majenko - comments under questions are for clarifying the question. If you think you have an answer it is preferable to post it, so it can be accepted and/or commented on.

@NickGammon it is pure supposition at the moment. It looks to not be the correct answer so far, so doesn't deserve to be an answer.

@Majenko - the OP has asked you to post your supposition as an answer. It can't get much clearer than that. :)

@NickGammon even after he negated (correctly) my supposition. The thing about VCC is wrong and cannot be the answer. The mentioning of the wrong resistor value in a calculation I take as a copy and paste from original source not his modified source. With no clarification on if that actually is incorrect in his code I have no valid answer to post.

@NickGammon Looking at the edited question with the code included it is plain that the resistor is not the problem either - so there is nothing about my comments that can be converted into a correct answer, and I won't post an answer I know to be blatantly incorrect.

Looking at your referenced diagram, you are connecting AREF to 3.3V, but don't have an analogReference(EXTERNAL)  in your code.  https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/ says not to do that since it shorts the external and internal references together during the analogueRead().  Maybe that could be causing some odd transients during the ADC switching?

One possibility that has not been mentioned yet: the issue may be
the calibration of your ADC converter. Your code carries the implicit
assumption that the voltage you measure is
V = Vref × RawADC ÷ 1023

The correct formula is
V = Vref × (RawADC + offset) ÷ scale

where offset is ideally 0 and scale is ideally 1024 (and not 1023,
as you are assuming). Since you are looking at relatively small
discrepancies, the “ideal ADC” assumption may not be a good enough. I
have calibrated 3 Arduino ADCs and found offsets between 2.2 and
2.4, and scale factors between 1026.1 and 1026.3. Thus, if you have an
accuracy issue, I recommend you calibrate your own ADC.
As a side note, you could expect slightly better accuracy if the
thermistor and the resistor are closer in resistance. Right now you have
a factor 3, which is not that bad, but you could use a 2.2 kΩ
resistor, which is a very standard value.

I was able to  figure out a function to calculate the offset - since there is an acceptable relation between measured and expected, whatever thermistors, Arduino boards, cables/wire or breadboards we are using. Your range suggestions for the offset helped to calibrate our curves.

So far I can see nothing wrong.
This is all about accuracy and being precise. That is how to deal with this problem. This is not a quick fix.
For example the resistor value has been: 10k, 7k, 6690 and 6990. That's too sloppy.
I think that you have not told us that the thermistor is at GND (I prefer it being at GND, that's good).
Test: At 25 °C the thermistor and resistor result in a ADC value of 249.5, and with that in the sketch the result is 25 °C. Very nice. Around 25 °C the sketch is accurate.
Instead of a short minimalistic calculation you could calculate everything. For example the resistance of the thermistor and the voltage at the analog pin. That would make it easer to check those values with a multimeter.
I prefer to let the Arduino do the calculation, and not trying to be smart and optimize something. Let the compiler to the optimizations.
We have to look further than the thermistor, the Arduino and the sketch.

How long is a long wire ? What kind of cable ? Shielded cable ? Is one wire connected to GND ? and at the end is only the thermistor ? The GND is not used for something else ? Are the wires of the thermistor or the cable touching a metal object or water ? A multimeter is not connected to something, but an Arduino is connected via the usb to the computer and perhaps to earth ground. With a power supply, there is a small capacitive coupling to the mains. What happen if the Arduino is battery powered and not connected to something ?
How well is the wire connected to the Arduino. Try to solder it if possible. If it is already soldered, was it a good weld ?
What else is going on with the Arduino board ? It could be GND offset caused by something that pushes current through the GND. A LCD display with its background light connected in the wrong way could cause this. Is the thermistor connected via a breadboard, and there is something else on that breadboard ? Then you have almost certainly a DC offset.
Could you try with another Arduino board and another computer ? Only the Arduino board, the thermistor + resistor and a USB cable to the computer. Without the long wires. Try a desktop computer, not a laptop (the usb 5V of a laptop could be less reliable). You are now caught in some kind of trap, and you get out by making a second test setup with a new set of components and not even using a single wire from the first setup.
The NTC could cool down via the metal legs.
Perhaps averaging a number of samples would help. When the final average     calculation is done with float, you could even increase the resolution beyond 10 bits of the ADC.

For now, I think that the problem is between the thermistor and the microcontroller on the Arduino board. Could you try to eliminate any DC offset of the GND and be sure to isolate the thermistor (from metal objects and water)

there seems to be two problems:
1) calibration: the digital sensor / analog sensor may not be calibrated properly - this can account for the gap between the two curves.
2) response time: the digital sensor seems to react much faster than the analog sensor. that could be due to placement, physical attributes (smaller thermal mass for example), ...

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
time delayed LEDs
I have two LEDs an I want the first one getting linear brighter and the second one do the exact same thing just one ore two seconds later. When one LED has reached 100, it should getting darker until there's no light and then start again from the beginning. I#m trying now for quite a long time but couldn't get it going.
int LED = 11;
int LED2 = 10;
void setup() {

Serial.begin(9600);
}
int x;
int x2;
void loop() {

for(x = 0; x<=100;x++)
{
while(x > 30)
{
for(x2 = 0; x2<=100;x2++)
{
analogWrite(LED2,x2);
delay(100);
}
}

analogWrite(LED,x);
delay(100);
Serial.println(x);

}
}

I just wanted to do the beginning but it isn't working. Can somebody pleas help me?

I'd be inclined to use sin and cos to create a sinusoidal brightness profile. Loop from 0 to 2xPI at whatever increment you want (maybe use a DEG2RAD conversion so you can work in degrees) and cycle around a circle. Use sin to calculate the brightness of one LED ((sin(angle) + 1) * 50.0) and cos for the other. The two LEDs will then be 90° apart around the circle.

@gamma, what about a graph that shows the brightness of both leds in time. I'm still confused what you want to achieve. Do you want other patterns as well ?

Note: I think you will need to adjust the timings.
Hope this help:
int LED = 11;
int LED2 = 10;

unsigned long start;

int lum = 0;  // Light level LED
int step = 1;
int lum2 = 0; // Light level LED2
int step2 = 1;

void setup() {
  Serial.begin(9600);
  start = millis();
}

void loop() {
  unsigned long now = millis();

  if (now % 100 == 0) {
    // Every 100 ms, light goes up/down 1 notch.
    light(LED, &lum, &step);

    if (now - start > 2000) {
      //  Time to start with LED2
      light(LED2, &lum2, &step2);
    }
  }
}

/*
 * Light up/down one notch on a pin.
 */
void light(int pin, int* p_lum, int* p_step) {
  analogWrite(pin, *p_lum);
  *p_lum += *p_step;

  if (*p_lum == 100) {
    *p_step = -1;
  }
  if (*p_lum == 0) {
    *p_step = 1;
  }
}

Thanks for your help. This is not exactly what I ment. The first one should start an go up and while thise is happening the second one should go up. So the second LED should do the same thing like the first one but two seconds later.

@gamma. See new version

Well I'm not quite sure if this is it. Anyway thanks for helping. I wanted it to go up and down like tw for loops:

Sorry for that. What I wanted to say was:
I wanted it to go up and down like tw for loops:
for(x = 0; x<=100; x++)
{
analogWrite(LED,x);
delay(100);
}
for (x = 100; x>=0;x--)
{
analogWrite(LED;x)
delay(100)
}
but this with two LEDs and the second one starts about 2 seconds later and ends about 2 seconds later. Your code almost does that but I think it looks like a little bit different.

Here is one way to do it.

Set up two output compare channels. They are identical except that they have slight different periods.
In their respective isr, flip the led

The next effect is that the duty cycle on the led goes from 0 to 100 and then 0 and then ....
The periods determine how long the 0 to 100 to 0 cycle is. The period differential determines how fast the led goes on and off.
You can do that to the other led, either in the same isr or through two other channels.


text:
Can I power arduino uno R3 with 9v battery through Vin?
I want to power up arduino through Vin port , what should be the input voltage ?

Here is the answer - https://arduino.stackexchange.com/questions/39041/powering-an-arduino-with-more-than-5-v/39043#39043

Does this answer your question? Powering an Arduino with more than 5 V

About 7.5V to 9V is best. A 9V battery is often not capable to supply enough current for an Arduino. Do you have a multimeter to measure the battery voltage drop when the Arduino is connected ?

Are you really sure? I must search for mine, but what i remember, that over the pins....
ok I looked, sry, Jot was right :D... on the Input Pins, you find three kinds right? 3.3, 5 an Vin, which will be a range of V for sure ;)

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Data not updated in real time
In my recent project, working with JSON and Arduino. Till now, I am getting proper JSON data and add this one into Arduino data. But here I face one problem. My data are not updated in real time.
For example, my JSON string is:
{"TPS_Json":"0.40"}

And below is my Arduino code:
#include<LiquidCrystal.h>
#include <ArduinoJson.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String response = "";
bool begin = false, finished;

//------------------------------ Variable ---------------------------------//

void setup()
{
  Serial.begin(9600);

  lcd.begin(16, 2);
}

void loop()
{
  //----------------------------TPS----------------------------//

  float TPS = analogRead(A0) * (5.0 / 1023.0);

  //-----------------------JASON DATA--------------------------//

  StaticJsonBuffer<100> jsonBuffer;

  while (finished == false)
  {
    if (Serial.available())
    {
      const char in = Serial.read();
      if (in == '{')
      {
        response = "";  // Blank the string
        begin = true;
      }
      if (begin)
      {
        response += (in); // Only write if within the {}
      }
      if (in == '}')
      {
        begin = false;   // Prevent any chars between } and { leaking through.
        break;
      }
    }
    delay(1);
  }

  JsonObject& root = jsonBuffer.parseObject(response);

  float TPS_Json = root["TPS_Json"];

  float TPS_Final = TPS + TPS_Json;

  lcd.setCursor(0, 0);
  lcd.print("      ");
  lcd.setCursor(0, 0);
  lcd.print(TPS);
  lcd.setCursor(8, 0);
  lcd.print("      ");
  lcd.setCursor(8, 0);
  lcd.print(TPS_Json);
  lcd.setCursor(0, 1);
  lcd.print("      ");
  lcd.setCursor(0, 1);
  lcd.print(TPS_Final);
}

So, now I add TPS_Json with TPS. Where TPS_Json is JSON data and TPS is an analog value from A0. And TPS_Final is the addition of TPS_Json and TPS. I displayed all this on LCD.
Suppose, TPS_Json = 0.40, TPS = 2.40... So addition is 2.80 means TPS_Final = 2.80...
And this all data displayed on LCD successfully.
But when I changed my analog value means TPS value then it is not updated and I'm not getting the correct result.
Suppose, I change the value of TPS means makes it 3.00 from 2.40 than my TPS_Final must be 3.40.But nothing updated. It updated when I send JSON data again. I don't know why this happens. I want to change it in real time means When I changed TPS then TPS_Final must be changed in real time.

The reasons it's not updating is because your code is sitting in the loop while (finished == false) {...} waiting for more json to arrive.
Try replacing the while loop with something along these lines:
  while ((finished == false) || Serial.available()) {
   if (Serial.available()) {
    const char in = Serial.read();
    if (in == '{')  {
        response = "";  // Blank the string
        begin = true;
        finished = false;
    }
    if (begin)
        response += (in); // Only write if within the {}
    if (in == '}') {
        begin = false;   // Prevent any chars between } and { leaking through.
        finished = true;
    }
   }
  }

and change the initial variable declarations at the start of the code to set finished to false:
// personally I always put each variables on a separate lines when setting initial values.
bool begin = false;
bool finished = false;

This will block until it's received at least 1 json string. After that it will check if there is new data on the serial port, if there is it will block until it's received the whole string, it there isn't any data waiting it will exit.
Oh and your response string is currently including the { } characters at the start and end, this contradicts your comments which imply that it doesn't.

Thank you for your effort. I tried out your code. Now my data is updated but I'm not getting JSON Data...It's displayed 0.00 instead of 0.40...

Code updated. If finished was false (not had any JSON or in the middle of a string) but there was no serial data waiting then invalid data would get added to the response string. I've added an if(serial.avalible()) to the code which should fix that.

Thank you. Now, it's working fine. Can you explain what is the fault in previous code?

I though I had explained it. When finished was false but there was no data waiting on the serial port it would still attempt to read the serial port. If this happened to be between the { and } characters junk would get inserted into the middle of the json string. Ultimately this is caused by serial ports being painfully slow in comparison to processors and so you end up having to wait for the message to finish.

Your code reads data from the serial interface and once it has read the input it re-evaluates the value of TPS_Final.  I've found it difficult to understand your question but I think you are saying this:
If you enter {"TPS_Json":"0.40"} in the serial monitor and A0 has a value that equates to 2.4 then you expect TPS = 2.80 on your LCD.  So do I.
Now if you change what ever is feeding A0 so that the value equates to 3.00 I think you are saying you expect you LCD to update to say TPS = 3.40, but it doesn't and you don't understand why.
IF that is the case then the answer is simple.  When you change the value for A0 you code is waiting for you to enter the serial data again, because it is a 'blocking function call' well a 'blocking' bit of code at any rate.  And until you enter a value in the serial monitor you code won't evaluate TPS again.
You need to change/remove the while loop so it your code will update the LCD even when the data is being entered by the serial interface.


text:
Arduino UNO IR blaster - storing codes in PROGMEM
I've setup an IR LED on my UNO, with the IRremote library, and have the code working to control an RGB LED strip from certain serial input, however as i'm storing the Raw infrared data in variables, i'm running out of RAM very quickly, and haven't managed to get code working that stores the IR data in PROGMEM, then buffers it to RAM for sending.
The current working code can be found at https://gist.github.com/dan-r/71294eaf9fe2354f1a0c7c13fc5f3bcd, and i've tried setting the int arrays as statics in PROGMEM, but whatever I do, I can't figure out how to buffer them into RAM, or even directly send them with irsend.

The Arduino Uno can not read data from PROGMEM (data in flash memory) in the same way as reading data from ram, there are special functions to read data from PROGMEM.
Create a buffer in ram and use one of those special functions to copy the data into that buffer.
Start with the Arduino PROGMEM reference.
Nick Gammon had made a great tutorial about PROGMEM.
All the PROMEM functions are in <avr/pgmspace.h>
Is the array of numbers always the same length ? That would make the sketch a lot easier.
Then perhaps something like this:
const unsigned int irTable[9][67] PROGMEM = { { ... }, { ... } }

unsigned int irBuf[200];

i = ...   // number of command
memcpy_P ( irBuf, &irTable[i][0], 67 * 2);
irsend.sendRaw (irBuf, 67, ...);

Works perfectly, all cleared up and into the irTable array, thank you for your help! :) (Final code is https://gist.github.com/dan-r/067b4857a0f44079c655855145e1518d for reference)

Well done ! But why lay back ? You could make a table of texts in PROGMEM with "brightup", "brightdown", "off" and so on, in the same order and the same index as the IR codes. Then you can search the table with texts to find the index of the IR code.

Hmm good idea, going to try that!


text:
433 MHZ connection between two Arduino (nano,uno) fails after some time
The goal of this part of my project is to establish a wireless connection between an Arduino nano and an Arduino uno. For this I use 433 MHZ receiver and sender. The nano sends, the uno receives and prints. I have working code and the connection works and I can send, receive and print my message.
But at some point the Uno receives just a part of the message and after this point always receives (or prints) just this part of the message:

Nano (sender):
#include <VirtualWire.h>
char *msg = "123456789123456789";

It is not always 2 digits, sometimes more are received.
I searched for errors. The nano is constantly sending and the uno flips to not receiving the whole message. So I reupload the code to the uno without modification and it works again for a few seconds/minutes, so I guess it's a problem at the receiving end.
Here is my code:
Sender(nano):
#include <VirtualWire.h>
char *msg = "123456789123456789"

void setup()   {
 Serial.begin(9600);

 pinMode(7,OUTPUT);
 pinMode(5,OUTPUT);
 digitalWrite(5,LOW); //GND
 pinMode(6,OUTPUT)
 digitalWrite(6,HIGH); //5V
 vw_setup(5000);
 vw_set_tx_pin(7);
}

void loop()     {
 vw_send((uint8_t*)msg, strlen(msg));
 vw_wait_tx();
 delay(500);
}

Receiver(Uno):
#include <VirtualWire.h>

int i;
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;

void setup() {

 Serial.begin(9600);
 pinMode(5,INPUT);
 pinMode(6,INPUT); // two data inputs, we use just one
 pinMode(7,OUTPUT);
 digitalWrite(7,LOW); //GND
 pinMode(4,OUTPUT);
 digitalWrite(4,HIGH); // 5V VCC
 vw_setup(5000);
 vw_set_rx_pin(6);
 vw_rx_start();
 Serial.println("Starting up");

}

void loop() {

 if(vw_get_message(buf,&buflen)) {
   for(i=0;i<buflen; i++) {
    Serial.print((char)buf[i]);
   }
 }
}

It doesn't happen after a certain time or number of messages. I have no clue what could be the problem.
Thanks in advance,
Niklas
Edit: Problem seems solved. Changing bitrate from 5000 to 2000 solved the problem, but I don't actually know why.

Try to also print the buflen variable on the receiver side to see if the data got corrupted (Serial.print will not print anything if it encounters a '\0' or other special characters) or if the data has not been received at all. You can also print the raw values to see what you get.

One thing I have noticed about those units is the power requirements.  You need to be able to provide the amperage that those units will use.  For instance, I couldn't get them to work at all with just USB power, but with a 2 Amp 12V supply they did just fine.  The fact that they start out working is a good sign.  So, are you sure you are giving them enough power?

Did you use the latest official VirtualWire library, or just a zip file you found somewhere on the internet ? The newer RadioHead has a few bugs fixed, look at the 'ask' examples of RadioHead, the usage is almost the same as VirtualWire. You need a piece of wire as antenne (16 cm) or else they almost don't work. 5000 bitrate is too much, everyone else uses 2000 for those very cheap 433MHz RF modules. Too low is not good and too high not good.

I think I/you solved it.
I printed out the buflen variable and at some point it switches to 2 instead of 18. Who knows why.
But changing the bitrate to 2000 helped @Jot
It's running and working for several minutes now, will test it at least a few hours.
Thanks!!

@Niklas - in Sender it might be better to change char *msg = "123456789123456789" to const char msg[] = "123456789123456789";  the compiler will allocate memory in a different way, I don't understand why/how I just get told it is better.

@CodeGorilla const variables are committed to flash memory.

@Niklas Did changing bps to 2000 solve it? How many metres are you transmitting, and are there any objects between the devices? If so, what material are the objects made from?

@user2497 Yes, it did solve it. 5-10cm distance between sender and receiver, no objects in between. I need the connection just for a galvanic separation

@Niklas Great ;) Have you tested with both a linear supply (like 7808) and switching supply (USB)?

Regarding the hardware problem, there are some advices in the comments.
As you wrote, the solution is to reduce the bitrate at 2000 bps.
The remaining question is why the receiver always truncates the message (after a receiving error occurs). The answer is in the definition of the buflen parameter of the vw_get_message function. The page https://www.pjrc.com/teensy/td_libs_VirtualWire.html says:

"buflen" should have the array's maximum size upon input, and upon return the number of bytes actually copied is retured.

Therefore, when a transmission error occurs, the buflen variable returns a smaller number to inform you how many characters are received. If you do not reset the buflen variable to VW_MAX_MESSAGE_LEN before calling vw_get_message again, you are telling the library that you expect a smaller number of characters and the function respects that size (thinking that you have a smaller buffer).
In other words, if you want try to receive the full message after a transmission error occured, set the buflen variable to VW_MAX_MESSAGE_LEN before each call of the vw_get_message function.

Those cheap 433 MHz RF modules can not handle a high bitrate. There are many different 433 MHz modules and the more expensive modules might be able to handle perhaps 10 kHz.
Every pulse from the receiver generates an interrupt. That means also the software has to be able to keep up with it.
For a basic Arduino board at 16 MHz (Arduino Uno, Nano, Leonardo, and so on) and the cheap RF modules the sweet spot is around 1 kHz to 2 kHz bps. The 2 kHz is a safe value.
The 433 MHz frequency requires in most countries that only 1/10 of the time a transmission might be active and the VirtualWire/RadioHead has overhead. That means that the resulting data speed with 2 kHz bps will be between 10 and 20 bytes per second.
The transceiver modules don't have all these (ridiculous) limitations. They can transmit data at a fast rate. Transceiver modules are for example nRF24L01+ modules, CC1101 modules, RFM69 modules, and so on.


text:
Is it ok to declare variables inside timer interrupts?
I am building a real time audio application using the Arduino DUE. This application needs big arrays like:
uint16_t sDelayBuffer0[46000];

The Due has only 96kb of RAM available so this array just ate up most ot its memory.
The problem is i need more arrays like this...
So, i was thinking, instead of declaring all of the arrays as global variables, to declare them inside the timer interrupt functions.
The loop() handles stuff like reading the ADCs. The actual effects are coded inside timer iterrupt funciton that are replayed over and over. So the code constantly loops in loop() and the selected timer interrupt function.
But other timer interrupt fucntions use other arrays. So i was thinking to declare every array that a corresponding timer interrupt function wants inside that fucntion.
So all arrays are not declared at the same time (since when we exit the timer interrupt function we were on and head either to loop or another interrupt function, the grabage collector will destroy the array right?)
The problem with this theory, is that this is a real time audio application. So is it wise to constantly declare a big array like this? Since the timer interrupt ficntion will run very very often. Won't i have delay problems iwth the actual sound? Or variable declarations happen extremely fast inside the CPU, even for big arrays?

Have you considered a simple compression algorithm to allow more samples? 8-bit DPCM (-127..127 and escape for full value) for instance.

What are you planning on doing in the timer interrupt that requires an array of 46000 integers?!?! It certainly can't be anything fast (and thus not suitable for running in an interrupt) if you need to process that much data every time...

The loop() reads the ADCs that contain the information from the guitar. The place to store it is the big array. The effect is applied and then it is sent to the DACs. This is all working by now. But i want more space. So i was considering instead of declaring the arrays as global variavbles - which is not possible. To declare them inside the corresponding timer interrupt function. But i dont know if declaring something this big, something that will be declared over and over again is viable in a real time audio application

@MikaelPatel Haven't thought about compression. But still, since it's a real time audio application, maybe i think its too much to compress/.decompress in real time, all the time

It sounds like you think you can access a variable declared in one function from another function. You can't.

I know! I wasn't suggsting that at all! Each function declares their own stuff. That is destroyed when another function comes into play!

Then I am at a loss as to what it is you are doing. It sounds like you are trying to make some kind of guitar FX pedal: read in through ADC, then send out (modified) through DAC. Perhaps if you actually detailed what you are really trying to achieve we can point you in the correct direction. As it is you have your brain fixated on wanting massive arrays. Chances are you don't want massive arrays at all, but you can't see past that, so you keep getting stuck.,

It does sound very much like a classic X-Y Problem.

The problem is i need more arrays like this...

you probably want to take a look at your processing flow to see if you need all of them at the same time. if you do, well, there is no alternative but to get a bigger chip.

No i do not need them at the same time! This is why i am thinking to declare them inside the functions. So as we move to another, the garbage collector destroys the previous array and space is freed up for the next array to be declared.

If you declare them as local variables, it should be ok, just make sure you have enough space in all cases.

If you don't need them all at the same time then declare a single array as a global and use the same array everywhere. No reason why you can't re-use the same variable for a different use in a different function as long as you can be sure you won't try to use it both ways once. And as others have said, nothing involving creating and pressing 46,000 values should ever be done in an interrupt.

First, I don't think it's a good idea to use 46000 * 2 = 92000 bytes of SRAM. That leaves only around 4K left. I hope you don't use a big stack trace, local variables or other global variables.
I don't know if creating an array costs a lot of space, anyway, constantly creating and removing arrays (in heap space) will make your free memory space a mess. This means, that after some time you cannot allocate arrays anymore, especially big ones which need consecutive memory.
Also, within interrupts the code should be as least as possible.
I suggest you use some arrays and reuse them for different reasons. Keep the name simple (like buffer), and reuse the array when needed, without the need to declare it and destroy it. This keeps your memory clear. Make sure the size is big enough for the maximum/worst case you use it for.
Update:
The above mostly assumes that the arrays are made in heap space, not as local variables. However, using local variables is ok.
But anyway, if you need a 2-byte 46000 array, don't expect to be able to use more arrays. In that case use external SRAM (like 23K256, 23LC1024).

I have already ordered a 23LC1024. But wiating for it to arrive, i am thinking some hacks. Because maybe the time to read/write to an SPI external memory is too big for real time audio applications. Other than that, the code is really small in the timer interrupt functions.

I suggest you do some timing tests (how long it takes to declare/destroy an array). Garbage collection inside interrupts I wouldn't advise. Better to declare them as local variables on the stack (and make sure you have enough memory left). You also can test for current free memory.

Declare them as local variables on the stack? This is the first time i read of theis concept. Can you post a link or something?

@user1584421. Local variables are allocated in the stack. Where else?

@Michael. Allocating space in the stack cost nothing. And it's freed after return from function. You are thinking about heap space.

@LookAlterno You are right ... just changing the pointer, which is negligible.

Local variables are automatically stored on the stack, you don't have to do anything for this.


text:
High Speed Thermocouple Readings
I'm currently attempting to take readings from 10 thermocouples using an Arduino Mega. I've been using MAX31850 1Wire Thermocouple Modules (with the Adafruit breakout) to perform the readings, but their response time has been very slow (~500ms each). I'm not sure if most of this latency is coming from the IC, or from the communications protocol, or perhaps even the DallasTemperature library.
For my application, I need to be able to read all 10 thermocouples in at most 250 ms (and faster would be better) and so I can afford up to 25ms per thermocouple. I would also like to be measuring with a precision of about 1-2 F.
I assume I will probably have to use a different amplifier, and I've seen recommendations online of using an external ADC to achieve higher speeds, which I would be happy to do, but I don't understand why that would make a substantial difference on speed since the onboard ADC can already sample at about 1/10 ms.
I would greatly appreciate any recommendations on how to achieve these speeds.

From Table 6 on page 22 of the data sheet for MAX31850 1Wire Thermocouple Modules, it appears that about 30 bytes of data are sent per reading (5 command bytes, 9 scratchpad data bytes, 2 x 8 module-id bytes).  At an apparent minimum of 60 μs per bit, those 30 bytes will take about 15 ms; at times of say 100 μs per bit, they would take about 24 ms.
Each reading also sends 3 each reset and presence-detect signals, adding up to a few milliseconds, and each reading requires a conversion time tCONV of typically 72 ms, per the last entry on page 4 in the Thermal Characteristics table.
Thus, it looks like the MAX31850 will take at least 87 ms per reading, if your units are all on the same 1Wire bus and you code things efficiently.  (Single units on a bus can use a slightly simpler protocol, which might reduce communication times to perhaps a third as much, but the typical tCONV would still dominate the time per reading.)
You might consider attaching an inexpensive Arduino Nano, Micro, or Mini to each of your MAX31850 units.  Each of those could communicate with its own MAX31850, allowing all the MAX31850s to convert simultaneously.  The small Arduinos could send results to the Mega by I2C or serial, in assigned time slots or upon request from the Mega.

That's an interesting idea. A pro mini would only cost $10, and I could probably get away with 1 for every two thermocouples.I'm not sure why the reading is taking so long. I'm also looking into the idea of trying to take the reading asynchronously.

1-wire transmission takes ~100us/1bit so 1ms/byte. so unless the adc is that slow, it shouldn't take you anywhere close to 500ms to take 1 reading, even if you factor in the overhead / reset.
there are dedicated chips but as you mentioned putting an amplifier (instrumentation amps for example) isn't that difficult. simpler with chips with built-in PGA + differential adc. My favorite here are some of the AVR chips (ATtiny85 or ATmega32U for example). But lots of Freescale / STM32F3 chips also work, so long as you are willing to dive into their and roll your own. Lots of fun.

Yeah, I was surprised by the latencies as well. I think that it's how long the module is taking to perform the reading, not the 1wire. Thanks

The onboard ADC of the Arduino Mega 2560 is only 10 bits. An external ADC in a thermocouple chip with a fast SPI interface is probably the best solution.
The Adafruit MAX31855 module seems to be able to do that.
The MAX31855 has a 14 bit ADC and a 5 MHZ SPI interface.
It needs a conversion time of 70ms. I think that is normal for these chips. I did not read the datasheet well enough how to get a value without waiting for it.

Thanks for the find. Reading asynchronously without waiting would also help a lot. I'll look into the libraries I'm using now to see if I can implement that idea. Thanks.


text:
Help with code. Fade in LEDs from off (shift register)
I used this tutorial here and decided it to overcomplicate the pattern. For further learning. My code in theory should start the LEDs at a low brightness and fade them in using this code. My expected output is as follows.

All 8 LEDs start out as off.
Fade in slowly.
LEDs turn of one by one from left to right.
LEDs turn on one by one right to left.
Fade out.
Repeat.

This is the loop that fades the LEDs in.
for (byte b = 1; b < 255; b++) {
  setBrightnessUp(b); //sets the brightness up function
  delay(20);
}

This is the function:
void setBrightnessUp(byte brightness) {// 0 to 255
  analogWrite(outputEnablePin, brightness);
}

However at this time it appears to be getting into my loop but not increasing the brightness at all. When the code first runs, the LEDs are on but at a minimum brightness. The rest of the code including the fade out at the end works fine.
Fade out functions:
for (byte b = 255; b > 0; b--) {
  setBrightness(b); //sets the brightness function
  delay(20);
}

void setBrightness(byte brightness) { // 0 to 255
  analogWrite(outputEnablePin, 255 - brightness);
}

Here is the complete code. Excuse the over commenting it helps me learn:
//sets pin out for control pins on shift register

int latchPin = 5;
int clockPin = 6;
int dataPin = 4;
int outputEnablePin = 3; //enables a PWM pin output

//uses byte (8bit binary variable)
byte leds = 0;

void setup() {
  // sets the pins to output mode
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode (outputEnablePin, OUTPUT);
}

void loop() {
  //attempted to make led fade in from 0
  leds = 0; // set led to no output ready for dimming effect
  updateShiftRegister(); //calls the function used for output
  delay(1000); //troubleshooting delay
  for (byte b = 1; b < 255; b++) {
    setBrightnessUp(b); //calls the brightnessup function
    delay(20);
  }
  leds = 255; //Sets the byte variable to 255 or 11111111
  updateShiftRegister(); //calls the function used for output
  delay(500); //waits 1/2 second

  //sets a variable i at 8 and runs while i is more than 1
  //minus 1 each loop
  for (int i = 8; i > -1 ; i--) {
    //Bitclear acts on a byte like its an array
    //it sets the bit at position i to 0 (or off)
    // the left most bit is 7 the right most 0
    bitClear(leds, i);
    updateShiftRegister(); //calls the display function
    delay(250); // waits
  }
  //sets a veriable i at 0 and runs while is less than 8
  //plus 1 each loop
  for (int i = 0; i < 8 ; i++) {
    //same as bitclear but turns on the bit at position i
    bitSet(leds, i);
    updateShiftRegister(); //calls the display function
    delay(250); //waits
  }
  //After the 2 other for loops are finished this will then fade
  //the LEDs out
  //sets the bite to 255 (11111111), while its more that 0
  //and minus 1 each loop
  for (byte b = 255; b > 0; b--) {
    setBrightness(b); //calls the brightness function
    delay(20);
  }
}

// this function outputs the data to the shifter
void updateShiftRegister() {
  digitalWrite(latchPin, LOW);//sets the latch pin to low(off)
  shiftOut(dataPin, clockPin, LSBFIRST, leds);
  // the first 2 functions set the data and clock pins needed
  //to receive data. The LSBFIRST tells it to start at the right
  //most bit (MSBFIRST is oposite). LEDs is our binary array (byte)
  // EG 0000000 would print no lights. It shifts this into the
  //shiftregister at 1 bit at a time from one end or the other
  //(determined by LSBFIRST or MSBFIRST)
  digitalWrite(latchPin, HIGH);  // sets the latch pin to high
  //the low to high state change triggers the output
}

//brightness down slowly
void setBrightness(byte brightness) { // 0 to 255
  analogWrite(outputEnablePin, 255 - brightness);
}

//supposed to fade the brightness up
void setBrightnessUp(byte brightness) { // 0 to 255
  analogWrite(outputEnablePin, brightness);
}

Board layout

I don't see a connection to pin 3...?

Yea its not in the diagram cause its part of the additional work exercise but is in my board.

I was mistakenly thinking that setting the brightness variable to 255 would mean that the LED is full on. This is wrong, 255 is actually off.
So with a little change in my code.
for (byte b = 255; b > 0; b--) {
  setBrightnessUp(b); //calls the brightnessup function
  delay(30);
}

The loop now works. I am still not sure why 255 is off and not on though.

Because the output enable on the shift register is active low.  A low turns it on and a high turns it off.  Newbies tend to want high to always turn something on and low to be off, but in the real world it is more often the other way round.


text:
How can I pass a long as parameter and get a char array in return?
I kind of new to C++, so I'm not sure how to perform such casting.
Example:
long myLong = 12345L;
convertToCharArray(myLong); //returns an array with the digits of myLong

BTW I'm working with Arduino IDE.

As with many things in C there are many ways of skinning this particular cat.
All of them rely on you first having made a character array to store the result in - you can't "return" an array from a function.
The simplest, though non-standard, way is to use ltoa(), which is an avr-libc specific function (not part of the standard libc functions):
long myLong = 12345L;
char myCharArray[10]; // Enough room for the answer + 1 NULL char

ltoa(myLong, myCharArray, 10);

The 10 in that function call defines the base to represent the number in - base 10 in this case: decimal.
Another way, which is more portable, is to format the string using snprintf():
snprintf(myCharArray, 10, "%dl", myLong);

In this case the 10 is the maximum length of string to prevent it overrunning the 10-character array we made.
A pure Arduino way of doing it would be to use the dreaded String class:
String myString = String(myLong);
myString.toCharArray(myString, 10);

Again in this example the 10 is the length of the buffer we are copying in to.
And there are more. You could do it manually, character by character using division and modulus operators, for example.

This is a job for pointers.
long myLong = 12345;
char* myCharArray = (char*)&myLong;

Now pointers and arrays work the same. So you can now use myCharArray[0] to refer to the first byte and myCharArray[1] for the second etc.

My phone won't let me edit that to fix the code proper. If someone wouldn't mind editing that for me I would greatly appreciate it.

I think he means he wants an ASCII representation of the number, not the raw bytes.

You're right. ASCII representation.

Well he referred to "casting" in the question so I told him how to cast it.  If you just want ascii use atol.

I really meant ltoa.

You might be looking for a function that returns the textual representation of a long number. In that case there is actually an AVR standard library function (avr-libc:stdlib.h ltoa):
const size_t BUF_MAX = 32;
char buf[BUF_MAX];
const int RADIX = 10;

long myLong = 12345L;
ltoa(myLong, buf, RADIX);

The buffer, buf, will contain the textual representation of the number, myLong, in the given RADIX.
Cheers!

ltoa isn't standard. It's pretty unique to avr-libc.

Let me fix that for your :)

Well for such situations I did found a solution.
To convert Float or Long or int into character array format, we could use dtostrf().
Syntax:
dtostrf(Source_var, StringLength, numVarsAfterDecimal,destinaton_var)

Source_var = the variable you want to convert (float/int/long)
StringLength = Length of the string (for your case just keep it 1)
numVarsAfterDecimal = required number of values after decimal point(keep it zero for now)
destination_var = the char variable to where the value must be stored(do not use square brackets).
For converting Long to array follow the below code
long myLong=12345L;
char var[5];
dtostrf(myLong,1,0,var);

If all goes well
Result will be like var[]={'1','2','3','4','5'}

I found this function very useful and it had been working great for me. Hope it does the same for you.
For more info on dtostrf() : Link

By using dtostrf(), you are implicitly converting the number to float. This is expensive, unneeded, and looses precision if the number is larger than 2^24.

I kind of new to C++, so I'm not sure how to perform such casting.

to recast it, just make a char pointer and pointer it to the variable. Fairly simple.
if you want to convert ti ascii, there are numerous ways, each with their own pros and cons.
I wrote a set of conversion routines here: https://dannyelectronics.wordpress.com/2017/07/04/a-very-fast-numeric-to-ascii-conversion-routine/
they are designed to convert 8 digit unsigned long to ascii but can be easily rewrite to convert 5 digit.


text:
SdFat Library what is dir_t*?
I'm using the SDFat library and the FatFile type has the functions:

bool FatFile::dirEntry(dir_t* dir)
Return a file's directory entry.
Parameters

[out] dir    Location for return of the file's directory entry.

Returns

The value true is returned for success and the value false is returned
    for failure.

And

uint8_t FatFile::dirName(const dir_t *dir, char *name)
Format the name field of dir into the 13 byte array name in standard
  8.3 short name format.
Parameters

[in] dir The directory structure containing the name.
[out]    name    A 13 byte char array for the formatted name.

Returns

length of the name.

From what I understand, I should be able to pass something like this into the functions:
dir_t Bass;
char dName [13];
FatFile BrowseFile;
BrowseFile.open("/Folder1/File1.txt", O_RDONLY);
Serial.print(BrowseFile.dirEntry(&*Bass));
Serial.print(BrowseFile.dirName(Bass,*dName));
Serial.println(dName);

to which the program should output
1
[Folder1's 8.3 name length]
[Folder1's 8.3 name]

However, I'm getting an error and I can't find any included examples that use these two functions in a sketch. if someone could explain what I'm doing wrong, it would be greatly appreciated.

However, I'm getting an error Then post the full error.

dir_t * is a pointer to a variable of type dir_t.
I don't know the API to which you refer, but the format for passing it would be:
dir_t Bass;
char dName[13];
BrowseFile.dirEntry(&Bass);
BrowseFile.dirName(&Bass, dName);
Serial.println(dName);

Thank you, that seems to be the correct format. Unfortunately, it returns information on File1.txt and not Folder1 which makes it less useful. Also, a link to the API is now in the question

Well, .dirEntry() gets the entry in the directory for the file, not the directory the file is in. FAT has no way of going "up" from a file. In fact I am not aware of any filesystem that has the concept of "up" - even going up a directory in a tree is actually going down into the directory called ".."

Oh, then I have a misunderstanding in regards to how FAT files work. Is there a good resource I can use to learn more about FAT? How would I go up a directory in a tree? Would it be as easy as saying BrowseFile.open([&directory],"..",O_READ?

In most filesystems a directory contains two special files ".", which is the current directory, and ".." which is the parent directory. If you want to go up the tree you have to get the ".." directory entry and open that as a directory. There's nothing like that for a file though, only directories.  You can start here for FAT information: https://en.wikipedia.org/wiki/File_Allocation_Table

what is dir_t*?

a pointer to a data type called  dir_t -> it must have been defined somewhere in  your code/libraries used.


text:
Photoresistor and another switch
I am using the circuit diagram below to turn ON/OFF the lights using Photo-resistor.
How can I use the Arduino to bypass the Photoresistor effect?
Let say I want to turn ON the lights even though Photoresistor doesn't want to.
Take note the 12V source is required by the LED. Knowing that Arduino must work with max 5V.

You could replace the circuit with these:

Use one Arduino analog input to measure the light.
Use a Digital Out (Preferable PWM) to control the LED.

Then you can apply whatever logic you want.

simulate this circuit – Schematic created using CircuitLab

Among the other answers, this is the best, especially because:

The arduino can read the light intensity. 2) You can choose of having the LED either on or either off, or its intensity to be inversely proportional to the amount of light 3) you can easily add hysteresis by software 4) you can choose the threshold level, without having to change the pull-up resistor.

One thing though: i would put R1 connected to the arduino GPIO and not to the gate, so that there won't be any divider. M1 must also be a 5V logic level MOSFET. Or you can use a BJT.

@next-hack R1 and R2 is NOT a voltage divider, its a common practice to pull down a MOSFET to ensure that it is in an normal OFF state and the value for R1 would be in 10K to 100k area. R2 is to protect Arduino from a faulty MOSFET that shortens the output and could be in 1K area.

I didn't write that R1 and R2's purpose is a divider, but the side effect is. To avoid this, you need to use R1 values at least an order of magnitude larger than R2, as you wrote. If you put R1 on the left (keeping R2), this constraint is removed. In this way, when the GPIO is uninitialized (i.e. during reset, in most  - but not all - MCUs the GPIO ia at high impedance), M1 is kept in the off state by the series R1+R2. However, some MCUs might have some pins which even during reset have a -relatively- strong pull up, so you might want R1 low enough to force off state on M1.

@next-hack Now you are splitting hair strands! Over and out.

Be careful with the 12V, the Arduino can not handle 12V at its pins.
The input can be the photoresistor with a resistor to 5V (not to 12V). Use a analog input to measure the amount of light.
The output can be with a resistor to the base of the transistor.
This is an example: PighiXXX transistor
Any unused digital output can be used.
Why do you need 12V for the led ? Is it a special led ?

There are several ways to add Arduino control; the question doesn't provide quite enough information to say which is best.
One of the simplest methods is to use a diode to clamp the transistor's base voltage to at most 5 V, as shown in the following diagram.  The voltage at the IO pin cannot exceed 5 V plus one diode drop.
With this circuit, setting the IO pin to be an input leaves the LED under photoresistor control.  Setting the IO pin as a low output turns off Q1, and setting it as a high output turns on Q1.   Note, R3 should limit the current drawn from the IO pin to at most about 25 mA, so 150 to 200 Ω may be suitable.

Yay! A fellow gschem user! ;)


text:
Ams1117 worked fine on battery, up in smoke with 12v power supply
I have a circuit that worked fine on a a 12v lead acid battery for a day. Once connected to a 12v 3a power supply it didn't work properly and then the ams1117 5v burned up and so did a 3.3v one within a few minutes.
The 12v power supply is a cheap Chinese model from eBay. My meter shows 12.3v but I don't have a scope.
I understand that ripples in the output of the power supply have probably caused this but what does that mean and how has it exceeded the rating of the converter? Is there a simple fix so I can use the power supply?
Would a 12v motor or relay be susceptible to the ripples?
I'm going to run my esp8266 from a different source but I'd like to keep using the power supply for the motor and 12v relays.

Full and detailed schematic?

The 12v power supply is a cheap Chinese model from eBay - probably has **** poor mains isolation then.

What does poor mains isolation mean?  No coil? No Diodes? Does that mean there's 240v on the 12v line?

There may well be some 240v component on the output, yes. It is common for the transformer insulation to be very poor, and the class X capacitor across it to be the wrong type or even non existent.

You should take a look at some of BigClive's teardowns of cheap Chinese usb chargers on YouTube to see how bad they can be.

Once you let out that magic smoke it probably is done for.  That's what makes it work, and usually you can't get it back in.

#SDsolar I spent most of today trying to get it back in again! #Majenko, BigClive was a terrific recommendation.

Running an Arduino board with 12V is almost always too much. With only a few leds the voltage regulator on the Arduino boards gets too hot.
The best voltage is 7.5V. Then the voltage regulator has only little power dissipation and it is just high enough to turn off the USB 5V power.
Or power the Arduino board with a 5V (from a USB charger, or USB power pack) to the USB connector.
Never use a power supply that is not certified. It is a safety risk that can be avoided with a few dollars more.
The cheap power supply can have ripples, but it can for example have noise in the MHz range, or a voltage spike when turned on, or voltage overshoot when more current is required.  There can also be a coupling to the mains as @Majenko wrote. I have had a few of those. Nasty stuff!
Even with a scope, you can not tell if the power supply is really okay.
If you have a unreliable power source or a voltage that is too high, then a DC-DC converter can convert it into a nice steady voltage.
However, you should first get rid of that cheap power supply and buy a good one.

Aside from certification (i'm not even sure what a sound certification in Australia would be), how would you evaluate a power supply?

With a table full of equipment and a qualified test person. For example with a temperature controlled box to test the temperature range. With a FLIR camera. With a power analyzer (to test in what way it gets it current from the mains). With equipment that simulate different loads. Inrush currents, transient tests, and so on, and so on.

ripples in the output of the power supply have probably caused this

probably not. calculate the power dissipation on the regulator and check against its datasheet to see how much temperature rise it was going through. that would help you avoid the same mistake next time.

I will look at the power versus the data sheet but I hadn't because it worked fine for a day on a lead acid battery. How could that change based on the type of power source?


text:
Can I cause breaking the main loop from an interrupt?
Consider this simple approach to make a light work in 3 different modes: on, off and blink:
attachInterrupt(buttonVector, switchMode, FALLING);

void loop() {
  switch(mode) {
    case 0: turnOff(); break;
    case 1: turnOn(); break;
    case 2: blinkOnce(); break;
  }
}

now if switchMode is something like this:
unsigned long last_interrupt_time = 0;
unsigned long interrupt_time = 0;
void switchMode()
{
  interrupt_time = millis();
  // debounce measures
  if (interrupt_time - last_interrupt_time > 200)
  {
    mode = (mode + 1) % 3;
  }
  last_interrupt_time = interrupt_time;
}

then once the button is pressed, the mode is changed and if we were in the blink mode (mode == 2) we'll wait until the blink is done (let's say that's 2 seconds) and only then the mode is actually switched to the "off" mode. Now, can I stop whatever was in the process of current loop, break it and get the "off" instantly?
PS Of'course there can be some workarounds, like
void switchMode()
{
  interrupt_time = millis();
  // debounce measures
  if (interrupt_time - last_interrupt_time > 200)
  {
    mode = (mode + 1) % 3;
    if(mode == 0)
      turnOff();
    if(mode == 1)
      turnOn();
  }
  last_interrupt_time = interrupt_time;
}

but is there something more elegant and general? (note that if there's 4 modes: on, off, blink, blink_slowly, than this won't work)

No, you can't. An interrupt cannot affect the flow of the existing procedure except by passing data or status to it through a variable.
In multi-threading terms what you are talking about is a semaphore - a shared flag which one thread or context (the interrupt) sets and another thread or context (the main loop) reads and responds to.
If you want to respond to it fast you must write your main loop in such a way that it is possible to respond to it fast.

but is there something more elegant and general?

there are certainly ways to do what you want to do. whether they are elegant / generic is up to debate. however, they are all well known and widely used so i suppose they are at least accepted.
the simplest would be to prohibit interrupt at beginning of the switch / case block. "mode" will always be atomic.
the 2nd would be a double read on "mode".
  do {
    mode_shadow = mode; //save mode
    switch (mode_shadow) {
      case ...
    }
  } while (mode_shadow != mode); //continue to execute the switch block if mode has changed

this is a classic case to ensure atomicity without inhibiting interrupts.
the 3rd possible approach is to make the switch / case block dependent on "mode" at each step of execution. this is often used in high reliability computing where you aren't sure if a piece of data you read is ever valid. here you can ensure that through two ways: 1) affirmative: a statement is only executed if "mode" meets expectation. or 2) exclusive: all statements are not executed as soon as "mode" fails to meet expectation. This will drop you out of any of the branches of the switch / case block. atomicity isn't assured in this case but it is only violated for a short period of time.
the last I would mention would be typical of an OS where a "global" variable is maintained so that each task accesses that global variable to know what's going on. RTOS does that via messages for example. Not as real time as approach #1 / #2 above but it is fairly generic.

As for delays, I have to reimplement them, right? Something like void interruptableDelay(int milliseconds, byte *stopThis) { usigned long t0 = millis(); while(!*stopThis && millis() - t0 < milliseconds) ; }

It is possible. You could use a setjmp()/longjmp()
combination, or you could just manipulate the stack in assembly right
before returning from the interrupt. This however, makes the program
very difficult to reason about, which can easily lead to introducing
very hard to find bugs. It is certainly not a good solution for your
specific problem.
The straightforward solution to your actual problem is to make your loop
non blocking, and this is achieved with the technique explained in the
Blink without delay Arduino tutorial. Your case is a little bit more
complex, as your LED can be in three modes. I suggest you consider
instead that it can actually be in four modes by saying that, while
it's blinking, the ON and OFF states are different modes:
static enum { OFF, BLINK_OFF, BLINK_ON, ON } mode;

I would let the interrupt handler take care of the button-controlled
mode switching:
void switchMode()
{
    // Debounce.
    static uint32_t last_interrupt_time;
    uint32_t interrupt_time = millis();
    if (interrupt_time - last_interrupt_time < DEBOUNCE_TIME)
        return;
    last_interrupt_time = interrupt_time;

    // Switch modes.
    switch (mode) {
        case OFF:  // OFF -> blink
            digitalWrite(LED_PIN, HIGH);
            mode = BLINK_ON;
            break;
        case BLINK_OFF:  // blink -> ON
        case BLINK_ON:   // ditto
            digitalWrite(LED_PIN, HIGH);
            mode = ON;
            break;
        case ON:  // ON -> OFF
            mode = OFF;
            break;
    }
}

And the loop() only has to deal with the blinking:
void loop()
{
    // This only has to handle the timing of the blinking.
    uint32_t now = millis();
    static uint32_t last_toggle_time;
    switch (mode) {
        case BLINK_OFF:
            if (now - last_toggle_time > TIME_OFF) {
                digitalWrite(LED_PIN, HIGH);
                mode = BLINK_ON;
                last_toggle_time = now;
            }
            break;
        case BLINK_ON:
            if (now - last_toggle_time > TIME_ON) {
                digitalWrite(LED_PIN, LOW);
                mode = BLINK_OFF;
                last_toggle_time = now;
            }
            break;
        default:
            // Nothing to do in the other modes.
            break;
    }
}

Another option is to have the interrupt handler only set a flag to
signal the button press. Then loop() would take care off all mode
changes. This can be a good option if you want the “state machine” (the
control of the mode) contained in a single function.


text:
Arduino Due not properly detecting SD card
I have an SD breakout for my Due that isn't properly detecting the SD card. On one card, it cannot detect at all, and the other it says that the SD isn't formatted with FAT, even though it is. Here is my wiring:

simulate this circuit – Schematic created using CircuitLab
So, I broke out my oscilloscope and started probing lines. One in specific I got worried about, is the SCK line and it's bouncing, specifically from the inductance of the jumpers. This is the SCK line from my scope:

My reaction was to put some buffer caps on there, and so I put 2x 300pf capacitors in parallel for a total of 600pf. This is the waveform as measured after I put in the debouncing caps:

This is much more tolerable, and I can accept this level of bouncing for the SCK line, as I doubt that there will be much misfiring. I upload the SD card test sketch that's on the website, here is the output:
Initializing SD card...Wiring is correct and a card is present.

Card type: SD2
Could not find FAT16/FAT32 partition.
Make sure you've formatted the card

What does The Arduino Due have that makes it hard to detect the card?

Remove the caps please. Perhaps the scope itself creates the overshoot.
The Due is not special. It should work.
Can you tell what kind of SD memory cards and which SD module you use ?
Try the SD Formatter, see the post at the Arduino.cc forum: "Don't Format SD cards with OS utilities!".
Some SD memory cards are not compatible. Perhaps you have more luck with an older 1GB or 2Gb SD memory card.

I don't think the scope itself has overshoot. The Resistance of the scope is 10M, and the caps help the inductions' load, as where they wouldn't with the scope being the inductive load. I'll try the formatter. Thank you!

Tried both. no cheese

Do you have long wires ? Or a breadboard with bad contacts ? Or a low voltage level of the power ? Everything runs at 3.3V ?

Actually, the SD card breakout has a Logic level translator that translates 3.3 to 1.8 volts. The wires themselves are long (2x4"). Another thing that I noticed is that the MOSI line never seems to go too low while transmitting signals (while my oscilloscope is watching). It seems to be always high.

That not very long, I hope it is not a flat ribbon cable, those cause a lot of crosstalk. Can you give a link to your SD card ? Every SD card and SD socket I use with Arduino is 3.3V. Some cards work with 1.8V as well, but for the Arduino you better stick with the old fashion 3.3V.


text:
Delay a part of the void loop
I have two different programs written for my Arduino. One checks the room temperature every 5 seconds. The other one looks for IR remote signals.
I would love to combine those 2 programs, yet the problem is the delay from the room temperature sketch.
If I would combine them. it means my IR script won't be working for a full 5 seconds (because of the delay of the room temperature script) then it will be able to receive a fraction of a second and then the temperature sketch goes again.
#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
int led = 12;
const int inPin = 0;

void setup() {
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop() {
  int value = analogRead(inPin);
  float millivolts = (value / 1024.0 ) * 5000;
  float celsius = millivolts / 10;
  Serial.println(celsius, 1);
  delay(5000);
  if(irrecv.decode(&results)) {
    //this checks to see if a code has been received
    if(results.value == 0xFF6897) {
      //if the button press equals the hex value 0xC284
        digitalWrite(led, HIGH);
        // turn the LED on (HIGH is the voltage level)
        delay(1000); // wait for a second
        digitalWrite(led, LOW);
        // turn the LED off by making the voltage LOW
        delay(1000); // wait for a second//do something useful here
    }
    irrecv.resume(); //receive the next value
  }
}

Does anyone know how to keep the IR part active and the temperature measure every 5 seconds, and do this simultaneously?
Or do I need another Arduino?

Take a look at the BlinkWithoutDelay example bundled with the IDE. It shows you exactly what you need to know.

that was kinda what I was looking it is not working flawless yet, but I think it will work Thank you!

EDIT: Modify the code according @Edgar's comment.
Check this alternative. The idea is executing code every 5 and 1 seconds.
The blink is true when you need the LED blinking. I don't know how long will you need to keep it blinking, but this keeps it as long as results.value keep being equals to 0xFF6897.
#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
int led = 12;
const int inPin = 0;

void setup() {
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop() {
  static boolean blink = false;
  static unsigned long startTemp = 0;
  static unsigned long startBlink = 0;
  unsigned long msTime = millis();

  //  Check for room temp every 5 seconds.
  if (msTime - startTemp >= 5000) {
    startTemp = msTime;
    int value = analogRead(inPin);
    float millivolts = (value / 1024.0 ) * 5000;
    float celsius = millivolts / 10;
    Serial.println(celsius, 1);
  }

  //  Blink every 1 second
  if (msTime - startBlink >= 1000 && blink) {
    startBlink = msTime;
    int state = digitalRead(led);
    digitalWrite(led, !state);
    //  Change blink to stop blinking after one pass (HIGH/LOW).
    //  Modify if you need to keep blinking for longer time.
    blink = (state == LOW);
  }

  if(irrecv.decode(&results)) {
    blink = (results.value == 0xFF6897);
    irrecv.resume(); //receive the next value
  }
}

this one looks very promising I will give this a try

@Anton. I didn't test the sketch and probably you have to adjust the blink variable to suit your needs.

Testing for millis() % 1000 == 0 is not a good idea. The millis() counter is updated every 1024 µs: most of the time it is incremented by 1, but once every 42 increments (roughly) it is incremented by 2. Thus you are going to miss some blinks.

so 1000 or 999  should fix it?

@Anton. Check the new edited version that follows Edgar's comment.

does anyone know how to keep ...

think about ways to conditionalize execution on time elapsed. I showed a short while ago ways to construct a software timer and you may want to look into that.