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

I used this tutorial here and decided it to overcomplicate the pattern. For further learning. My code in theory should start the LEDs at a low brightness and fade them in using this code. My expected output is as follows.

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

This is the loop that fades the LEDs in.

    for (byte b = 1; b < 255; b++) {
      setBrightnessUp(b); //sets the brightness up function
      delay(20);
    }

This is the function:

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

However at this time it appears to be getting into my loop but not increasing the brightness at all. When the code first runs, the LEDs are on but at a minimum brightness. The rest of the code including the fade out at the end works fine.

Fade out functions:

    for (byte b = 255; b > 0; b--) {
      setBrightness(b); //sets the brightness function
      delay(20);
    }

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

Here is the complete code. Excuse the over commenting it helps me learn:

    //sets pin out for control pins on shift register

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

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

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

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

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

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

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

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

Board layout

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

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

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.


sender: user

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

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

Example:

    long myLong = 12345L;
    convertToCharArray(myLong); //returns an array with the digits of myLong
BTW I'm working with Arduino IDE.

sender: assistant

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.


message:
SdFat Library what is dir_t*?

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.

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.


message:
Photoresistor and another switch

I am using the circuit diagram below to turn ON/OFF the lights using Photo-resistor.

How can I use the Arduino to bypass the Photoresistor effect?
Let say I want to turn ON the lights even though Photoresistor doesn't want to.

**Take note the 12V source** is required by the LED. Knowing that Arduino must work with **max 5V**.

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

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

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


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

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

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.


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

Consider this simple approach to make a light work in 3 different modes: on, off and blink:

    attachInterrupt(buttonVector, switchMode, FALLING);

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

now if `switchMode` is something like this:

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

then once the button is pressed, the mode is changed and if we were in the blink mode (`mode == 2`) we'll wait until the blink is done (let's say that's 2 seconds) and only then the mode is actually switched to the "off" mode. Now, can I stop whatever was in the process of current loop, break it and get the "off" instantly?

PS Of'course there can be some workarounds, like

    void switchMode()
    {
      interrupt_time = millis();
      // debounce measures
      if (interrupt_time - last_interrupt_time > 200)
      {
        mode = (mode + 1) % 3;
        if(mode == 0)
          turnOff();
        if(mode == 1)
          turnOn();
      }
      last_interrupt_time = interrupt_time;
    }

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

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


message:
Arduino Due not properly detecting SD card

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

<!-- 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

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


message:
Delay a part of the void loop

I have two different programs written for my Arduino. One checks the room temperature every 5 seconds. The other one looks for IR remote signals.

I would love to combine those 2 programs, yet the problem is the delay from the room temperature sketch.

If I would combine them. it means my IR script won't be working for a full 5 seconds (because of the delay of the room temperature script) then it will be able to receive a fraction of a second and then the temperature sketch goes again.

    #include <IRremote.h>

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

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

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

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

Or do I need another Arduino?

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
      }
    }


message:
15x15x15 LED cube with thermal sensors

I'm trying to wrap my head around a public art project that I've recently received funding for, and I'm hoping that someone here can help me with a bit of guidance.

The concept I'm working on is a kind of 'digital campfire' that builds and falls in intensity as people approach and depart.

The way I imagine it working is with a 15x15x15 RGB LED cube that plays fire-like animations of varying intensities in response to the presence of nearby people - detected by a 360 degree array of thermal sensors (probably something like Omron D6T sensors, rather than IR movement sensors).

Full disclosure: I'm an Arduino noob. I've tinkered with LEDs and soldering, but even the thought of building a non-responsive 4x4x4 LED cube hurts my brain. That said, I have a couple of months up my sleeve, a bit of cash, and a willingness to forge new neural pathways to get this done.

My main questions at this point are:

- Can an Arduino even handle the processing power required to run a thermal activated 15x15x15 LED cube, even with multiplexing?
- I'm considering 15-cubed because I want the object to have a fairly large physical presence, and have a relatively high definition. Is there any game-changing reason I should seriously consider something smaller? I anticipate being able to connect to a 240v power outlet (I'm in Australia), but running off battery would be ideal.
- How difficult would it be to build a 360 degree thermal sensor array consisting of, say, 8 separate thermal sensors? The programming is clearly beyond me, and I expect to out-source this...

Any help or suggestions would be hugely appreciated. And don't be gentle – if my expectations need to be 're-aligned' to something closer to reality, I'd rather that happen sooner than later.

Cheers,

Adam

body:
The answer to "Can an Arduino even handle the processing power" is probably No, but no one can really answer because you have not specified the problem.

Just for starters you have >3k LEDS, if you want to control RGB that means ~10k devices.

To operate at moderate brightness (10mA per LED) you will need at least a 35A power supply. This will require external high power circuitry to switch/control.

Do you need to individually control each LED? To control 10k devices you will need serious external circuitry.

Do you need to control brightness or just switch individual devices on/off?

You could probably achieve a solution, but 15 modules each controlling 15*15 LEDS may be achievable, 32 or 64 is probably more realistic.

Either way soldering by hand would be impractical, you need to design a board for each module.

You could use an Arduino on each module, but a ATMega chip would achieve the same end, without the unnecessary peripheral circuitry.


body:
firstly we need a bit more detail, I'm assuming by saying a 15x15x15 cube you actually mean a cube with a 15x15 array of LEDs on each face, so you would have a total of 1350 LEDs. we also need to know if you intend to have just single colour LEDs of whether you want multi colour or even RGB with full control (like a monitor)
assuming you only want single colour with on/off control then look into the MAX7219 or MAX7221 IC's, these can be bought with LED matrix's already fitted, and each IC can drive an 8x8 matrix of LEDs, so you would need 4 ICs to do each side (these can be daisy chained) and so a total of 24 ICs for the whole cube.
but note that that would allow for 16x16 on each side.

the arduino can easily drive this many, what you need to consider is how often you want the LEDs to "update" i.e. the frame rate. the more you try and drive the slower you can drive it, however from experience i believe the arduino could easily drive that many LEDs in this arrangement.

on the subject of current the MAX72xx ICs work by multiplexing the output for you, so at most only 8 out of each 64 LEDs are on at any one time, so if you drive each at 10mA your maximum current would be 1.7A, probably a bit much for batteries (unless you use something big, AA's or a 9V won't cut it.) but still reasonable.

if you wanted individual brightness control things get more complicated, and the rate at which you could update the outputs would sharply drop off. I still think it would be feasibly for this many LEDs but you may find your update rate is only 10-20 times a second so any motion may not appear very smooth.
but this way will require a lot more wiring, and will be a lot more complex to program.

if you want full RGB control then the amount of connections and components required would grow to ridiculous proportions, you would need 3 connections plus power to each LED so about 4000 connections between your control circuitry and your LEDs, and your current requirements would go through the roof due to so many LEDs being on at the same time.

and if I read wrong and you actually want 3375 LEDs on each face, for a total of 20250 LEDs then this becomes extremely impractical, even with output multiplexing (mentioned above in the MAX72xx bit) the current requirements would be insane. not to mention the time taken to update all those LEDs would drastically slow down how quickly you could update them. even at a max data rate of 30MHz (SPI) you will probably only be able to update your LEDs at around 1-2 times a second, and there would not be enough RAM in the arduino to remember the previous output states when you are calculating your next ones.

a raspberry pi may be more suitable from that point of view, but the current and the update rate would still be a problem.


message:
serial data gets spoiled

I use this small program on my Raspberry Pi to recieve a string sent by my arduino.

    import time
    import serial

    ser = serial.Serial('/dev/ttyACM0', 9600)

    def check_for_command():
        bytestoread = ser.inWaiting()
        if bytestoread != 0:
            temp = ser.read(bytestoread)
            print(temp)

    while 1:
        check_for_command()
        time.sleep(0.1)

