body:
OK. So I never got the reinterpret_cast, thing to work. Went with Majenko's solution.
This code goes above Setup

    // UNION, used to re-jig float
    union ifloat {
    uint8_t bytes[4];
    float val;
    };
    // END UNION
And this is the modified code, with all the comments and bug print statements removed.

      // MtrV, MtrC, MtrW, MtrKWh
     //void AddressRegistry_0()
     result = sdm220_modbus.readInputRegisters(0x48, 2);
     if (result == sdm220_modbus.ku8MBSuccess)
     {
    signed long MtrKWh1 = sdm220_modbus.getResponseBuffer(0x0);
    word MtrKWh2 = sdm220_modbus.getResponseBuffer(0x1);
    byte msb3 = MtrKWh1;
    byte msb4 = MtrKWh1 >> 8;
    byte msb1 = MtrKWh2;
    byte msb2 = MtrKWh2 >> 8;
    ifloat f;
    f.bytes[3] = msb4;
    f.bytes[2] = msb3;
    f.bytes[1] = msb2;
    f.bytes[0] = msb1;
    Serial.println(f.val,3 );
      }
     else
     {
    rs485DataReceived = false;
    Serial.println("Fail sdm220_modbus.readInputRegisters(0x0, 1) ");
     }

And it is giving me the right numbers!
Thanks for input to all who did, it helps some times to be show which door to walk through.
Majenko, if you have time, and inclination, it would really help my understanding if you could describe your code. I am using it, but not sure how it works,or what most of it is doing. If you have the time.


sender: user

message:
What is the best way/module to talk to an Arduino from far away (WIFI)?

I am new to Arduino and IoT. I plan to build a product that I will connect to an app and they have to be able to communicate from a very far distance (kilometers).

Bluetooth is not a good option then (because the distance is too far). So would Wifi work? I read something about a module called esp8266 that might be what I am searching for.

sender: assistant

body: Esp8266 range is about 400m. So if you have your mobile within 400m then you may be able to communicate. But for long distance communication I would not prefer but if you have any Internet connection available nearby esp then you may be able to transmit your messages via it. Well for long distance communication  I would prefer you to use any GSM shield in which you need to plug in a sim card and it can be used upto when you have coverage in that area.


body:
The simplest option is to use GSM for the communication. Range isn't an issue, since point A isn't communicating with point B, instead point A and point B are both communicating via third party communication subsystem C which has a much greater coverage than anything you could build yourself.

I use GSM modules for communication with agricultural monitoring and control systems at remote locations. It works well, and you're pretty much guaranteed to have a signal.

