body:
We are working on a project that requires a temperature sensor to tell the Arduino Due to turn a digital pin to HIGH (3.3V) to active a relay so a heating pad can be powered on.

We have diagnosed all possibilities and the only explanation as to why the switch will not active is the digital pins are only reading 1.8 V on the relay.

We are using a JQC-3F(T73) relay. We are using two digital pins to give it plenty of voltage and amps to switch on and off when needed.

so any explanation as to why it isnt working? thanks.

title: Why would digital outputs on Arduino Due be less than 3.3V?

Answers: 1

body:
The output impedance for the MCU used in the Due is about 46ohm. Along with the relay's impedance this forms a voltage divider that results in a final voltage that is lower than the unloaded voltage from the output.

In any case, **do not** connect an inductive load directly to a MCU; use a driver such as a ULN2803 instead, being certain to connect the flyback connection of the driver chip properly.


body:
I am using Digispark ATTiny85 and i need to send and receive data through the serial port of my computer.
Does anyone have an idea as to how do i proceed with sending STRINGS and NUMBERS through the serial port ??

I have read that the ATTINY 85 does not have a serial port.
If that is the case is there any alternative ??

title: Digispark Serial Port Communication

Answers: 5

body:
Its quite simple, you need a program on your PC that will send data (that you type) to the serial port.

If you are on Windows then you want a 'Terminal Emulator' program, I don't know what its called on Linux but it will be along the same lines.

If you are using the Arduino IDE then there is already something built in, the Serial Monitor will do the job.  You don't even need to be using the IDE for programming you should be able to use the monitor anyway.

Also you can write your own application to do it, but don't do that unless you really have to.

body:
The ATTiny85 does not have a hardware serial port, but you can use the Arduino SoftSerial library to implement a serial port in software. Have a look at [SoftSerial][1]. Or for better performance, including full duplex operation (transmit and receive at the same time) [this][2] may be better.

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerial
  [2]: https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html

body:
> have read that the ATTINY 85 does not have a serial port.

It depends on your definition of serial port.

From a hardware perspective it has a usi. That can be configured as a uart. Whether it fits your need or not is up to your application. Read the datasheet to be sure.

body:
You may use `DigiCDC` to virtually create a serial device. It's slow but does the job as mentioned in [this][1] article.

A serial-echo program would look something like this:
```c++
#include <DigiCDC.h>

void setup() {
  SerialUSB.begin();
}

// the loop routine runs over and over again forever:
void loop() {

  if (SerialUSB.available()) {
    SerialUSB.write(SerialUSB.read());
  }

   //SerialUSB.delay(10);
   /*
   if you don't call a SerialUSB function (write, print, read, available, etc)
   every 10ms or less then you must throw in some SerialUSB.refresh();
   for the USB to keep alive - also replace your delays - ie. delay(100);
   with SerialUSB.delays ie. SerialUSB.delay(100);
   */
}
```

  [1]: https://digistump.com/wiki/digispark/tutorials/digicdc

body:
You have a number of options.

 1. Go the DigiCDC/SerialUSB path. Or whatever replaces it.

 2. (harder), use an I2C to serial bridge, SC16IS750. This has a 64 byte buffer limit so input should be short, typically [Esc] or "U" (for firmware update), but basic menu control is possible.

 3. Use SendOnlySoftwareSerial, on a free pin as Tx and hook up an FTDI cable or a serial to USB adapter. This is good for PuTTy, Screen, MiniCom etc.

NB. I have no issues with blowing away the bootloader and just using the usb for power to get option 3 to work.


body:
I set out to see how much space some arrays have. I used this test code

    bool state = false;

    uint16_t BuffA[46000];
    uint16_t BuffB[20000];
    uint16_t BuffC[20000];
    uint16_t all = 0;

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

    void loop(){
    if (state==false){
    Serial.println(sizeof(BuffA));
    Serial.println(sizeof(BuffB));
    Serial.println(sizeof(BuffC));
    all = sizeof(BuffA) + sizeof(BuffB) + sizeof(BuffC)
    Serial.println(all);
    state = true;
      }
    }

I got this answer from the serial:

    92000
    40000
    40000
    40928

 1. Why are the results doubled from those i initiated? Shouldn't the first one be 46kb and the other two 20kb?
 2. Why is the last value only 40928?
 3. The RAM of Due is 96kb. Does this mean that with the initialization of only three arrays it's almost full? Ifi crossed the RAM limit, would the IDE throw an error?
 4. If i still need more RAM, can i use and external one with Due for high speed RAM acquisition?