the code on the arduino is rather simple:

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

    void loop(){
    Serial.println(“Hello Pi”);
    delay(2000);

the annoying part is. I recieve this:

> b'Hello Pi\r\n'

instead of the clean
>
> Hello Pi

How do I get rid of those extra bits without using a list for each character.

Thank in advance!

body:
The `b` prefix in Python 3 just means that it is a `bytes` literal. It's not part of the output, that's just telling you the type.

The `\r\n` is a common Carriage-Return and Newline line-ending characters. You can remove that from your string by calling `strip()`.

Since these are floating-point numbers being returned, I'm guessing you're going to want to use them in some way after they are read, too:

    import serial

    ser = serial.Serial('/dev/ttyACM0', 9600)
    while True:
       value = float(ser.readline().strip())
       print('New value is {0:0.2f}'.format(value))

See also:

- [What does the 'b' character do in front of a string literal?][1]

  [1]: https://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal


body:
Use this line

    temp = ser.readline(bytestoread).decode('ascii')

instead of

    temp = ser.read(bytestoread)


message:
How to create a String with Temperature Value From An int Value

The following code is for a temperature controlled relay which turns a DC fan on and off when the temp threshold is breached. I'm using a DS1820 Temperature sensor and the code for this has several variables including WholeDegrees & FractDegrees Which are the whole number of degrees and the fractional number of degrees. I'm wanting to be able to set the threshold to lets say 23.25 Degrees so that when the temp rises above that then the fan comes on.

I'm trying to do this by using a two condition if statement howeveer, the FractDegrees are causing me a problem because if condition 1 is true and and the WholeDegrees is greater than 22 but the second condition the FractDegrees is lower than 25 then the relay turns the fan off again. So I get the fan turning on for a split second and then off, then on & off again which isn't a problem when the temperature sensor is at roughly the temp I want to set the threshold at but when it's at say 40 Degrees The fan cuts in and out whilst cooling until the sensor is roughly at the threshold value again.

I have kinda had a go already but failed which you might see in the //'d out code but is there a way that I can put these two values WholeDegrees & FractDegrees into a string so that I could have a string with the temp value and then use a single condition if statement to turn the fan on and off by checking the strings value instead?? I'd want the string to be "WholeDegrees.FractDegrees" So that I could just use the if statement to ask if the temp was greater than 23.25 degrees.
The code I tried returned a value of "0.0" which obviously wasn't the temperature value but I couldn't understand why......

    #include <OneWire.h>
    int inPin = 10; // define D10 as input pin connecting to DS18S20 S pin
    OneWire ds(inPin);
    int relay1 = 8; // define relay Signal Pin to Digital Output 8
    //String stringOne, stringTwo, stringThree;

    void setup(void) {
      Serial.begin(115200);
      pinMode(relay1, OUTPUT);

    }

    void loop(void) {
      int HighByte, LowByte, TReading, SignBit, Tc_100, WholeDegrees, FractDegrees;
      byte i;
      byte present = 0;
      byte data[12];
      byte addr[8];
      //stringOne = String(WholeDegrees);
      //stringTwo = String(".");
      //stringThree = String(FractDegrees);

      if ( !ds.search(addr)) {
        ds.reset_search();
        return;
      }

      ds.reset();
      ds.select(addr);
      ds.write(0x44, 1);

      delay(250);

      present = ds.reset();
      ds.select(addr);
      ds.write(0xBE);

      for ( i = 0; i < 9; i++) {
        data[i] = ds.read();
      }
      Serial.print("Temperature: ");
      LowByte = data[0];
      HighByte = data[1];
      TReading = (HighByte << 8) + LowByte;
      SignBit = TReading & 0x8000;
      if (SignBit)
      {
        TReading = (TReading ^ 0xffff) + 1;
      }
      Tc_100 = (6 * TReading) + TReading / 4;
      WholeDegrees = Tc_100 / 100;
      FractDegrees = Tc_100 % 100;
      if (SignBit)
      {
        Serial.print("-");
      }
      Serial.print(WholeDegrees);
      Serial.print(".");
      if (FractDegrees < 10)
      {
        Serial.print("0");
      }
      Serial.print(FractDegrees);
      Serial.print(" C\n");
      //int tempthresh;
      //tempthresh = (stringOne&&stringTwo&&stringThree);
      //stringOne += stringTwo;
      //stringOne += stringThree;
      //Serial.println(stringOne); // RETURNS VALUE OF 0.0 When I want Temperature Value to be returned
      //Change The Figure "22" To Adjust The Temperature Threshold To Turn Fan On.
      //Currently Set to Keep Temperature At Or Below 23.25 Degrees
      if ((WholeDegrees > 22)&&(FractDegrees >= 25)) digitalWrite(relay1, HIGH);
      else digitalWrite (relay1, LOW);
      delay(250);

    }

body:
In the Arduino IDE, in the Library Manager, are the OneWire library (by a lot of people including Paul Stoffregen) and the DallasTemperature library (by Miles Burton and others). You need both.

The DallasTemperature makes using the DS18B20 easier. Especially when there is more than one DS18B20 sensor connected. It can get the temperature by index or with the unique ID number that each DS18B20 has.
Start with the examples of the DallasTemperature that appear in the Arduino IDE menu, for example the "simple" example.

Then you have the temperature as a float, and you can compare it with 23.25.

Even the OneWire library comes with the DS18x20_Temperature example that shows how to calculate the temperature as a float.


body:
As has been pointed out looking for a temperature to that level of accuracy on a sensor that is only accurate to 1 degrees in an application which only needs accuracies of a few degrees is just adding extra complications for no real world benefit. In this situation just looking at the whole number part is good enough.

But ignoring the final application this is still a programming question which should be answered.

Using strings to compare numerical values is a very very bad idea. Even ignoring the wasted memory and CPU time involved converting things to a string performing a string to string comparison to evaluate the value is often problematic at best. Normally you'd do it by converting the string to a float.

Which brings us to the easiest solution, as Jot indicated, use a float:

    float temp = WholeDegrees + FractDegrees/100.0;
    if (temp >= 23.25) { ... }

That's by far the clearest and easiest way to perform the calculation but floats are CPU intensive. There are other, faster ways to do it.

You could do everything in 100ths of a degree, this is a better because ints are a lot quicker to work with and take up less memory than floats. But unless you add comments it's not quite as clear as the float version.

    int temp = WholeDegrees*100 + FractDegrees;
    if (temp >= 2325) { ... }

Or finally you could do something like your original attempt but fixing the logic. This would probably be the fastest and lowest memory of the lot since it only involved 8 bit calculations which on an 8 bit processor is a big benefit. But of the 3 it's also the least obvious what is happening.

    if ( (WholeDegrees > 23) || ( (WholeDegrees == 23) && (FractDegrees >= 25)) ) { ... }


body:
This code goes to some lengths to separate the temperature into whole- and fractional-degrees, and to do it in floating point. Unless there is more to the job that isn't shown in this code and requires either of those representations, you can do the whole job with integers, much more simply.

The DS18x20 series return temperatures as fixed-point integers. The "DS1820" that you referred to has only 1/2 degC resolution so testing to 0.25 degrees won't be useful. It delivers the result with 1 fraction-bit (binary point to the left of bit-0). This is equivalent to the number of 1/2-degreesC:

    DS1820
    +---------------+---------------+---------------+---------------+
    |   |   |   |   |   |   |   |   |   |etc|16 | 8 | 4 | 2 | 1 |.5 |
    +---------------+---------------+---------------+-----------^---+

                                                     binary point

If you're using the DS18b20 or DS18s20, the result is delivered with 4 fraction bits, binary point to the left of bit-3, or the number of 1/16-degreesC:

    DS18x20
    +---------------+---------------+---------------+---------------+
    |   |   |   |   |   |   |etc|16 | 8 | 4 | 2 | 1 |.5 |.25|   |   |
    +---------------+---------------+---------------^---------------+
                                         binary point       .125 .0625

To detect a temperature threshold you only need to compare that single 16 bit number to the equivalent 16-bit representation of the threshold value.

Using your threshold of 22.25 degC, you'd compare to "44" for a DS1820: (2 * 22.25). The remaining fraction, .5, gets truncated off. Or compare to "356" for one of the DS18x20 types: (22.25 * 16).

This function to converts a 4-place fixed point number to an ASCII decimal string for printing:

    /*
     * Name:          q12p4toa
     *
     * Function:      Converts a q12p4 binary number to ASCII decimal
     *
     * Description:   Convert a 4 binary-places signed fixed point number (Q12.4) to
     *                an ASCII string as: sdddd.dddd
     *                Up to 3 left zeroes are replaced with spaces; 4 decimal places
     *     are always generated.
     *
     * Parameters:    pbuf            - -> array of at least 10+1 bytes
     *            q12p4         - A fixed-point number to 4 binary places
     *
     * Returns:       pbuf
     *
     */

    char *q12p4toa(char *pbuf, int16_t fixp)
    {
       // If neg, write the sign and negate the number
       *pbuf++ = ' ';      // don't use this leading space if sending to Blynk
       if( fixp < 0 ){
          *pbuf++ = '-';
          fixp = -fixp;
       }
       // Handle the rest as an unsigned int
       (void)snprintf(pbuf, 9+1, "%d.d",
        fixp >> 4, (uint16_t)(10000L/16 * (fixp & 0xF)));
       return(pbuf);
    }


message:
Can I use an ESP8266 as a replacement for an original Arduino?

I want to learn Arduino, but I'd like to use the ESP8266 as it has built in wifi. I understand that I can use the Arduino IDE for this board.

However, what about books and resources out there? Are these two boards so similar that I can follow original Arduino examples? I'm primarily thinking in terms of connectivity to, say, sensors.

I'm a beginner at this and will not be able to figure out how to bridge compatibility gaps.

body:
Yes, No and Maybe is the best answer :)