For those times when GSM isn't a possibility (no signal, or the customer doesn't want the subscription cost) you really need *line of sight* between the two locations. Then you can use a highly directional antenna (e.g., parabolic dish or Yagi array) to extend any other suitable wireless communication signal over a long range (WiFi can reach tens of kilometres with parabolic dishes) and there are companies that specialise in that kind of equipment (such as [this one that claims 8 mile range](http://www.simplewifi.com/8-mile-antenna.html) - of course you need two of them, one for each end of the link).  Of course, with some skill and determination it's possible to get [incredibly long distances from WiFi](https://www.wired.com/2007/06/w_wifi_record_2/). Not for your average user though...


body:
**LoRa** is apparently the most popular [low-speed, low-power, wide-area network][1] at the moment.

Many people use LoRa for direct point-to-point links around a kilometer.
Other people use LoRa for "last mile" wireless links as part of a **LoRaWAN** to some gateway hard-wired to the internet, much like a Wifi access point -- except trading off data rates in order to get longer wireless range than WiFi.

details:

* "LoRa is de facto dominant" -- ["LoRaWAN across the globe: LoRa Internet of Things networks overview"][2]
* [LoRa range tests][3] using the RFM95 [Anarduino LoRa Modules][4], similar to the , [LoRa IoT Development Kit][5] (using a ["LoRa Bee"][6]), [RFM95W LoRa Module for Arduino][7], [RFM95W Breakout Board for LoRa][8], [RFM95 LoRa mikroBUS Module][9], etc.
* ["LoRa range experiments Urban test"][10] using the Microchip RN2483 module; I can't quite see which breakout board he's using -- I'm guessing it's one of the [Sodaq LoRabee RN2483][11], the [RN2483 LoRa Technology PICtail][12], the [Azzy RN2483 breakout board][13], the [Azzy LoRaWAN RN2483/RN2903 Breakout board][14] , etc.
* [The Vinduino][15] measures wind and soil moisture using an Arduino and reports back those measurements with a [Globalsat LM-210 LoRa module][16]
* "LoRaWAN ... Range: 2-5km (urban environment), 15km (suburban environment)" --
["11 Internet of Things (IoT) Protocols You Need to Know About"][17]
* [LoRaWAN Part 1: How to Get 15 km Wireless and 10-Year Battery Life for IoT][18]
* "low power wide area (LPWA) technologies have become popular. In various LPWA technologies, narrowband (NB)-IoT and long range (LoRa) are two leading technologies." -- ["A survey on LPWA technology: LoRa and NB-IoT"][19]
* "[The LoRa shield: an Open Source Arduino’s long-range communication module][20]" apparently uses the [Open-Electronics LoRa shield for Arduino - Mounted][21]
* ["Building your own private LoRa network"][22] mentions several different LoRa shields
* [The LoRa Alliance][23]
* [arduino-lmic][24]: the IBM LMIC (LoraMAC-in-C) library, slightly modified to run in the Arduino environment
* ["LoRa and Long Range Wireless IoT"][25]
* "The low data-rate (down to few bytes per second) and LoRa modulation lead to ... more than 22km (13.6 miles) in LOS links and up to 2km (1.2miles) in NLOS links in urban environment (going through buildings)." -- ["Extreme Range Links: LoRa 868 / 900MHz SX1272 LoRa module for Arduino Waspmote and Raspberry Pi"][26] tested a [SX1272 LoRa module][27] on a Multiprotocol Radio Shield on an Arduino Uno and links to a few other LoRa modules / [LoRaWAN kits][28].

  [1]: https://en.wikipedia.org/wiki/LPWAN
  [2]: https://www.i-scoop.eu/internet-of-things-guide/iot-network-lora-lorawan/
  [3]: http://forum.anarduino.com/posts/list/46.page
  [4]: http://www.anarduino.com/?cid=24
  [5]: https://www.tindie.com/products/edwin/lora-iot-development-kit/
  [6]: https://www.tindie.com/products/edwin/lora-bee/
  [7]: https://www.tindie.com/products/blkbox/rfm95w-915mhz-module-for-arduino/
  [8]: https://www.tindie.com/products/arduinopraxis/rfm95w-breakout-board-for-lora-applications/
  [9]: https://www.tindie.com/products/CascoLogix/rfm95-lora-mikrobus-module/
  [10]: http://www.hexnut.net/2016/02/lora-range-experiments-urban-test.html
  [11]: https://shop.sodaq.com/en/lorabee-rn2483.html
  [12]: https://www.microchipdirect.com/productsearch.aspx?Keywords=RN-2483-PICTAIL
  [13]: https://www.tindie.com/products/DrAzzy/rn2483-breakout-bare-board/
  [14]: https://www.tindie.com/products/DrAzzy/lorawan-rn2483rn2903-breakout-board-assembled/
  [15]: https://hackaday.io/project/6444-vinduino-a-wine-growers-water-saving-project
  [16]: https://hackaday.io/project/6444-vinduino-a-wine-growers-water-saving-project/log/39541-lora-network-module-review
  [17]: https://www.rs-online.com/designspark/eleven-internet-of-things-iot-protocols-you-need-to-know-about
  [18]: https://www.digikey.com/en/articles/techzone/2016/nov/lorawan-part-1-15-km-wireless-10-year-battery-life-iot
  [19]: http://www.sciencedirect.com/science/article/pii/S2405959517300061
  [20]: https://www.open-electronics.org/the-lora-shield-an-open-source-arduinos-long-range-communication-module/
  [21]: https://store.open-electronics.org/index.php?_route_=FT1190M
  [22]: https://docs.mbed.com/docs/lora-with-mbed/en/latest/intro-to-lora/
  [23]: https://www.lora-alliance.org/
  [24]: https://github.com/matthijskooijman/arduino-lmic
  [25]: https://www.postscapes.com/long-range-wireless-iot-protocol-lora/
  [26]: https://www.cooking-hacks.com/documentation/tutorials/extreme-range-lora-sx1272-module-shield-arduino-raspberry-pi-intel-galileo/
  [27]: https://www.cooking-hacks.com/sx1272-lora-module-for-arduino-raspberry-pi-intel-galileo-868-mhz
  [28]: https://www.cooking-hacks.com/shop/wireless/lorawan


message:
ESP32 in Arduino-IDE with FS.h and SPIFFS

I'm working on a webserver on ESP32 in Arduino IDE and would like to load an html-file. Tried to use SPIFFS.open from the library FS.h from [github][1].
Errormessage says SPIFFS was not declared in this scope. (As far as I can see, there's no bracket in the wrong place.)

I did not find any example for ESP32 and FS.h and desperately hope for some help. Thanks in advance.

Here is my code:

    #include "FS.h"
    #include "WiFi.h"

/*Wifi Access data*/
const char* ssid_ap = "AccessPoint";
const char* password_ap = "12345678";

const char * ssid_sta     = "<SSID>";
const char * password_sta = "<Password>";

/* set global variables */
byte WiFiMode = 0;  // WIFI_STA = 1 = Workstation  WIFI_AP = 2  = Accesspoint
int request_counter;
String sHTML;
String sHTMLRequest;

/* Create instance of server on Port 80 */
WiFiServer server(80);
WiFiClient client;

/*
 * ******SETUP*******************************************************
 */
void setup() {

/*initialize GPIO*/

/*start serial communication */
  Serial.begin(115200);
  SPIFFS.format();
  Serial.println("Spiffs formatted");

/* start WiFi as workstation (STA), if not possible
   start as Acess Point
   initialize server */
  WiFi_Start_STA();
  if (WiFiMode == 0) WiFi_Start_AP();
}

/*
 * **LOOP*************************************************************
 */
void loop() {

  /* Check if a client has connected */
  client = server.available();
  if (!client)
  {
    return;
  }

 /*Wait for the client to send data */
  Serial.println("neuer Client verbunden");
  /*Count Aufruf der Seite: */
  request_counter ++;
  unsigned long clTimeout = millis()+250;
  while(!client.available() && (millis()<clTimeout) )
  {
    delay(1);
  }
  if(millis()>clTimeout)
  {
    Serial.println("time-out bei Client-Verbindung!");
    return;
  }

/****** open html files  *******/
 SPIFFS.begin();
 File f = SPIFFS.open("/home.txt", "r");
    if (!f) {
    Serial.println("file open failed");
    }
    f.close();

  }

/**********************************************************************
 *
 **************** FUNCTIONS ********************************************
 *
 **********************************************************************
 */

/*
 * Fct tries to start WiFi in workstation mode,
 * if not possible sets WiFiMode=AP
 * starts server
 */
void WiFi_Start_STA() {
  unsigned long timeout;

  WiFi.mode(WIFI_STA);   //  Try to start WiFi as Workstation

  WiFi.begin(ssid_sta, password_sta);
  timeout = millis() + 12000L;
  while (WiFi.status() != WL_CONNECTED && millis() < timeout) {
  delay(10);
  }

  if (WiFi.status() == WL_CONNECTED) {
    server.begin();
    WiFiMode = WIFI_STA;

  Serial.print("Verbunden mit IP - Addresse: ");
    for (int i = 0; i < 3; i++) {
      Serial.print( WiFi.localIP()[i]);
      Serial.print(".");
    }
    Serial.println(WiFi.localIP()[3]);

  }
  else {
    WiFi.mode(WIFI_OFF);

    Serial.println("WLAN-Verbindungsaufbau fehlgeschlagen");
    }
}

/*
 *starts WiFi in AP-mode
 *starts server
 */
void WiFi_Start_AP() {
  WiFi.mode(WIFI_AP);   // Access Point mode
  WiFi.softAP(ssid_ap, password_ap);
  server.begin();       // start server
  IPAddress ApIP = WiFi.softAPIP();   //read IP of Access Point
  WiFiMode = WIFI_AP;

  Serial.print("ESP-Netzwerk: ");
  Serial.print(ssid_ap);
  Serial.print(" aufgebaut. ");
  Serial.print( " IP-Addresse: ");
  Serial.println(ApIP);
}

  [1]: https://github.com/espressif/arduino-esp32/tree/master/libraries/FS

body:
The answer is belated but since the question is still open...

The code does not include spiffs library. The line below should fix the problem.Note it should be below the the include statement for FS

    include <SPIFFS.h>

So the code should look like

    #include "FS.h"
    #include "WiFi.h"
    #include "SPIFFS.h"


message:
Programmatically Change Arduino Com Port Name

I have some devices that, when I plug in, will display a unique name, usually a serial number, as opposed to "COM #" is there any way I can have my Arduino Uno (or Mega) give itself a different name in my program's set up structure?

Edit: My purpose here is that I'm writing a program on the computer side that needs to find the Arduino among multiple possible COM ports. I'm deploying this program over multiple computers that I don't have admin access to so changing the registry is likely a non-starter.

Right now, I'm going through each port and sending a *`idn?\n` (which my program responds to with a specific string). For another device I have, I can search the possible connections for a port named [device serial number] and test that one first.

body:
On Windows you can change the "Friendly names" assigned to devices and COM ports are devices.  The process is basically open the device manager, open the device properties, find the 'Device Key' and then locate that in the registry and change the 'Friendly Name' value.

See this page for more details:
https://www.eightforums.com/customization/15321-tutorial-how-change-device-names-device-manager.html


body:
1.  If you read [this](https://arduino.stackexchange.com/questions/11823/can-i-change-the-usb-device-name-of-arduino) So it says:

   You'll have to change the software on the Arduino USB chip itself,
    and you may need to modify the drivers for the Arduino USB interface
    on the computer side. It's not trivial, and probably not worth it.

Then according to this you need to toggle and tinker with the Driver software

2. Wait that means it is not the correct answer. So according to your plan you need to maybe toggle with IDE that is instead of manually changing the ports you want the software to identify on its own. So for that purpose you have to tweak with Arduino board bootloader, and say it send a message to the Arduino IDE on startup . After that you have to tweak with Arduino ide source codes and then tweak it to Search for that message and then it reads down the address that is its COM


message:
RasPi GPIO into Arduino Digital Inputs

So I'm making a Robot for my AP Comp Sci Class, and I'm borrowing an Arduino, as well as a Pi from the school. What I plan to do is have my Pi output from the normal GPIO pins and into the Arduino's digital inputs to "Tell" the Arduino what servos to run. The reason I'm doing it this way is so I don't have to screw with interfacing and all that crap. Is it safe for the Arduino? If so, what would I need for resistors and such?

body:
I think you are talking about writing to a GPIO and that being received by the Arduino if so the Pi is 3.3v and the Arduino is 5V so you will need a "Level Shifter" to boost the voltage to 5V so the Arduino can read the signals.

Other than that there is no problem with doing what you are doing, apart from its a lazy solution and you won't score very highly.  I know you don't want to mess with protocols but if you can use I2C from the Pi then use that to send messages to the Arduino.  Your protocol could be as simple as 1 byte saying which pin you want to light up, you'll get better marks.

Edit

To use I2C is really quite simple because someone has done almost all the work for you in Wire.h, so just include that file and then to send a byteits simply a case of:

    Wire.beginTransmission(device_address);
    Wire.write(data_byte);
    Wire.endTransmission();

Reading data sheets for devices makes it look a lot harder with all the transmission sequence diagrams, but you don't need to worry about that its all done for you.  The hardest bit to remember is the pull up resistors on the data lines.

Have a look at these links for more information:

 - http://tronixstuff.com/2010/10/20/tutorial-arduino-and-the-i2c-bus/
 - http://howtomechatronics.com/tutorials/arduino/how-i2c-communication-works-and-how-to-use-it-with-arduino/
 - https://www.arduino.cc/en/Tutorial/MasterReader


message:
Any good way to inverse a function?

I'm guessing that the answer to this is "no," but I'm curious if there is any way to save writing some code by specifying a function to do the opposite of whatever another function does. For example the inverse of:

    int FW (int in)
    {
      int out=2+in;
      Return out
    }

would be

    int RV (int in)
    {
      int out=in-2;
      Return out
    }

However, would there be any way to call the inverse of `FW()` if it was a more complicated function that still had one and only one input for each output?

body:
No. A function does what it does and that is all. No other function can know what some other function does.

You could write a function that does different things depending on what parameters you pass to it, but that's the closest you can get, and is pretty pointless when you can just write different functions anyway.


message:
What is the meaning of [type]* for arrays?

I've seen * used with arrays in some programs but not in others. [The page on arrays](https://www.arduino.cc/en/reference/array) doesn't mention it at all, but I often see it near functions when values are being passed.

Where would I find more information on this?

body:
You are asking about Pointers -
 https://www.tutorialspoint.com/cprogramming/c_pointers.htm.


message:
Create an a message from two inputs[Programming Help]

I'm a bit new to this and I have the following function that I'm having trouble getting it to compile. The intent is to create a message to write out to a software serial port. Inputs are two int values of Function address and the data passed to the device while the output is a series of char characters

    void Create_Message(int Address, int Data)
    {
      byte S1Add = 1;
      byte FuCode = 2;
      byte AddHi = Address>>8;
      byte AddLo = Address;
      byte DatHi = Data>>8;
      byte DatLo = Data;
      byte AdDa[] = {AddHi,AddLo,DatHi,DatLo};
      unsigned int crc=CRC(AdDa,4);
      byte CrcHi = crc >> 8;
      byte CRCLo = crc & 0xFF;
     /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
     * to
     *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
     */
     unsigned char cmd[]={S1Add,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CRCLo};

      digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
      for (int i=0; i< clen; i++)
      {
        RS485Serial.write(cmd[i]);   // Send string someplace
        Serial.write(cmd[i]); //echo back
      }
      digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
    }

    byte CRC(byte AdDa, int Size )
    {
    unsigned int crc16 = 0xFFFF;
    int pos = 0;
    int i = 0;

    /*Write CRC*/
      for (pos = 0; pos < Size; pos++) {
        crc16 ^= AdDa[pos];          // XOR byte into least sig. byte of crc

        for (i = 8; i != 0; i--) {    // Loop over each bit
          if ((crc16 & 0x0001) != 0) {      // If the LSB is set
            crc16 >>= 1;                    // Shift right and XOR 0xA001
            crc16 ^= 0xA001;
          }
          else                            // Else LSB is not set
            crc16 >>= 1;                    // Just shift right
        }
      }
      /*Note, this number has low and high bytes swapped,
      so use it accordingly (or swap bytes)*/
      byte crc[]={crc16>>8,crc16};
      return crc;
    }
Any help with optomizition would also be greatly appreciated :)

body:
If you want help with optimisation then "Code Review" would be the better forum.

Its very difficult to optimise code that's hard to read.  You have used an inconsistent formatting style (which might be because of the post but your failure to fix it indicates a lack of interest in the answers.

You passed all you function arguments by value, you should pass them by constant reference.

You are doing a number of implicit casts, because you have mismatched types.

You are sending a byte to serial.write, what happens if the value is outside of the printable range, it would be better to print this as a hex number.

I assume someone has already pointed out CRC should return a byte*.

As for the algorithm, the code isn't readable enough to comment on that.


message:
Arduino-based mains frequency monitor

I'm looking to put together a simple mains frequency monitor based on the Arduino platform. The mains here are 250 V @ 50 Hz, but obviously these fluctuate slightly, which is the whole point of the exercise. (I am not interested in capturing voltage fluctuations, only frequency fluctuations).

I have never used any Arduino products before, but I am familiar with PIC-based MCUs. I understand Arduino should be somewhat simpler. Also, I am not an electronics engineer.

Presumably, the Arduino will sample the mains frequency for a second or two, and then report the result somehow. I guess the easiest way is for a computer connected to the Arduino by USB to receive the result and act accordingly. Otherwise, other options include adding an Ethernet module to the Arduino and having it HTTP POST the result to a web server.

(I assume doing this naive method is preferable to recording a time series and then performing a Fourier transform?)

Size isn't a huge concern, but a compact device is preferable over a larger one as I'll be 3D-printing a custom enclosure for it. Therefore I would like to use the Arduino Nano if it's suitable.

Here is what I have so far:

 1. The 250V mains will be half-rectified with an IN4004 (?) transistor (together with a 1K resistor and 0.22 uF cap), and that will go into a 4N35 optocoupler.
 1. A digital (?) GPIO pin from the Arduino goes into the base of the 4N35 and emitter goes to GND.
 1. The Arduino samples for a short time the number of pulses on that pin, does a simple calculation, and reports the result.

Here are my uncertainties so far:

 1. Based on my research, I believe the Arduino can reliably be powered by USB. If this is correct, this would be ideal as it would avoid me having to build a low voltage DC power supply for it.
 1. How stable is the clock on the Arduino? How many decimal places on the frequency can I realistically achieve?
 1. I presume I'll need to debounce the result from the optocoupler? Will there be some noise as the transistor transitions between states? Are there built-in debouncing functions or will I need to write my own? How is this likely to affect available clock cycles and therefore the accuracy of the measurement?
 1. I've seen PIC projects where it interacts with the computer by emulating a keyboard. While simple, this wouldn't be ideal as the computer it's connected to must also remain usable. The software processing the result should run in the background while a user can continue using the computer. How simple is it to write some software (in C#) that will recognise the Arduino connected via USB, and communicate with that device in particular?

I also welcome any other comments and suggestions. Thank you.

**Edit:** Following these helpful comments and suggestions, I've made some revisions and asked a [follow-up][1] question.

  [1]: https://arduino.stackexchange.com/questions/38813/arduino-based-mains-frequency-monitor-follow-up

body:
It sounds like you're well on your way to creating a solid project.  I will attempt to answer some questions and offer some suggestions on approaching this.

Rather than counting the number of AC pulses per time period, you might get better results seeing how many Arduino clock ticks you get between a sampling of say, 50 (debounced) pulses.  This will give you bigger numbers to work with.  Doing the opposite (seeing how many pulses per time period) will not give the same precision.  If you only got 49 pulses in a second, did you just barely miss the 50th, or was it a whole 2% off?  Since the Arduino clock can count much faster, it would be better to count those ticks instead.

 1. Arduinos can be reliably powered by USB, as long as you don't draw too much current.  Your application sounds like it shouldn't draw much at all.
 2. The clock on the Arduino isn't going to compare with using a separate real-time clock circuit, but it should be good enough to measure trends and differences.  Keep your code predictable, using as few conditional branches as possible that might alter how long your code takes to run each cycle.
 3. Debouncing is probably a very good idea in this situation.  There are several debouncing libraries available for the Arduino, or you can roll your own.  Once again, the library should written as to not introduce inconsistent delays into the code.  For this reason, it might be better to write your own specifically suited for this application.  You might need to borrow an oscilloscope and see how long the pulses are from your optocoupler circuit.  The closer you can get them to being a 0V/5V square wave, the better.
 4. Arduinos come in many flavors.  Some can emulate keyboards, but most act natively as serial ports.  If you can read data from a serial port, then you can read the output from the Arduino.  This should be trivial in C#, or just use a terminal emulator or the Arduino IDE's serial console to view the results.  Once again, if you are outputting data while still measuring, then you should use use fixed width output so that the program takes the same amount of time to run each cycle.  It would be far more accurate instead to take your measurements silently, and output the results afterward later so that you don't have to account for serial port buffer delays.  Take another "flush" delay before starting measurement cycle again.


body:
I would use a step-down transformer with that 1N4004 rectifier diode to limit the *peak rectified voltages* to less than the Arduino's safe input voltage. I would also be inclined to add a zener diode to ground at the Arduino's input to "clamp" or limit that input voltage to whatever your Arduino's safe upper limit is.

At some point you might also find it beneficial to double the 50hz using a full-wave rectifier to give you more pulses to count for finer resolution.

A low current fuse in there somewhere wouldn't be a bad idea either.


body:
It's a safety issue at the very least. A catastrophic failure of the opto & everything is gone. At least with a "wall bug" style transformer, you've given yourself & your device a large safety margin.

I assume your opto will be triggered at line voltage & frequency to subsequently switch a 3.3 or 5v bus to an Arduino input pin at the 50hz line rate.

The opto you've chosen turns ON at ~1 volt & it needs a current limit of ~10ma thru it. You'll need to calculate a dropping resistor value to bring the *rectified peak voltage* down so that the opto isn't overloaded in either category. You'll need to also compensate for the eventual surge/peak voltages well above the typical line voltages.

There could conceivably be enough constant "noise" riding in on the line that prevents the opto from regularly seeing the "zero crossing" moment that your pulse counter relies on.

Transforming that line voltage to a much lower level decreases ambient line noise by the same transformer ratio, increases safety & makes it easier for the opto to detect the zero crossing in the presence of line noise etc.
bc


body:
> I understand Arduino should be somewhat simpler [than PIC].

The whole Arduino platform (boards, core library and IDE) makes it super
easy to get started and do _simple_ things. However, if you want to
“push the limits” and use the full potential of the MCU, you may have to
dig into low-level programming, and this has a steep learning curve.

> The 250V mains will be half-rectified with an IN4004 (?) transistor
> (together with a 1K resistor and 0.22uF cap), and that will go into a
> 4N35 optocoupler.

1 kΩ seems way too low to me: your resistor will dissipate on
average 31 W, and it will burn unless it is a heavy-duty power
resistor. You should choose a resistor that limits the current to a
value low enough to avoid overheating, but still high enough to reliably
turn on the optocoupler. If these two constraints end up being
incompatible, you will need a step-down transformer in addition to (not
instead of) the optocoupler.

> A digital (?) GPIO pin from the Arudino goes into the base of the 4N35
> and emitter goes to GND.

The base of the optocoupler is typically left floating. You connect the
Arduino input to the collector, using either the internal or an external
pullup resistor, and you ground the emitter.

> 1. I believe the Arduino can reliably be powered by USB.

Yes, powering through USB is fine. The Arduino itself draws very little
power. Only when _it_ is powering something else you may worry about
power limits. Here it would seem your Arduino will only be sourcing a
very small amount of current into the output transistor of your
optocoupler, so you will be fine.

> 2. How stable is the clock on the Arduino?

Terrible. Most Arduinos are clocked off a [ceramic resonator][]. These
are typically specified with 0.5% frequency tolerance, but their
frequency is constantly fluctuating, and is also strongly dependent on
ambient temperature. This makes those Arduinos grossly unsuited for any
job requiring precise timings. I would recommend you get an Arduino
sporting a real quartz crystal, like the Leonardo or the Micro. A quartz
crystal can be quite inaccurate, but at least its frequency is stable.
It's _orders of magnitude more stable than a ceramic resonator_. C.f.
for example this article about the [Arduino clock frequency
accuracy][arduino-frequency].

> 3. I presume I'll need to debounce the result from the optocoupler?

If the capacitor after your half-wave rectifier is well dimensioned,
your signal should be clean and not need debouncing. The Arduino digital
inputs all have [Schmitt triggers][] which clean up the input noise as
long as it is not excessive. If you really need debouncing (check with a
scope if you can), well... there are no provisions for doing so in the
Arduino core library, but there is a [Debounce][] tutorial among the
examples shipped with the Arduino IDE, and there are a few third party
debounce libraries floating around the Web.

> 4. How simple is it to write some software (in C#) that will recognise
> the Arduino connected via USB, and communicate with that device in
> particular?

As stated in other answers, your Arduino will be seen by your computer
as a virtual serial port. I don't know C#, but any decent programming
language should allow you to easily read data from a serial port.

**Measuring method:**

You will time one or several periods of the input signal. There are
several ways of doing so. In roughly increasing order of complexity and
accuracy:

1. You continuously monitor the digital input, in a loop, and whenever
   you see a transition from LOW to HIGH you record the current time
   using [`micros()`][micros].

2. You use an interrupt pin as the input and you have the interrupt
   handler record the time with `micros()`.

3. You use the _input capture_ facility of your 16-bit timer running at
   the full CPU speed.

The methods using `micros()` have a resolution of 4 µs. Both will
give you some software-induced jitter because they depend on the timing
of your program execution. The advice given by GuitarPicker: “Keep your
code predictable, using as few conditional branches as possible that
might alter how long your code takes to run each cycle” is relevant only
to the first method. The interrupt method is immune to your main loop
timing, but it is still affected by the CPU processing other interrupts.

The _input capture_ method will give you single-cycle resolution and
accuracy, with zero software-induced jitter. That would be my first
choice, but it requires digging into the MCU datasheet and doing some
low-level programming.

[ceramic resonator]: https://en.wikipedia.org/wiki/Ceramic_resonator
[arduino-frequency]: http://jorisvr.nl/article/arduino-frequency
[Schmitt triggers]: https://en.wikipedia.org/wiki/Schmitt_trigger

[Debounce]: http://www.arduino.cc/en/Tutorial/Debounce
[micros]: https://www.arduino.cc/en/reference/micros

------------------------------------------------------------------------

**Addendum**: Here are some tentative answers to a comment posted by
Ozzah to his own question:

> I probably want 4 decimal places if possible.

If you want 10−4 _absolute_ accuracy, you may need to
calibrate your clock, even if it is a crystal. If you only require
10−4 _stability_ (variations of the frequency), then even a
ceramic resonator may be (barely) up to the task, if you don't mind
recalibrating it every few weeks, and assuming your indoor temperature
doesn't vary by more than ≈ 10°C.

> I want the highest resolution and best tolerance possible.

Then a quartz crystal is definitely a plus. It's roughly 100 times
more stable than the ceramic resonator.

But if you really want the “best”, you may as well follow Milliways'
advice and get a GPS reference. Some options, in increasing order of
price and accuracy:

1. A simple GPS module for the Arduino. Make sure you get one with a
   1PPS output (a “one pulse per second” reference signal). You may want
   an external antenna for better reception.
2. A GPSDO (GPS disciplined oscillator). This is typically a lab-grade
   frequency standard consisting of an OCXO (oven-controlled crystal
   oscillator) disciplined by a feedback loop into tracking GPS time. It
   gives the same long-term stability as the simple GPS module but has
   far better short-term stability.
3. A rubidium-based GPSDO. This is similar to the above but has also a
   rubidium atomic frequency reference. Still better short-term
   stability. Now we are talking about stabilities in the
   10−11 to 10−12 range. Provably overkill for
   your use case.

From the software point of view, I would recommend you start with the
interrupt method, just to get a prototype working easily, and then go to
the input capture method, as it will give you the best accuracy. It
should be possible to be cycle-accurate with the interrupt method, but
that would require some non-trivial tweaks.

Note also that the Arduinos based on the ATmega32U4 (Leonardo and Micro
at least) have _two_ 16-bit timers with input capture capability. You
can then time both the mains signal and a 1PPS reference in parallel. If
your Arduino has only one 16-bit timer (like the Nano), you would have
to time one of the signals with the interrupt method.

> I'm trying to find a way to determine which Arduino boards use
> crystals for the MCU clock and which use ceramic resonators. From what
> I can see, they all have a crystal, but presumably that's for the USB
> interface?

Yes, the USB/serial interface is clocked off a crystal more often than
the main MCU. The Arduinos that do _not_ have a separate USB/serial
bridge (like those based on the ATmega32U4) seem to have the main MCU
clocked off a crystal.

> How can I get a list of Arduinos that use crystals?

It's often stated in the product page. E.g., the page of the [Arduino
Micro](https://www.arduino.cc/en/Main/ArduinoBoardMicro) states
(emphasis mine): “It has 20 digital input/output pins (of which 7 can be
used as PWM outputs and 12 as analog inputs), **a 16 MHz crystal
oscillator**, a micro USB connection, an ICSP header, and a reset
button.”

Arguably, the info is not very prominent, and a compiled list would be
useful. I think this could be a very good question to ask in this site.


body:
> Based on my research, I believe the Arduino can reliably be powered by USB.

it can also be powered by the mains directly. ST wrote such an application note for its STM8 but the basic principle is the same. The beauty of this approach is that your zero cross detection can be done without the use of an optocoupler, directly through a gpio pin.

> How stable is the clock on the Arduino? How many decimal places on the frequency can I realistically achieve?

depending on your board. crystals are usually specified to 20ppm but typically within 10ppm at room temperature. resonators, which some arduino uses, are 0.1 - 1%.

if you are n't too picky, even the internal oscillators will do -> you can average the measurement over a long period of time to minimize jitter.

> I presume I'll need to debounce the result from the optocoupler?

generally no.

when you measure frequencies, you typically count the input signal. for low frequencies like the mains, you do the other way around: count the internal clock and use the input signal to gate its counting.

This allows frequency calculation down to quite a few decimal points: you should average approximately 8M counts per half cycle.

that's a lot of effective digits.


message:
How to run my IDUINO Yun Shields stand-alone?

Experts,

How can I power and communicate with the IDUINO shield *stand-alone*? In other words, without any additional uC for it to plug into.

Failing in that, can a Nano (cheaper, smaller) be wired to give the Yun what it needs?

body:
Yes, you can. All you need do is provide it with a regulated 5V supply on the 5V pin and it should power up and boot.

There's not a lot of IO on it though, so connecting to sensors and such would be hard, which is where the Arduino comes in handy. You communicate using the UART, so any microcontroller with a UART can be connected to it.


message:
NRF24L01 integrated antenna exposed out of the box

I'm going to try my hand at making a few sensors that are to report status to a central server. To make them wireless, I'm going with nRF24L01 modules. I intend to enclose the sensors (Arduino Mini Pro + nRF24L01 + battery pack + a couple of other small components) in a simple PVC box.

A couple of the sensors would be about 10 meters away from the server, which, as far as specifications go, is about the maximum range of the radio modules. Especially the ones with the integrated antenna that I'm using. I thought that maybe I could squeeze some radio performance by exposing the antenna, so that the radio signal isn't attenuated by the PVC case. I could carve a small opening in the lid and have the nRF24L01 stick out, so that the electronics would be protected inside but the antenna strip would enjoy open air.

I would like some thoughts on this idea. I'm especially trying to understand if I just had the most novel idea ever, since I can't seem to find anything about it on the net. Has anyone ever tried this in real life? Does it make sense? Is it worth the trouble?  I'm not looking for a theoretical analysis (I get that fine), only for actual experience. Thank you.

body:
In general no, this would make little or no difference. PVC has very little effect on RF signals.

After all, the antenna on your typical WiFi router is inside a PVC tube and it doesn't suffer from it.

Instead you would do better constructing a *dipole antenna* from a couple of pieces of carefully measured wire.

For instance [this instructable tells you how](http://www.instructables.com/id/Enhanced-NRF24L01/).


message:
Voltage divider arduino 5v and Ethernet board 3.3

I have an `Arduino Nano 5v` module and I just received an Ethernet Interface Board - `ENC28J60` that runs at `3.3v`. (https://www.sparkfun.com/products/765)

Might sound a dumb question but I will power the Ethernet board from a Voltage regulator that can deliver 3.3v but then I have to connect via `SPI` to my Arduino controller. I guess I can't connect my Arduino pins directly to the Ethernet board right? because HIGH in the pin will be 5v instead of 3.3v.

> Do I need to add a Voltage divider for those pins connections? And in case I need to what resistance values are the right ones to use?

Thanks

body: From experience with 3.3v ESP8266es with 5v Arduinos, only the signals _to_ the 3.3v device need to be converted (5v high -> 3.3v high). A 3.3v level _to_ the Arduino is high enough for 5v logic to still read it as HIGH. That means you can get away with just a voltage divider on each of the Arduino -> ENC28J60 pins.


message:
Error in IR receiver project

I'm trying to receive remote information with an IR receiver and this is my code:

    #include <IRremote.h>

    int RECV_PIN = 11;
    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void setup() {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }

    void loop() {
      if (irrecv.decode(&results)) {
        Serial.println(results.value, HEX);
        irrecv.resume(); // Receive the next value
      }
      delay(100);
    }

I tried to upload this to Arduino and it says:

    exit status 1
    redefinition of 'int RECV_PIN'

How can I fix this?

body:
Apparently the name `RECV_PIN` is used somewhere else, presumably in `IRRemote.h` -- although not in any version of it I can find.  Anyway, just change the name of `RECV_PIN` to something which doesn't conflict.

For example:

    int MY_RECV_PIN = 11;
    IRrecv irrecv(MY_RECV_PIN);


message:
Adding null character to char array

I have this code written and functioning that will write out the chars in `cmd` to a serial port for an input of ASCII text representing byte values.

    void SendCTRL (String &input)
    {
      //Adjust Data
      const char *hin = input.c_str();    // Get character array
      int clen = input.length()/2;
      unsigned char cmd[clen+1]; // Leave a byte for null terminator
      for (int i=0; i < 2*clen; i+=2)
      {
        cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
      }

      //Send Data
      cmd[clen] = 0;                     // Null-byte terminator
      digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
      for (int i=0; i< clen; i++)
      {
        RS485Serial.write(cmd[i]);   // Send string someplace
      }
      digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
    }

As the majority of the byte values fed are constant, I'm trying to create similar output for the following code when I feed the function below only the byte values that change frequently:

    void Create_Message(int Address, int Data)
    {
      //Adjust Data
      Address--;
      byte SvAdd = 1;
      byte FuCode = 6;
      byte AddHi = Address>>8;
      byte AddLo = Address;
      byte DatHi = Data>>8;
      byte DatLo = Data;
      byte AdDa[] = {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo};
      unsigned int crc=CRC(AdDa,sizeof(AdDa)/sizeof(AdDa[0]));
      byte CrcHi = crc & 0xFF;
      byte CrcLo = crc >> 8;
      /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
      * to
      *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
      */

      //Send Data
      unsigned char cmd[9]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo};
      cmd[8]=0; //Null-byte terminator
      digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
      lcd.setCursor(0, 1);
      for (int i=0; i< sizeof(cmd)/sizeof(cmd[0]); i++)
      {
        RS485Serial.write(cmd[i]);   // Send string someplace
      }
      digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
    }

I'm reading the Values written by RS485.write() and, in both cases, the data is good. However, for the 2nd section of code, the Arduino seems to write out the null-byte while it does not write the byte out in the 1st block. If I remove the allocation for the null-byte in the second code, it does not get a response from my device.

I'm guessing that the issue is that I am not setting my null-byte terminator correctly or otherwise missing something (I'm pretty new here XD )

**Update: it seems like using `sizeof(cmd)/sizeof(cmd[0])` to determine the send length interfered with data transmission when I set this to a constant the code works just fine.**

body:
In the second code example, the value of `sizeof(cmd)/sizeof(cmd[0])` is 9, due to the declaration `unsigned char cmd[9] ...`

Thus, the `for` loop will write out 9 bytes, with indices 0, 1, ... 8.  Due to `cmd[8]=0;` earlier in the code, the last byte will be zero.  To prevent that, one might instead use the expression  `sizeof(cmd)/sizeof(cmd[0])-1` in the `for` loop:

    for (int i=0; i< sizeof(cmd)/sizeof(cmd[0])-1; i++)
       RS485Serial.write(cmd[i]);

Note, this doesn't explain why it should be so that “If I remove the allocation for the null-byte in the second code, it does not get a response from my device”, although practically anything can happen if you say `cmd[8]=0;` after allocating only 8 bytes of storage.


body:
In addition to James's answer, to print (or send) a null terminated string you do not have to know the length of the string. Just print the characters till you find the null. So this code works better.

    for (int i=0; cmd[i] != 0; i++)
    {
     RS485Serial.write(cmd[i]);   // Send string someplace
    }

    //or

    int i=0;
    while(cmd[i] != 0)
    {
        RS485Serial.write(cmd[i++]);   // Send string someplace
    }


message:
Disable Reset when Com Port Connected/Disconnected

I've noticed that when I open and close the com port my Arduino is connected to, the device resets. This makes the program run the setup profile again and it loses the previous variable states. Is there any way to prevent this?

body:
If you review the Uno schematic, you can see the circuitry that enables an automatic reset when serial communication starts.  The circuitry is intended to allow easy program downloading.

There are two or three ways to prevent that reset:  add a 10 μF capacitor from ground to reset;  use a much-lower resistance for the pullup on reset; cut a trace from the serial-interface pin (eg CTS) that pulls reset.

The first method is relatively easy to implement, and easy to remove whenever you want to install a new program.

References:  [Disabling AutoReset On SerialConnection](https://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection) and [ArduinoISP on Uno requires 10uF cap -- WHY?](http://forum.arduino.cc/index.php?topic=104435.0), both at Arduino.cc.


message:
PROGMEM : pgm_read_float_near() equivalent for double? (Arduino Due)

I'm using an Arduino Due where double have a size of 8 bytes. In my software, I use double table const stored in prog memory, I was using an UNO before and used pgm_read_float_near() to retrieve these values. What function should I use?

body:
Arduino Due (ARM Cortex-M3) doesn't need anything like `PROGMEM` as it has access into the flash memory in the same way as into the `RAM`. The `const` qualifier is enough to keep it in program memory only.

The `AVR` based boards like `UNO` needs PROGMEM because there are different instructions for fetching data from program memory and `g++` is not very advanced in this way (some other compilers supports it directly - for example in gcc you can use __flash and __eeprom instead, but not in g++ as it was rejected for some reasons)

**Edit:**

Currently there are also AVRs with a new design (they are more like xmegas) and they are having flat address space (emulation) so with single pointer you can fetch RAM, FLASH, EEPROM and so on. But it's limited to the devices with smaller FLASH (all of it must fit into 64kB/16b pointers). In those cases you can just use const for global arrays and it'll be stored in FLASH (and not in FLASH and loaded into RAM upon startup like old AVRs) and string literals doesn't need P_STR / F() macros

For example:
- Atmega4809 (nano every, uno wifi r2) and variants: 808, 809, 1608, 1609, 3208, 3209, 4808
- Attiny(2/4/8/16/32)(0/1/2)(2,4,6,7) - eg Attiny212 1616 ...
- It should be also possible on AVR16/AVR32 devices, but 64kB/128kB ones needs PROGMEM again (compiler can't optimize it into FLASH as you have only snapshot of 32kB in direct address space, but it's possible to change it - however there is also erratum about it not working properly)


body:
For anyone looking for an equivalent, you can manually copy the bytes into a double like:
```cpp
double pgm_read_double(const double* address) {
    double result;
    memcpy_P(&result, address, sizeof(double));
    return result;
}
```
And use `memcpy_PF` for `far` addresses. **But** know that many MCUs [have access into the flash memory in the same way as into the RAM](https://arduino.stackexchange.com/a/38474/77085), so you don't need to use this at all.


message:
Does the Node MCU v3 (LoLin) not have a builtin led?

Trying a simple led blinking program I could not get the builtin led on a LoLin Node MCU v3 working. The `LED_BUILTIN` constant is set to pin 16 / GPIO16 / D0.

Reading several articles and QA I think that the Node MCU boards are supposed to have a the on-board led on pin 16. However, if I address this port nothing happens.

With the same code I can blink the data led which is on a RX pin, pin 2.

Is the builtin led missing on the LoLin Node MCU v3, or could it be that the led on my board is broken?

body:
the ESP8266 has a builtin led that is attached to D4 as labeled on LoLin boards which maps to GPIO2. One thing to Note is that the led is active low. In other words ... setting PIN 2 to '0' will turn the LED ON and setting PIN 2 to '1' will turn the LED OFF

[Lolin Builtin_Led Picture][1]

This is the only LED on the LoLin boards and differs from other devkits that have an LED on GPIO16.

  [1]: https://s-media-cache-ak0.pinimg.com/originals/65/d4/f9/65d4f900af42813b46f10d1636b0492d.jpg


body:
I have nodeMCU v3 and Pin 2 worked for me.

    #define LED_BUILTIN 2

    void setup() {
      pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                        // but actually the LED is on; this is because
                                        // it is acive low on the ESP-01)
      delay(1000);                      // Wait for a second
      digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
      delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
    }


body:
The NodeMCU with the CP2102 serial and a slightly narrower pin footprint does have 2 LEDs.

```
$led1 = BUILTIN_LED;  //D0, 16, BUILTIN_LED: OnBoard LED
$led2 = 2;    //Pin 5 D4/2 Internal LED for LoLin V3
```

The `$led1 = BUILTIN_LED` (on GPIO 16) is **not* on the LoLin NodeMCU v3.


message:
Using a MIDI connector both as MIDI In and Out (not simultaneously)

I asked this question also in Electrical Engineering (stack exchange), however on question is more appropriate on this board (question 5). For completeness, I kept all questions intact, but made question 5 bold.

Electrical Engineering StackExchange Question Link: [*Using a MIDI connector both as MIDI In and Out (not simultaneously)*](https://electronics.stackexchange.com/q/305990),

In my current (Arduino) project I have (currently) 3 MIDI INs and 2 MIDI OUTs. However, it would be nice if I can configure each of the MIDI connectors as IN or OUT by software (Arduino).

The circuits I am using are:

[![MIDI In][2]][2]

And

[![MIDI Out][3]][3]

What I would like is to use the connector shown in the above picture as MIDI In OR MIDI out. I have not tried it yet, since I have too many doubts and I do not want to break a component. However, I thought about it (with my limited electronic knowledge), and I think:

1. Pin 2 afaik for MIDI In, normally has +5V. In the MIDI Input circuit it is not connected, but in the MIDI Output circuit, it is connected to GND. I don't think this is good when being used as MIDI out, resulting in a short circuit (?). So I guess I have to make it +5V when used as MIDI Input and GND when used as MIDI Output (so putting HIGH or LOW 'digital' for Arduino).

2. Pins 1 and 3 remain in both circuits untouched (so I assume I can do the same).

3. Pin 4 and 5 is a bit tricky, since they are connected. I think I have to use one or two transistors to create two alternative paths for pins 4 and 5 for MIDI Input and Output. Or can I just set a specific voltage on pins 4 and 5 when used as MIDI In or Out? (and what would those values be?).

4. For the MIDI input, an optocoupler is used, while for MIDI output, directly the Arduino is used. I wonder if I have to use for both an optocoupler (since people might connect it accidentally to a MIDI output from a MIDI device.

**5. I'm not sure how to handle the RX and TX pins ... for 5 MIDI devices, I would need to use 5 RX and TX pins, but the Arduino (Mega) only has 4 of each. But this is probably a question for the Arduino board.**

  [2]: https://i.stack.imgur.com/yC8rr.png
  [3]: https://i.stack.imgur.com/sQIBu.png

body:
I suggest you have a look at the 4051 or 4052 chip ([datasheet][1]). The 4051 is a 1:8 analog multiplexer while the 4052 contains two 4:1 multiplexers. So basically it allows you to switch one pin on your Arduino to any out of 4 or 8 MIDI circuits.

In the case of TX, it's really simple. You just need a pullup resistor on each output so that the pins don't float when not switched to.

In the case of RX, you have to make sure that you don't miss any transmissions. If your MIDI sources are not sending simultanously, that's easy as well... but probably they are. In that case you cannot use an existing RX UART. Since MIDI is very slow, you could still switch back and forth between the inputs and catch all the bits (you would be writing a software UART then). But if you're not short of pins, it would be much easier to just use SoftwareSerial for one input.

  [1]: http://www.ti.com/lit/ds/symlink/cd4052b.pdf


message:
analogRead seems to freeze some seconds the program

I have the following code that reads a `RFID` reader, it was working perfect without any dealy and then I try to an analog read from a potentiometer using `analogRead`.

The analog read works fine but then when I hover the card over the `RFID` it takes about 7 seconds or so to go into the line where I turn on a `LED`.

Im sure Im doing something wrong with `analogReader` because this is the first time I use it.

> I really appreciate any help

        #include <MicroView.h>

        MicroViewWidget *widget;        // create widget pointer

        #define MAX_BITS 100                 // max number of bits
        #define WEIGAND_WAIT_TIME  3000      // time to wait for another weigand pulse.

        unsigned char databits[MAX_BITS];    // stores all of the data bits
        unsigned char bitCount;              // number of bits currently captured
        unsigned char flagDone;              // goes low when data is currently being captured
        unsigned int weigand_counter;        // countdown until we assume there are no more bits

        unsigned long facilityCode=0;        // decoded facility code
        unsigned long cardCode=0;            // decoded card code

        int sensorPin = A1;    // select the input pin for the potentiometer
        int sensorValue = 0;  // variable to store the value coming from the sensor

        // interrupt that happens when INTO goes low (0 bit)
        void ISR_INT0()
        {

          bitCount++;
          flagDone = 0;
          weigand_counter = WEIGAND_WAIT_TIME;

        }

        // interrupt that happens when INT1 goes low (1 bit)
        void ISR_INT1()
        {

          databits[bitCount] = 1;
          bitCount++;
          flagDone = 0;
          weigand_counter = WEIGAND_WAIT_TIME;
        }

        void setup()
        {

          pinMode(2, INPUT_PULLUP);     // DATA0 (INT0)
          pinMode(3, INPUT_PULLUP);     // DATA1 (INT1)
          pinMode(5, OUTPUT);           // LED

          Serial.begin(9600);

          // binds the ISR functions to the falling edge of INTO and INT1
          attachInterrupt(0, ISR_INT0, FALLING);
          attachInterrupt(1, ISR_INT1, FALLING);

          digitalWrite(sensorPin, HIGH);      // Internal Pull-up
          pinMode(sensorPin, INPUT);          // make pin as INPUT

          uView.begin();                      // start MicroView
          uView.clear(PAGE);                  // clear page
           uView.setCursor(5,0);
          uView.print("TEST");
           uView.setCursor(0,20);
           uView.print("RFID READ");
          widget = new MicroViewSlider(0, 35, 0, 1024);    // make widget as Slider
          //widget2 = new MicroViewSlider(0, 20, 0, 1024, WIDGETSTYLE1);    // make widget as Silder STYLE1
          uView.display();                    // display the content in the screen buffer

          weigand_counter = WEIGAND_WAIT_TIME;
        }

        void loop()
        {

          // This waits to make sure that there have been no more data pulses before processing data
          if (!flagDone) {
            if (--weigand_counter == 0)
              flagDone = 1;
          }

    //****** THIS IS THE NEW CODE THAT FREEZE FOR ABOUT 7 SECONDS THE PROGRAM ***//
          sensorValue = analogRead(sensorPin);    // read sensorPin
          widget->setValue(sensorValue);          // set value of sensorPin to widget
          //widget2->setValue(sensorValue);         // set value of sensorPin to widget
          uView.display();

    //****** THIS IS THE NEW CODE THAT FREEZE FOR ABOUT 7 SECONDS THE PROGRAM ***//

          // if we have bits and we the weigand counter went out
          if (bitCount > 0 && flagDone) {
            unsigned char i;

            Serial.print("Read ");
            Serial.print(bitCount);
            Serial.print(" bits. ");

            if (bitCount == 32){

              // **** AFTER 7 SECONDS I GET INTO THIS CODE ****///

              uView.clear(PAGE);      // clear the page buffer
              uView.setCursor(0,0);

              digitalWrite(5, HIGH);

            }

             // cleanup and get ready for the next card
             bitCount = 0;
             facilityCode = 0;
             cardCode = 0;
             for (i=0; i<MAX_BITS; i++)
             {
               databits[i] = 0;
             }
          }
        }

body:
`analogRead()` is fine, it takes only about 110 µs, but there are
several other issues with your code that you should fix:

1. Any variable that is shared between interrupt code and normal code
   should be declared `volatile` in order to prevent the compiler to do
   some unsafe optimizations.

2. Any such variable that is more than one byte in size should be
   accessed from the main program with interrupts disabled.

3. You should take care of not writing into `databits[]` past the end of
   the array.

4. Counting loop iterations is a very bad way of measuring elapsed time,
   as the counting speed will change whenever you change your loop code.
   Use `micros()` instead.

There is also an issue with how you use `flagDone`. You set it to 1,
then you call `analogRead()`, `MicroViewSlider::setValue()` and
`uView.display()`, then you read it back. What if your ISR has set it
back to 0 in the meantime? I suspect this is the main cause of the
problem you see.

I suggest you use `flagDone` to inhibit the ISRs: the main loop sets it
to `true` to tell the ISRs “Let's say we are done with this card. Please
do not touch anything while I process the already received information.”
And later it sets it to `false` meaning “You can proceed reading bits
now.”

Given the above considerations, I would try something along these lines:

    volatile bool flagDone;     // if we are done, pause the reading
    volatile uint8_t bitCount;  // number of bits received so far
    volatile uint32_t rxTime;   // last time we got a bit

    // Interrupt that happens when INTO goes low (0 bit).
    void ISR_INT0()
    {
        if (!flagDone && bitCount < MAX_BITS) {
            rxTime = micros();
            databits[bitCount++] = 0;
        }
    }

    // Same thing, but writes 1 instead of 0 into databits[].
    void ISR_INT0() { ... }

    void loop()
    {
        // Safely read rxTime.
        noInterrupts();
        uint32_t rxTimeCopy = rxTime;
        interrupts();

        if (bitCount > 0 && micros() - rxTimeCopy >= WEIGAND_WAIT_TIME) {
            // Assume we are done reading this card.
            flagDone = true;

            // Do whatever with databits[].
            // ...

            // Get ready for the next card.
            bitCount = 0;
            flagDone = false;  // do this last: it re-enables the ISR
        }
    }


message:
fatal error: avr/io.h: No such file or directory

I'm compiling a project on Due that was working correclty using UNO. I get this error : **'avr/io.h: No such file or directory'**. Searching across the web, it seams I'm not the only one to get that error when using Arduino Due but didn't clearly figured out why it appears.

Of course, the file is present where it should be, I verified ..\Arduino\hardware\tools\avr\avr\include\avr\io.h

I opened it and see something like that :

    ...

    #if defined (__AVR_AT94K__)
    #  include <avr/ioat94k.h>
    #elif defined (__AVR_AT43USB320__)
    #  include <avr/io43u32x.h>
    #elif defined (__AVR_AT43USB355__)
    #  include <avr/io43u35x.h>
    #elif defined (__AVR_AT76C711__)
    #  include <avr/io76c711.h>
    #elif defined (__AVR_AT86RF401__)
    #  include <avr/io86r401.h>
    #elif defined (__AVR_AT90PWM1__)
    #  include <avr/io90pwm1.h>
    #elif defined (__AVR_AT90PWM2__)
    #  include <avr/io90pwmx.h>
    #elif defined (__AVR_AT90PWM2B__)
    #  include <avr/io90pwm2b.h>
    #elif defined (__AVR_AT90PWM3__)
    #  include <avr/io90pwmx.h>
    #elif defined (__AVR_AT90PWM3B__)
    #  include <avr/io90pwm3b.h>
    #elif defined (__AVR_AT90PWM216__)
    #  include <avr/io90pwm216.h>
    #elif defined (__AVR_AT90PWM316__)
    #  include <avr/io90pwm316.h>
    #elif defined (__AVR_AT90PWM161__)
    #  include <avr/io90pwm161.h>
    #elif defined (__AVR_AT90PWM81__)
    #  include <avr/io90pwm81.h>

    ...

so I suppose that a line referring to my card is missing or something like that ?

I'm using Arduino 1.6.12

body:
The Due is SAM architecture. avr/io.h is specific to the AVR architecture of the Uno's microcontroller. The compiler will not look in the avr tools folder for that file and even if it did it wouldn't help because that file is not compatible with the SAM architecture.

This error indicates that part of the code you're attempting to compile (probably a library) is AVR specific. You will need to either port that code to the SAM architecture or find an alternative that is already compatible with Due.


message:
What's wrong with my code?

I was trying to do a LED display that turns on a LED at pin 13 that goes on then turns off after a delay then the next pin (which is pin 12 counting down) will turn on and then turn off.

I also put in a potentiometer that can change the delay to make it faster or slower.

Here's the code:

    float pinOn = 13;
    int outMin = 0;
    int outMax = 13;
    float delayNum = 1000;

    void setup () {
      for (int i=outMin; i<=outMax; i++) {
      pinMode(i, OUTPUT); }
      Serial.begin(9600);
    }

    void loop () {
      // Reads Potentiometer -- sets delay relative to the Potentiometer input
      int sensorValue = analogRead(A0);
      delayNum = sensorValue;
      // Turns on the Pin designated by 'pinOn'
      digitalWrite(pinOn, HIGH);
      delay(delayNum);
      digitalWrite(pinOn, LOW);
      // Checks if 'pinOn' is 0 which then resets it back to 13 if not 0 then counts down
      if (pinOn = 0) {
        pinOn + 13;
      } else {
        pinOn - 1;
      }
    }

All it does is turn on pin 13 for a moment then permanently turns on pin 1 and 0 and it gets stuck like that.

body:
`if (pinOn = 0)` is doing an assignment (single =) not a comparison (double ==), so `pinOn` is begin set to `0` each time through the loop. The result of an assignment is the value being assigned. So it's the same as `if ( 0 )`, which is false.

Now, on to the two branches. `pinOn + 13` is a statement and the result is not being assigned to anything. You need an equals sign somewhere:

    if (pinOn == 0) { // == means "is equal to"
      pinOn += 13; // same as pinOn = pinOn + 13
    }
    else {
      pinOn -= 1;
    }


message:
More than 500 pins

For a project I need 400-1000 pins controlled by one arduino. Each pin should work similar as arduino pin, so something like 5V, 90mA. Is using dozens of shift registers a good idea? And what power source should I connect?
My idea is following:[![enter image description here][1]][1]

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

So one shift register requires 3 input pins to control it, and if one shift register has 12 output pins, I can connect 4 more shift registers to one shift register. Is it a good idea and will it work?

body:
You don't connect shift registers as a tree. That would be awfully slow.
Instead, you connect them as chains. Shift registers are meant to be
chained by connecting the serial out of one register to the serial in of
the next one, while both registers share the latch and clock lines. You
can chain as many as you want this way: a chain of four 8-bit shift
registers behaves like a single 32-bit shift register. See for example
this [Arduino tutorial on the
595](https://www.arduino.cc/en/tutorial/ShiftOut) to see how the
chaining works.

There is an issue, however, in making long chains: whenever you want to
change the state of one single output you have to shift the whole chain
again. And the longer the chain the longer it takes. Thus it is more
efficient to put in a single chain outputs that you will likely want to
change together, and use independent chains for outputs that are most
likely going to change at different times.

As for the wiring, you need three Arduino pins to drive one chain of
registers: data, clock and latch. But you can share the data and latch
pins between many chains, as long as you have a dedicated clock pin for
each chain. You should then be able to drive _n_ independent chains
using _n_ + 2 Arduino outputs.

As for the power, you have to estimate your power consumption (not just
the shift registers, but also whatever _they_ are sourcing current into)
and find a 5 V power supply big enough to power your whole circuit.


body:
Here is a whole different approach.

Look at how they built the motion-controlled coffee table:

http://www.evilmadscientist.com/?s=LED+coffee+table
[![enter image description here][1]][1]

It has hundreds and hundreds of connections, so they subdivided the board so they could have distributed Arduinos.

So it is possible to control that many pins, and it may be best to use multiple Arduinos.

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


message:
I want to make a counter but i don't know what i'm missing or am doing wrong

this is the code i made but it gives me an error about te } and also i need to know how to make delays with this

    int ledPin = 4;
    int buttonPin=2;
    int buttonState = 0;         // variable for reading the pushbutton status

    void setup()
    {
      pinMode(ledPin, OUTPUT);
      pinMode(buttonPin, INPUT);
      Serial.begin(9600);
    }

    void loop()
    {
      if (buttonPin=(LOW);
     {
     Serial.println("someone pressed it");
    }
      else
      {
        Serial.println("nothing");
      }
    }

thanks for helping!

body:
You forgot bracket here

    if (buttonPin=(LOW);

Should be

    if (digitalRead(buttonPin)==(LOW)){

To make a delay of 0.5 seconds for example:

    delay(500);


message:
Johnny-five driving LCD Matrix or call Arduino library from Johnny-five

I would like to know if it's possible to drive an LED Matrix like [this one][1] with johnny-five.
If not, how can i call Arduino library/code from johnny-five.

If I Write method on sketch into the Arduino, can I call them from J5 REPL?

  [1]: http://wiki.sunfounder.cc/index.php?title=Full_Color_RGB_LED_Matrix_Driver_Shield_+_RGB_Matrix_Screen

body: After research, it can't be done, as J5 use firmata to drive the Arduino, the only way is to write a library to use with.


message:
Running out of pins in a 4x7-segment display clock

I've been playing around with the 7-segment displays and so far I've only been able to make 1 working display hooked up to a potentiometer that changes the number on the display with a switch that turns it into a counting-up timer

My main goal is to make a Clock but that uses 4 7-segment displays and I've already used up 7 pins for 1 display so now I either need to make more pins (I'm using Arduino Uno which has 14 Digital pins + 6 if you use the Analog In pins)
or use the 7-segment decoders

if I use the 7 segment decoder that will take up 4 per display which totals up to 16 which is well in range the required amount of Pins

so can someone teach me what is easier to do:

Making more pins using the 8-bit shift registers
or
Use the 7-segment decoders to make space

and if you think one is easier can you tell me how to use them because I have no idea and I've been tinkering with the decoder for the past hour or two
(btw the 7-segment displays are all Common Anode)

body:
The basic idea is this:

First, connect segment A of each display together, and all the segment Bs together, and all the segment Cs and so on.  Each "group" is driven by one pin on the Arduino.  For this you will need seven pins.

Your displays will have either a common anode or common cathode - perhaps you have that connected straight to +5v or straight to ground currently.  Instead, you connect the "common" pin from each display to a spare pin on your Arduino - so using another four pins.

Remember the resistors too.

Now, you can light up any segment on any display, by setting the appropriate segment pin and the appropriate common pin to the right values.

Make sense?


message:
Interruption triggered twice when set to FALLING

I have a simple sketch with a button that triggers an interruption set to happen when the button pin goes from HIGH to LOW. It has debouncing so no repetitions happen when the button is pressed, but sometimes when releasing the button the interruption also fires. Why would that be? Shouldn't the debouncing take care of any micro-rising during the release of the button?

    volatile int contador = 0;
    int n = contador;

    long t = 0;
    void setup() {

        pinMode(2, INPUT_PULLUP);
        attachInterrupt( 0, incrementaContador, FALLING);
    }

    void loop() {
        if (n != contador) {
            n = contador;
        }
    }

    void incrementaContador() {

        if ( millis() > (t + 50) ) {
            contador++ ;
            t = millis();
        }
    }

This same code works correctly when set to LOW instead of FALLING.

body:
>  but sometimes when releasing the button the interruption also fires

Yes, well when you release the button it may also bounce. In other words OFF/ON/OFF so that will count as a press. A capacitor over the switch might be better.

Example:

[![Hardware debounce][1]][1]

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


message:
TLS Client ESP8266

My ESP8266 collects data and sends it to a webserver over HTTP. I would like to use TLS for this but I cannot figure out how to get ESP8266 running on the Arduino framework to use this.

My curent code is based on `ESP8266HTTPClient` and when searching the ESP8266 pages on GitHub 50% of the information tells me that it's impossible to use HTTPS and the other half of the info tells me it's possible but not documented with `WiFiClientSecure` but that looks like a whole different way of communicating HTTP..

Link: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/WiFiClientSecure.h

    void senddata() {
      String testdata = "{\"tickle\": {\"id\": " + String (package.id) + ",\"value1\": " + String (package.value1) + ",\"value2\": " + String (package.value2) + "}}";
      Serial.println("Starting the journey to Salador..");
      http.begin("https://myserver/_db/Salador/upload");
      http.addHeader("Content-Type", "application/json");
      int httpCode = http.POST(testdata);
      if(httpCode > 0) {
          Serial.println("[HTTP] POST... code: ");
          Serial.println(httpCode);

      }
      else {
          Serial.println("[HTTP] POST... failed, error: ");
          Serial.println(http.errorToString(httpCode));
      }
      http.end();
    }

body:
I don't think you can easily mix the HTTP wrapper and the WiFiClientSecure. At the moment if you want to do HTTPS you have to do the HTTP portion of the transaction manually by sending the individual headers and then the body, then parsing the response yourself.

It's not that hard, and the example you point to shows you how it can be done - print the headers and body to the client, then read the data back looking for specific things (like a blank line to separate headers from body, etc).

----

Although: I do see this clue in the BasicHttpClient.ino example:

    // configure traged server and url
    //http.begin("https://192.168.1.12/test.html", "7a 9c f4 db 40 d3 62 5a 6e 21 bc 5c cc 66 c8 3e a1 45 59 38"); //HTTPS

So maybe if you know the fingerprint of your HTTPS server you can connect directly with HTTPS. How you get that fingerprint though is not something I know yet.


message:
can I give the 9v input power for arduino mega 2560 using vin pin?

I am using Arduino mega 2560. I have some doubts about powering my microcontroller.
Can I use the 9v battery to power my arduino through the VIN terminal?![enter image description here](https://i.stack.imgur.com/wR3kZ.jpg)
I have uploaded an image. Check whether it is a correct method or not?

body:
Yes!

> The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may become unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

> The power pins are as follows:
> - Vin. The input voltage to the board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

https://www.arduino.cc/en/Main/ArduinoBoardMega2560

Vin is the same as the external positive power input.


message:
Grab keys from an ordinary USB keyboard

**Arduino USB**

I want to write an Arduino Sketch (if there is no other possibility it can also be plain c) , to grab keyboard inputs from my ordinary USB keyboard. Preferably without expensive hardware, but as mentioned, if there is no other possibility, this will do it too.

Is this possible with [V-USB][1]? I looked a their website, but it seems like this only supports being slave and to imitate a keyboard.

  [1]: https://www.obdev.at/products/vusb/index.html

body:
As suggested in the comments, you have two options:

As suggested by Majenko, you can use the [Arduino USB Host Shield][1]:
[![Picture of USB Host Shield][2]][2]

Alternatively you could use a PS2 keyboard instead (as suggested by Gerben). Arduino already has a library to handle PS2 keyboards, so the implementation of it would be easy. For reference (and example program)
[playground.arduino.cc/Main/PS2Keyboard][3]

If you do not have access to a PS2 keyboard or just want to use a USB keyboard, Gerben further suggests that most USB keyboards can be converted to PS2 keyboards with an adapter:
[![USB to PS2 adapter][4]][4]

The keyboard must be able to support both formats (USB & PS2).

The following webpage shows the connections needed to go from USB to PS2:  [USB to PS/2 adapter pinout][5]

[![Pinout connection][6]][6]

  [1]: https://www.arduino.cc/en/Main/ArduinoUSBHostShield
  [2]: https://i.stack.imgur.com/eZA2P.jpg
  [3]: http://playground.arduino.cc/Main/PS2Keyboard
  [4]: https://i.stack.imgur.com/drW7l.jpg
  [5]: http://pinouts.ru/InputCables/usb_ps2_mouse_pinout.shtml
  [6]: https://i.stack.imgur.com/gzsz0.png


body:
I am able to use this library: https://github.com/techpaul/PS2KeyAdvanced and USB's data +/- connected to pins 2+3 of an arduino to read keys on standard keyboards.

    keyboard.begin( 3, 2); // D3= data+, D2= data-

 A standard keyboard is one which doesn't need a driver to work on any computer. I'd tried several libraries, serial keyboard adapters, and ps2/usb converters, and this method works best. Since the ps2-USB converter is just a physical pin change with no logic, standard USB keyboards just magically with with the PS2 libraries; even caps lock and what not...


message:
How to get 38 Khz clock from Timer 0/2 in Arduino Mega 2560?

I have been trying to generate a PWM wave of 38 Khz (13 microsec= ON period , 13 microsec= OFF period).  Currently I am using Timer 0 to generate the PWM wave , however i am confused as to how to prescale the 16Mhz input clock frequency so that i can get 38 Khz from it .

The code is as follows -

    #include<avr/io.h>
    #include<util/delay.h>

    uint8_t  dutycycle;
    void pwm_init()
    {
      // Configure PB.7 as output pin
      DDRB |= (1<<PB7);
      DDRG |= (1<<PG5);

      // Clear o/p on Match and Fast PWM Mode
      TCCR0A |=(1<<COM0A1) | (1<<WGM01) | (1<<WGM00) | (1<<COM0B1);// COM0A1/0b1 are the ouput ports , and WGM01 and WGM02 are used for fast PWM mode
      TCCR0B |=(1<<WGM02) | (1<<CS01);//WGM02 is used to set the fast pwm mode with max value stored in OCRA. CS01 is used to prescale the clock frequency to 16Mhz % 8 .
            OCR0A = 52;

    }
    void dutycycleA(uint8_t dutycycle)
    {
     OCR0B = (dutycycle * 52)/100 ;
    }
    int main()
    {
      pwm_init();

      while(1)
      {
       dutycycle=50;
       dutycycleA(dutycycle);
       _delay_ms(1000);
            }
    }

So , the code is supposed to keep checking the value of OCR0B with the timer value and if it is less than that , then the output is logic HIGH , and if it is same as the timer value , then it'll be logic LOW . the duty cycle is given as 50 so that a pulse waveform of 50% duty cycle is reached .

However I am unable to obtain 38Khz output .

Please help me figure out where I have gone wrong and also suggest corrections to my approach , if wrong .

Thank you .

PS - I am using Eclipse Neon platform.

body:
<s>It appears that you didn't set any Clock Select bits.  Per datasheet,
>clkT0 can be generated from an external or internal clock source, selected by the Clock Select bits (CS02:0). When no clock source is selected (CS02:0 = 0) the timer is stopped.

That could account for getting no output at all, if that's what's happening. </s> [I had overlooked `(1<<CS01)` in your TCCR0B setup.]

You have the COM0A1 and COM0B1 bits set, and you apparently assume COM0A0 and COM0B0 are clear. (Note that in the code below, I say `TCCR1A = ...` and  `TCCR1B = ...` instead of using `|=`, because `|=` is not reasonable to use for initial setup).  In the #7 fast PWM mode that you selected via WGM bits, this would lead to OC0A and OC0B clearing on their respective Compare Matches and setting at BOTTOM, which looks more or less ok for the OC0B pin, if you have OCR0B set to about half of OCR0A.  If the OC0A pin clears, however, it probably gets set again a cycle later, if I understand correctly.  (However, I'd want to actually test the code, with oscilloscope connected, to say for sure.)

Note that the OCR0A count of 52 and prescaler of 8 will set up a counting frequency of 1600000/(52+1)/8 Hz, ie about 37735.85 Hz, while a count of 51 would give 38461.54 Hz.  If accuracy matters, you can use simpler and more accurate code like the following.  It uses a prescale of 1 and count of 209, to generate a toggle frequency of 1600000/(219+1) Hz, ie about 76190.48 Hz, and a square wave frequency of about 38095.24 Hz.   Note, this code is written for timer 1; it should be straightforward to adapt to timer 0, because 209 is less than 255, the upper limit of TCNT0.

    // Generate a constant frequency on PB1, using Fast PWM - jw May 2017
    enum { OC1Apin = 9 };    // Arduino digital pin #9 = OC1A = PB1

    void setup() {  // Set up timer 1
      noInterrupts();               // Turn off interrupts during setting
      TIMSK1 = 0;                   // Turn off timer 1 interrupts
      // Set timer 1 to Fast Pwm mode with OC1A (dig pin 9) toggling
      TCNT1 = 0;                    // Zero the counter
      TCCR1A = 1<<WGM11 | 1<<WGM10  // for Fast Pwm with TOP from OCR1A
        | 1<<COM1A0;                // To toggle OC1A PB1 D9 on Compare Match
      TCCR1B = 1<<WGM13 | 1<<WGM12// for Fast Pwm with TOP from OCR1A
        | 1;                      // Start timer 1 with prescale 1
      // Set OCR1A *after* setting up TCCR1A & TCCR1B
      OCR1A = 209;                // Gen. about 38095.24 Hz
      pinMode(OC1Apin, OUTPUT);
      interrupts();
    }
    void loop() {}

---

*Edit 1:* Here are some of the differences between this code and that shown in the question, aside from using timer 1 instead of 0:

• Initialization of TCCRxA and TCCRxB registers here is done using *Register = expression* forms, rather than  *Register |= expression* forms.  Just OR-ing your bits in may be a problem if some other CS bits are set.  For example, in the Arduino environment, initialization for `millis()` will set a prescale factor of 64, by setting both of the CS00 and CS01 bits, so that when you say `TCCR0B |=(1<<WGM02) | (1<<CS01);` you end up with both of the CS00 and CS01 bits still set, and a prescale of 64 instead of 8.

• `TCCR1B = ... | 1;  // Start timer 1 with prescale 1` sets the CS00 bit and leaves the CS01 and CS02 bits clear, selecting prescale 1, while `TCCR0B |= ... | (1<<CS01);` selects a prescale factor greater than 1.

• The code shown here generates a square wave because it toggles a pin at a constant rate.  The code in the question sets OCR0B to 26, which will give 27 clock-cycles to half of each output cycle, and 26 clock-cycles to the other half.

• The code shown here generates a frequency of about 38095 Hz, which is about 0.25% high, vs a frequency 0.7% low for the code in the question.

---

*Edit 2:* One way to get a fixed number of pulses is to set up an interrupt handler that is invoked once per toggle (or, once per cycle if appropriate).  It can decrement a counter, and shut off an output pin when the counter gets to zero.  Or could set the output pin low and the CS bits to 0 to stop the counter.  For example, if timer 1 is in use:

    volatile byte TogCounter;
    ...
    // In setup():
    TIMSK1 = 1<<TOIE1;  // Enable timer 1 overflow interrupt at TOP
    ...
    // Define a timer 1 ISR
    ISR(TIMER1_OVF_vect) {      // ISR for timer 1 overflows
      if (TogCounter) {         // Don't decrease if not counting
        --TogCounter;
        if (!TogCounter) {
          pinMode (TogPin, INPUT); // Disable output when count runs out
          // If desired, set a volatile wavetrain-is-done flag here
        }
      }
    }

To output a specified number of cycles *n*, set the mode of `TogPin` to `OUTPUT` and set `TogCounter` to *2·n*.  Note, waveforms will be of more-consistent length if you also clear the counter register just before starting any pulse train.

To generate a sequence like *m1* cycles on, *n1* off, *m2* cycles on, *n2* off, etc, you could set up an array containing *m1*, *n1*, *m2*, *n2*, etc; then each time `TogCounter` runs down, toggle `TogPin` from INPUT to OUTPUT or vice versa, and load the next array entry into `TogCounter`.


body:
A few ways to get there. 38khz has a period of 421 ticks on a 16mhz Mcu. So

Approach 1. Use the pwm module to Generate it.

Approach 2. Use the timer overflow interrupt to generate it. Simply flip the output pin in the isr.

Approach 3. Use the compare interrupt to generate it. In the isr increment the compare match register by 120 and then flip the output pin.

All of them are fully supported by your chip. The first approach once set consumes no CPU processing power.

edit: this link, https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-avr-timer2/, will hopefully provide some inspiration to you. It is for a different application but the gist of the problem is the same.

here is the output, adopting it to generate a 38Khz (37,679Hz to be exact) pulse train on a user specified pin using timer2 compare ch b interrupt.
[![enter image description here][1]][1]

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

i think you will benefit a lot in getting the code going on your own but if you really struggle, I can provide you the code as well. but you get a lot more if you try to get it going on your own.


message:
P I D AND GY80 10 DOF

I am running the program for GY80 10 DOF , and runs fine . Date is printed on the serial monitor[![enter image description here][1]][1]
How ever I have failed to use this program for my WalkerBot
(walker bot is a Robotic suit that I want to build for 4 years old my grand son He can not walk due to C P )
Unless the PID is not introduced in the program it will not be good for Balancing of the walker Both the program is as under , and my further questions are in comments
I need help Please
I tried to use the Code Control to insert the codes But it did not work , I may be excused for that Please

the codes

      #include <Wire.h>
      #include <GY80.h>

         GY80 sensor = GY80(); //create GY80 instance

      void setup()
      {
        // initialize serial communication at 115200 bits per second:
        Serial.begin(115200);
        sensor.begin();       //initialize sensors
      }

         // How to envelop this program with PID
         // where the gyro output is supposed to maintain the vertical position of the //bot , and the accelerometer will be doing countermeasure of tilts
    // unless they both are on a feedback with PID this bot will not balance
    //as the servomotors if do not respond in runtime the bot will fall
    void loop()
    {
        GY80_scaled val = sensor.read_scaled();       //get values from all sensors
        // print out values

        Serial.print("Mag:");                         //magnetometer values
        Serial.print(val.m_x,2);
        Serial.print(',');
        Serial.print(val.m_y,2);
    // tried to get some output from here for using in PID but failed
    if(val.m_y,2 >2 ||val.m_y,2<0){Serial.print("Output has been managed");}
    but there was no output
        Serial.print(',');
        Serial.print(val.m_z,2);
        Serial.print(' ');
        Serial.print("Acc:");                         //accelerometer values
        Serial.print(val.a_x,3);
        Serial.print(',');
        Serial.print(val.a_y,3);
        Serial.print(',');
        Serial.print(val.a_z,3);
        Serial.print(' ');
        Serial.print("Gyro:");                        //gyroscope values
        Serial.print(val.g_x,1);
        Serial.print(',');
        Serial.print(val.g_y,1);
        Serial.print(',');
        Serial.print(val.g_z,1);
        Serial.print(' ');
        Serial.print("P:");                           //pressure values
        Serial.print(val.p,5);
        Serial.print(' ');
        Serial.print("T:");                           //temperature values
        Serial.println(val.t,1);

        delay(250);        // delay in between reads for stability
    }

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

body:
I am sorry, but I may not have understood your post, but I think the problem is your code doesn't work and you don't know why.  I think the problem is with this line:

    if(val.m_y,2 >2 ||val.m_y,2<0){

It is because it is not valid code, I suspect its a cut and paste error and should be

    if(val.m_y > 2.0 || val.m_y < 0.0){

the `,2` you use in the print statements specifies the number of digits to print after the decimal point (I think).


message:
How to choose SDA/SCL pair on Arduino Due?

On Arduino Due, there are two pairs of SDA/SCL pins that I can use for I2C. There is SDA0 and SCL0  at, respectively, pins 20 and 21 and another near AREF. How do I choose which one of them I use? I also read that pins 20 and 21 have built-in pull-up resistors, is that true?

body:
Pins 20 and 21 are the default I2C pins. A lot of libraries assume you use these, and would require some extra work to get working with SDA1/SCL1.

They also have their pullup resistors already present on the board of the Due ([see schematic](https://www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf)).

So just use pins 20 and 21, unless you have a good reason to use the other.


body:
How to choose SDA/SCL pain on due from software.
wire.h has two instances of TwoWire i.e. Wire and Wire1.

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

Wire uses

    #define PIN_WIRE_SDA         (20u)
    #define PIN_WIRE_SCL         (21u)

and Wire1

    #define PIN_WIRE1_SDA        (70u)
    #define PIN_WIRE1_SCL        (71u)

observe which instance is used by your library
e.g.

    #define WIRE Wire1 or #define WIRE Wire

if library is using Wire then its default i2c at pin 20 and 21.

if library is using Wire1 then its i2c at pin 70 and 71 near AREF.

make changes accordingly. if you want to use default i2c use "Wire" instance or
if you want to use i2c near AREF use "Wire1".

most important don't forget to modify Wire1.begin() or Wire.begin() accordingly.

as mentioned in earlier comment second i2c (pin 70 and 71 near AREF) doesn't have pullup resistor handle it while using second i2c.


message:
How to manage dependencies?

I want to include a dependency like [Logging](https://playground.arduino.cc/Code/Logging). On its page it says:

- Download zip file
- Put the Logging folder in "libraries\".

I don't want to believe (with a Maven mindset) that this is the way we manage dependencies in Arduino projects. That means, everybody who checks out my package would have to repeat those steps locally (or do you include "libraries\" in the version control) What's the best practice for dependency management?

body:
Arduino is meant to be easy way for non-technical people and so it hides as much as it can from plain view to be simple.

For simple project it works at the cost of overhead of copying libraries here and there and using Arduino's "IDE". Calling programs "sketches" and manipulate it to hide, that it is in C++. And so on and so on.

If you want to make more complicated projects, version control, good environment and such, you need to leave "simply Arduino way" and start using more powerful and complicated tools.

I personally use
https://github.com/sudar/Arduino-Makefile
https://github.com/ladislas/Bare-Arduino-Project
and have it in GIT repositories.

This way I can share libraries between projects in group, also links to libraries outside the tree works, as well as gits submodules, both allowing you to have updated libraries from 3rd party aviable to all projects, also those old ones.

I still use a lot of Arduino (like setup/loop, digitalRead and such), but also I use "normal" g++ constructs on the way. Later I will diverge even more to plain C/g++/.. code probably, using some RTOS or so, but now my needs are not so far yet. (google "arduino rtos" I am currently reading https://github.com/greiman/NilRTOS-Arduino )

Arduino is not meant to be "best practice" anyway. It is meant to be "fast and easy way to do something, when you know nothing". And it works, as anybody and his dog can start with Arduino and if interested, he can go more far on his own, or he can stick with easy and have fun anyway.


body:
If you want the project to be self contained you can put the library dependencies in the sketch folder. So the folder structure of the Foo sketch with the Logging library dependency would look something like this:

    Foo
    |_Foo.ino
    |_src
      |_Logging
        |_Logging.h
        |_Logging.cpp

And in Foo.ino you will include the library like this:
<!-- language: lang-cpp -->

    #include "src/Logging/Logging.h"
Unfortunately some libraries use the incorrect include syntax which still works when the library is installed in one of the libraries folders but not when located in the sketch folder. The Logging library does use the correct include syntax but sometimes to put libraries in the sketch folder you will need to fix this. For example, let's say you have a library named Bar and in Bar.cpp you see this:

    #include <Bar.h>
That won't work because if installed in the sketch folder Bar.h will not be located in one of the standard include paths so you need to edit Bar.cpp and change the include syntax to:

    #include "Bar.h"

Which will cause the local folder to be searched for the included file.

The downside to this system is that you may end up with multiple copies of a library so it's more work to update or modify each copy. Of course that can also be a benefit because each project can have its own known-working version of the library that will not be affected by any updates you may make to the same library used in other projects.

I generally just add instructions for how to install library dependencies in the usual manner to the documentation for a project. That should be within the capabilities of the average Arduino user. If a specific version of a library is necessary then you document that. However, there are cases where I have wanted to hand over a self-contained project to someone who is not familiar with the use of the Arduino IDE and that is when I have used the system described above for all necessary 3rd party libraries.


message:
Dynamically switching pin out

I have a connector with 10 pins, and a bus which uses 2 of the 10 pins.

What I need to do is, in software, attach my arduino to 2 of the 10 pins. I cannot wire it directly as the 2 pins required may be in a different position in different environments.

What are my options?

**EDIT:** Just some background. I have to connect to an OBD II port of a vehicle and cannot to the CAN bus. On some vehicles is may not be on the standard pins in the OBD connector, so I would like to be able to programatically switch the pins being used, in software.

body: Probably you need two SP10T switches, where you can programmatically decide which of the SPI pins will be sent to which of the 10 outputs which are connected to the 10 pin bus.


message:
LED sequence control by button

I want to make sequential LED by using arduino that controlled by button.
If I press + button, LED will increase from L1 to (L1 and L2 is HIGH), then I press button again, L1, L2, and L3 will be HIGH. If I press again, all the LED (L1, L2, L3, L4) will be high.
Same case if I press “ – “ button, LED will be lower from the previous state. Which mean that if L1, L2, and L3 is HIGH. There will be L1 and L2 only HIGH if I press ‘ – ‘ button. I dont how to do it. This is code for increase but I dont know how to make it reverse flow.

    const int buttonPin = 2; // the pin number of the pushbutton input pin
    int ledPins[] = {3, 4, 5,};
     // variables will change:
     int buttonState = 0; // variable for reading the pushbutton status
     int buttonPressCount = 0;
     int numberOfLED = 3;
     void setup() {
      // initialize the LED pin as an output:
      for (int i = 0; i < numberOfLED; i++) {
       pinMode(ledPins[i], OUTPUT);
      }
      pinMode(buttonPin, INPUT);
     }
     void loop() {
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);
      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if (buttonState == HIGH) {
       for (int i = 0; i < numberOfLED; i++) {
        if (buttonPressCount % numberOfLED == i) {
         // turn LED on:
         digitalWrite(ledPins[i], HIGH);
        } else {
         // turn LED off:
         digitalWrite(ledPins[i], LOW);
        }
       }
       buttonPressCount++;
       delay(400);
      }
     }

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

body:
My original answer was probably over-kill....Just keep track of how many leds are lit:

<!-- language: lang-c -->

    int ledPins[] = {3, 4, 5,};
    const int num_leds = sizeof(ledPins) / sizeof(ledPins[0]);  // 3 in this example
    byte num_leds_lit = 0

    void set_leds() {
        for (int i = 0; i < num_leds; i++) {
            digitalWrite(ledPins[i], i < num_leds_lit ? HIGH : LOW);
        }
    }

Then, on button press, increase the count:

<!-- language: lang-c -->

    if (num_leds_lit < num_leds) {
        num_leds_lit += 1;
        set_leds();
    }

Then to turn the leds off with the other button press:

<!-- language: lang-c -->

    if (num_leds_lit > 0) {
        num_leds_lit -= 1;
        set_leds();
    }

------------------------- Original answer

There are a few ways to do it. One way would be to use a bitmask. I would write a function to turn the leds on/off

<!-- language: lang-c -->

    // Each bit represents the state of one LED (0 == off, 1 == on)
    byte led_bits = 0;
    int ledPins[] = {3, 4, 5,};
    const int num_leds = sizeof(ledPins) / sizeof(ledPins[0]);  // 3 in this example
    // Need a mask to make sure we don't set too many bits
    const byte led_mask = 0xFF >> 8 - num_leds;   // 00000111B in this case

    void set_leds() {
        for (int i = 0; i < num_leds; i++) {
            // Turn on/off based on state of bit
            digitalWrite(ledPins[i], (1 << i) & led_bits ? HIGH : LOW);
        }
    }

Then, on button press, set the mask:

<!-- language: lang-c -->

    led_bits << = 1;          // Shift left (001 -> 010)
    led_bits |= 1;            // Set lsb    (010 -> 011)
    led_bits &= led_mask;     // Ensure max bits: (1111 -> 0111)
    set_leds();

Then to turn the leds off with the other button press:

<!-- language: lang-c -->

    led_bits >>= 1;          // Shift right (011 -> 001)
    set_leds();