title: Sizeof variables and Due's RAM

Answers: 3

body:
The [`sizeof`](http://www.cplusplus.com/faq/sequences/arrays/sizeof-array/) operator's result is *number of bytes*, not number of array elements.  Your arrays in the program above have two bytes per element, hence twice as many bytes as elements.

If you want to report the *number of elements*, divide the total size by the number of bytes per element.  For example:

    nElements = sizeof BuffA /  sizeof BuffA[0];

As `uint16_t` variables have 16 bits, the total `all` will exceed the maximum (65535) that `all` can hold.  Consider using `uint32_t` type for that variable. For example:

    uint32_t all = sizeof BuffA/sizeof BuffA[0] + sizeof BuffB/sizeof BuffB[0] + sizeof BuffC/sizeof BuffC[0];

Because the type of `sizeof` is [`size_t`](http://www.cplusplus.com/reference/cstring/size_t/), a “type able to represent the size of any object in bytes”, one need not cast any of addends to `uint32_t` for the result to not overflow.

body:
`sizeof` doesn't return the number of elements. It returns the number of **bytes**. Since they are `uint16_t` arrays each element is 2 bytes - hence twice the size.

The reason your last number is only 40928 is because of integer wraparound. You only provide a 16-bit unsigned variable to store it in, so all you get is the lower 16 bits of the answer.

    92000 + 40000 + 40000 = 172000

    172000 in hex is 0x29FE0

    0x29FE0 truncated to 16 bits is 0x9FE0

    0x9FE0 in decimal is 40928.

> The RAM of Due is 96kb. Does this mean that with the initialization of only three arrays it's almost full? Ifi crossed the RAM limit, would the IDE throw an error?

It would, but you aren't actually using the arrays for anything, so the compiler threw them away.

> If i still need more RAM, can i use and external one with Due for high speed RAM acquisition?

There are ways of interfacing the SAM3X with external RAM, but I don't thing the Due exposes all the signals you need. I would change to a chip with more RAM, such as the PIC32MZ with 512kB of RAM and 200MHz operation.

body:
1. A variable of uint16_t has 16 bits, thus two bytes, so for e.g. BuffA[46000] this means 46000 * 2 = 92000 bytes.

2. The variable all is also 16 bits and can contain only as max value 65,535.
92000 + 40000 + 40000 = 172000 bytes but that does not fit in 16 bits.
Therefore the value is clipped ... make it a uint32_t variable.

3. The total is 172.000 bytes, this mean it will not fit in 96KB. What are the value ranges you want to store? If the values are max 255

4. You can use extra RAM. DRAM is very hard to use, EEPROM is only usable when you don't have to write it too often. Otherwise use SRAM, e.g. the 23LC1024's which can store 128 KB RAM and are only DIP8.


body:
I am onto a project where a need more memory. I saw the 23LC1024 chips are very popular with the Arduino DUE.

A very helpful person told me he did some timing tests on the 23LC1024 and a page read/write of 32 bytes costs about 100 μs.

I am interested in real time audio manipulation application (using the Arduino Due's ADCs and DACs).

This time of 100μs per 32 bytes seems a lot for the application, though i am not sure.

Are there benchmarking tests of the Arduino DUE for the time it takes to read/write to its memory, so i can compare with this chip and decide what to do?

title: Time to read/write memory on the DUE

Answers: 0


body:
I'm building a [complex I2C-based networking protocol][1] and have noticed that the Wire.onReceive() handler is called both for I2C read and write operations. When the master writes to the slave, it is called as you'd expect. But it also seems to be invoked when the master reads from the slave which is unexpected.

Ideally, I'd like a transaction with both a read and a write - e.g. the master writes a value (for instance a variable argument) and then reads back from the slave the result (for instance, the lookup of that variable.)

Compiled on the SAMD21 ArduinoCore, the following programs generate this result:

    1400,700
    >>> x is
    <<< hello
    >>>
    >>> x is
    <<< hello
    >>>
    1404,702
    >>> x is

Showing that the onReceive is called twice as often as onRequest.

I don't see this behavior documented anywhere.

Master:
<!-- language-all: lang-cpp -->
    #include <Wire.h>

    void setup()
    {
      Wire.begin();        // join i2c bus (address optional for master)
      Serial.begin(9600);  // start serial for output
    }

    void loop()
    {
      Wire.beginTransmission(4); // transmit to device #4
      Wire.write("foobar");        // sends five bytes
     // Wire.write(3);              // sends one byte
      Wire.endTransmission(true);    // stop transmitting

      Wire.requestFrom(4, 6);    // request 6 bytes from slave device #2

      while(Wire.available())    // slave may send less than requested
      {
        char c = Wire.read(); // receive a byte as character
        Serial.print(c);         // print the character
      }

      delay(500);
    }

Slave

    #include <Wire.h>

    void setup()
    {
      Wire.begin(4);                // join i2c bus with address #4
      Wire.onReceive(receiveEvent); // register event
      Wire.onRequest(requestEvent);
      Serial.begin(9600);           // start serial for output
    }

    long inCount = 0;
    long outCount = 0;

    void loop()
    {
      char c[200];
      snprintf( c, 200, "%d,%d\n", inCount, outCount );
      Serial.print( c );
      delay(1000);

    }

    // function that executes whenever data is received from master
    // this function is registered as an event, see setup()
    void receiveEvent(int howMany)
    {
    inCount++;

      Serial.print( ">>> ");
      while(1 < Wire.available()) // loop through all but the last
      {
        char c = Wire.read(); // receive byte as a character
        Serial.print(c);         // print the character
      }

      Serial.println();         // print the integer
    }

    // function that executes whenever data is requested by master
    // this function is registered as an event, see setup()
    void requestEvent()
    {
      Serial.println( "<<< hello ");

      outCount++;
      Wire.write("hello "); // respond with message of 6 bytes
                           // as expected by master
    }

  [1]: http://hackaday.com/2017/05/27/hackaday-prize-entry-makernet/

title: Why is Wire.onReceive() called during requests?

Answers: 0


body:
I'm trying to send an array of numbers from python to Arduino over the serial connection. I can reliably read a small incoming set of numbers (for example 123435678) from python, which I can then parse since I know how many digits are supposed to be in each number (for example, 1, 23456, 78). I do this with my Arduino code:
<!-- language-all: lang-cpp -->

    void getInput() {
         char buff[9];
         int field1;
         char field2[6];
         char field3[3];

      Serial.readBytes(buff, 8); //read 8 bytes from the Serial port
      buff[9] = '\0'; //null terminate the string we just read
      Serial.println(buff); //check that we got it
      for(int i=0; i<buff_len;i++) { //now we divide up the string into separate numbers
        if(i==0) {
          field1 = buff[0] - 48; //turn it into an int using ASCII
        }
        if(i>=1 && i<6) {
          field2[i-1] = buff[i];
          field2[5] = '\0';
        }
        if(i>=6) {
          field3[i-6]=buff[i];
          field3[2] = '\0';
        }
      }
      for(int i=0;i<buff_len;i++) { //clear the buffer
        buff[i]=0;
      }
    }

But if I wanted to send a whole array whose contents I don't know in advance, for example like this:

    for i in range(200):
        ser.write(i)

What's the best way to get these numbers to Arduino and file them away in an int array? Should I make the array in python first as a `numpy.linspace()` and send that?

title: Fastest way to read an array of numbers from python

Answers: 1

body: If you don't know the length of the data then you need to be sending start and end markers so your other code can tell where the transmission starts and ends.  I usually use < and >, so the data packet might look like <12345678>.  You don't have to use those particular characters, just pick something that you know won't show up in your data.


body:
I'm writing a sketch for a Wemos D1 Mini to display a web page. This works and I can get Unicode characters to display, but if I try to use ones with surrogate pairs like 🔊 I get a compile error;

      s += "\uD83D\uDD0A";
Error
>\uD83D is not a valid universal character

How can I get this character in my code?

title: Use a Unicode surrogate pair character in Arduino IDE

Answers: 2

body:
After some trial and error, I got it using the python style `u"\U0001F50A"` without the leading u of course

      s += "\U0001F50A";

Too bad I didn't think about googling the error msg, would have saved me some time.

body:
There is a nifty new feature in C++11 called [string literal](http://en.cppreference.com/w/cpp/language/string_literal), this example shows how to use it with any single line or multi line or utf8 text. You just define starting and ending sequence, in following case `---` (starting sequence becomes `R"---(` and ending sequence `)---"`) and make sure that this sequence does not appear in encapsulated text. This is great for integrating websites into arduino projects:

    static const char _index_html[] PROGMEM = R"---(
    <html>
    <head>
    <link rel="icon" type="image/png" href="/favicon.png"/>
    </head>
    <body>
    ...
    </body>
    </html>
    )---";


body:
Has anybody else noticed that the Arduino Mega pins 20/21 are exceedingly unreliable over long periods of time? It has been the case four times now where I have hooked up no more than 3 I2C devices to these pins and had them fail after approx. 10 days of light use on average.

For example, my team and I had 3 sensors hooked up and were successfully running tests for about two weeks, then right before our launch, I2C stopped working entirely, returning completely incorrect (all zero) data every time.

Again, I have had this issue four separate times in the past, some where pull-up resistors are present, others not.

I seem to be unable to find related information on the web.

Has anyone else noticed this?

title: Arduino Mega - I2C pins (20/21) unreliable

Answers: 1

body:
The I2C pins on the Arduino Mega 2560 board are 100% reliable, but you have to use them correctly.

The Wire library could halt when something is wrong with the hardware I2C bus. In that case the sketch stops. The Wire library should have timeouts programmed in case something is wrong with the hardware, but sadly it doesn't have timeouts.

**Hardware**
The hardware I2C bus on the Arduino Mega 2560 board is a 5V I2C bus, because the Arduino Mega 2560 has 10k pullup resistors to 5V for SDA and SCL.
The wires for I2C can only be short. Long wires will not work.
The worst thing is when SDA and SCL are in a flat ribbon cable next to each other. The crosstalk between SDA and SCL will make the I2C very unreliable.
Because it is a 5V I2C bus, you may not connect 3.3V sensors to that 5V I2C bus. In that case you need a level converter.
The total value of all pullup resistors in parallel should not be too high (more sensitive for electrical noise, longer wires are not possible) and not be too low. The I2C specificiation is maximum 3 mA pulling of down current to get the signal low.
Everything that is connected to the I2C bus must have proper power supply. If one sensor has a power supply that fails, then that sensor will probably pull down the SCL and SDA signals.
A test with a breadboard might fail, due to bad contacts of the breadboard.

**Software**
The Arduino Wire library is often used in a wrong way.
If one of the sensors is an Arduino board as a I2C slave, then the code for the slave must be done right, because there are many ways to do it wrong.
You could check the return value of every Wire.endTransmissions for an error, and check every return value of Wire.requestFrom for the amount of data that is received.

If you tell us everything about the sensors, the wires (with photos), the logic level converters, the sketch, and so on, then we can tell you what the problem is.


body:
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

title: How to get DHT11 temperature/humidity sensor to update on Arduino Uno

Answers: 1

body:
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][1] example shows how to use millis.

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


body:
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);
    }