Assuming that you want to replace a Arduino Uno board with an ESP8266 **based** board.  Your best choice at the moment would be a Wemos D1.  It has the same form factor as the UNO, but it has less pins, 9 digital and 1 analog.

If you are not bothered about the form factor, you could also try a Node-LUA, or a Wemos D1 Mini.  If you have steady hands you could try just using the heart of these three boards directly, which is usually called an ESP8266-12E, but it has 1mm pitch and no voltage regulation.

There are a lot of sites around that have tutorials on using ESPs.  They are mostly interchangeable with Arduino boards from a software perspective, they have more memory and a faster clock speed.

The biggest difference between an Arduino based board and an ESP board is **most** Arduino use 5v and **most** ESP based boards use 3.3v.  Make sure you read the datasheet before you hook up you sensors.

There is an ESP-32 as well.  This is not interchangeable with an Arduino Uno at the moment.


body:
> Are these two boards so similar that I can follow original Arduino examples?

for most applications, an mcu is useful not because of its core - which is almost fully transparent to a high level language programmer - but because of its peripherals: timers, serial comms, interrupts, adc/dac, ...

sure, there are applications that don't require those functionalities; or those functionalities could be emulated. but you will find it much easier if the mcu does have those functionalities.

so all it takes is to take a look at the datasheet of your esp and ask yourself if you see those peripherals. after that, the answer is clear.


message:
MIDIUSB - Why is the command put twice?

Consider this function:

    void noteOn(uint8_t pitch) {
      midiEventPacket_t noteOn = {0x09, 0x90 | 9, pitch, 127};
      MidiUSB.sendMIDI(noteOn);
    }

`midiEventPacket_t` is defined as:

    typedef struct
    {
     uint8_t header;
     uint8_t byte1;
     uint8_t byte2;
     uint8_t byte3;
    }midiEventPacket_t;

The first nibble of the first byte of a MIDI message is the command: ` 0x90` ["note on"] and the second nibble is the MIDI channel: `9`, so what's sent over the wire should be `0x99` meaning "Note On, channel 9", with the two more bytes representing the pitch and the velocity.

My question is, why do all of the examples start with: `{0x09, 0x90 | 9,`? I'm not understanding the use of the struct here. Intuitively, I thought I would need: `{0x90 | 9, pitch, 127, 0}`. Why do all of the examples have that seemingly strange syntax?

EDIT
====
After getting a great explanation below, here's my new function!

```void noteOn(uint8_t pitch) {
  midiEventPacket_t noteOnPacket;
  noteOnPacket.header = USB_CABLE_NUMBER | (MIDI_NOTE_ON >> 4);
  noteOnPacket.byte1 = MIDI_NOTE_ON | CHANNEL;
  noteOnPacket.byte2 = pitch;
  noteOnPacket.byte3 = MIDI_BUTTON_ON_VELOCITY;
  MidiUSB.sendMIDI(noteOnPacket);
}
```

body:
From the specs:

> The first byte in each 32-bit USB-MIDI Event Packet is a Packet Header contains a Cable Number (4 bits)
followed by a Code Index Number (4 bits). [...]

> [...]

> The Cable Number (CN) is a value ranging from 0x0 to 0xF indicating the number assignment of the
Embedded MIDI Jack associated with the endpoint that is transferring the data. The Code Index Number
(CIN) indicates the classification of the bytes in the MIDI_x fields. The following table summarizes these
classifications.

>CIN | MIDI_x Size | Description

>[...]

>0x9 | 3 | Note-on

>[...]

No rationale is given *why* the CIN is required if the full message is also included, but it could be used for quicker routing of the event to the routine that will process it.


message:
is there a timeout for Ethernet.begin?

I'm working on a project, but just for testing, I haven't connected it to the internet yet, even though the code SHOULD be ready to roll out.

When trying to test some of my code with the serial console, I realized my program was locking up and I traced it down to here. Now my arduino uno and ethernet shield isn't currently connected to the internet, so my question is, how could I timeout this function so that I can keep my program running when there's no internet to connect it too.

Here's my code in the setup function

    if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, ip);
      }

If anyone has any thoughts or suggestions, I'd definitely appreciate it.

body:
The default timeout is 1 minute for DHCP. There is also a response timeout, and in the library millis is used for timeouts. I don't know if there is a timeout for everything, but I suppose there is.

If it stops working when no ethernet cable is connected, that would be a bug. If something like that is in the library, then you have no way to bypass the Ethernet.begin when it took too long. How long did you wait ?

This is the source code for Ethernet.begin: [Ethernet.cpp][1]

  [1]: https://github.com/arduino-libraries/Ethernet/blob/master/src/Ethernet.cpp


message:
Burn smell from arduino uno

I have did something stupid.. I connected 10K Ohm potentiometer at its maximum value PARALLEL with a LED. The positive long leg of the led to arduino 5v and the negative leg to the GND.
After giving arduino 5v from USB Mobile Charger ( Output: 5V , 1A ) I smelt a burn and quickly removed the charger from the outlet.
I waited a few hours and connected the arduino ( without any components ) to the charger again. and the arduino worked. I then connected it to the PC and uploaded the blink sketch of the on-board led and it worked !
Then I uploaded a sktech for blinking led on other pins and it worked also !

My question is:
1) What is damaged on the board ?
The smell is near the regulator but I'm not sure if it's from the regulator itself or just a component near it.

2) Can it be safe to still using the arduino board on USB Power or Battery Power without any problems ?

body: That burn is likely the smell of the potentiometer, not the arduino. I would check the arduino with a multimeter set to resistance to make sure that the Vin trace resistance is nominal.


message:
Feasability question

I have some experience with Arduino, but not (yet) with other AVRs or Raspberry/Orange.

I want to make a project with some slave devices (mostly Arduino Unos, one Arduino Mega). These all need to communicate with a controller.

This controller has about the following requirements: - It need to respond every 5 ms to some messages from the devices, within the next 5 ms. - It needs about 128 KB RAM space, but more would be more comfortable (although 1 GB is enough). - I need quite some 'programming' space (like FLASH) - The program that needs to run on it will be reasonable complex, so using a nice programming language would be convenient (Python/Java/C++) - SD or other nonvolatile storage is mandatory - nRF24LR01+ 2.4 GHz RF Transceiver - Like upto 8 LEDs for status showing - WIFI would be nice - Using an adapter (12V/2A?) would be good, no intention to run it on batteries

I think I can do it with a Teensy or Due, but those are reasonable expensive. Another option is an STM32 kind of AVR.

However, I an noticed Orange Pi Zero, which are very cheap. But I wonder if I get myself in trouble? I know Linux commands, never installed it on a computer though. Someone made a remark in another related question to go for a stronger AVR, but afaik an Orange should be suited very well for this (seeing the limited electronics involved).

Or would it be better to go for a Teensy or STM32?

body:
A Pi gives you lots of CPU power but I'm not sure how good it would to on the tight timing requirements.

It doesn't have everything you ask for but something like the NUCLEO-F746ZG may be an option. That gives you a 200+ MHz Arm M7 with floating point, 2 MB of flash and 512 kB of RAM. It has USB and Ethernet built in and has arduino compatible headers for connecting shields to give you things like an SD socket or a radio link.
Plus you get 8 UARTs, (no more software serial :-)) and 6 SPI busses (obviously not all on the arduino headers)

You can program it either natively or in c++ using the mBed framework & online compiler.

It is around $20. There are cheaper variants with less processing power / memory available for a little less.


