message:
MH-Z19 with Arduino null output

I want to get CO2 value by using MH-Z19. I tried this code with Arduino uno R3 but I always get this result (CRC 0/0). I didn't understand where is the problem.
I linked A0 with TX of sensor and A1 with RX, I powered the card with 3.3V/Vin to visualize the result on PC via USB port.

     #include <SoftwareSerial.h>;

     SoftwareSerial mySerial(A0, A1); // A0 - к TX сенсора, A1 - к RX

     byte cmd[9] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79};
      unsigned char response[9];

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

     void loop()
    {
    mySerial.write(cmd, 9);
     memset(response, 0, 9);
     mySerial.readBytes(response, 9);

      int i;
    byte crc = 0;
     for (i = 1; i < 8; i++) crc+=response[i];
     crc = 255 - crc;
     crc++;

      if ( !(response[0] == 0xFF && response[1] == 0x86 && response[8] == crc) )
     {
    Serial.println("CRC error: " + String(crc) + " / "+ String(response[8]));
      } else {
    unsigned int responseHigh = (unsigned int) response[2];
    unsigned int responseLow = (unsigned int) response[3];
    unsigned int ppm = (256*responseHigh) + responseLow;
    Serial.println(ppm);
    }

body:
From the [datasheet][1], working voltage for MH-Z19 is 3.6V to 5.5V, so 3.3V is not enough. (Although the interface runs at 3.3V).

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

Also, the Uno might not run reliably at 16MHz and 3.3V.

[![enter image description here][3]][3]

Edited image from [datasheet][4] page 303.

  [1]: http://eleparts.co.kr/data/design/product_file/SENSOR/gas/MH-Z19_CO2 Manual V2.pdf
  [2]: https://i.stack.imgur.com/9ftnM.png
  [3]: https://i.stack.imgur.com/VPYhP.jpg
  [4]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf


sender: user

message:
Arduino Yun V2.0.1 can't configure WiFi

I can't configure at 192.168.240.1. It's giving me this message multiple times:

1- AJAX/HAR Error:0 has not allowed Arduino Configuration Wizard to complete.

Details of my board:

Arduino Yun V2.0.1 anders evinrud

![enter image description here](https://i.stack.imgur.com/VeYRB.jpg)

sender: assistant

body:
I have this error too when I typed a wrong password to connect to the green 'osjs' interface.
have you changed the password of your board ?
have you tried the 2 possible passwords ( "arduino" or "doghunter" ) depends on the image installed ?
hacve you cleared your browser cache / test with another browser ?


message:
About multiple void loops and functions

I'm still a beginner at Arduino coding -- I've been researching on how to make functions using void instead of doing goto because reasons...

one thing I've noticed about void is that it has this `void loop() {...}` parenthesis, **what is it for?** (and can you provide an example of using it?)

say I make a void function `void function1()` to call the function I have to use `function1();` **can I make a function that loops?** like the ol' `void loop() {...}` command we all know and love or **do all void functions loop?** if not then what happens to a void function after it reaches the end of its function?

body:
The void in front of the function definition just tells what type the function returns.  In the case of void it means the function returns nothing.  If the function returned an int then it would be defined with int instead of void.

eg:

    int addNumbers(int num1, int num2){
        int retval = num1 + num2;
        return retval;
    }

    int sum = addNumbers(3, 4);
    Serial.print(sum);  // prints 7

No, the loop only loops because main (see main.cpp in the core) is the "real" program that is running on your micro and it calls loop over and over.  It's not that the loop function on it's own repeats.  It is literally being called repeatedly by the main function.

That example also gets to what the parenthesis are for.  That's where the arguments that the function takes go.  In the function definition you tell it what types they'll be and give them names.  In the function call you put in whatever values you want to function to use.  In the case of void loop(), it takes no arguments so the parenthesis are empty.

I would suggest you look at a basic tutorial on C++.  There are many good ones on the web.  The concept of functions isn't something that you can reason your way through by doing.  Go read a little and you'll get it pretty quick.


message:
Arduino Mega - Multithreaded (run two loops simultaneously)

I am new to Arduino and I am not sure about how to get two loops run parallel to each other. I have tested the individual loops and both of them work perfectly before I combined them together.

One loop will take input from the LCD touchscreen. One loop will take input from vibration sensor which will determine the state (on/off) of LED. Once the LED is turned on, it has to stay at the ON state for 3 seconds before switching to OFF state.

The problem I am facing is that when the LED is triggered to ON state by vibration sensor, I have to wait 3 seconds for the input from LCD to get processed. Is there any way I can combine these two loops in such a fashion that I run them simultaneously, i.e. run two inputs together?

body: You can combine the 2 programs into 1 program.  But when you start wanting to do multiple things at once then you can't have any code that "blocks" and waits to finish before letting the next thing happen.  The Arduino has a single core, it can't do multithreading.  But if you write non-blocking code you can make things appear to happen at the same time.  I imagine the problem with your code now is that you have probably used the delay function.  That function blocks, so nothing else can happen while the delay is running.  Instead you have to use millis to record the time and periodically check against that time to see if it is time to take the next step instead of calling a delay to wait for the next step.  See the "[Blink Without Delay](https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay)" example that comes with the IDE and any of the multitude of tutorials about it on the web to see how it works.


body:
I totally second Delta's answer. Make the two loops "non blocking", then run them one after the other.

Just wanted to add another solution, to be applied only when strictly needed. And only if the program really needs it. And only if other solutions are not enough. And... Well, you understood.

You can use FreeRTOS to have a sort of "multi-threading" environment. You have, IIRC, four "threads" which can jump from one loop to the other. You will have to carefully design it (particularly the shared memory) but in the end you will have even blocking "threads" running in parallel. [Here][1] are some more infos.

  [1]: https://create.arduino.cc/projecthub/feilipu/using-freertos-multi-tasking-in-arduino-ebc3cc


message:
How to access the member of union in loop?

Trying to get the address of receiving XBee's data in the loop in API mode with escape.
Sent data can be received properly. However, in order to identify XBee, I need the address in the loop. In other words I need those address1 to 7 which is in union XbEE_FRAME. How to get the address in main loop. Following is the code. Appreciate your help.

    #include <SoftwareSerial.h>

    struct SENSOR_DATA{
       char rpm;   // worked
      //float rpm;
      //float strain;
      //unsigned long sampling_interval;
    };

    boolean xbee_rx(struct SENSOR_DATA *ret) {
      union LEN_FRAME{
        byte len_array[2];
        word len;
      }lenlen;
      static int len_i = -1;

      union XbEE_FRAME{
        byte buf[25]; // 30
        struct {
          byte frame_type;
          byte frame_id;
          byte address1;
          byte address2;
          byte address3;
          byte address4;
          byte address5;
          byte address6;
          byte address7;
          byte reserved1;
          byte reserved2;
          byte recieve_options;
          struct SENSOR_DATA sensor_data;
          byte checksum;
        } frame;
      } xbee;
      static int buf_i = -1;
      static bool escape = false;
      static byte sum;

      while (Serial.available() > 0) {
        byte b = Serial.read();

        //Serial.print(b, HEX);

         //b = Serial.read();
        if (
          b != 0x7e &&
          buf_i == -1 &&
          len_i == -1
          ) {
          continue;
        } else if (b == 0x7e){
          buf_i = 0;
          lenlen.len = 0;
          len_i = 0;
          sum = 0;
          escape = false;
          continue;
        } else if (b == 0x7d){
          //Serial.print("es: ");
          //Serial.println(b,HEX);
          escape = true;
          continue;
        }

        if (escape){
          b = b ^ 0x20;
          escape = false;
        }

        if (len_i < 2){
          lenlen.len_array[1 - len_i] = b;
          len_i++;
        } else {
          xbee.buf[buf_i++] = b;
          sum += b;
        }
        if (
          len_i == 2 &&
          buf_i >= sizeof(xbee.buf)
          ){
          len_i = -1;
          buf_i = -1;
          // frame recieved !!
          if (sum == 0xff){ // check sum!
            *ret = xbee.frame.sensor_data;
            return true;
          }
        }
      }
      return false;
    }

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

    void loop() {
      //mySerial.println("work");
      // put your main code here, to run repeatedly:
     struct SENSOR_DATA data;
      if (xbee_rx(&data)){
        //Serial.print(data.rpm);

         // if(b == 0x40 )  //&& b == 0xd5 && b == 0xaa && b == 0xac
      }
    }

body:
I don't think you can.

The structures are defined within a function so the loop() won't have access to them.

Further the parameter returned from the function `xbee_rx()` is of type `SENSOR_DATA` which is a sibling in the `frame` structure to the data you want to read.


body:
Function xbee_rx() only returns the contents of `struct SENSOR_DATA` which doesn't include those addresses. You could instead 1) return the contents of the entire `struct {...} frame` which does contain them (making sure `loop()` 's buffer is large enough; or 2) instead of returning all of that data at all, make the `union {...} xbee` static so it persists after `xbee_rx()` exits, and return a pointer to `sensor_data`, with which loop() can access any member of it, such as `p->address1`.

Update:
The caller - rather than the called-function - allocates the memory buffer and the called-function uses that memory instead of its own, effectively passing the data to the caller. Here's your code, slightly re-written, with my initialed comments. I have not tried to run it but it does compile:

    #include <SoftwareSerial.h>

    struct SENSOR_DATA{
       char rpm;   // worked
      //float rpm;
      //float strain;
      //unsigned long sampling_interval;
    };

    //-jr-: Here we define what an XbEE_FRAME is and make it a data-type
    // but we don't allocate any storage. This is just information to the
    // compiler:
    typedef union {
        byte buf[25]; // 30
        struct {
          byte frame_type;
          byte frame_id;
          byte address1;
          byte address2;
          byte address3;
          byte address4;
          byte address5;
          byte address6;
          byte address7;
          byte reserved1;
          byte reserved2;
          byte recieve_options;
          struct SENSOR_DATA sensor_data;
          byte checksum;
        } frame;
    } XbEE_FRAME;

    //-jr-: This function expects a pointer to memory (i.e., its address)
    // allocated for data of type 'XbEE_FRAME' - the union from your
    // original code. Note that we don't allocate any memory for it here;
    // the caller is expected to do that, and this function will use what
    // the caller allocated.
    boolean xbee_rx(XbEE_FRAME *pXbF) {
      union LEN_FRAME{
        byte len_array[2];
        word len;
      }lenlen;
      static int len_i = -1;

      static int buf_i = -1;
      static bool escape = false;
      static byte sum;

      while (Serial.available() > 0) {
        byte b = Serial.read();

        //Serial.print(b, HEX);

         //b = Serial.read();
        if (
          b != 0x7e &&
          buf_i == -1 &&
          len_i == -1
          ) {
          continue;
        } else if (b == 0x7e){
          buf_i = 0;
          lenlen.len = 0;
          len_i = 0;
          sum = 0;
          escape = false;
          continue;
        } else if (b == 0x7d){
          //Serial.print("es: ");
          //Serial.println(b,HEX);
          escape = true;
          continue;
        }

        if (escape){
          b = b ^ 0x20;
          escape = false;
        }

        if (len_i < 2){
          lenlen.len_array[1 - len_i] = b;
          len_i++;
        } else {
           //-jr-: Note how we changed our reference from 'xbee.buf...' to
           // 'pXbF->buf...'! The '.' style addressing is used to refer to
           // memory we can name directly, as when you allocated that union
           // here. But now we  have to refer to it by the  pointer we received -
           // its address. The '->' symbol is how you address members of a
           // union or struct through a pointer:
          pXbF->buf[buf_i++] = b;
          sum += b;
        }
        if (
          len_i == 2 &&
          buf_i >= sizeof(pXbF->buf)
          ){
          len_i = -1;
          buf_i = -1;
          // frame recieved !!
          if (sum == 0xff){ // check sum!
        //-jr-: Notice that here we don't try to return any data;
        // we don't have to. Since We did everything in memory the
        // caller owns, the caller already has the data!
            return true;
          }
        }
      }
      return false;
    }

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

    void loop() {
      //mySerial.println("work");
      // put your main code here, to run repeatedly:

       //-jr-: Define the entire XbEE_FRAME here and pass its address to
       // your function. The function will use _this_ local storage
       // (instead of its own) to buffer the data, so it will already
       // be here when your function returns:
       XbEE_FRAME data;     //-jr- Define the entire union here
       if (xbee_rx(&data)){    //-jr-  and pass its address to the function
          //-jr-: You can address a member such as address3 as:
          //      data.frame.address3
        //Serial.print(data.rpm);

         // if(b == 0x40 )  //&& b == 0xd5 && b == 0xaa && b == 0xac

      }
    }

Update:

> How to get the SENSOR_DATA sensor_data?

Use: `data.frame.sensor_data.rpm` (lower case).

 - `SENSOR_DATA` only describes the kind of contents in a struct, not any actual data in memory.
 -  `sensor_data` is one instance of such a struct.

To go a bit further, suppose frame{} contained more than one `SENSOR_DATA` in it, maybe named sensor_data_a, sensor_data_b, ..., etc. Now to get the data from, say, `sensor_data_a` it should be clear that you need to refer to the particular instance you're interested in.


message:
In the AnalogRead example, would the thing work if I remove or short the A0 and the ground pin?

What I want to know is that how exactly does analogRead work because I have want to use it with a flex sensor and it has only two pins.I tried to find other examples on the internet, but this is the only example I find.If the middle pin of the 10k potentiometer and a0 pin are shorted or the gnd  pin is removed altogether,then would this thing work?

body:
I think you are confused because the ADC input measures voltage, not resistance.

To convert from resistance to voltage you need to pull in the opposite direction on the variable resistance with a fixed resistor.  As in the following image from [this tutorial][1].

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

  [1]: https://learn.sparkfun.com/tutorials/flex-sensor-hookup-guide
  [2]: https://i.stack.imgur.com/UkqHA.png


message:
If else statement not mutually exclusive?

When I'm running some test on my encoder motors using the following provided code by Makeblock, it appears that the `if..else..` statement is not mutually exclusive ie. I can control Encoder_1 and Encoder_2 at the same time. How come?

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

    case ENCODER_BOARD:
          if(port == 0)
          {
            uint8_t slot = readBuffer(7);
            int16_t speed_value = readShort(8);
            speed_value = -speed_value;`

            if(slot == SLOT_1)
            {
              Encoder_1.setTarPWM(speed_value);
            }
            else if(slot == SLOT_2)
            {
              Encoder_2.setTarPWM(speed_value);
            }
            else if(slot == SLOT_3)
            {
              Encoder_3.setTarPWM(speed_value);
            }
            else if(slot == SLOT_4)
            {
              Encoder_4.setTarPWM(speed_value);
            }
          }

    int16_t readShort(int16_t idx)
    {
      valShort.byteVal[0] = readBuffer(idx);
      valShort.byteVal[1] = readBuffer(idx+1);
      return valShort.shortVal;
    }

    uint8_t readBuffer(int16_t index)
    {
      if(BluetoothSource == DATA_SERIAL)
      {
        return buffer[index];
      }
      else if(BluetoothSource == DATA_SERIAL2)
      {
        return bufferBt1[index];
      }
      else if(BluetoothSource == DATA_SERIAL3)
      {
        return bufferBt2[index];
      }
    }

All the code are taken from [here][1] and I am not the owner. I myself still studying how these whole code works. I am hoping someone out there who have experience with these kind of implementations be able to help me out.

  [1]: https://github.com/Jc7tee/OPEN__MegaPi/blob/master/Firmware_for_MegaPi.ino

body: Exactly one of the blocks in `if{..} else {...}` will be executed.  Your misunderstanding is elsewhere.


body:
`if` and `else if` clauses are mutually exclusive. If the `if` is true then the `else if` *cannot* run.

Therefore it must be the case that the code you posted is being executed twice (at least) - once for SLOT_1 and once for SLOT_2.  Just so fast that you *think* it's happening at the same time.


body:
Yes they are mutually exclusive.

Note that the following construct is more appropriate:

    switch (slot)
    {
    case SLOT_1:
         Encoder_1.setTarPWM(speed_value);
         break;

    case SLOT_2:
         Encoder_2.setTarPWM(speed_value);
         break;

    case SLOT_3:
         Encoder_3.setTarPWM(speed_value);
         break;

    case SLOT_4:
         Encoder_4.setTarPWM(speed_value);
         break;

    default: // other cases/error
         // Handle error situation
         break;
    }

You can do the same with BluetoothSource.

Also you can do multiple commands within one case statement, like:

    case SLOT_4:
         Encoder_4.setTarPWM(speed_value);
         Encoder_Extra.setTarPWM(speed_value);
         break;

Note that the switch/case only works where you compare one variable/expression.


body:
> am hoping someone out there who have experience with these kind of implementations be able to help me out.

Match out the brackets (to your logic) and the issue will be clear.

Your inadvertently created a duffs machine


message:
ESP8266 Library Method List

Is there a place that lists all the common methods used with the standard ESP8266 libraries in Arduino?

body: Looking at the GitHub page, there is a document explaining how everything works, https://arduino-esp8266.readthedocs.io/en/latest/


message:
Arduino Compiling Error

I recently format my  Windows 8 and installed Windows 8.1 . In Windows 8, I was using Arduino IDE and there was no error in compiling.But then I installed Windows 8.1 and re-installed Arduino IDE.I tried various codes for motor drivers and everything but they didn't compile.So, I tried to compile blink LED example first and even it didn't compile.It shows the following error on UPLOADING BLINK LED Example-

    Arduino: 1.8.2 (Windows 8.1), Board: "Arduino/Genuino Uno"

    C:\Program Files\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files\Arduino\hardware -tools C:\Program Files\Arduino\tools-builder -tools C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files\Arduino\libraries -libraries C:\Users\Admin\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10802 -build-path C:\Users\Admin\AppData\Local\Temp\arduino_build_754363 -warnings=none -build-cache C:\Users\Admin\AppData\Local\Temp\arduino_cache_657645 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\Arduino\hardware\tools\avr -verbose C:\Program Files\Arduino\examples\01.Basics\Blink\Blink.ino
    C:\Program Files\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files\Arduino\hardware -tools C:\Program Files\Arduino\tools-builder -tools C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files\Arduino\libraries -libraries C:\Users\Admin\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10802 -build-path C:\Users\Admin\AppData\Local\Temp\arduino_build_754363 -warnings=none -build-cache C:\Users\Admin\AppData\Local\Temp\arduino_cache_657645 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\Arduino\hardware\tools\avr -verbose C:\Program Files\Arduino\examples\01.Basics\Blink\Blink.ino
    Using board 'uno' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
    Using core 'arduino' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
    Detecting libraries used...
    "C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\sketch\Blink.ino.cpp" -o "nul"
    Generating function prototypes...
    "C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\sketch\Blink.ino.cpp" -o "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\preproc\ctags_target_for_gcc_minus_e.cpp"
    "C:\Program Files\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\preproc\ctags_target_for_gcc_minus_e.cpp"
    exit status 1
    Error compiling for board Arduino/Genuino Uno.

I tried RE-installing the software and drivers.It didn't work

Why is this happening?What is the Solution?

body:
Right click on the Arduino icon, select properties. Under the compatibility tab, check "Run this program in compatibility mode" and select Windows XP. You might also want to run it as administrator.

This should hopefully solve the issue.

[Source](http://forum.arduino.cc/index.php?topic=179586)


body:
Uninstall Arduino. Then find the Arduino folder in your Appdata folder and delete it. Then reinstall Arduino. This is happening because after a library import, there might have been a clash in the Appdata and since uninstalling doesn't delete Appdata, just reinstalling wouldn't help. This happened to me when a PPM and Servo library clashed!

Note: Do this only after you try uploading a blank sketch and it still fails! Also be careful while in the Appdata folder.


message:
Three or more Arduino slaves sending bytes to 2 different I2C devices

I'm trying to connect 3 Arduinos with this scheme: Arduino1 Master, Arduino2 Slave, Arduino3 Slave. The slave devices need to communicate with each other and I'm trying to programming Arduino2 and transmit bytes to the other slave device Arduino3 and Master Arduino1 at the same time. Is that possible?

Master CODE:

    #include <Wire.h>

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

    void loop() {
      Wire.requestFrom(0x04, 2);
      while (Wire.available()) {
        var1 = Wire.read();
        var2 = Wire.read();
      }
    }

Arduino1 Slave:

    #include <Wire.h>

    void setup() {
      Wire.begin(0x05);
      Wire.onReceive(receiveEvent);
    }

    void loop() {
    }

    void receiveEvent(int howMany) {
      var1 = Wire.read();
      Serial.print("VAR1 is : ");
      Serial.println(var1);
    }

Adrduino2 Slave code:(Where I think I'm wrong)

    #include <Wire.h>
    int var = 123;
    int var2 = 123;
    int var3 = 123;

    void setup() {
      Wire.begin(0x04);
      Wire.onRequest(requestEvent);
    }

    void loop() {
      Wire.beginTransmission(0x05);
      Wire.write(var);
      Wire.endTransmission();
    }

    void requestEvent() {
      Wire.write(var1);
      Wire.write(var2);
    }

Is this the correct way to make the Arduino2 send to 2 devices?

body:
As soon as an Arduino starts writing data, it is a Master. Do you use Arduino Mega 2560 and Arduino Uno and Nano boards ? In theory those ATmega microcontrollers can handle collisions in a multi-Master bus, and in theory the Wire library handles collisions as well. However, everyone tries to avoid that, because it causes a lot of problems. You would even have to program a complete new layer in the code to re-transmit data until it was received without collision.

Select one Arduino board as Master, and use the Master to read and write data. If you want to transfer data from one Slave to the other Slave, then use Master to read the data from one Slave and write the data to the other Slave.

It is possible to use other busses between the two Slave Arduino boards.


message:
Convert to and from Unix Timestamp

What is the best way to convert between date, hours, min, seconds to Unix timestamp in milliseconds in Arduino? I need to have this conversion, since I'm using RTC (date, hours, min, secs etc) and communicating Unix timestamp over BLE

I found some snippet of codes online, but have not tested it extensively yet.
<!-- language-all: lang-cpp -->

      byte second = epoch`; epoch /= 60;
      byte minute = epoch`; epoch /= 60;
      byte hour   = epoch$; epoch /= 24;

      unsigned int years = epoch/(365*4+1)*4; epoch %= 365*4+1;
      unsigned int year;
      for (year=3; year>0; year--)
      {
          if (epoch >= days[year][0])
              break;
      }

      unsigned int month;
      for (month=11; month>0; month--)
      {
          if (epoch >= days[year][month])
              break;
      }

      year  = years+year;
      month = month+1;
      unsigned int day   = epoch - days[year][month]+1;

      unsigned int weekday  = (dayOfMonth += month < 3 ? year-- : year - 2, 23*month/9 + dayOfMonth + 4 + year/4- year/100 + year/400)%7;

And to convert to Unix timestamp:

    unsigned long epoch = (((year/4*(365*4+1)+days[year%4][month]+dayOfMonth)*24+hour)*60+minute)*60+second;

Are there any library in Arduino that implement this? I would trade off reliability over size of the program.

body:
I think that the two most used libraries are the [Adafruit RTClib][1] and the [pjrc.com TimeLib][2].
They both have functions to convert the epoch, and they both are reliable. But both lack the timezone and the DaylightSavingTime.
I think you find the pjrc.com TimeLib just slightly more suitable to handle the epoch time (which is a 32-bit unsigned long defined as 'time_t').

  [1]: https://github.com/adafruit/RTClib
  [2]: https://www.pjrc.com/teensy/td_libs_Time.html


body:
There is a standard way of doing those conversions in C, which is
through the functions defined in `<time.h>`. This API being standard,
you can test it in your computer. Recent versions of the avr-libc
support this: see [time.h in avr-libc][]. These functions can handle
local time if you provide a function implementing the DST rules: see
`set_dst()`. Examples are provided for US and EU rules.

[time.h in avr-libc]: http://www.nongnu.org/avr-libc/user-manual/group__avr__time.html


body:
Here's an example to convert seconds (Unix time) to Date & Time using TimeLib.h:

    #include <TimeLib.h>

    unsigned long offset_days = 3;    // 3 days
    unsigned long t_unix_date1, t_unix_date2;

    void setup() {
      Serial.begin(115200);
      t_unix_date1 = 1564398600;
      Serial.print("t_unix_date1: ");
      Serial.println(t_unix_date1);
      offset_days = offset_days * 86400;    // convert number of days to seconds
      t_unix_date2 = 1564398600 + offset_days;
      Serial.print("t_unix_date2: ");
      Serial.println(t_unix_date2);
      printf("Date1: M-d-d d:d:d\n", year(t_unix_date1), month(t_unix_date1), day(t_unix_date1), hour(t_unix_date1), minute(t_unix_date1), second(t_unix_date1));
      printf("Date2: M-d-d d:d:d\n", year(t_unix_date2), month(t_unix_date2), day(t_unix_date2), hour(t_unix_date2), minute(t_unix_date2), second(t_unix_date2));
    }

    void loop() {

    }


message:
Servotimer2, detach "stop"

I'm still struggling with the Servotimer2 library

I have an Arduino uno board with a servo motor with the servotimer2 library because I'm using a music shield beside the servomotor and the music shield library and the servo.h wasn't compatible.
But finally I make the two of them working together with the servotimer2.h but now I want my servo to rotate 90 or 180 and then "stop" for a minute and come back again, rotate, stop, rotate,stop, rotate, stop... short of thing so I read this [what is commonly done to stop a servo after reaching desired point][1] and now I know that servo can't stop, but they can detach
so I tried making something like this

    #include <ServoTimer2.h>  // the servo library
    #define rollPin  9

    ServoTimer2 servoRoll;

    void setup() {
      servoRoll.attach(rollPin);

    }

    // this function just increments a value until it reaches a maximum
    int incPulse(int val, int inc){
       if( val + inc  > 2000 )
          return 1000 ;
       else
           return val + inc;

    }

    void loop()
    {
       mover();
       parar();

    }

    void mover() {
     int val;

       servoRoll.attach(rollPin);
       val = incPulse( servoRoll.read(), 2);
       servoRoll.write(val);
       delay(10);

    }
    void parar() {

      servoRoll.detach();
         delay(100);
    }

but the servo is only moving very slow and I think is not detaching in any moment. I'm quite lost, I'm very noobie and in the post([what is commonly done to stop a servo after reaching desired point][1]) they said things like making while(true){} loop in the setup? or use millis() and other things that I don't understand quite well
But someone tried to do something like control the time the servo is stopping with the delay, so I tried something like this

    #include <ServoTimer2.h>  // the servo library

    // define the pins for the servos
    #define rollPin  9

    int pos = 0;

    ServoTimer2 servoRoll;    // declare variables for up to eight servos

    void setup() {
      servoRoll.attach(rollPin);     // attach a pin to the servos and they will start pulsing

    }

    //from https://learn.adafruit.com/multi-tasking-the-arduino-part-1/a-clean-sweep

    void loop()
    {
     for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
      {                                  // in steps of 1 degree
        servoRoll.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
      {
        servoRoll.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }

    }

but with this code, my servo is only moving once, and then stops and don't move again

and I think that my servo with the servotimer2 library is only moving with this

       int incPulse(int val, int inc){
       if( val + inc  > 2000 )
          return 1000 ;
       else
           return val + inc;
    }

    void loop()
    {
     int val;

       val = incPulse( servoRoll.read(), 1);
       servoRoll.write(val);
      delay(10);
    }

so, any ideas of what I'm doing wrong?
  [1]: https://arduino.stackexchange.com/questions/4076/what-is-commonly-done-to-stop-a-servo-after-reaching-desired-position

body:
_my servo is only moving once, and then stops_ You mean it turns 180° then no more? Once it has reached 180° (or 2000 µs) you need to decrease `val` by one to go the other way (from 2000 to 1000). For example:

    int direction = 1;  // 1 or -1
    void loop()
    {
       int val;

       val = incPulse( servoRoll.read(), direction);
       servoRoll.write(val);
       if (direction <= 1000 || direction >= 2000) {
          direction = -direction;
       }
       delay(10);
    }


message:
Open source PLC Wifi

I'm working on a project that involves a device called the plduino (aka Open Source PLC). This is the website for the device:

https://www.digital-loggers.com/plc.html

and the GitHub:

https://github.com/digitalloggers/PLDuino

Using the examples on the GitHub, I've been able to figure out other parts- storing on the SD card, the GUI, digital IO, etc. But I haven't been able to figure out the WiFi module (which seems to be through a ESP8266 device). I looked through the libraries directory on the GitHub link, but didn't find anything that looked like it connected to the internet or could send or receive data. The documentation says the device can connect to wifi, but is otherwise very little help.

Has anyone used this before? How do I make this device connect to wifi?

body:
This is not particularly easy to figure out. The ESP8266 is addressable via a serial port. The ESP8266 firmware is called NodeMCU, which sits on top of the ESP8266 firmware and allows you write Lua code to implement custom Wifi functions. The PLC comes with example Lua that starts a webserver and publishes a webpage that allows you to check and set the status of the PLC (but only if you connect to the PLC, which is in access point mode.)

If you want it to behave like wifi on a normal desktop computer, you have to do some Lua programming (I could not find any Lua code online that did basic things out of the box, but there are a fair number of examples and snippets on the NodeMCU sites.)

In spite of how cool this device is, I ultimately decided it was just too much work to get the Wifi integration working (the Arduino stuff is of course pretty easy). You also have the problem of how to get your data logs somewhere. Since the data is on the Duino and the ESP8266 is the web interface, you either have to poll the Duino (which the example code does) and upload to a site (e.g. AWS), or log the data on the Duino, then send it over the serial port for upload -- MORE Lua and Duino coding. Plus if you want to put your data on AWS IoT (for example) the Duino/NodeMCU technically does not support the TLS 1.2 and X.509 cert handling you need to register (although they are apparently some workarounds now.) Life. Is. Too. Short. For. That.

I switched to Raspberry Pi, which is about 1000 times simpler, even though it does not have the cool features like open collectors and optical isolators. I'm now looking at Pi enclosures, such as the nice BC packaging from Phoenix Contacts. I decided it was simpler to make my own custom PLC for my home HVAC automation project than it was to code the DL-PLC. Bummer. Maybe they'll do a Pi version of this someday.

The repositories for my DL-PLC and RPi projects are on GitHub (https://github.com/dglcinc/HVAC-plc and https://github.com/dglcinc/HVAC-pi), you may find my Lua code and implementation notes useful if you want to get the wifi working on the DL-PLC. I *did* get it working in station mode (so you can join it to your home access point, address it with a DHCP IP, etc.) but that's about as far as I got.


message:
Image Breakdown

I've been trying to figure out a way to store an image on the Arduino, and I couldn't figure it out. What I've been trying to do with this image is the following:

 - Test that the arduino has the image by displaying on a touchscreen (I have the adafruit 2.8 inch touch screen)
 - Break down the image into an array, in which contains pixel by pixel color RGB color info of the image

`int pictureData = [[100,50,0],[176,255,5],...]; // RGB Values within the array`

How can I store an image and break it down as shown? Is there no way to do this? I would appreciate any help! Thank you very much!

I am using Arduino IDE for code and I have Arduino Uno/MEGA, which ever is necessary for this task. All info of screen is on adafruit: https://www.adafruit.com/product/376

The below image shows an example of displaying the image:

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

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

body:
240 by 320 pixels.  That's 76800 pixels.  In your example it looks like you want 3 bytes per pixel, so that's 230400 bytes.  An Arduino Mega has 8K bytes of SRAM memory.  There's enough room in the memory on the Arduino Mega to hold 0.003% of your image.

Maybe you could store the image on an SD card and put it on the screen little piece by little piece, but that is going to be painfully slow.


body:
I presume you are trying to create a system that has one image stored, and want the image to be available without needing an SD card reader on the system.

If the logic of your program is small enough to fit into about 18KB of flash memory, you can store one 230KB image in flash on a Mega. (230KB+18KB+8KB = 256KB = Mega flash size.  8KB is [Mega bootloader size](https://arduino.stackexchange.com/questions/3819/why-bootloader-size).)  See the [PROGMEM](https://www.arduino.cc/en/Reference/PROGMEM) page at arduino.cc for examples of declaring and accessing arrays from flash.

If you end up needing lots more flash for the logic of your program, consider compressing the 18 bits of each pixel to 16 bits.  The 230KB figure is 240·320·3.  Each pixel on the display uses six bits per color, stored in three bytes per pixel.  Instead of keeping all the bits, you could clip the blue to its high four bits; ie, save 6-6-4 for RGB in two bytes instead of 6-6-6 in three bytes.  Or could clip two of the colors to their high five bits; eg, save 6-5-5 or 5-6-5.  At two bytes per pixel, an image would take 240·320·2 = 153600 bytes of flash, leaving roughly 94KB for program logic.

In all of these approaches, image data would be brought into RAM row by row or column by column, unpacked, and copied to the RAM buffers in the display.

One could also apply some compression algorithms to the image instead of using BMP format.

If you need more images than one, you could further reduce image quality, for example could save 3-3-2 high bits of color per pixel, or could save only every other pixel in a row or column or both, reducing storage to a half or fourth as much.  Or you could have one reasonably good image stored 6-6-4 at 16 bits per pixel, so about 154KB, plus several monochrome images stored one bit per pixel, or about 10KB each.

---

*Edit 1:* Re “how would I take an image and convert it into the RGB array?”, one straightforward approach is to write an image-converter program (that runs on your development system) to read an image file and output C code representing the image data in arrays; that is, to produce C-style arrays printed in ASCII.   Again, this recommendation is predicated on the notion that you are trying to create a system that has one image stored, and want the image to be available without needing an SD card reader on the system.

I recommend writing the image-converter program in Python.  See, for example, the accepted answer at  [*Convert an image to 2D array in python*](https://stackoverflow.com/q/27026866), to which you would need to add a few lines of code to write out C code to a file, so that you could include that code into a sketch.  Also see  [*How to get an array from RGB values of a bitmap image?*](https://stackoverflow.com/q/21885713) and [*Working with .bmp files in python 3*](https://stackoverflow.com/q/20276458).

Some C-language examples appear in answers to  [*How to convert a .bmp image into Byte array using C Program*](https://stackoverflow.com/q/29058452) and [*How to convert an image to WORD (uint16) array?*](https://stackoverflow.com/q/10103716), which are among the first links in [a stackexchange search for “convert bmp image to array”](https://stackoverflow.com/search?q=convert+bmp+image+to+array).

Wikipedia's [BMP file format](https://en.wikipedia.org/wiki/BMP_file_format) article shows the layout of BMP files in general.  Using various image-handling libraries (as recommended in SE questions listed above) sidesteps having to deal with low-level BMP details.  However, you may be able to use a simple program or application to produce [RGB565 color format](https://www.google.com/search?num=50&site=&source=hp&q=rgb565+format&oq=rgb+565&gs_l=hp.1.2.0j0i10k1l9.1334.4865.0.8711.8.7.0.0.0.0.129.701.4j3.7.0....0...1.1.64.hp..1.7.697.0..0i131k1j0i22i30k1j0i22i10i30k1.fao6DuqNlpc) files, eg as at [*Bitmap to RGB565 format* on codeguru.com](http://forums.codeguru.com/showthread.php?374650-Bitmap-to-RGB565-format), and then write a simple program to convert that particular form to C-style arrays printed in ASCII.


message:
Can I connect my Arduino Uno to a power source and a battery at the same time?

My aim is to be able to power my Arduino while there is a power supply and if there isn't the Arduino automatically switches over to the battery. The components connected to the Arduino are pir sensor, smoke sensor, SIM 800L, temperature sensor, 6v relay.

body: Yes, to my knowledge this is done automatically, and there is no harm when connecting the Arduino to two power sources. When I power my Arduino I have it connected to my computer and the wall. So theoretically, if the electricity in the wall stopped coming, it would start taking power from the computer. Same works for battery.


body: Most mainstream and reputable Arduino variants (the UNO or Pro, for example) have protection circuitry that allows it to basically ignore where its power is coming from, as long as the voltage isn't above 20v. This is because almost every Arduino device funnels its power through an appropriate regulator, ensuring there is no problem with the voltages or available current suddenly changing (switching power feeds). However, you should account for what happens when you plug an external power source in the same loop as a battery that might be a different voltage. If you're going to try to have them manually switch then you'll need an external circuit (perhaps using a transistor that shuts off the battery when the power supply is active, with capacitors for a buffer), else you could have problems with popping batteries. But be warned, if you plug your battery into the PWR (5V/3V3) pin(s) of the Arduino, then you'll need to provide your own protection.


message:
I have cooked 3 regulators applying 12 V to RAW pin. Am I doing something wrong or did I get a bad batch?

I'm trying to make a simple keypad lock that has a 12 V magnetic lock.  I supplied 12 V to the RAW pin on the Pro Mini with plans to actuate the relay with the 5 V from VCC pin.  The lock was grounded on the terminal strip that the 12 V came from, and then the positive 12 V was switched through the relay.

Everything was working well until I powered the board through the RAW pin with 12 V.  When I did that all three failed the smoke test.

My question is, am I doing something incorrectly or did I happen to get a bad batch (all three of the boards came in the same shipment, I assume they came from the same lot)?

body:
The Pro Mini's 5V regulator (MIC5205) can supply a maximum of 150 mA, from which the Pro Mini uses about 20 mA, leaving around 130 mA for other applications.

[![Pro Mini power supply][1]][1]

Check the data sheet of the relay, to get the maximum current draw. For example, the RWH-SH-105D relay requires around 70 mA in the "on" position. While this is under the 130mA limit, you may be using other IOs or powering other modules.

To reduce the current draw, use a transistor to drive the relay like this:
[![Relay driver][2]][2]

  [1]: https://i.stack.imgur.com/y6dK9.jpg
  [2]: https://i.stack.imgur.com/rS2AE.png


body:
A magnetic lock will be based on a solenoid, which will probably draw quite a high current from the 12 V rail. When that load is switched, **a voltage spike will appear into the 12V rail** due to the inductance of the supply wires. The longer the wires and the higher the current, the bigger the voltage spike.

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

<!-- End schematic -->

If the spike goes above 20V (and it can easily happen, believe me) then **it will exceed the maximum rating of the MIC5205 voltage regulator and fry it** unless you prevent that with some extra components. The voltage rating of the regulator input capacitor in the Pro Mini probably isn't up to the task of handling 20+ V spikes either and may be getting damaged too.

Note that **the Pro Mini is specified to work with input voltages only up to 12 V**, so you are operating it with no margin whatsoever! You should **consider reducing that voltage** in first place. You could use a DC/DC converter module to step down the 12V to a more suitable 7V and provide isolation from the spikes at the same time.

Apart from that, **consider using a transient voltage suppressor (TVS or transzorb diode) and/or a large decoupling capacitor (with an adequate voltage rating)** as close as possible to the input of the Pro Mini or the DC/DC converter (if you use one). You might want to try decoupling your magnetic lock with a properly selected capacitor as well.

----------

Bonus: thermal considerations
-----------------------------

Thermal issues shouldn't be the main culprit here, but be aware that the tiny MIC5205 can get extremely hot and enter thermal shutdown mode when operated at 12 V input voltage.

The junction to ambient thermal resistance of the regulator is 220 C/W. Its maximum operating junction temperature is 125 C. At 25 C ambient temperature that means the maximum allowable temperature rise is 100 C and the maximum allowable power dissipation is 455 mW. Because the regulator is dropping 7V, the maximum allowable current will be only 65 mA (instead of the 150 mA max that the MIC5205 can source in more favorable conditions). The consumption of the Pro Mini is around 20 mA, so that leaves you with only 45 mA for your application. You should consider whether this is enough for your application or not (some 5V relays draw around 80 mA, which will greatly exceed this 45 mA calculated limit, when connected to the VCC pin of the Pro Mini).


message:
Understanding how methods and pointers inside a function work

[After this question][1] i starteted going deep with the theory, and started studyng step-by-step with the ["Beginning C, for Arduino "
Jack Purdum.][2]

I finished to study the functions chapter, but i still have some doubts on the code, i hope this will be not a dumb question.

----------

Why there is a Method "Print" not a Data Type inside the Function Argument List?
------------------------------------------------------------------------

----------

    static void printImuData(Print &printer, int16_t Time0,
            int16_t AcX, int16_t AcY, int16_t AcZ,
            int16_t GyX, int16_t GyY, int16_t GyZ)
    {
        printer.print(Time0); printer.print(",");
        printer.print(AcX);   printer.print(",");
        [...]
    }

    [...]

    printImuData(dataFile, Time0, AcX, AcY, AcZ, GyX, GyY, GyZ);
    if (Serial_plus_SD)
        printImuData(Serial, Time0, AcX, AcY, AcZ, GyX, GyY, GyZ);

I though the answer was "because you can pass data to a function by-value or by-reference" in fact the first input in the argument list is the left value (memory address) of a Method, but i am very confused.

Function arguments are used to pass data to the function that it may need to perform its task.

I tried to answer to the following questions to understand the code.

 **1. What task does this function perform?**

The function will print some data on a Serial Monitor or SD Card

 **2. What data do i need to send to the function?**

I need to send one Method through the left value of a pointer and 7 intergers.
I can't understand why a method.

 **3. What data do I get back from it?**

Nothing because is a void, it will perform some task inside the function (print inside the object thas is pointed?) but nothing will return to the caller.

In the book  basic example is a function that returns the value 0 or 1 if is a Leap Year.

The function argument is an int and returns an int.

    void loop()
    {
     if (Serial.available() > 0) {
      int bufferCount;
      int year;
      char myData[MAXCHARS + 1]; // Save room for null
      bufferCount = ReadLine(myData);
      year = atoi(myData); // Convert to int
      Serial.print("Year: ");
      Serial.print(year);
      Serial.print(" is ");
      if (IsLeapYear(year) == 0) {
       Serial.print("not ");
      }
      Serial.println("a leap year");
    }
    }
    /*****
    Purpose: Determine if a given year is a leap year
    Parameters:
    int yr The year to test
    Return value:
    int 1 if the year is a leap year, 0 otherwise
    *****/
     int IsLeapYear(int yr)
     {
     if (yr % 4 == 0 && yr % 100 != 0 || yr % 400 == 0) {
      return 1; // It is a leap year
     } else {
      return 0; // not a leap year
     }
    }
    /*****
    Purpose: Read data from serial port until a newline character is read ('\n')
    Parameters:
    char str[] character array that will be treated as a null-terminated string
    Return value:
    int the number of characters read for the string
    CAUTION: This method will sit here forever if no input is read from the serial port
    and no newline character is entered.
    ****/
    int ReadLine(char str[])
     {
      char c;
      int index = 0;
      while (true) {
      if (Serial.available() > 0) {
      index = Serial.readBytesUntil('\n', str, MAXCHARS);
      str[index] = '\0'; // null termination character
      break;
      }
     }
     return index;
    }

Like in my the last question, I have a civil engineer background and i am a self-taught, so is my first time with coding :)

**Thank you for your patience.**

  [1]: https://arduino.stackexchange.com/questions/36052/understanding-why-should-avoid-string-and-alternative-solutions
  [2]: http://www.apress.com/us/book/9781484209417

body:
"There are no stupid questions, just stupid answers"

> Why there is a Method "Print" not a Data Type inside the Function Argument List?

There is no "Method" Print in the argument list.  There is a reference (not a pointer which would be a * not a &) to an object called `printer` that is of type Print.  The code you have provided doesn't define `Print` but its a could guess that it is probably something to do with printing.  By supplying the `printer` argument you can print this data to anything that inherits from the Print base class, Serial is a good possibility, but you could write a class that derived from Print and wrote the data to an LED matrix, etc.
I can tell its not a Method, because you are calling the print method of printer, so it has to be either a class or structure.

> The function will print some data on a Serial Monitor or SD Card

I can see why you thought that but you are being too specific, it prints to anything that derives from Print, `Serial` and `dataFile` derive from it, but they might not be the only things.

> I need to send one Method through the left value of a pointer and 7 integers. I can't understand why a method.

An example might help:

    class CGPrinter : public Print
    {
      // Some code....
      virtual void print (const char* input) {// do something}
    }

    void loop()
    {
      CGPrinter cgp;
      printImuData (Serial, 1,2,3,4,5,6,7);
      printImuData (cgp, 1,2,3,4,5,6,7);
    }

`Serial` is an object, a variable, a specific instance of type of class that can print data.

CGPrinter is my new super sexy printing class that will read the characters that you 'print'.  To print the 7 integers to CG's printer class is exactly the same call as the one to write it to the Serial Monitor, because both classes derive from Print.

> 3. What data do I get back from it?

Yes, correct on both points.

Does it make more sense now?  If not, just say and I'll try and clarify it.


message:
It is possible to carry a pic c code for arduino

Code C for **PIC16F887**, I want to be able to try this code in **ATMEGA328**, but I do not know how, I do not know the outputs of the pic, that is, none of the pic I know.

*Thank you for helping me. Grateful.*

    /*
    Universidad del Azuay
    Microcontroladores
    Proyecto Piano
    Autores: Juan Pablo León, Santiago Vazques
    Tutor: Ing. Kenneth Samuel Palacios Baus
    Fecha: 2 de enero de 2015
    */

    //Declaración de Funciones
    void ndo(); //Nota Do
    void sdo(); //Nota Do Sostenido
    void nre(); //Nota Re
    void sre(); //Nota Re Sostenido
    void nmi(); //Nota Mi
    void nfa(); //Nota Fa
    void sfa(); //Nota Fa Sostenido
    void nsol(); //Nota Sol
    void ssol(); //Nota Sol Sostenido
    void nla();  //Nota La
    void sla(); //Nota La Sostenido
    void nsi(); //Nota Si
    void ndo2(); //Nota Do

    //Programa Principal
    void main (){
    osccon=0x77; //Ocilador de 8bits interno del PIC16f887

    TRISC=0XFF; //Puerto C habilitamos como entrada  para las notas normales
    PORTC=0;;

    TRISB=0XFF; //Puerto B habilitamos como entrada para los sostenidos
    PORTB=0;

    TRISD=0X00; //Puerto D habilitamos como salida para el sonido del parlante
    PORTD=0;

    ANSELH = 0x00;
    ANSEL=0x00;      // Bits AN6:AN0 como E/S digital.

        while(1){

            PORTB=0xFF;  // 255   11111111
            switch(PORTB)
            {
                   case  0b00000001: sdo();  break;  //#Do
                   case  0b00000010: sre();  break;  //#Re
                   case  0b00000100: sfa();  break;  //#Fa
                   case  0b00001000: ssol(); break;  //#Sol
                   case  0b00010000: sla();  break;  //#La
            }

            PORTC=0xFF;  // 255   11111111
            switch(PORTC)
            {
                   case  0b00000001: ndo();  break;  //Do
                   case  0b00000010: nre();  break;  //Re
                   case  0b00000100: nmi();  break;  //Mi
                   case  0b00001000: nfa();  break;  //Fa
                   case  0b00010000: nsol(); break;  //Sol
                   case  0b00100000: nla();  break;  //La
                   case  0b01000000: nsi();  break;  //Si
                   case  0b10000000: ndo2(); break;  //Do
            }
        }

    }

    void ndo(){      //Do
            PORTD=1;
            delay_us (1911);
            PORTD=0;
            delay_us (1911);
    }

    void sdo(){      //#Do
            PORTD=1;
            delay_us (1804);
            PORTD=0;
            delay_us (1804);
    }

    void nre(){     //Re
            PORTD=1;
            delay_us (1702);
            PORTD=0;
            delay_us (1702);
    }

    void sre(){     //#Re
            PORTD=1;
            delay_us (1607);
            PORTD=0;
            delay_us (1607);
    }

    void nmi(){     //Mi
            PORTD=1;
            delay_us (1517);
            PORTD=0;
            delay_us (1517);
    }

    void nfa(){     //Fa
            PORTD=1;
            delay_us (1432);
            PORTD=0;
            delay_us (1432);
    }

    void sfa(){     //#Fa
            PORTD=1;
            delay_us (1351);
            PORTD=0;
            delay_us (1351);
    }

    void nsol(){    //Sol
            PORTD=1;
            delay_us (1276);
            PORTD=0;
            delay_us (1276);
    }

    void ssol(){    //#Sol
            PORTD=1;
            delay_us (1203);
            PORTD=0;
            delay_us (1203);
    }
    void nla(){     //La
            PORTD=1;
            delay_us (1136);
            PORTD=0;
            delay_us (1136);
    }

    void sla(){    //#La
            PORTD=1;
            delay_us (1121);
            PORTD=0;
            delay_us (1121);
    }

    void nsi(){    //Si
            PORTD=1;
            delay_us (1012);
            PORTD=0;
            delay_us (1012);
    }

    void ndo2(){   //Do
            PORTD=1;
            delay_us (955);
            PORTD=0;
            delay_us (955);
    }

Code file taken from this video: https://www.youtube.com/watch?v=2jVZnKjCltw

body:
No, you can not run Microchip PIC16F887 on an Atmel ATMEGA328 directly.  Any code that does useful work likely interfaces with the "outside world" through the processor's inputs and outputs (ADC, GPIO, ect).  It is very unlikely any two processor designs approach interfacing to the outside world in the same way.

The process of recoding software / firmware to run on different processors is called [porting][1].  It is a time consuming and costly process which is repeated over and over again.  Porting is most often done because people or companies want to use the same software / firmware despite changing hardware due to speed increases, size reductions or cost reductions.

  [1]: https://en.wikipedia.org/wiki/Porting


body:
There are two things you need to learn:

1. What the instructions in the PIC program mean, and
2. What the equivalent instructions (or functions for abstracted concepts) are in the Arduino API.

For instance, it looks like you may be making sounds of specific pitches. For that you would replace much of your code with the `tone()` function.

Reading IO pins would be done with `digitalRead()`, and `pinMode()` to set them to INPUT mode.

Basic C constructs like `switch`, and `if() { } else { }` etc are the same, but given the abstractions the Arduino API gives you it's probable you'd be using them in different ways anyway.

So in a nutshell: learn what your program is doing, then write the equivalent program for the Arduino.


message:
Use SPI and I2C in the same circuit (ATtiny85/84)

There is a previous question about this same topic [here][1], but it does not answer my question.

I want to use a generic I2C OLED 128x64 px display and an SPI RF24 radio in the same sketch. I know that it's theoretically possible to do so as long as they're not used at the same time - my question concerns the implementation of this circuit. Can I just leave the two devices as-is without needing some kind of external apparatus to switch power to each one of them?

I know that for SPI a chip will just ignore everything when its CS pin is pulled high, and from my tests the SPI communications don't affect the SDA line of the I2C - the problem comes when I try and use the CLK and SCL line with [this setup][2]. The pullup resistor in my circuit is stopping the I2C SCL line from working. When I remove the wire (green in the breadboard schematic shown) that connects the CLK to one end of the diode the I2C starts working and the display updates, but the radio doesn't work. If I remove the pullup resistor from the circuit the I2C starts working again, but the radio doesn't work anymore. I tried switching the CLK signal with a transistor, but it doesn't look like the 2n2222 transistor I was using is fast enough to switch the CLK signal. Will I have to go with the tiny84, or is there a way to get this to work on the ATtiny85?

  [1]: https://arduino.stackexchange.com/questions/32406/i2c-and-spi-at-the-same-time
  [2]: https://www.hackster.io/arjun/nrf24l01-with-attiny85-3-pins-74a1f2

body: In the setup shown, you have 3 pins free, yes? Although hardware i2c may not be directly possible through software, the use of the other GPIO pins can be used for either a logic circuit to switch around the pull up resistor/green wire/whatever OR you can just use software i2c which is a lot easier to do.


message:
Arduino ISP ATtiny problems

As I was trying to program my ATtiny chip with my arduino, I ran across some problems. Note that I know that this problem is faced almost in every Q and A site and forum so don't flag me as repeat _yet_. (I was trying to burn the bootloader so my chip runs at 8MHz)

So this is the error code:

    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -v -v -v -pattiny85 -cstk500v1 -PCOM1 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0xe2:m

     avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM1
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03

    avrdude done.  Thank you.

    Error while burning bootloader.
* **deleted attempt 2 to 9** *

Although a solution to this problem will be very nice, that is not my intention here. I tried almost all solutions I have found and non of them work, and I want to know why. So these are my questions:

1. What does this code actually mean? The for example the "programmer", is it referring to the Arduino or the ATtiny(or the highly unlikely, laptop that im using.)
2. How do I access more error codes, if there are any, as I think that these codes really do not tell that much.
3. [Solved]To prevent Arduino from auto-resetting, almost all tutorials connect the Reset pin to the Ground pin with a 10uF capacitor, and I don't have one. I tried with various other capacitors that I have(22uF, 0.4uF, 0.22uF, 47uF, and 330uF). I do not know how does the capacitance affect the anti auto-resetting function, so some explanation here is helpful.
[solved]

**EDIT: I disconnected the ATtiny and the same error code persists. This, I conclude as either I never had a proper connection with the ATtiny, or the problem is with the communication of my laptop with the Arduino.**

body: I did not download Arduino as ISP into my arduino. I realize how much of an idiot I am. The capacitor wasn't even needed for some reasons. I might make an intensive tutorial on this project.


message:
Cannot obtain reading from meter (Modbus)

I have a system in which I am taking readings from a meter and processing it through an Arduino Nano. My code looks as follows:

    #include <SoftwareSerial.h>

    #define SerialControl 7
    #define RS485Tx HIGH
    #define RS485Rx LOW

    SoftwareSerial RS485Serial(11, 12);
    uint8_t window[8]; // Initialising window of 8 bytes

    byte SendKWh[] = { 0x01, 0x03, 0x40, 0x34, 0x00, 0x02, 0x90, 0x05 };

    // 0x01: Meter Address, 0x03: Read Function Code, 0x40: Register Address Variable (Start address high bit)
    // 0x34: Register Address Variable (Start address low bit)
    // 0x00: Register Quantity (High Bit), 0x02: Register Quantity (Low Bit)
    // 0x90: CRC check code (CRC code Low bit)
    // 0x05: CRC check code (CRC code High bit)

    void dumpWin() {
      for (int i = 0; i < 8; i++) {
        Serial.print(window[i], HEX);
        Serial.print(" ");
      }
      Serial.println();
    }

    void ReadRx() {
      // Sliding Window Implementation for reading data
      if(RS485Serial.available()) {
        uint8_t b = RS485Serial.read();
        dumpWin();
        // Slide the contents of the array down
        for (uint8_t i = 0; i < 7; i++) {
          window[i] = window[i+1];
        }
        window[7] = b; // Next frame inserted at the top of previous
        if ((window[0] == 0x01) && (window[1] == 0x03) &&
          (window[2] == 0x40) && (window[3] == 0x34)) {
          // Doing something with window[4] and window[5] here
        }
      }
    }

    void setup() {
      Serial.begin(115200);
      pinMode(SerialControl, OUTPUT);
      RS485Serial.begin(9600);
    }

    void loop() {
      static uint32_t ts = millis();
      if (millis() - ts >= 2000) {
        ts = millis();
        digitalWrite(SerialControl, RS485Tx);
        RS485Serial.write(SendKWh, sizeof(SendKWh));
        RS485Serial.flush();
        digitalWrite(SerialControl, RS485Rx);
        RS485Serial.listen();
      }
      ReadRx();
    }

The `ReadRx()` is behaving odd and `dumpWin()` is giving `0 0 0 0 0 0 0 0` output. I have been trying but I'm not able to figure out where am I going wrong. Your help is appreciated!

EDIT 2: I changed the code as suggested by @Majenko but still `window[]` O/P is `0` for all. I am not able to understand as to why it is not able to read the values from `RS485Serial`.

body:
You need to stop thinking quite so linearly. You are working with asynchronous systems, so your code has to be asynchronous too.

Something more like this:

    #include <SoftwareSerial.h>

    #define SerialControl 7

    #define RS485Tx HIGH
    #define RS485Rx LOW

    SoftwareSerial RS485Serial(11, 12);

    byte SendKWh[] = { 0x01, 0x03, 0x40, 0x34, 0x00, 0x02, 0x90, 0x05 };

    // 0x01: Meter Address, 0x03: Read Function Code, 0x40: Register Address Variable (Start address high bit)
    // 0x34: Register Address Variable (Start address low bit)
    // 0x00: Register Quantity (High Bit), 0x02: Register Quantity (Low Bit)
    // 0x90: CRC check code (CRC code Low bit)
    // 0x05: CRC check code (CRC code High bit)

    uint8_t window[8]; // Initialising window of 8 bytes

    void dumpWin() {
      for (int i = 0; i < 8; i++) {
        Serial.print(window[i], HEX);
        Serial.print(" ");
      }
      Serial.println();
    }

    void ReadRx() {
      if(RS485Serial.available()) {
        uint8_t b = RS485Serial.read();
        dumpWin();
        // Slide the contents of the array down
        for (uint8_t i = 0; i < 7; i++) {
          window[i] = window[i+1];
        }

        window[7] = b; // Next frame inserted at the top of previous

        if ((window[0] == 0x01) && (window[1] == 0x03) &&
            (window[2] == 0x40) && (window[3] == 0x34)) {
              // Doing something with window[4] and window[5] here
        }
      }
    }

    void setup() {
      Serial.begin(115200);
      pinMode(SerialControl, OUTPUT);
      digitalWrite(SerialControl, RS485Rx);
      RS485Serial.begin(9600);

    }

    void loop() {
      static uint32_t ts = millis();

      if (millis() - ts >= 2000) {
          ts = millis();
          digitalWrite(SerialControl, RS485Tx);
          RS485Serial.write(SendKWh, sizeof(SendKWh));
          RS485Serial.flush();
          digitalWrite(SerialControl, RS485Rx);
          RS485Serial.listen();
      }

      ReadRx();
    }

Notice how I use `millis()` to send the command every 2 seconds asynchronously (i.e., without `delay()`). The RS485 is kept in READ mode *except for the brief moment while you send*. Also note the use of `flush()`  to wait until the last symbol has been transmitted by the UART (software in this case) interface. It's important, otherwise you may cut off the transmission part way through (I don't think it's such a problem with SoftwareSerial, but with a hardware UART missing it out would be fatal).

The reading just reads one character and returns to the loop. Each iteration through the loop will (if a character is available) read just one character. Only when all 8 have been received and the contents of the window match up can you process anything (which you would put in place of the comment).

This method also leaves you free to implement other things in `loop()`, as long as they don't use `delay()` as well.


message:
ToF Laser Sensor (VL53L0X) not working

I have this time of flight laser distance sensor: http://www.dx.com/de/p/cjmcu-vl53l0x-tof-laser-distance-measuring-sensor-module-purple-449081#.WSbn52jyi70

The example code of the VL53L0X-arduino library is not working; I always get the serial message

> 65535 TIMEOUT

However, I guess that the problem is at the sensor. The communication is via I2C, so that the [i2c scanner][1] should find it's address, right?

This finder doesnot find any address - am I right, that then the problem is at the sensor?

I connected VCC to (nearly) 5V, GND to GND, SCL to A5 and SDA to A4 (Arduino Uno)

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

body:
You have to pull XSH high (3.3V) in order to turn the device on (either via an I/O port or via a pullup resistor to 3.3V).

Also, the device is rated for a maximum of 3.3V, you might damage it if you connect it to 5V.

Regards


body:
I had the same problem using [this sensor][1]. The solution was to connect

 - VCC -> 5V
 - GND -> GND
 - SCL -> A5 (SCL)
 - SDA -> A4 (SDA)
 - DNC -x Not connected
 - GN2 -> GND
 - XSH -> 5V
 - INT -x Not connected

And then to use [the code mentioned here][2] by Ted Meyers. I used Nano with ATmega328P and Arduino IDE 1.8.5.

<hr>

CODE:

    #include <Wire.h>

    #define VL53L0X_REG_IDENTIFICATION_MODEL_ID         0xc0
    #define VL53L0X_REG_IDENTIFICATION_REVISION_ID      0xc2
    #define VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD   0x50
    #define VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD 0x70
    #define VL53L0X_REG_SYSRANGE_START                  0x00
    #define VL53L0X_REG_RESULT_INTERRUPT_STATUS         0x13
    #define VL53L0X_REG_RESULT_RANGE_STATUS             0x14
    #define address 0x29

    byte gbuf[16];

    void setup() {
      // put your setup code here, to run once:
      Wire.begin();        // join i2c bus (address optional for master)
      Serial.begin(9600);  // start serial for output
      Serial.println("VLX53LOX test started.");
    }

    void loop() {
      Serial.println("----- START TEST ----");
      test();
      Serial.println("----- END TEST ----");
      Serial.println("");
      delay(4000);
    }

    void test() {
      byte val1 = read_byte_data_at(VL53L0X_REG_IDENTIFICATION_REVISION_ID);
      Serial.print("Revision ID: "); Serial.println(val1);

      val1 = read_byte_data_at(VL53L0X_REG_IDENTIFICATION_MODEL_ID);
      Serial.print("Device ID: "); Serial.println(val1);

      val1 = read_byte_data_at(VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD);
      Serial.print("PRE_RANGE_CONFIG_VCSEL_PERIOD="); Serial.println(val1);
      Serial.print(" decode: "); Serial.println(VL53L0X_decode_vcsel_period(val1));

      val1 = read_byte_data_at(VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD);
      Serial.print("FINAL_RANGE_CONFIG_VCSEL_PERIOD="); Serial.println(val1);
      Serial.print(" decode: "); Serial.println(VL53L0X_decode_vcsel_period(val1));

      write_byte_data_at(VL53L0X_REG_SYSRANGE_START, 0x01);

      byte val = 0;
      int cnt = 0;
      while (cnt < 100) { // 1 second waiting time max
        delay(10);
        val = read_byte_data_at(VL53L0X_REG_RESULT_RANGE_STATUS);
        if (val & 0x01) break;
        cnt++;
      }
      if (val & 0x01) Serial.println("ready"); else Serial.println("not ready");

      read_block_data_at(0x14, 12);
      uint16_t acnt = makeuint16(gbuf[7], gbuf[6]);
      uint16_t scnt = makeuint16(gbuf[9], gbuf[8]);
      uint16_t dist = makeuint16(gbuf[11], gbuf[10]);
      byte DeviceRangeStatusInternal = ((gbuf[0] & 0x78) >> 3);

      Serial.print("ambient count: "); Serial.println(acnt);
      Serial.print("signal count: ");  Serial.println(scnt);
      Serial.print("distance ");       Serial.println(dist);
      Serial.print("status: ");        Serial.println(DeviceRangeStatusInternal);
    }

    uint16_t bswap(byte b[]) {
      // Big Endian unsigned short to little endian unsigned short
      uint16_t val = ((b[0] << 8) & b[1]);
      return val;
    }

    uint16_t makeuint16(int lsb, int msb) {
        return ((msb & 0xFF) << 8) | (lsb & 0xFF);
    }

    void write_byte_data(byte data) {
      Wire.beginTransmission(address);
      Wire.write(data);
      Wire.endTransmission();
    }

    void write_byte_data_at(byte reg, byte data) {
      // write data word at address and register
      Wire.beginTransmission(address);
      Wire.write(reg);
      Wire.write(data);
      Wire.endTransmission();
    }

    void write_word_data_at(byte reg, uint16_t data) {
      // write data word at address and register
      byte b0 = (data &0xFF);
      byte b1 = ((data >> 8) && 0xFF);

      Wire.beginTransmission(address);
      Wire.write(reg);
      Wire.write(b0);
      Wire.write(b1);
      Wire.endTransmission();
    }

    byte read_byte_data() {
      Wire.requestFrom(address, 1);
      while (Wire.available() < 1) delay(1);
      byte b = Wire.read();
      return b;
    }

    byte read_byte_data_at(byte reg) {
      //write_byte_data((byte)0x00);
      write_byte_data(reg);
      Wire.requestFrom(address, 1);
      while (Wire.available() < 1) delay(1);
      byte b = Wire.read();
      return b;
    }

    uint16_t read_word_data_at(byte reg) {
      write_byte_data(reg);
      Wire.requestFrom(address, 2);
      while (Wire.available() < 2) delay(1);
      gbuf[0] = Wire.read();
      gbuf[1] = Wire.read();
      return bswap(gbuf);
    }

    void read_block_data_at(byte reg, int sz) {
      int i = 0;
      write_byte_data(reg);
      Wire.requestFrom(address, sz);
      for (i=0; i<sz; i++) {
        while (Wire.available() < 1) delay(1);
        gbuf[i] = Wire.read();
      }
    }

    uint16_t VL53L0X_decode_vcsel_period(short vcsel_period_reg) {
      // Converts the encoded VCSEL period register value into the real
      // period in PLL clocks
      uint16_t vcsel_period_pclks = (vcsel_period_reg + 1) << 1;
      return vcsel_period_pclks;
    }

  [1]: https://www.aliexpress.com/item/VL53L0X-World-smallest-Time-o-f-Flight-ToF-laser-ranging-sensor/32721080939.html?spm=a2g0s.9042311.0.0.nAtRHE
  [2]: https://groups.google.com/forum/#!msg/diyrovers/lc7NUZYuJOg/ICPrYNJGBgAJ


body: One other thing to check as I had this error myself and it was simply because I hadn't soldered the header pins of the nano or the TOF device which I had just stuck into my breadboard. I am using a iHaospace VL53l0x from Amazon. I only thought of it once I ran the i2C scanner check, which didn't recognise (see) the device, so that go me thinking - (https://gammon.com.au/i2c). The I2C scanner Sketch code to use in Arduino's IDE is two thirds down that page. I also should point out that you need to run the serial monitor at the 115200 baud rate not lower or you might get gobbledygook. Now it all works just as it should with the standard Arduino Adafruit example, no #include wire.h required.


body: I had this problem. After connecting VL53L0X, the script hung at the start. Scanning of i2c devices also hung up. Washing the soldering points of contacts helped. Apparently the device is very sensitive to dirt on the contacts.


message:
What do I do with the potentiometer on Adafruit RGB LCD

So I just got my [Adafruit RGB backlight positive LCD 16x2 + extras - black on RGB](https://www.adafruit.com/product/398) In [this picture](https://cdn-shop.adafruit.com/970x728/398-11.jpg) it shows a potentiometer beside the LCD. Anyone know where this is supposed to go?

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

If it helps, I'm mounting the shields on an [Adafruit I2C Controlled + Keypad Shield Kit for 16x2 LCD](https://www.adafruit.com/product/715)

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

body:
The potentiometer is for setting the contrast level of the LCD. The Shield Kit shown also comes with a pot (the one with the orange face). Assembled it should look like this:

[![Assembled LCD Shield Kit][1]][1]

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

Notice the pot in the lower right corner to the right of the microcontroller ic and above the reset button.


body:
The contrast is set by inputting an analog voltage into Pin 3 on the LCD header. The analog voltage is created using the potentiometer and is easily adjusted by the user when in operation.

The diagram below shows (only) the circuit needed to adjust the contrast on the LCD display.

[![LCD Contrast wiring][1]][1]

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


message:
I want to declare an array with variable size and also I want to ask from the user to enter it?

I'm using C++ language.
double coordinates [length][5];

body:
You'll have to dynamically allocate it.

    int length;
    double **coordinates;
    cin >> length;
    coordinates = new double*[length];
    for (int i = 0; i < length; i ++ {
        coordinates[i] = new double[5];
    }


message:
Can't use two SPI devices at the same time

I can use the MFRC522 using the following code:

    #include <SPI.h>
    #include <MFRC522.h>

    MFRC522 mfrc522(10, 9);

    void setup() {
        SPI.begin();
        mfrc522.PCD_Init();
    }

    void loop() {
        if (  mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
             // Do stuff
        }
    }

And it works great. I can also use the dot-matrix (8x8) using the following code:

    #include "LedControl.h"

    LedControl lc = LedControl(12,11,8,1);

    void setup() {
        lc.shutdown(0,false);
        lc.setIntensity(0,3);
        lc.clearDisplay(0);

        lc.setLed(0,2,5,true);
        lc.setLed(0,5,5,true);

        lc.setLed(0,2,2,true);
        lc.setLed(0,3,1,true);
        lc.setLed(0,4,1,true);
        lc.setLed(0,5,2,true);
    }

    void loop() {
    }

And it works just fine as well. However, when I try to use both of them using the following code:

    #include <SPI.h>
    #include <MFRC522.h>
    #include "LedControl.h"

    LedControl lc = LedControl(12,11,8,1);
    MFRC522 mfrc522(10, 9);

    void setup() {
        SPI.begin();
        mfrc522.PCD_Init();

        lc.shutdown(0,false);
        lc.setIntensity(0,3);
        lc.clearDisplay(0);

        lc.setLed(0,2,5,true);
        lc.setLed(0,5,5,true);

        lc.setLed(0,2,2,true);
        lc.setLed(0,3,1,true);
        lc.setLed(0,4,1,true);
        lc.setLed(0,5,2,true);
    }

    void loop() {
        if (  mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
             // Do stuff
        }
    }

In that case only one of them works (the MFRC522). I know that since they are connected in SPI mode they need to have different SS pins, so I used pin 10 for MFRC522 and pin 8 for dot-matrix. So, what's wrong? Why dot-matrix doesn't work at the same code with MFRC522??

body:
The `LedControl` doesn't use `SPI` library but it's using `shiftOut` internally. So you can't use them both at the same pins as the `SPI` interface takes over them.

Basically `SPI.begin()` takes over the control on its pins and that means when you use `digitalWrite` or `pinMode` on those pins, it'll be ignored (at least on some of them).

If you add `SPI.begin()` into the second example (`LedControl` one) it'll stop working. However you can change pins for `LedControl` to other (free) pins and it should be working again.

And also there are mixed signals between both devices:

    HW SPI wiring:
    13  CLK    output
    12  MISO   input
    11  MOSI   output
    9   SS     output

    and LedControl wiring is:
    12  MOSI   output (not really)
    11  CLK    output

Something from the datasheet about alternate pin functions:
> - **SCK/PCINT5 – Port B, Bit 5**

SCK: Master Clock output, Slave Clock input pin for SPI channel. When the SPI is enabled as a
Slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI is
enabled as a Master, the data direction of this pin is controlled by DDB5. When the pin is forced
by the SPI to be an input, the pull-up can still be controlled by the PORTB5 bit.

PCINT5: Pin Change Interrupt source 5. The PB5 pin can serve as an external interrupt source.
> - **MISO/PCINT4 – Port B, Bit 4**

MISO: Master Data input, Slave Data output pin for SPI channel. When the SPI is enabled as a
Master, this pin is configured as an input regardless of the setting of DDB4. When the SPI is
enabled as a Slave, the data direction of this pin is controlled by DDB4. When the pin is forced
by the SPI to be an input, the pull-up can still be controlled by the PORTB4 bit.

PCINT4: Pin Change Interrupt source 4. The PB4 pin can serve as an external interrupt source.
> - **MOSI/OC2/PCINT3 – Port B, Bit 3**

MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI is enabled as a
Slave, this pin is configured as an input regardless of the setting of DDB3. When the SPI is
enabled as a Master, the data direction of this pin is controlled by DDB3. When the pin is forced
by the SPI to be an input, the pull-up can still be controlled by the PORTB3 bit.

OC2, Output Compare Match Output: The PB3 pin can serve as an external output for the
Timer/Counter2 Compare Match. The PB3 pin has to be configured as an output (DDB3 set
(one)) to serve this function. The OC2 pin is also the output pin for the PWM mode timer
function.

PCINT3: Pin Change Interrupt source 3. The PB3 pin can serve as an external interrupt source.
> - **SS/OC1B/PCINT2 – Port B, Bit 2**

SS: Slave Select input. When the SPI is enabled as a Slave, this pin is configured as an input
regardless of the setting of DDB2. As a Slave, the SPI is activated when this pin is driven low.
When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB2. When
the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB2 bit.

OC1B, Output Compare Match output: The PB2 pin can serve as an external output for the
Timer/Counter1 Compare Match B. The PB2 pin has to be configured as an output (DDB2 set
(one)) to serve this function. The OC1B pin is also the output pin for the PWM mode timer
function.

PCINT2: Pin Change Interrupt source 2. The PB2 pin can serve as an external interrupt source.


message:
Arduino Due power supply

I have an Arduino Due.  It communicate to the computer with the native usb port. It is also powered by the native port. Anyway, the connected sensors are pretty sensitive to the current, thus I would like to use a power supply (as a portable smartphone charger) in order to provide the current at the Arduino.

How can I say to the Arduino to get the current from another 'port' (e.g. the serial programming) and use the native port only for the communications?

body: You can't really fiddle with the power circuitry of the Due. If external sensors need more power than the due can provide through its internal 5V connection, whatever you choose that to be (dictated by the USB connection used) then you will either have to use a higher voltage to feed the barrel jack, or better, power the sensors separately to the Due. Just remember to connect the grounds.


message:
Doubt on Processing Power

The datasheet of arduino mega claimed that the board has 16Mhz processing power. But the question that doubt me is what would happen to the board if the board has no enough processing power.

For example,  if the board is used in an application that involves a lot of calculation in each loop. Would it stall the board?

Personally, i think the board would just give slower response instead of stalling the board. It was due request is done in sequential method in the code. Therefore it would not accumulate up the request until stalling the device like PC and I think it would be just at most an arduino which is always busy.

Is it what would happen if the board has no enough processing power?

body:
Processing Power is a bit of a misnomer. Clock Frequency is a better description.

In general one assembly instruction gets executed each clock cycle. That means approximately 16 million instructions per second (there are a couple that take more than 1).

Your C program gets compiled into those instructions and executed at 16 million instructions per second.

If your routine is 16 million instructions long (when loops are unrolled) then it will take 1 second to execute.

Unlike a PC, which is constantly switching between tasks, an Arduino does only one thing, and that is the one thing you programmed it to do. Because of that execution time is predictable. If it took 1 second to execute today it will take 1 second tomorrow,  and 1 second next week.


message:
Reading and processing a PWM on AtTiny45

I have this question and I can't find answers!

I wanted to use an AtTiny45V (due to low voltage requirements, it will run at 1.8 volts) to read a PWM from an Arduino, and then process this information.

Explained better:

let's say, I hook up one pin of the AtTiny to an Arduino pin (named `connection`), and in the IDE I write:

    AnalogWrite(connection,X)

I want the AtTiny to write high on a port based on the X value.

Example:

X = 20 writes high on AtTiny PB5

X = 25 writes high on AtTiny PB5 and PB3

etc...

So, basically I want to read the duty cycle from the Arduino PWM and let the AtTiny do something based on duty cycle value.

Is this possible?

Thanks

body:
If I understood correctly you want to drive a digital output on the AtTiny45V based on the PWM value from your Arduino, right?

I would suggest to use a simple low-pass RC filter to extract the mean value from the PWM and read as an analog voltage in the AtTiny45V. As the frequency of your PWM is known, you can easily design your filter to extract the mean value of your signal.
Then, based on your PWM mean value, you can define which pin will be set.


body:
You don't need to read the duty cycle, just the time that the PWM signal is high. First wait for the input pin to go high, then start a timer, wait for the signal to go low again, and finally read the timer value. If other tasks need to be performed concurrently then use pin change interrupt to detect the high and low transitions.

If the ATtiny is running Arduino software then the solution is even easier - just use the [pulseIn()][1] function.

This technique works for all PWM values *except* 0 and 255. With these values the pin stays low or high permanently, so there are no transitions to time. The easiest way around this is to simply avoid transmitting 0 or 255.

Alternatively you could pass the PWM signal through an RC filter to produce a 'DC' voltage, then read it with the ADC. However this will slow the response time down, and the signal will produce intermediate values as it goes from one voltage to another. To get good resolution the RC filter would need to have a long time constant, and you might have to average several readings to get a stable value.

  [1]: https://www.arduino.cc/en/Reference/PulseIn


message:
Arduino-based mains frequency monitor follow-up

Following my
[previous question][1], I'm getting closer to thinking about putting together this mains frequency monitor. I would just like to do a sanity check on my electronics before I order the components and the board. Please keep in mind I am not qualified in this so I have had to research how all this will work.

[![Circuit layout][2]][2]

**A** and **B** inputs will accept power from a 16VAC 1.25A unregulated power pack.

**C1** is a 1µF 25V 85°C ceramic capacitor. I guess this is mostly unnecessary as the power pack should filter any DC bias, but it won't hurt.

**D1** is an IN4001 1A standard recovery diode.

**R1** is a 300ohm 500V 3W resistor. The RMS power is 16VAC, which is half-wave rectified, so that's sqrt(2) * 16 = ~24V peak @ 300ohm = 80mA peak, and about 25mA on average (right?)

**IC1** is a 4N28 optocoupler. It's weird, in one data sheet I see 80mA max forward current on inputs but in another I see 60mA. Anyway, the average should be 25mA so I guess that's probably going to be okay?

The Arduino I will use is the Arduino Micro, as it's quite small and also has a 16Mhz **crystal oscillator** that will provide a more stable clock than a ceramic resonator. The Arduino will be powered by USB, which I believe is 5V. The digital I/O pins I believe will also operate at 5V and are rated at 40mA max.

**C** will come from one of the Arduino's digital output pins, and **D** will go to the Arduino's GND.

**R2** is a 150ohm 500mW 250V resistor, that should ensure the **C**→**D** current does not exceed 40mA @ 5V.

Now, assuming the components look okay and the circuit looks okay (I assume the circuit is fine), I just had some questions:

 1. Do I need to add anything to the output of the 4N28 coming from the input? I think with a regular transistor, some of the base current gets added to the collector current?
 1. What can I expect the response on the output of the 4N28 to look like? I assumed that it would more-or-less be a square wave, where even a tiny current on the input would activate the transistor and allow the output current to flow freely on the other side, but someone has suggested that this might not be the case?
 1. The way it is set up, the Digital I/O pin can be "trying" to output or not, and that's basically irrelevant to what the transistor is doing. When the transistor is on, the output current from the pin will successfully flow to GND. I assume there is a way to detect this in the Arduino? Something like setting the output pin to 1 and check in loop when there is or is no current flowing?

Thank you!

  [1]: https://arduino.stackexchange.com/questions/38437/arduino-based-mains-frequency-monitor
  [2]: https://i.stack.imgur.com/sBIbH.png

body:
You should remove the capacitor. It won't remove any DC offset because there can be no DC offset. From where would the DC offset be relative? There is only two points in the circuit, and both of them are direct from the transformer and is an AC waveform. There is no concept of a DC offset in such a circuit.  All the capacitor will do is impose a phase change between the current and voltage of the AC waveform limiting the current during the conducting period of the diodes. You have a resistor for that function.

You make some incorrect assumptions about how to read the data. You talk about outputting a signal and somehow finding out if the transistor is on or not by if that signal is being output. That's completely backwards. Instead you should treat the transistor like a simple pushbutton and provide it with a pullup (or pulldown if you prefer) resistor, like this:

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

<!-- End schematic -->

You should feed the signal into an interrupt-enabled pin (such as D2 on the Uno as shown) so that an interrupt can be used for capturing the incoming edge time. Better would be to use the Input Capture peripheral, but that is harder to program for as there is no (AFAIK) library for it.

Yes, it would be possible to use the internal pullup resistor of the input pin instead of an external one, however using an external one allows you to fine tune the resistance which, coupled with the gate capacitance of the input pin, forms a low-pass filter limiting the frequency range you can monitor. At 50Hz it shouldn't be a problem though, so the choice is yours. Personally I use an external one.