title: for loop reads pots, passes value to PWM pins, can this be in the same for loop?

Answers: 2

body:
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.

body:
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:

<!-- language-all: c++ -->

    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.


body:
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.

title: Arduino Zero timer setup

Answers: 2

body:
> 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.

body:
BOTTOM UP

The arduino Zero uses an Atmel samd21 µController. [This video](https://www.youtube.com/watch?v=FTARNR9SLMs) 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](http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf)
- Consult the [Atmel Software Framework(ASF)](http://asf.atmel.com) 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](https://github.com/arduino/ArduinoCore-samd). 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 ;)


body:
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](https://controllino.biz/controllino/maxi/) 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!

title: Controllino Debugging

Answers: 1

body:
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.


body:
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.

title: Lowest memory consumption for arrays

Answers: 2

body:
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

body:
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:

<!-- language-all: c++ -->

    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);


body:
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);

title: DHT11 is not reading Temperature and Humidity when Arduino is powered on using DC power Supply (12V)

Answers: 1

body:
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/

  [1]: http://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-arduino/


body:
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.

[![][1]][1]

**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][2] and the electronic layout inspired from [here][3]. 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)][4] 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

 1. other thermistors (every single one behave similarly as the orange line in the figure 1)
 2. other digital temperature sensors (every single one behave similarly as the yellow line in the figure 1)
 3. 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)
 4. we switched the pad resistor, no effect
 5. other arduinos (did not changed anything, every single one was repeatedly demonstrating the same behaviour )
 6. 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;
    }

  [1]: https://i.stack.imgur.com/Nd0Wc.png
  [2]: https://playground.arduino.cc/ComponentLib/Thermistor2
  [3]: https://learn.adafruit.com/assets/571
  [4]: http://www.omega.com/temperature/pdf/44000_THERMIS_ELEMENTS.pdf