message:
Simulate 9-pin joystick output

[![Arduino Joystick Recorder][1]][1]

I have built this little setup, which is supposed to record and replay input from a classic 9-pin Joystick. I connected the 9 pin connectors to the Arduino, read the input on the left side from the Joystick, and then passed it to the right side by setting the corresponding pins to HIGH.

It does work, and I can play games on the Commodore 64, however, I noticed that with this setup current is passed to the Commodore 64, which is very likely harming the machine a lot (I stopped immediately after noticing).

So my question is: how do I need to modify this setup so that no current is going from the Arduino to the Commodore 64 anymore?

Picture of the setup:

[![Setup][2]][2]

  [1]: https://i.stack.imgur.com/8bJSt.png
  [2]: https://i.stack.imgur.com/wpYCb.jpg

body:
I would isolate the two devices using opto-isolators.

<!-- 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/FUHVG.png)

<!-- End schematic -->

Turning the output ON will illuminate the infra-red LED in the opto-isolator which turns on the photo-transistor connecting the input to GND. Both devices are then completely galvanically isolated (unless of course you take power from the C64 for the Arduino).

Another option, if you don't care about galvanic isolation, is to just use a simple transistor (small signal NPN or logic level N-channel MOSFET) to make an Open Drain output:

<!-- 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/cuWg1.png)

<!-- End schematic -->

Again, set the output HIGH and the transistor will turn on connecting the C64 input to ground.


message:
How do i power recycle on SD card

I am working on my home made project where i am using SD card to log GPS data into it,As well as i have to access that data from the SD card on my computer while all the system is connected to battery power, so i also have a USB to SD chip USB2240 from Microchip, this SD controller suits best to my application, Because USB2240 has a card detect pin connected to one of the pin of Arduino, from which i can control interface of SD card between Arduino for logging and the computer for the USB..

But I have to Recycle power to the SD card whenever SD Card is interfaced with the USB controller USB2240.

So for an Example : when the device is powered 'ON' , The SD card is interfaced with the Arduino - which logs data to the card, But when i connected the system to my computer to get the logged file on my computer, Then it's not working, Here i have to disconnect power to SD card and Reconnect it...

How do i achieve Power recycle all on it's own when i connected to the USB OR to the Arduino.

Thanks

body:
I just read the

[USB2240 Part listing][1]

and it looks really handy for interfacing a PC to the flash.

However, I believe you are taking the wrong approach by trying to power recycle it yourself.

**To address your question about how to power recycle it:  If you are physically moving the connection cable then that should power recycle it automatically.**

If not, then you have some other problem with your software not tolerating the disappearance then reappearance of the SD card.  In other works, it is likely a software problem.  The SD card should always remain connected so the software does not get confused and require a reset.

It is like how you need to eject USB devices in Linux.  If you don't, then you can get file corruption because the buffers may not be fully flushed.  Back in the day we used sync; sync; sync to ensure buffers were written out to storage devices, even just to do a normal shutdown.  Fortunately, modern Linux takes care of that, with the exception of USB flash memory.  With that you need to actually go through the eject process to avoid damage or system confusion.

But a much better approach would be to just leave it on one or the other.
Then use some sort of communications (it doesn't have to be USB) between the two computers for memory access.

  [1]: https://www.microchip.com/wwwproducts/en/USB2240


message:
Powering on the PC

I located the two pins that are responsible for powering up the PC. They are connected to the `Power On` button and one pin has an output of `5 V` while the other is the `ground`.

So far so good, the problem is when I connect the `5 V` one to the Arduino `VIN` and a ground cable from the PC power source to the Arduino `GND`, instead of powering my board, the PC starts and then promptly stops, as if I pressed the `power button` and did not release it.

It seems that electricity passes through the Arduino without powering it. I tested the `VIN` and `GND` pins with a normal breadboard power source and they are not broken, as the board starts up with no problem.

Why is the computer starting up instead of powering the Arduino? How can I use my Arduino to start up the PC?

My plan was to power the Arduino with the `5 V` pin and send a `digitalWrite(somePin, HIGH)` for a short amount of time to the ground pin from the PC that would normally be connected to the power button, thus "closing" the circuit like the normal case button would.

body:
The two pins aren't +5V power and ground.

One of them will be what you think, the other will be a signal wire with a pull up/down.

So if the ground wire really is ground then the other wire is the button input and is pulled up with a resistor, probably in the 10k region.

You can't power an arduino with a ~10k resistor in series with the power, it's just not going to work. But it will pull enough current to make it look like the button is pressed all the time.

What you need to do is:

1) Find out which pin is the signal pin. The easiest way to do this is find some other ground point on the computer (e.g. from one of the HDD power connectors) and measure the voltage from that to the button wires when the button is pressed. If both wires go to 0V then it's the wire that's normally +5 that is the signal, if they go to +5 then it's the wire normally at 0V that's the signal.

2) Fine a real power source. Most PC power supplies have an always on supply that will be at 5V when the PC is off. Use that to power the arduino.

3) Now you know which wire is the signal wire and have a usable power source you can connect the signal wire to one of the arduino pins and drive it to the correct state. Ideally you'd do this via an open collector type interface so that you don't get two different things pulling to very slightly different idle levels.


body:
The signal you found is called `PS_ON` and it is an *active_low* input which should be *momentarily* grounded by a switch to *toggle* the PC power supply's on/off state.

Trying to use this instead as a power *source* for the Arduino loads it, causing it to drop, the Arduino to brown out and release it, and then the process repeats.

As @Andrew mentioned, you need to find the 5v standby power *supply* output, and use that as the Arduino's power source instead.  This is called `VSB`.  Since it is already regulated to 5V, you can't pass it through the Arduino's Vin as it will not meet the regulator's dropout voltage needs.  Instead you should route it in as an external 5v source, much as done with the USB power input.

To activate the signal, you'll then want to use a `digitalWrite()` to briefly set the output *low* (not high).

However, when you are not driving it low, rather than driving it high (to a voltage potentially higher than the power supply pulls it up to), what you should do is simulate an `open collector` output by changing the pin mode to an input, *without* pullup.


message:
Arduino UNO only works with Monitor Serial opened

My Arduino Uno will not work without the Serial Monitor opened. I have a PHP script to send data to the board. When I send the data, the `TX` and `L` LEDs light up, but the action is not executed. It is only executed when the Serial Monitor is opened. Can you please help me?

Code in Arduino:

    int const RED = 2;

    int status = 0, temp =0;

    void setup() {
      pinMode(RED, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {

      if(Serial.available() > 0) {
        temp = Serial.read();
        if(temp != -1)
          status = temp - '0';

        Serial.print("status: ");
        Serial.println(status);

        if(status == 1)
          digitalWrite(RED, HIGH);
        else
          digitalWrite(RED, LOW);

        delay(1000);
      }

    }

PHP script:

    <!DOCTYPE html>
    <html>
     <head>
      <title>Alarme</title>
     </head>
     <body>
      <form action="#" method="post">
       <input type="submit" name="alarme" value="ON">
      </form>

      <form action="#" method="post">
       <input type="submit" name="alarme" value="OFF">
      </form>
     </body>
    </html>

    <?php

    $port = fopen("/dev/ttyUSB0", "w");
    fwrite($port, ($_POST['alarme'] == 'ON') ? 1 : 0);
    fclose($port);

My circuit is simple, it only consists of one LED and a 220 ohm resistor.

body:
The problem was the auto-reset of the Arduino, I disabled it.

To disable, I connected a 10uf capacitor on the GND and RES. As in the image below:

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

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


message:
Creating a file in an SD card

I have an Arduino Mega connected to an SD card reader (Catalex branded), that at least detects the card as it displays the info of the card. But when I try to create a file, it does not create it. I am using the following code:

    if (SD.exists("data.txt")) {
      Serial.println("data.txt exists.");
    } else {
      Serial.println("data.txt doesn't exist.");
    }
    File root=SD.open("data.txt", FILE_WRITE); //open of the File for writting
    if (SD.exists("data.txt")) {
      Serial.println("data.txt exists.");
    } else {
      Serial.println("data.txt doesn't exist.");
    }

I also tried with this code:

    File root2 = SD.open("file.txt", O_RDWR | O_APPEND);
        if (!root2) {
           // It failed, so try and make a new file.
            root2 = SD.open("file.txt", O_RDWR | O_CREAT);
            if (!root2) {
              // It failed too, so give up.
            Serial.println("Failed to open file.txt");
             }
        }

[Update]

I also tried with this easier code and it does not work either:

    #include <SD.h>

    const int chipSelect = 10;
    Sd2Card card;

    void setup() {
      Serial.begin(115200);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      Serial.print("Initializing SD card...");
      // see if the card is present and can be initialized:
      if (!SD.begin(chipSelect)) {
        Serial.println("Card failed, or not present");
        // don't do anything more:
        return;
      }
      Serial.println("card initialized.");
    }

    void loop() {
      File myFile = SD.open("Data.txt", FILE_WRITE);
      if (myFile) {
        for (int i = 0; i < 101; i++) {
          myFile.print(i);
          myFile.print(" multiplied by two is ");
          myFile.println(i * 2, DEC);
        }
        Serial.println("Finished");
        myFile.close();
      } else {
        Serial.println("Error opening Data.txt");
      }
      //do nothing else
      do { } while(1);
    }

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

    // open a new file and immediately close it:

    Serial.println("Creating example.txt...");
    myFile = SD.open("example.txt", FILE_WRITE);
    myFile.close();

This is what you missed (I guess..).
Please see the link and check the steps followed:
https://www.arduino.cc/en/Tutorial/Files


body: If you want to make it sure it will not have problem with SD card format then format it to FAT it's most compatible format type.


message:
Delay only some function

I have code which control thermometer, OLED and nanoservo via MQTT. I want to refresh temperature every 10s. It works but my servo receive command only when temperature is refreshed. How can I configure my loop so my servo can receive MQTT command anytime I send it?

Here in my code (I combined several example codes...):

  #include <ESP8266WiFi.h>
  #include <Servo.h>
  #include <PubSubClient.h>

  #include <OneWire.h>
  #include <DallasTemperature.h>

  #include <Wire.h>
  #include "SH1106.h"
  #include "thermometer.h"

  // Data wire is plugged into pin 2 on the Arduino
  #define ONE_WIRE_BUS 14 // je D5 was 2 (D4)

  // Setup a oneWire instance to communicate with any OneWire devices
  // (not just Maxim/Dallas temperature ICs)
  OneWire oneWire(ONE_WIRE_BUS);

  // Pass our oneWire reference to Dallas Temperature.
  DallasTemperature sensors(&oneWire);

  SH1106 display(0x3c, D1, D2);
  #define DEMO_DURATION 3000
  typedef void (*Demo)(void);

  int demoMode = 0;
  int counter = 1;

  // Update these with values suitable for your network.

  const char* ssid = "******";
  const char* password = "******";
  const char* mqtt_server = "192.168.100.220";     /// MQTT  Broker
  const char* topic_state = "/blinds/state";
  const char* topic_command = "/blinds/command";

  IPAddress my_ip (192, 168, 100, 224);
  IPAddress my_gateway (192,168, 100, 1);
  IPAddress my_subnet (255, 255, 255, 0);

  WiFiClient espClient;
  PubSubClient client(espClient);
  long lastMsg = 0;
  char msg[50];
  int value = 0;

  Servo myservo;
  int state = 0;
  int prevstate = 0;
  int dirc = 0;
  int spintime = 0;
  int servoPin = D4; //CHANGE TO WHATEVETR PIN YOUR USING

  void reconnect();
  void callback(char* topic, byte* payload, unsigned int length);

  void setup() {
    Serial.begin(115200);
    setup_wifi();
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);

  // Start up the library
    sensors.begin();

  // Initialising the UI will init the display too.
    display.init();
    display.flipScreenVertically();
    display.setFont(ArialMT_Plain_10);

  }

  void servo_move() {
    Serial.println("State Change. Rotating Servo");
    if ( dirc == 180) {
   client.publish(topic_state,"open");
    }
    else if (dirc == 0) {
   client.publish(topic_state,"close");
  }
    myservo.attach(servoPin);
    myservo.write(dirc);
    delay(spintime);
    myservo.detach();

    Serial.println("Returning to main loop");
    return;
  }

  void setup_wifi() {

    delay(10);
    // We start by connecting to a WiFi network
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.setPhyMode(WIFI_PHY_MODE_11N);
    WiFi.config(my_ip, my_gateway, my_subnet);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
  }

  void callback(char* topic, byte* payload, unsigned int length) {
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (int i = 0; i < length; i++) {
   Serial.print((char)payload[i]);
    }
    Serial.println();
    char *blindcommand = (char *) payload; // convert mqtt byte array into char array
    blindcommand[length] ='\0';            // Must delimit with 0

    Serial.print(blindcommand);
    if (strcmp(blindcommand,"open") == 0) {
   Serial.println(" 433MHZ OPEN COMMAND RECEIVED");
   dirc = 180; // direction for servo to run
   spintime = 50; // << CHANGE TO WHATEVER TIME YOU NEED TO OPEN YOUR BLINDS
   state = 1; //sets current state
    }
    else if (strcmp(blindcommand,"close") == 0) {
   Serial.println(" 433MHZ CLOSE COMMAND RECEIVED");
   dirc = 0;
   spintime = 150; // << CHANGE TO WHATEVER TIME YOU NEED TO CLOSE YOUR BLINDS
   state = 2; //sets current state
    }
    if (state != prevstate) {
   Serial.println("State change!");
   servo_move();
    }
    prevstate = state;

  }
  char temperatureVonku[15];
  String tempUnit = " °C";

  void temperature(){
    float temperatureFloat;
    sensors.requestTemperatures();
    temperatureFloat = sensors.getTempCByIndex(0);

    dtostrf(temperatureFloat, 7, 1, temperatureVonku);

     client.publish("temp/outside", temperatureVonku);    /// send char
     delay(10000);
  }

  void dispTempVonku() {
   display.drawRect(1, 1, DISPLAY_WIDTH -1, DISPLAY_HEIGHT -1);
   // Font Demo1
   // create more fonts at http://oleddisplay.squix.ch/
   display.setTextAlignment(TEXT_ALIGN_LEFT);
   display.setFont(Roboto_Bold_12);
   display.drawString(5, 5, "Temp: ");

   display.drawXbm(7, 24, Img_width, Img_height, thermometer);
   display.setTextAlignment(TEXT_ALIGN_CENTER);
   display.setFont(Roboto_Bold_28);
   display.drawString(64, 22, temperatureVonku + tempUnit);
  }
  void dispTempVnutri() {
   display.drawRect(1, 1, DISPLAY_WIDTH -1, DISPLAY_HEIGHT -1);
   display.setTextAlignment(TEXT_ALIGN_CENTER);
   display.setFont(ArialMT_Plain_16);
   display.drawString(64, 22, "Hello World");
  }

  Demo demos[] = {dispTempVonku, dispTempVnutri};
  int demoLength = (sizeof(demos) / sizeof(Demo));
  long timeSinceLastModeSwitch = 0;

  void reconnect() {
    // Loop until we're reconnected
    while (!client.connected()) {
   Serial.print("Attempting MQTT connection...");
   // Attempt to connect
   if (client.connect("ESP8266Client", "******", "******")) {

     Serial.println("connected");
     client.subscribe(topic_command);
   } else {
     Serial.print("failed, rc=");
     Serial.print(client.state());
     Serial.println(" try again in 5 seconds");
     // Wait 5 seconds before retrying
     delay(5000);
   }
    }
  }
  void loop() {

   temperature();

    if (!client.connected()) {
   reconnect();

    }
    client.loop();
    // clear the display
    display.clear();
    // draw the current demo method
    demos[demoMode]();

    display.setTextAlignment(TEXT_ALIGN_RIGHT);
    display.drawString(10, 128, String(millis()));
    // write the buffer to the display
    display.display();

    if (millis() - timeSinceLastModeSwitch > DEMO_DURATION) {
   demoMode = (demoMode + 1)  % demoLength;
   timeSinceLastModeSwitch = millis();
    }
    counter++;

   //delay(10000);

  }

Thank you.

body:
I assume your servo only receives data when you keep the delay(10000).

The problem is that with a delay, the Arduino does kind of nothing during that time, so it cannot control your servo.

What you want is to call every 10 s the temperature update, but keep the servo control always running.

So keep a last-time-called variable (type unsigned long) that keeps the time of the last call to update the temperature. When 10 s have passed (you can check somewhere in the loop), you call it, and update the last time to the current time.


message:
Start I2C communication at an external event

I'm working on a Arduino Uno and a ADC ADS1115. Devices communicate by I2C where Arduino is the master.

I would like to use the ADC to the maximum of his possibility.

So i configure the ADC to set a pin when a conversion finish and use this pin as an external interrupt.
But i can't read the data because I2C interrupt can't work in a external interrupt handler.
I think to use a timer to have a fixed sampling rate too, but it's the same issue.

There is my code below, and if you have any idea of how i can doing my goal let's share it ;)

    #include <QueueArray.h>
    #include <ADS1115_Vibratec.h>

      Adafruit_ADS1115 ads;

      QueueArray <uint16_t> fifo;

      int i=0;

    void setup() {

     Wire.begin();

     Serial.begin(115200);

     ads.Config( ADS1115_REG_CONFIG_OS_NOEFFECT,
              ADS1115_REG_CONFIG_MUX_DIFF_0_1,
              ADS1115_REG_CONFIG_PGA_6_144V,
              ADS1115_REG_CONFIG_MODE_CONTIN,
              ADS1115_REG_CONFIG_DR_860SPS,
              ADS1115_REG_CONFIG_CMODE_TRAD,
              ADS1115_REG_CONFIG_CPOL_ACTVLOW,
              ADS1115_REG_CONFIG_CLAT_NONLAT,
              ADS1115_REG_CONFIG_CQUE_1CONV);

     ads.Set_ConvReady_function();

     attachInterrupt(0,interrupt,RISING); //INT0 -> pin 2, fonction interrupt,    front montant

      }

      void loop() {

       while (!fifo.isEmpty ())
       {
          Serial.write(fifo.dequeue());
          Serial.println();

       }

      }
      void interrupt()
      {
        fifo.enqueue(ads.ReadConvert());
      }

body:
You could set a 'volatile' flag in the interrupt routine. In the loop() you can check if the flag is set. That is how the i2dev uses the interrupt for the MPU-6050. See the [MPU6050_DMP6.ino][1] example.

First thing to do is set the I2C clock to 400 kHz. Keep the wires short and pullup resistors low.

    Wire.begin();
    Wire.setClock(400000L);   // 400 kHz I2C clock speed

You can let the [MultiSpeed I2C Scanner][2] run for a while to see if it is stable.

The ADS1115 has also I2C High-Speed Mode up to 3.4MHz. The Arduino can not do that. The Arduino has a fast SPI mode, but the ADS1115 has no SPI bus.

Using an interrupt adds extra overhead. A fixed software timer with millis might be just as fast.

Do you want the maximum of 860 Samples per second? The Arduino Uno or Mega or Leonardo are too slow for that. Do you want to continuously read data or just a burst and store it in ram ?

  [1]: https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/examples/MPU6050_DMP6/MPU6050_DMP6.ino
  [2]: http://forum.arduino.cc/index.php?topic=197360


message:
Arduino as Slave | SPI | Answers too late

I hope you can help me :)