title: Analog thermistor readings are wrong

Answers: 3

body:
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.

 1. 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 ?
 2. 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 ?
 3. 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.
 4. 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.
 5. The NTC could cool down via the metal legs.
 6. 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)

body:
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), ...

body:
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][adc] 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.

[adc]: https://www.logre.eu/wiki/Réponse_de_l'ADC_d'un_Arduino/en


body:
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?

title: time delayed LEDs

Answers: 2

body:
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;
      }
    }

body:
Here is one way to do it.

1. Set up two output compare channels. They are identical except that they have slight different periods.
2. 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.


body: I want to power up arduino through Vin port , what should be the input voltage ?

title: Can I power arduino uno R3 with 9v battery through Vin?

Answers: 2

body: 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 ?

body:
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 ;)


body:
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.

title: Data not updated in real time

Answers: 2

body:
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.

body:
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.


body:
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.

title: Arduino UNO IR blaster - storing codes in PROGMEM

Answers: 1

body:
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][1].
Nick Gammon had made a great [tutorial about PROGMEM][2].
All the PROMEM functions are in <[avr/pgmspace.h][3]>

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, ...);

  [1]: https://www.arduino.cc/en/Reference/PROGMEM
  [2]: http://www.gammon.com.au/progmem
  [3]: http://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html