I am communicating between Raspberry Pi 3 and Arduino Uno with SPI. I am using the Arduino as slave and it works pretty fine. The only problem that i have, is the following:

For receiving data from the Arduino, my Raspi sends a byte. But i always have to send 2 bytes for the correct response. Is it even possible for the Arduino to response on the first byte?

Sorry for my english

body:
The only way you can respond on the first byte is if the Arduino already knows, and is primed, what to send on that byte *before it begins to be clocked into the Arduino*.

It is normal to have to send at least 2 bytes - the first is often used as either a register address, or a "read register" command.


body:
> Is it even possible for the Arduino to response on the first byte?

Yeah. There is nothing preventing your slave to respind on the first byte, so long as your code allows it.


body:
Because of the way SPI works, the slave cannot *respond* to the first byte in a meaningful way. It can send something (eg. 0x00) but not a response.

See [my page about SPI](http://www.gammon.com.au/spi). During an SPI transfer each bit is sent, and a bit received, simultaneously, as in this graphic:

[![SPI transferring bits][1]][1]

You can see that as the first bit is received by the slave, it also has to send a response. There is no way that this response can react to the 8 bits, 7 of which haven't been received yet, by the time it has to send the first bit of response.

> But i always have to send 2 bytes for the correct response.

You don't have to send 2 bytes all the time. For example, you can send one byte (eg. "send me the temperature") and then send zeroes after that, while you read back a (say) 4-byte temperature. So in this case you send 5 bytes to get a 4-byte response.

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


message:
Weird issue with software serial?

Hi i am trying to write a library to communicate between the arduino and the esp 8266. I wrote a command that that sends an AT command to the esp chip. So far I have tested these commands : AT, AT+GMR, AT+CIFSR, AT+CIPMUX=1 etc. with no issue the communication seem robust.

When I tried to send the AT+CIPSERVER=1 command the function did not work. After some attempts to debug the program I manage to get it working but I do not understand why. And this is my issue, I though it was working because of the extra delay that was occurring in my code but after some testing that was not the reason.

Could anyone please explain to me what is happening ? I will continue to work on the code until I figure it out.

**The code :**

**Header file**

    #ifndef _ESPLIB_h
    #define _ESPLIB_h

    #if defined(ARDUINO) && ARDUINO >= 100
     #include "Arduino.h"
    #else
     #include "WProgram.h"
    #endif

    #include <SoftwareSerial.h>

    // Definitions
    #define DEBUG  1
    #define BUFFSIZE 64
    #define TCPORT  23050
    #define ESPTIMEOUT 10000
    enum espResponse {
     ok,
     error,
     other
    };

    // AT Commands
    #define CRLF "\r\n"
    #define Q  "=?"
    #define AT  "AT"
    #define GMR  "+GMR"
    #define RST  "+RST"
    #define CMUX "+CIPMUX=1"
    #define CWMOD "+CWMODE"
    #define CSERV "+CIPSERVER=1"
    #define CFSR "+CIFSR"
    #define CSEND "+CIPSEND"

    class espdevice
    {
     public:
      // Functions
      espdevice(int rx, int tx, int baud);
      void serialEnable(void);
      //boolean tcpServerInit(void);

      #if DEBUG
       void serialDebug(void);
      #endif

     private:

      // Variables
      // Serial Setup parameters
      int _rx;
      int _tx;
      int _baud;

      // Software Serial
      int _espSerialIndex = 0;
      char _espSerialBuffer[BUFFSIZE];
      SoftwareSerial *_espSerial;

      // private functions
      //espResponse _sendEspCommand(const char* cmd);
      boolean _sendEspCommand(const char* cmd);
      espResponse _espCommandOK(void);
      boolean _espSerialAvailable(void);

      // Debug mode
      #if DEBUG

      // variables
      int _serialIndex = 0;
      char _serialBuffer[BUFFSIZE];

      // functions
      void _serialDebug(int select);
      int _arduinofreeRam(void);
      boolean _serialAvailable(void);

      #endif

    };

    #endif

**What I am executing**

      _sendEspCommand("AT+CIPMUX=1\r\n");
   _sendEspCommand("AT+CIPSERVER=1,23050\r\n");
   _sendEspCommand("AT+CIFSR\r\n");

**Now the function definition**

    boolean espdevice::_sendEspCommand(const char* cmd)
    {
     // variables
     int count = 0;
     boolean flag = false;
     espResponse status = other;

     // sending the command to the ESP
     _espSerial->write(cmd);
     #if DEBUG
      Serial.print("command echo : ");
      Serial.write(cmd);
      Serial.println();
     #endif

     //while (!(status==ok||status==error) || count < 1000) **<- why this thing works  ??????????????**
     //while (status == other && count < ESPTIMEOUT) <- does not work
     while ((status == other) || (count < ESPTIMEOUT)) <- THIS works too
     //while(count < ESPTIMEOUT) <- does not work
     {
      //while (!_espSerial->available()) {};
      if (_espSerialAvailable())
      {
       Serial.println ("Data Are available");
       status = _espCommandOK();
       #if DEBUG
        Serial.print("Data Received from ESP : ");
        Serial.print(_espSerialBuffer);
        Serial.println("");
        Serial.println(status);
       #endif
       /* //code used with the not working part
       if (status == ok)
       {
        flag = true;
        break;
       }
       else if (status == error)
       {
        flag = false;
        break;
       }
       else
       {
       }
       */
      }
      count++;
     }
     Serial.println(count);
     return flag;
    }

**And the two other functions that are called**

**_espSerialAvailable()**

    boolean espdevice::_espSerialAvailable(void)
    {
     boolean stringFound = false;
     // Read the serial buffer if data are available
     while (_espSerial->available() > 0)
     {
      char charBuffer = _espSerial->read();

      if (charBuffer == '\n')
      {
       _espSerialBuffer[_espSerialIndex] = 0; // terminate the string
       stringFound = (_espSerialIndex > 0); // only good if we sent more than an empty line
       _espSerialIndex = 0; // reset for next line of data
      }
      else if (charBuffer == '\r')
      {
       // ignoring carriage retun
      }
      else if (_espSerialIndex < BUFFSIZE && stringFound == false)
      {
       _espSerialBuffer[_espSerialIndex++] = charBuffer; // auto increment index
      }
     }

     return stringFound;

    }

**_espCommandOK()**

    espResponse espdevice::_espCommandOK(void)
    {
     if (strcmp(_espSerialBuffer, "OK") == 0)
     {
      return ok;
     }
     else if (strcmp(_espSerialBuffer, "ERROR") == 0)
     {
      return error;
     }
     else
     {
      return other;
     }
    }

**The output from the serial ports for each case**

**working**

    creating an new tcp server
    command echo : AT+CIPMUX=1

    Data Are available
    Data Received from ESP : AT+CIPMUX=1
    2
    Data Are available
    Data Received from ESP : OK
    0
    10000
    command echo : AT+CIPSERVER=1,23050

    Data Are available
    Data Received from ESP : AT+CIPSERVER=1,23050
    2
    Data Are available
    Data Received from ESP : no change
    2
    Data Are available
    Data Received from ESP : OK
    0
    10000
    command echo : AT+CIFSR

    Data Are available
    Data Received from ESP : AT+CIFSR
    2
    Data Are available
    Data Received from ESP : +CIFSR:STAIP,"192.168.1.16"
    2
    Data Are available
    Data Received from ESP : +CIFSR:STAMAC,"5c:cf:7f:fd:ce:14"
    2
    Data Are available
    Data Received from ESP : OK
    0
    10000

**not working**

    creating an new tcp server
    command echo : AT+CIPMUX=1

    Data Are available
    Data Received from ESP : AT+CIPMUX=1
    2
    Data Are available
    Data Received from ESP : OK
    0
    98
    command echo : AT+CIPSERVER=1,23050

    10000
    command echo : AT+CIFSR

    Data Are available
    Data Received from ESP : AT+CIFSR
    2
    Data Are available
    Data Received from ESP : +CIFSR:STAIP,"192.168.1.16"
    2
    Data Are available
    Data Received from ESP : +CIFSR:STAMAC,"5c:cf:7f:fd:ce:14"
    2
    Data Are available
    Data Received from ESP : OK
    0
    224

body:
I will leave this here in case anyone is interested. So i am communicating with the esp module at 9600 baud rate. After I send a command to the ESP I was waiting for its response before sending the next command without any delay.

What I found out is that for some reason although I was sending the command to the ESP the esp was not executing the command. So i added a delay(100) to see if the RX of the ESP was disabled during that time and i think i was correct since the commands were executed correctly.

I manage to get the delay down to delay(5). it Breaks after that.

I am using an Arduino micro and an ESP-01.


body:
This may not be the answer you need if you are using it for something else, but if you are using a Micro, I would use the hardware serial Serial1 instead of SoftwareSerial. I've done many projects using a Leonardo (same processor) with ESP8266 as it gives me an extra hardware serial port which isn't connected to the Serial Monitor serial port.

I haven't tried the SoftwareSerial library for a few years, but I remember at the time that it doesn't handle duplex or high baud rates well.

What baud rate are you using? I couldn't see any begin in the code.

EDIT: You might also want to add the 'ATE0' command to turn off command echo.  The serial receiver is probably getting swamped with data.


message:
Updating Array Values Incrementally Overwrites The Existing Values, Why?

I have a global array. I'd like to update the array while the program running.
But, I've found that my program below doesn't work as I expected.

**Please checkout the program source:**

    #define RespLength 10
    char* response[] = {"0","0","0","0","0","0","0","0","0","0"};
    int idxUpd  = 0;

    void setup() {
        // put your setup code here, to run once:
        Serial.begin(115200);
        Serial.println("Start");
    }

    void loop() {
      // put your main code here, to run repeatedly:
        char assign[5];
        int wkt = random(10, 99);
        dtostrf(wkt, 4, 1, assign);

        response[idxUpd]  = assign;

        Serial.print("Iteration "+String(idxUpd)+" : ");
        for (int i=0;i<RespLength;i++){
            Serial.print(response[i]);Serial.print(",");
        }
        Serial.println();
        delay(500);

        idxUpd++;
        idxUpd = idxUpd >= 10 ? 0 : idxUpd;
    }

**Expected output:** please concern to the patern

    Iteration 0 : 12.2,0,0,0,0,0,0,0,0,0,
    Iteration 1 : 12.2,23.7,0,0,0,0,0,0,0,0,
    Iteration 2 : 12.2,23.7,65.3,0,0,0,0,0,0,0,
    Iteration 3 : 12.2,23.7,65.3,0,0,0,0,0,0,0,
    Iteration 4 : 12.2,23.7,65.3,15.9,0,0,0,0,0,0,
    Iteration 5 : 12.2,23.7,65.3,15.9,10.1,0,0,0,0,0,
    Iteration 6 : 12.2,23.7,65.3,15.9,10.1,11.6,0,0,0,0,
    Iteration 7 : 12.2,23.7,65.3,15.9,10.1,11.6,78.9,0,0,0,
    Iteration 8 : 12.2,23.7,65.3,15.9,10.1,11.6,78.9,98.2,0,0,
    Iteration 9 : 12.2,23.7,65.3,15.9,10.1,11.6,78.9,98.2,68.6,90.1,

**Current output:**

    Iteration 0 : 85.0,0,0,0,0,0,0,0,0,0,
    Iteration 1 : 28.0,28.0,0,0,0,0,0,0,0,0,
    Iteration 2 : 36.0,36.0,36.0,0,0,0,0,0,0,0,
    Iteration 3 : 70.0,70.0,70.0,70.0,0,0,0,0,0,0,
    Iteration 4 : 56.0,56.0,56.0,56.0,56.0,0,0,0,0,0,
    Iteration 5 : 74.0,74.0,74.0,74.0,74.0,74.0,0,0,0,0,
    Iteration 6 : 94.0,94.0,94.0,94.0,94.0,94.0,94.0,0,0,0,
    Iteration 7 : 94.0,94.0,94.0,94.0,94.0,94.0,94.0,94.0,0,0,
    Iteration 8 : 26.0,26.0,26.0,26.0,26.0,26.0,26.0,26.0,26.0,0,
    Iteration 9 : 71.0,71.0,71.0,71.0,71.0,71.0,71.0,71.0,71.0,71.0,

From the result above, I can conclude that if I update the array value incrementally, it just overwrites the other element in the array.<br>
So, How can I have my `expected output`?

body:
C/C++ Arrays don't work the way you are used from scripting languages.
Your

    char* response[] = {"0","0","0","0","0","0","0","0","0","0"};

allocates a consecutive space in memory with the lenght of 20 bytes.
So you have 10 pointers that point to static memory.

In your loop you have a array of `char assign[5]` that gets assigned to every single of those pointers with `response[idxUpd]  = assign;`. You copy **pointers** and **not values** here. So the only value you really have is that in your `assign` variable. So as you update the pointes of the array, you get the results you see.


body:
You are using a char pointer (char*) instead of a char.

When you say;

    response[idxUpd]  = assign;

you are assigning not the value but a pointer to that value. That points to `assign` for every element in `response[]`. Every `response[]` get the same pointer value, every `response[]` get the same value.

Use this:

    #define RespLength 10
    int response[] = {0,0,0,0,0,0,0,0,0,0};
    int idxUpd  = 0;

    void setup() {
        // put your setup code here, to run once:
        Serial.begin(115200);
        Serial.println("Start");
    }

    void loop() {
      // put your main code here, to run repeatedly:
        int wkt = random(10, 99);
        response[idxUpd]  = wkt;

        Serial.print("Iteration "); Serial.print(idxUpd); Serial.print(" : ");
        for (int i=0;i<RespLength;i++){
            Serial.print(response[i] );Serial.print(",");
        }
        Serial.println();
        delay(500);

        idxUpd++;
        idxUpd = idxUpd >= 10 ? 0 : idxUpd;
    }

I don't understand why you are converting a `int` to a `float`. That value doesn't change, so I omitted the `dtostr()` call.


message:
Void value not ignored as it ought to be

im trying to build an rc plane using arduino nano and nrf24l01 as receiver but im having some issues in the code

it has error on the line
`done = radio.read(joystick,sizeof(joystick));` which says that void value not ignored as it ought to be

the whole code is below

    #include <nRF24L01.h>
    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>
    #include<Servo.h>

    Servo Throttle,Rudder,Elevator,LeftAileron,RightAileron ;

    const uint64_t pipe = 0xE8E8F0F0E1LL;
    RF24 radio(9,10);
    int joystick[5];

    void setup()
    {
      /*Serial.begin(9600);
      delay(1000);
      Serial.println("Starting Rx");*/ //Enable serial for debugging

      attachMotors();

      calibrateMotors();

      radio.begin();

      detachMotors();

      radio.setPALevel(RF24_PA_MAX);
      radio.setPayloadSize(10);
      radio.setDataRate(RF24_250KBPS);
      radio.setRetries(15,15);

      radio.openReadingPipe(1,pipe);
      radio.startListening();;
    }

    void loop()
    {
      detachMotors();

      if(radio.available())
      {
        bool done=false;
        while(!done)
        {
          done=radio.read(joystick,sizeof(joystick));
        }

      attachMotors();

      int a=joystick[0];
      int b= joystick[1]; //stores values from tx
      int c=joystick[2];
      int d=joystick[3];
      int e=joystick[4];

      //Serial.println(a);
      //Serial.println(b);
      //Serial.println(c);
      //Serial.println(d);
      //Serial.println(e);
     // Serial.println(f);

      delay(20);
      Throttle.writeMicroseconds(a);   //write values to motor
      Rudder.write(b);
      Elevator.write(180-c);

      if(d== LOW)
      {
      LeftAileron.write(180); ////to activate right aileron
      RightAileron.write(180);
      delay(15);
      }

      else if(e == LOW)
      {
        LeftAileron.write(0);  //to activate left aileron
        RightAileron.write(0);
        delay(15);
      }
      else
      {
        LeftAileron.write(100);
        RightAileron.write(110); //Ailerons at neutral pos
        delay(15);
      }
        }
      else
      {
        calibrateMotors();
        delay(15);

      }
      }

    void attachMotors()
    {
      Throttle.attach(3);
      Rudder.attach(4);
      Elevator.attach(5);
      LeftAileron.attach(6);
      RightAileron.attach(7);
    }

    void calibrateMotors()
    {
      Rudder.write(90);
      Elevator.write(90);
      LeftAileron.write(100);
      RightAileron.write(110); //centering servo shafts
    }

    void detachMotors()
    {
      Throttle.detach();
      Rudder.detach();
      Elevator.detach();
      LeftAileron.detach();
      RightAileron.detach();
    }

body:
Something changed while you were looking away. This is the updated description of `read()`. As you can see, it not longer returns a `bool`.
Use `available` to determine if packets are available:

    /**
       * Read the available payload
       *
       * The size of data read is the fixed payload size, see getPayloadSize()
       *
       * @note I specifically chose 'void*' as a data type to make it easier
       * for beginners to use.  No casting needed.
       *
       * @note No longer boolean. Use available to determine if packets are
       * available. Interrupt flags are now cleared during reads instead of
       * when calling available().
       *
       * @param buf Pointer to a buffer where the data should be written
       * @param len Maximum number of bytes to read into the buffer
       *
       * @code
       * if(radio.available()){
       *   radio.read(&data,sizeof(data));
       * }
    void read( void* buf, uint8_t len );


message:
Arduino I2C via USB Serial cable?

An Arduino UNO is given.
I want to establish an I2C communication channel between Arduino UNO and a Linux Machine which have only USB ports available to communicate with peripherals.
Currently I can communicate with Arduino board via USB Serial cable (TXD and RXD which are on pins D0 and D1).

My question is: is there any way to use those pins as SCL/SDA to communicate via I2C with Arduino Board?

I am thinking that the only way to accomplish this is to buy an USB to I2C Adapter and connect to A4 (SDA) and A5 (SCL); but maybe I'm wrong.

I have also seen that way: https://gist.github.com/kraftb/8c0bbcc35a9778608d74. Basically to use an intermediate Arduino board.

body:
With [SoftwareI2CLibrary][1] you can specify other pins, I haven't tested it with RX and TX.

I would recommend the USB serial interface is fast (2M baud) in perspective to that we are discussing a Arduino with a speed of 16MHz.

  [1]: https://playground.arduino.cc/Main/SoftwareI2CLibrary


message:
arduino on battery for long time use

I have a small project with arduino UNO R3 + RTC clock DS3231, that control through a relay a electrovalve (12V).

I would like to use the entire circuit on battery.

The electrovalve (a small motor) has a consumption of 500mA and will be active 4 times a day for 15 second.

I have a 7Ah battery, and I had calculated that my system will work only around 34 hours with it... is there any way to optimize circuit consumption ?

Thanks for any suggestion !

body:
You can turn off the entire Arduino and let it wake by your RTC. That way you can conserve a lot of power. ([link][1])

Also you will have losses from the power regulator when powering the Arduino from 12V. You might consider using a Arduino Pro mini with 3.3V powered by two AA batteries. That should last for years.

  [1]: https://playground.arduino.cc/Learning/ArduinoSleepCode


message:
SD card fail of initializing

I have an Arduino Mega and a catalex card reader which yesterday worked, but today I tried another time and the sd card where not detected, I am using the example code from Arduino website for the card info. I have tried conecting the reader to the SPI ports in the middle of the board and it was not solved. Anyone has another idea of what can be failing?
<!-- language-all: lang-cpp -->

    #include <SPI.h>
    #include <SD.h>

    // set up variables using the SD utility library functions:
    Sd2Card card;
    SdVolume volume;
    SdFile root;

    // change this to match your SD shield or module;
    // Arduino Ethernet shield: pin 4
    // Adafruit SD shields and modules: pin 10
    // Sparkfun SD shield: pin 8
    // MKRZero SD: SDCARD_SS_PIN
    const int chipSelect = 10;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.print("\nInitializing SD card...");

      // we'll use the initialization code from the utility libraries
      // since we're just testing if the card is working!
      if (!card.init(SPI_HALF_SPEED, chipSelect)) {
        Serial.println("initialization failed. Things to check:");
        Serial.println("* is a card inserted?");
        Serial.println("* is your wiring correct?");
        Serial.println("* did you change the chipSelect pin to match your shield or module?");
        return;
      } else {
        Serial.println("Wiring is correct and a card is present.");
      }

      // print the type of card
      Serial.print("\nCard type: ");
      switch (card.type()) {
        case SD_CARD_TYPE_SD1:
          Serial.println("SD1");
          break;
        case SD_CARD_TYPE_SD2:
          Serial.println("SD2");
          break;
        case SD_CARD_TYPE_SDHC:
          Serial.println("SDHC");
          break;
        default:
          Serial.println("Unknown");
      }

      // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
      if (!volume.init(card)) {
        Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
        return;
      }

      // print the type and size of the first FAT-type volume
      uint32_t volumesize;
      Serial.print("\nVolume type is FAT");
      Serial.println(volume.fatType(), DEC);
      Serial.println();

      volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
      volumesize *= volume.clusterCount();       // we'll have a lot of clusters
      volumesize *= 512;                            // SD card blocks are always 512 bytes
      Serial.print("Volume size (bytes): ");
      Serial.println(volumesize);
      Serial.print("Volume size (Kbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);
      Serial.print("Volume size (Mbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);

      Serial.println("\nFiles found on the card (name, date and size in bytes): ");
      root.openRoot(volume);

      // list all files in the card with date and size
      root.ls(LS_R | LS_DATE | LS_SIZE);
    }

    void loop(void) {

    }

body:
Add these Two Lines for better initialization of SD card:

    void setup{
        pinMode(10, OUTPUT); // change this to 53 on a mega(don't follow this!!)
        digitalWrite(10, HIGH); // Add this line
    }

Check [this link][1], may be useful to your current problem.

  [1]: https://embedjournal.com/arduino-sd-card-initialization-failed/