body:
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:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/K7CWd.png

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.

title: 433 MHZ connection between two Arduino (nano,uno) fails after some time

Answers: 2

body:
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.

body:
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.


body:
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?

title: Is it ok to declare variables inside timer interrupts?

Answers: 2

body:
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).

body:
> 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.


body:
I'm currently attempting to take readings from 10 thermocouples using an Arduino Mega. I've been using [MAX31850 1Wire Thermocouple Modules][1] (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.

  [1]: https://cdn-shop.adafruit.com/datasheets/MAX31850-MAX31851.pdf

title: High Speed Thermocouple Readings

Answers: 3

body:
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.

body:
From Table 6 on page 22 of the data sheet for [MAX31850 1Wire Thermocouple Modules](https://cdn-shop.adafruit.com/datasheets/MAX31850-MAX31851.pdf), 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.

body:
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][1] 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.

  [1]: https://www.adafruit.com/product/269


body:
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

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/yICKe.jpg

title: Help with code. Fade in LEDs from off (shift register)

Answers: 1

body:
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.


body:
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.

title: How can I pass a long as parameter and get a char array in return?

Answers: 5

body:
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.

body:
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][1]):

    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!

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga5a3fce5fbd20140584619ba9aed09f75

body:
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()`](http://www.atmel.com/webdoc/avrlibcreferencemanual/group__avr__stdlib_1ga5a3fce5fbd20140584619ba9aed09f75.html), 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()`](http://www.atmel.com/webdoc/avrlibcreferencemanual/group__avr__stdio_1ga77070c245d4ca4f7ec7d7144260fb875.html):

    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`](https://www.arduino.cc/en/Reference/StringObject) 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.

body:
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][1]

  [1]: http://www.hobbytronics.co.uk/arduino-float-vars

body:
> 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.


body:
I'm using the [SDFat library](https://github.com/greiman/SdFat) 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.

title: SdFat Library what is dir_t*?

Answers: 2

body:
`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);

body:
> what is dir_t*?

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


body:
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**.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/QcoNh.png

title: Photoresistor and another switch

Answers: 3

body:
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][1]
Any unused digital output can be used.
Why do you need 12V for the led ? Is it a special led ?

  [1]: http://www.pighixxx.com/test/portfolio-items/control-lcd-backlight/

body:
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.[![schematic with diode clamp added][1]][1]  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.

  [1]: https://i.stack.imgur.com/vsmqW.png

body:
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.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/mea5m.png)

<!-- End schematic -->


body:
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.

title: Ams1117 worked fine on battery, up in smoke with 12v power supply

Answers: 2

body:
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.

body:
> 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.


body:
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)

title: Can I cause breaking the main loop from an interrupt?

Answers: 3

body:
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.

body:
> 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.

body:
It is possible. You could use a [setjmp()/longjmp()][setjmp]
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:

<!-- language-all: c++ -->

    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.

[Blink without delay]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

[setjmp]: http://www.nongnu.org/avr-libc/user-manual/group__setjmp.html


body:
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:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/OGFmZ.png)

<!-- End schematic -->

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:

[![enter image description here][1]][1]

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:

[![enter image description here][2]][2]

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?

  [1]: https://i.stack.imgur.com/1hoBv.png
  [2]: https://i.stack.imgur.com/uFnQl.png

title: Arduino Due not properly detecting SD card

Answers: 1

body:
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!][1]".
Some SD memory cards are not compatible. Perhaps you have more luck with an older 1GB or 2Gb SD memory card.

  [1]: https://forum.arduino.cc/index.php?topic=228201.0


body:
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?

title: Delay a part of the void loop

Answers: 2

body:
> 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.

body:
**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
      }
    }