message:
Receive data from multiple wireless sensors simultaneously

I want to receive data from multiple (2/3) wireless sensors at the 512 Hz data rate simultaneously at a single receiver (bluetooth or any other wireless standard). Is it possible with one receiver or I need  multiple receivers?

I am novice to wireless communication please guide me to any available resources.
Thank you.

body:
It is possible to do this with Zigbee. The API mode in the Xbee modules enables this.

Unlike the AT mode in Zigbee the API mode enables you to distinguish between the packets that you receive from different slaves.

In the API mode, you send each data packet with as a frame with a header which contains start delimiter byte, most significant byte (which tells where the start byte is at), least significant byte (which tells the end of the byte), an API identifier, the data that you want to send and a checksum byte.

This link provides a nice tutorial which shows how to setup Xbees on API mode with an Arduino and Python:
http://serdmanczyk.github.io/XBeeAPI-PythonArduino-Tutorial/

I hope this helps.


sender: user

message:
Attempt stacking 'CAN-BUS' and 'USB Host' Shields on Mega 2560

I've run into a case of 'In theory it works, but in reality'....

I'm using the CAN-BUS Shield V1.2 from Seeed studio. Many things are written in broken english, so I'm starting to wonder if I can trust all of the information. http://wiki.seeed.cc/CAN-BUS_Shield_V1.2/

The USB Host Shield is a discontinued official Arduino model. https://www.arduino.cc/en/Main/ArduinoUSBHostShield

(I would link to the libraries, but I am unable to post more than 2 links)

CAN-BUS Pins:

    AREF
    ICSP (SCK, MISO, MOSI)
    P9 - CS (SS)
    P2 - INT
    NC
    IOREF
    RST
    3.3V
    5V
    Vin

USB Host Pins:

    ICSP (SCK, MISO, MOSI)
    P10 - SS
    P7 - GPX
    P8 - INT (actually RES?)
    P9 - RES (actually INT?)

The only conflict I see is Pin 9 (CS on CAN, RES on USB). This is where it gets hazy... While the documentation on the bottom of the USBHost page implies that Pin 9 is RES, in the code Pin 9 is actually INT.

So, assuming Pin 9 is actually INT, I re-routed it to Pin 45 on on the Mega and changed it in the UsbCore.h file:

    //typedef MAX3421e<P10, P9> MAX3421E; // old
    typedef MAX3421e<P10, P45> MAX3421E; // new

Here is a snippet of the code I am running:

    #include <PS3BT.h>
    #include <usbhub.h>

    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #include <SPI.h>
    #endif

    #include <Bounce2.h>
    #include <Time.h>
    #include <TimeLib.h>
    #include <SPI.h>
    #include "mcp_can.h"

    const int SPI_CS_PIN = 9;

    MCP_CAN CAN(SPI_CS_PIN); // Set CS pin

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

        // THIS WORKS
        if (Usb.Init() == -1) {
            Serial.print(F("\r\nOSC did not start"));
        }
        Serial.print(F("\r\nPS3 Bluetooth Library Started"));

        // THIS FAILS
        while (CAN_OK != CAN.begin(CAN_500KBPS))
        {
            Serial.println("CAN BUS Shield init fail");
            Serial.println(" Init CAN BUS Shield again");
            delay(100);
        }
        Serial.println("CAN BUS Shield init ok!");
    }

The CAN-BUS Fails to init until I physically remove the USB Host Shield.

If I remove the CAN-BUS code, The USB Host Shield functions normally.

If I remove the USB Host code, the CAN-BUS Shield still DOES NOT init.

I tried to sift through the CAN-BUS init code a little, and I can only assume it's failing to communicate via SPI. What am I missing here?

sender: assistant

body:
I think that there is an hardware bug on the USB Master shield:
IC3, the 3-state buffer which converts MISO to 5V, is always active...
The enable pin of this 74LVC1G125 (pin 1) should be connected to the pin ss_3V3.
Then you can stack this shield with another one.


message:
Connecting Saleae Logic 8 to MISO (pin 12) on Uno 3 w/ NRF24L01+ halts program

I have an `NRF24L01+` with the base module (regulates voltage) connected to an Arduino Uno 3.  I'm using the `tmrh20` `NRF24` library and am running one of the example programs.  I'm trying to sniff the SPI bus so I have a Saleae Logic 8 hooked up.  As soon as I connect the clip to the `MISO` pin the Arduino program stops executing.  I'm able to reproduce this 100% of the time.  It seems it is only the `MISO` pin that is causing the problem.  For the library I am using `MISO` uses `pin 12` on the Uno 3.

Anybody know what is going on?  It seems as if the Saleae is grounding `pin 12` when I hook it up.  Not sure why it is only `pin 12` that is an issue though.

I can reproduce the same problem when I manually connecting pin 12 straight to `GND` as well.

I can collect samples without `MISO` just fine but that of course only tells me half the story.

Any suggestions?

EDIT:
Here are some links and resources for more information.

I'm basically following the instructions from this article:
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo

The breakout board
http://www.addicore.com/1x-nRF24L01-Adapter-p/ad279.htm

And it's schematic:
[![enter image description here][1]][1]

Link to the datasheet for the radio itself:
http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24L01
[![enter image description here][2]][2]
And some photos of how I have it wired up:
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/JDou1.jpg
  [2]: https://i.stack.imgur.com/QYMpk.jpg
  [3]: https://i.stack.imgur.com/MHRzN.jpg

body:
It would appear from your description that the leads on your logic analyzer distort of the SPI MISO waveform and the Arduino does not read incoming data correctly.

To avoid this, you could place an digital isolator between the Arduino and the Logic 8.

Any decent oscilloscope should also allow you to read the SPI bus.


message:
What is the maximum length an Interrupt Service Routine?

In general, what's the maximum length of instructions that can be included in an Interrupt Service Routine?

[The docs][1] say an ISR should be "as short and fast as possible", but that's bit vague.

For example, I have an ISR that gets called for each pulse on an motor's encoder.

    void on_encoder_pulse(){
        encoder_change = true;
        count1 += 1;
        count2 += last_call;
        last_call = millis();
    }

Will this run without interruption?

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

body:
In general, on AVR devices, interrupts have been turned off (by hardware) when an ISR (interrupt service routine) begins execution.

Thus, if `on_encoder_pulse()` is an ISR and is invoked due to an interrupt,  it will run uninterrupted.

An ISR that within itself turns the interrupt system back on before it's done runs the risk of other interrupts being serviced before it completes.

The suggestion that ISR's be “as short and fast as possible” is intended to avoid other interrupts being missed, as will happen if an interrupt source activates multiple times while the interrupt system is off.  Most interrupt sources latch a bit and will be handled when the interrupt system is re-enabled; some don't latch a bit, and won't be seen if some ISR is long-winded.


body:
As already explained by jwpat7, interrupts are, by default, not
interruptible. Thus, if another interrupt fires while your ISR is
running, it will no be serviced until your ISR completes. This delay you
impose on other interrupts is called _latency_. So your question boils
down to “_how much latency can the other interrupts tolerate_”.

There is no simple answer: it all depends on the timing requirements
of whatever those interrupts are servicing. For example:

* The `millis()` counter is updated by interrupts. Any latency longer
  than 1024 µs (on the Uno) can make it loose tics.
* If you are using the serial port to receive data, a latency longer
  than one byte time (1040 µs at 9600 pbs, less at higher baud
  rates) will make you loose data.
* If you are using the Servo library, _any_ interrupt latency will
  create jitter in the drive signal, and at some point this may become
  visible as mechanical jitter.

Then, if you really need a precise answer, you will have to check the
timing requirements of _every_ piece of hardware and _every_ library you
are using. And then check the latency already imposed by the ISRs in
those libraries, as your latency can come in top of that.

If your program relies on `loop()` looping fast enough, you should also
keep in mind that interrupts also slow that.


body:
> What is the maximum length an Interrupt Service Routine?

This depends on the max latency before servicing any other waiting Interrupt Service Routine (ISR).

An AVR ISR will execute with further interrupts disabled until the running ISR is completed. Any other interrupt(s) during the execution will be delayed. Data may be lost if the delay is too long. This depends on the interrupt source and frequency of interrupts.

In general an ISR (for incoming data) should only capture the data that could be lost and delay processing to the main loop function. A good example is the ISR for the Arduino Hardware Serial (USART) handling. Data sent and received are queued.

A traditional method (design pattern) is to have very short ISRs that capture data and push to an event queue. All processing is done in the main loop. This gives short latency and faster response, and reduces the risk of ISRs depending on each other, etc.

Cheers!


message:
Arduino Mega 2560 + ESP8266 Problem with GET Request

I have an ESP8266 module connected to my Arduino Mega 2560. My goal is to send a GET request as below to the network:

    api.pushingbox.com/pushingbox?devid=vEB39F555B1B8295?tempData=cabbages

If that is successful, I will get the string "cabbages" along with the timestamp inside my Google Sheets. Note that I intend to change the string "cabbages" with many other data once this is working, but for now, just cabbages. Pasting the link above inside a web browser and pressing Enter seems work fine, but doing it automatically from inside Arduino with ESP8266 attached is somehow not as I expected.

After connecting to my home wifi I tried making a GET request to Google.com:

    void setup()
    {
      Serial.begin(115200);
      Serial2.begin(115200);

      delay(3000);
      Serial2.write("AT\r\n");
      delay(3000);
      Serial2.write("AT+CWMODE=1\r\n");
      delay(3000);
      Serial2.write("AT+CIPMUX=0\r\n");
      delay(3000);

      Serial2.write("AT+CIPSTART=\"TCP\",\"www.google.com\",80\r\n");
      delay(500);
      Serial2.write("AT+CIPSEND=80\r\n");
      delay(500);
      Serial2.write("GET / HTTP/1.0\r\n");
      delay(500);
      Serial2.write("User-Agent: curl/7.37.0\r\n");
      delay(500);
      Serial2.write("Host: www.google.com\r\n");
      delay(500);
      Serial2.write("Accept: */*\r\n\r\n\r\n");
    }

    void loop()
    {
      if (Serial2.available()) {
        Serial.write(Serial2.read());
      }
      if (Serial.available()) {
        Serial2.write(Serial.read());
      }
    }

And I get the response as follows, which is actually the Google home page:

    AT
    OK
    AT+CWMODE=1
    OK
    AT+CIPMUX=0link is builded
    Recv 80 bytes

    SEND OK

    +IPD,1410:HTTP/1.0 200 OK
    Date: Fri, 23 Sep 2016 08:49:38 GMT
    Expires: -1
    Cache-Control: private, max-age=0
    Content-Type: text/html; charset=ISO-8859-1
    P3P: CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."
    Server: gws
    X-XSS-Protection: 1; mode=block
    X-Frame-Options: SAMEORIGIN
    Set-Cookie: NID=87=TS-mbT3JjN_vZQurH0M4e1tbNsgmSPF4ALY_ohGFUD6uz76RmbxY41AA_XtC75Wqxfcqu5v1lbLxy-tMa_yrn5-BHrxN7Hn6CeYVnEfG1bBsVd78Y6eHtJ0hOUQPIwaDM0_2wGPO52e7HQ; expires=Sat, 25-Mar-2017 08:49:38 GMT; path=/; domain=.google.com; HttpOnly
    Accept-Ranges: none
    Vary: Accept-Encoding

    <!doctype html><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><link href="/images/branding/product/ico/googleg_lodp.ico" rel="shortcut icon">

<nobr>Search Images Maps Play YouTube News Gmail Drive More »</nobr>

<nobr>Web History | Settings | Sign in</nobr>

<form action="/search" name="f">

 	<input name="ie" value="ISO-8859-1" type="hidden"><input value="en" name="hl" type="hidden"><input name="source" type="hidden" value="hp"><input name="biw" type="hidden"><input name="bih" type="hidden">
<input style="color:#000;margin:0;padding:5px 8px 0 6px;vertical-align:top" autocomplete="off" class="lst" value="" title="Google Search" maxlength="2048" name="q" size="57">

<input class="lsb" value="Google Search" name="btnG" type="submit"><input class="lsb" value="I'm Feeling Lucky" name="btnI" onclick="if(this.form.q.value)this.checked=1; else top.location='/doodles/'" type="submit">	Advanced searchLanguage tools

<input id="gbv" name="gbv" type="hidden" value="1"></form>

Advertising ProgramsBusiness Solutions+GoogleAbout GoogleGoogle.com.my

© 2016 - Privacy - Terms

CLOSED

However, when I try it with the actual URL I intend to use:

    void setup()
    {
      Serial.begin(115200);
      Serial2.begin(115200);

      delay(3000);
      Serial2.write("AT\r\n");
      delay(3000);
      Serial2.write("AT+CWMODE=1\r\n");
      delay(3000);
      Serial2.write("AT+CIPMUX=0\r\n");
      delay(3000);

      Serial2.write("AT+CIPSTART=\"TCP\",\"api.pushingbox.com\",80\r\n");
      delay(500);
      Serial2.write("AT+CIPSEND=135\r\n");
      delay(500);
      Serial2.write("GET /pushingbox?devid=vEB39F555B1B8295&tempData=cabbages HTTP/1.0\r\n");
      delay(500);
      Serial2.write("User-Agent: curl/7.37.0\r\n");
      delay(500);
      Serial2.write("Host: api.pushingbox.com\r\n");
      delay(500);
      Serial2.write("Accept: */*\r\n\r\n\r\n");
    }

    void loop()
    {
      if (Serial2.available()) {
        Serial.write(Serial2.read());
      }
      if (Serial.available()) {
        Serial2.write(Serial.read());
      }
    }

I get the following response:

    AT
    OK
    AT+CWMODE=1
    OK
    AT+CIPMUX=0
    OK
    AT+CIPSTART=Accept: */*ERROR
    ERROR
    ERROR

    +IPD,212:HTTP/1.0 408 Request Time-out
    Cache-Control: no-cache
    Connection: close
    Content-Type: text/html

408 Request Time-out

    Your browser didn't send a complete request in time.

    CLOSED

The code is exactly the same except for the different URLs used, so what is causing the problem here? Why can't I send "api.pushingbox.com/pushingbox?devid=vEB39F555B1B8295?tempData=cabbages" to the internet? Please help! :-/

body:
I did notice you also changed

AT+CIPSEND=80\r\n

to

AT+CIPSEND=135\r\n

probably you send your request wrong or something?!?
(sorry I post this as answer but I didn't unlock comments yet)


body:
First you must check if the problem is on your side or not.
You call http://api.pushingbox.com and you send parameter which are "pushingbox?devid=vEB39F555B1B8295&tempData=cabbages"

When I glue them together
http://api.pushingbox.com/pushingbox?devid=vEB39F555B1B8295&tempData=cabbages
and copy past this on my browser, I get an error with "Daily limit exceeded" with a status of 429 meaning "too many request".
So maybe there is a problem with the server?


message:
How to find gain for this device?

I am doing a project with Arduino to find CO2 in an environment. For this purpose, I bought a breakout board with an MG811 sensor on it. I bought it from eBay and it came with no datasheet. I searched on the internet and found the datasheet for the MG811.

With the help of the datasheet, I also found the formula to convert the input voltage to PPM. But later I realized that the device also has an amplifier on it, which is giving me higher voltages. I searched thoroughly and found the original device [on Taobao][1].

Can someone please tell me how can I determine the gain so that I can convert the values I read to original values?

One more question. On the given web link, I also found that this device comes with a pin called TCM and with Google translate, I found that it shows temperature compensated output. Can you please explain me the use of this pin as well? If it is more advantageous for me, I'll use this instead of the normal analog output pin.

  [1]: https://item.taobao.com/item.htm?spm=a1z10.5-c.w4002-2077762790.41.bccRQd&id=10525511439

body:
The [MG811 spec](http://eph.ccs.miami.edu/precise/GasSensorSpecs/CO2.pdf) gives you the range of measurement, but without the values and connections of the surface mount op amp on the board the only way to determine the voltage output for each CO2 concentration is with a Voltmeter and an already calibrated CO2 PPM meter, which you could perhaps borrow from a lab or university.  Once you have the CO2 values and Voltages that correspond, you can build a formula or function to convert the digital values to voltages and then to CO2 concentrations.

The other option is to trace the tracks on the PCB and create a schematic and then post the spec above and the schematic with resistor values included on the [electronics Stack Exchange](https://electronics.stackexchange.com/).


message:
Ooops, no LSM303 detected ... Check your wiring!

**History**

I have an [Adafruit 10DOF IMU Breakout][1] which has been working on my `Mega` for some time. This morning my `program` did not run so I starting *troubleshooting*.

**Scenario**

I eventually plugged the IMU breakout into my `Uno` with the *out-of-the-box accelerometer reader program from Adafruit. That's when I started seeing

`Ooops, no LSM303 detected ... Check your wiring!`

And upon close inspection have verified all wires are in the correct spot.

---

# Question

How do I troubleshoot this further? Also, I'm starting to think that my IMU may be fried. How can I test this?

  [1]: https://learn.adafruit.com/adafruit-10-dof-imu-breakout-lsm303-l3gd20-bmp180/connecting-it-up

---

**\* AHRS out-of-the-box Program from Adafruit:**
<!-- language-all: lang-cpp -->

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_LSM303_U.h>
    #include <Adafruit_BMP085_U.h>
    #include <Adafruit_L3GD20_U.h>
    #include <Adafruit_10DOF.h>

    /* Assign a unique ID to the sensors */
    Adafruit_10DOF                dof   = Adafruit_10DOF();
    Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);
    Adafruit_LSM303_Mag_Unified   mag   = Adafruit_LSM303_Mag_Unified(30302);
    Adafruit_BMP085_Unified       bmp   = Adafruit_BMP085_Unified(18001);

    /* Update this with the correct SLP for accurate altitude measurements */
    float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;

    /**************************************************************************/
    /*!
        @brief  Initialises all the sensors used by this example
    */
    /**************************************************************************/
    void initSensors()
    {
      if(!accel.begin())
      {
        /* There was a problem detecting the LSM303 ... check your connections */
        Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
        while(1);
      }
      if(!mag.begin())
      {
        /* There was a problem detecting the LSM303 ... check your connections */
        Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
        while(1);
      }
      if(!bmp.begin())
      {
        /* There was a problem detecting the BMP180 ... check your connections */
        Serial.println("Ooops, no BMP180 detected ... Check your wiring!");
        while(1);
      }
    }

    /**************************************************************************/
    /*!

    */
    /**************************************************************************/
    void setup(void)
    {
      Serial.begin(115200);
      Serial.println(F("Adafruit 10 DOF Pitch/Roll/Heading Example")); Serial.println("");

      /* Initialise the sensors */
      initSensors();
    }

    /**************************************************************************/
    /*!
        @brief  Constantly check the roll/pitch/heading/altitude/temperature
    */
    /**************************************************************************/
    void loop(void)
    {
      sensors_event_t accel_event;
      sensors_event_t mag_event;
      sensors_event_t bmp_event;
      sensors_vec_t   orientation;

      /* Read the accelerometer and magnetometer */
      accel.getEvent(&accel_event);
      mag.getEvent(&mag_event);

      /* Use the new fusionGetOrientation function to merge accel/mag data */
      if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation))
      {
        /* 'orientation' should have valid .roll and .pitch fields */
        Serial.print(F("Orientation: "));
        Serial.print(orientation.roll);
        Serial.print(F(" "));
        Serial.print(orientation.pitch);
        Serial.print(F(" "));
        Serial.print(orientation.heading);
        Serial.println(F(""));
      }

      /* Previous code removed handling accel and mag data separately */
      //  /* Calculate pitch and roll from the raw accelerometer data */
      //  Serial.print(F("Orientation: "));
      //  accel.getEvent(&accel_event);
      //  if (dof.accelGetOrientation(&accel_event, &orientation))
      //  {
      //    /* 'orientation' should have valid .roll and .pitch fields */
      //    Serial.print(orientation.roll);
      //    Serial.print(F(" "));
      //    Serial.print(orientation.pitch);
      //    Serial.print(F(" "));
      //  }
      //
      //  /* Calculate the heading using the magnetometer */
      //  mag.getEvent(&mag_event);
      //  if (dof.magGetOrientation(SENSOR_AXIS_Z, &mag_event, &orientation))
      //  {
      //    /* 'orientation' should have valid .heading data now */
      //    Serial.print(orientation.heading);
      //  }
      //  Serial.println(F(""));

      /* Calculate the altitude using the barometric pressure sensor */
      bmp.getEvent(&bmp_event);
      if (bmp_event.pressure)
      {
        /* Get ambient temperature in C */
        float temperature;
        bmp.getTemperature(&temperature);
        /* Convert atmospheric pressure, SLP and temp to altitude */
        Serial.print(F("Alt: "));
        Serial.print(bmp.pressureToAltitude(seaLevelPressure,
                                            bmp_event.pressure,
                                            temperature));
        Serial.println(F(""));
        /* Display the temperature */
        Serial.print(F("Temp: "));
        Serial.print(temperature);
        Serial.println(F(""));
      }

      delay(100);
    }

-- EDIT --

I'm pretty sure the board is dead. The program stops at `accel.begin()`, `mag.begin()`, or `bmp.begin()`; I've tried each individually.

body:
I this one of many Arduino invented terminology ?
Normally function returns ZERO on success and -1 or positive number identifying the error.

    if(!accel.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
    while(1);
  }


body:
Check each of your conditional statement at
```
if(!accel.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
    while(1);
  }
  if(!mag.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
  if(!bmp.begin())
  {
    /* There was a problem detecting the BMP180 ... check your connections */
    Serial.println("Ooops, no BMP180 detected ... Check your wiring!");
    while(1);
  }
```

by commenting the others.


body:
I had a similar issue. Turns out it was faulty wiring, probably due to a cheap breadboard (as a noob you would expect perfect connectivity from something like a breadboard! Turns out: not at all!)

Here's how I went about debugging it, using an i2c scanner to debug connectivity (find library + example [here][1]).

 1. remove the `while(1)` loops that halt your program, so the program doesn't 'stop' on error
 2. Use an 'error variable' e.g. `fail`. Initialize e.g. as `fail=0` at start of script so it's global. Add `fail=1` for every _oops case_ in `initSensors()`
 3. in `loop()`, check if `fail==0`, if yes, continue with outputting the 10DOF sensor values, if there is an error (`fail==1`) call `initSensors()` and the `i2cscanner()` so you get a debugging view of your connectivity. This would look like below, and will keep calling the debug function until you connected it properly.

Hope this was useful or at least interesting to you, good luck.

Screenshot of i2c scanner:

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

  [1]: https://playground.arduino.cc/Main/I2cScanner/
  [2]: https://i.stack.imgur.com/775Vg.png


message:
writing and uploading sketch as cpp file

I want to use only `*.cpp` files and no `*.ino` anymore. I read a lot of stuff about how to upload c++ instead of arduino sketches. But still I was not able to find a step by step guide how to do it.

Actually I am developing my sketch within Spacemacs (Emacs) and uploading it with Arduino-Makefile (https://github.com/sudar/Arduino-Makefile)

When I now want to start a new project with only `*.cpp` and `*.h` files to use classes etc. how would I start? Does anybody has the time to describe a rough step-by-step without the trivial stuff?

body:
See my post about [How the IDE organizes things](https://arduino.stackexchange.com/a/13182/10794).

Also see my [page about how to avoid the quirks of the IDE sketch file pre-preprocessing](http://www.gammon.com.au/forum/?id=12625).

You can certainly manage without .ino files. As Edgar Bonet says, they are really C++ files with certain pre-processing (see link above).

> but what about these loop() and setup() functions

Effectively, the Arduino IDE supplies a main function that looks like this:

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

    int main ()
      {
      init ();    // initialize hardware, including timers and timer interrupts
      setup ();   // user setup
      while (true)
        loop ();  // stuff to be done repeatedly
      return 0;   // this will never be executed
      }

(It's slightly more complex, to allow for USB where applicable, but that is the idea).

> But still I did not found the step by step guide how to do it.

I'm pretty sure there are a lot of example "make" files around which show the idea.

I have an example [here](https://arduino.stackexchange.com/a/15898/10794).


message:
Results for GP2Y1010AU0F Dust Sensor

I am using Dust Sensor GP2Y1010AU0F

I downloaded the code from the manufacturer here:
http://www.waveshare.com/wiki/Dust_Sensor

<!-- language: lang-cpp -->

    /*********************************************************************************************************
    *
    * File                : DustSensor
    * Hardware Environment:
    * Build Environment   : Arduino
    * Version             : V1.0.5-r2
    * By                  : WaveShare
    *
    *                                  (c) Copyright 2005-2011, WaveShare
    *                                       http://www.waveshare.net
    *                                       http://www.waveshare.com
    *                                          All Rights Reserved
    *
    *********************************************************************************************************/
    #define        COV_RATIO                       0.2            //ug/mmm / mv
    #define        NO_DUST_VOLTAGE                 400            //mv
    #define        SYS_VOLTAGE                     5000

    /*
    I/O define
    */
    const int iled = 7;                                            //drive the led of sensor
    const int vout = 0;                                            //analog input

    /*
    variable
    */
    float density, voltage;
    int   adcvalue;

    /*
    private function
    */
    int Filter(int m)
    {
      static int flag_first = 0, _buff[10], sum;
      const int _buff_max = 10;
      int i;

      if(flag_first == 0)
      {
        flag_first = 1;

        for(i = 0, sum = 0; i < _buff_max; i++)
        {
          _buff[i] = m;
          sum += _buff[i];
        }
        return m;
      }
      else
      {
        sum -= _buff[0];
        for(i = 0; i < (_buff_max - 1); i++)
        {
          _buff[i] = _buff[i + 1];
        }
        _buff[9] = m;
        sum += _buff[9];

        i = sum / 10.0;
        return i;
      }
    }

    void setup(void)
    {
      pinMode(iled, OUTPUT);
      digitalWrite(iled, LOW);                                     //iled default closed

      Serial.begin(9600);                                         //send and receive at 9600 baud
      Serial.print("*********************************** WaveShare ***********************************\n");
    }

    void loop(void)
    {
      /*
      get adcvalue
      */
      digitalWrite(iled, HIGH);
      delayMicroseconds(280);
      adcvalue = analogRead(vout);
      digitalWrite(iled, LOW);

      adcvalue = Filter(adcvalue);

      /*
      covert voltage (mv)
      */
      voltage = (SYS_VOLTAGE / 1024.0) * adcvalue * 11;

      /*
      voltage to density
      */
      if(voltage >= NO_DUST_VOLTAGE)
      {
        voltage -= NO_DUST_VOLTAGE;

        density = voltage * COV_RATIO;
      }
      else
        density = 0;

      /*
      display the result
      */
      Serial.print("The current dust concentration is: ");
      Serial.print(density);
      Serial.print(" ug/m3\n");

      delay(1000);
    }

My results seems rounded or always returning in certain 'steps'.
(below are my results)
Is there a rounded error in the code or something else that could be going on?

    The current dust concentration is: 134.84 ug/m3
    The current dust concentration is: 134.84 ug/m3
    The current dust concentration is: 134.84 ug/m3
    The current dust concentration is: 134.84 ug/m3
    The current dust concentration is: 134.84 ug/m3
    The current dust concentration is: 134.84 ug/m3
    The current dust concentration is: 134.84 ug/m3
    The current dust concentration is: 124.10 ug/m3
    The current dust concentration is: 124.10 ug/m3
    The current dust concentration is: 124.10 ug/m3
    The current dust concentration is: 113.36 ug/m3
    The current dust concentration is: 113.36 ug/m3
    The current dust concentration is: 124.10 ug/m3
    The current dust concentration is: 124.10 ug/m3
    The current dust concentration is: 113.36 ug/m3
    The current dust concentration is: 113.36 ug/m3
    The current dust concentration is: 113.36 ug/m3
    The current dust concentration is: 124.10 ug/m3
    The current dust concentration is: 124.10 ug/m3
    The current dust concentration is: 124.10 ug/m3
    The current dust concentration is: 134.84 ug/m3
    The current dust concentration is: 134.84 ug/m3
    The current dust concentration is: 124.10 ug/m3

body:
Its because the resolution of the analog read is 10 bits or 1024 discrete values.

In your code the density is basically calculated as:

    density = (((5000 / 1024.0) * analog_value * 11) - 400) * 0.2

You can calculate the resolution as:

    (5000 / 1024.0) * 11 * 0.2

and you get `10.7421875`, which matches your observation.

If your filtering (calculating the average over last 10 values), would calculate and return a float, you would get smoother values.


message:
How to control MKR1000 from outside your local network

I want to send an HTTP command to MKR1000 from outside my local network.

So far, all the googled resources point to getting the local IP (example 192.168.0.10) of MKR1000 and sending a command like `http://192.168.0.10/H` to it and then parse it.

How do I send a command to MKR1000 from outside its local network?

I should clarify that I want this to be a consumer product and can't have the end-user fiddling with their routers for port forwarding etc.

body:
The only way I can think of to achieve this would be to port forward your router, and forward port 80 (http) to your MKR1000. You can check out https://portforward.com/ for instructions on that.

If you don't want to port-forward, you'd have to have the MKR1000 connect to a centralized IOT server somewhere, and have the user go through the server to access the MKR1000. That's how other iot devices such as nest cameras do it.


body:
You **now** can try this [**UPnP_Generic library**](https://github.com/khoih-prog/UPnP_Generic) to do the auto-portforwarding for you without manually touching the router.

---
---

Many of us are **manually port-forwarding** in Internet Gateway Device (IGD, Router) in order to provide access to local Web Services from the Internet.

  This library provides the easier way to automatically port-forward by using the [**Simple Service Discovery Protocol (SSDP)**](https://datatracker.ietf.org/doc/html/draft-cai-ssdp-v1-03), running on nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, ESP8266/ESP32, using ESP WiFi, WiFiNINA, Ethernet W5x00, ESP8266/ESP32 AT-command WiFi supporting **UDP Multicast**.

  The SSDP provides a mechanism whereby network clients, with little or no static configuration, can discover network services. SSDP accomplishes this by providing for multicast discovery support as well as server based notification and discovery routing.

  The [**SSDP**](https://en.wikipedia.org/wiki/Simple_Service_Discovery_Protocol) is used for **advertisement and discovery of network services and presence information**. It accomplishes the task without assistance of server-based configuration mechanisms, such as Dynamic Host Configuration Protocol (DHCP) or Domain Name System (DNS), and without special static configuration of a network host. SSDP is the basis of the discovery protocol of **Universal Plug and Play (UPnP)** and is intended for use in residential or small office environments.

  This [**UPnP_Generic library**](https://github.com/khoih-prog/UPnP_Generic) is created to automatically **update your IGDs with the requested port-forward information**, using one of the many available boards / shields. See [**Currently Supported Boards**](https://github.com/khoih-prog/UPnP_Generic#currently-supported-boards).

  The time between checks to update the UPnP Port Mappings is **configurable** to match your use case, and is set in the examples at 10 minutes. The LEASE_DURATION is also configurable and default to 10hrs (36000s). The Virtual Server Name can also be specified in the sketch and is shown in the IGD, e.g. `NRF52-W5X00` or `ESP8266-WIFI` as in the following picture:

  The UPnP_Generic code is very short, can be immersed in your Projects and to be called in the loop() code.


message:
NodeMCU ESP8266 on Arduino IDE doesn't detect Wifi

I am using a NodeMCU 1.0 v3 and I am trying the example sketch (wifiscan) but it just doesn't pick up any AP in the house. My phone and laptops etc are able to pick up the APs though.

Other sketches upload and work fine but the wifi aspect of it doesn't work. I even got an LCD sketch to work properly but it isn't able to find any access points or even join any access points. I have been trying to get it to work for hours now.

I first tried using the latest Arduino IDE (1.6.12), then I uninstalled and tried using 1.6.1 but no luck. My upload settings are NodeMCU 1.0 (ESP-12E module), 80Mhz, 115200, 4M (3M SPIFFS).

body:
My gut feeling is that your hardware is just flakey.
I have one NodeMCU 1.0 that occasionally works, and occasionally does not.

On that one, it requires power cycling (unplugging and replugging) it a couple of times for it to start working.

The Arduino ESP8266 core is pretty solid, and wifi support should just work in it.

Just to make sure, you could post your simplest sketch which doesn't work (one that lists AP's, so that it can't be a ssid/password kind of issue), so people can check if there's a problem in the code..

Also, to be really sure, you could check your power system. NodeMCU has a 5v to 3.3v converter in it, and a usb plug, so that part should be ok. How many amps is the USB power supply rated at? If it's very low (<250ma) it could be an issue. You can also try adding a capacitor (something decent sized, >220uf at a random guess? I tend to go for ~1000uf) between gnd and 3.3v, and one between gnd and 5v pins. Watch polarity of-course, and double check, you don't want to short the power lines :)
There's a very small chance stabilizing the power in that way might help..


body: Your router might be using 5GHz Wifi which the ESP8266 doesn't support but your other devices likely do. Try setting your wifi network to 2.4GHz.


body: My DHCP table was full. I rebooted router and added more values for dhcp range (192.168.1.100-192.168.1.150) and the device now connects.... took me a day to figure this out.


message:
How to Factory reset ESP8266?

I want to use ESP8266 to send emails. I tried twice flashing the Firmware to a particular firmware as suggested in a tutorial. Now both my ESP are unresponsive to AT commands. Let me know the way to RESET it. CH_PD + VCC + RST (Tried this combination), No success there any thing i am missing?

body: AT commands are executed by the AT interpreter firmware. If you've been attempting to flash other firmware to the ESP8266 module, there is no longer any code in it that interprets AT commands. If you want to it to respond to AT commands again, you'll need to re-flash it with that firmware.


body:
You need to reflash the "AT Firmware" you probably overwrited.
Just follow the [instructions in the Espressif board][1] to get the latest one using their "Flash Download Tool".

  [1]: http://bbs.espressif.com/viewtopic.php?f=57&t=433


message:
How can the Arduino check if it is connected to a PC and the PC is on?

I have been searching around the Internet to find if there is a way to check whether an Arduino is connected to a PC or not.

For example: if my PC is turned on, the Arduino will listen to any serial commands it receives, BUT if my PC is turned off, the Arduino will receive some random characters.

How can the Arduino check if it is connected to PC and the PC is on?

body:
As suggested by Paul & Gerben, you could check the 5V USB line to see if it has a voltage or not.

I am assuming from your question that the Arduino is not powered from the USB line. I am also assuming that the USB port is not powered when the PC is turned off.

All you have to do is connect VUSB to a digital input through a resistor like so:
[![Circuit Diagram][1]][1]

----------

Alternatively, you could have the computer send a pre-determined message telling the Arduino that its alive.

If the Arduino receives this message then it lights up the LED on pin 13. If the Arduino hasn't received the "I'm alive" message for a while (ie. a timeout) it then turns off the LED.

A simple PC program could be written to automate this task.

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


message:
Sum values, store them and print the last value

I have a mass flow meter connected to an Arduino Uno board. I have managed to read the volume flow in L/hour, but now I'm struggling to implement a code that stores the values so that I see the number of Liters used.

For instance, I can see on my monitor this:

0 L/hour

0 L/hour

And if I have some water running through,

10 L/hour

20 L/hour

20 L/hour

Then when I stop the flow it goes back to 0.

0 L/hour

Is there any ways to sum up time instances, get the total number of liters and keep it printed during every instance?

Mathematically is not that difficult (Volume = Volume Flow in L/hour * time), but I don't know how to implement this. Can anyone help with this? It can be in seconds or ms or whatever.

Paul

body:
This  will be helpful.

reading is your flow meter value in L/Hour

    float reading;//value of the flow meter
    long startTime;
    float total=0;

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

    }

    void loop() {
    //read your flow meter to reading variable.
     total+=reading*float((millis()-startTime))/3600000.0;
     Serial.println(total);

    }


body:
What you want to do is *integrate* the flow rate vs time curve. You have to keep track of the current flow rate. You also need to choose some unit of time measurement; this depends on how often you're sampling the flow rate. For instance, if you sample it every second, then you should convert your L/hr flow rate to L/s. This means a flow rate of 10L/hr is equivalent to 10L/3600s = 0.002778 L/s. So, if you get a reading of 10 L/hr for 10 seconds, `0.002778 L/s * 10 s = 0.02778 L` of water flowed through your valve or whatever. An accumulating sum is what you need. You can try something like this:

    #define INTERVAL 1000  // sampling interval in millisec
    #define HR_TO_SEC 2.778E-4  // number of hours in a second

    int curr_rate = 0;  // current flow rate in L/hr
    unsigned long lastRead = 0;  // the last time the rate was sampled
    float totalVolume = 0;

    void loop(){
      if (millis() - lastRead >= INTERVAL){
        lastRead += INTERVAL;
        curr_rate = getFlowRate();   // or whatever function you call; should take << 1 sec
        totalVolume += curr_rate * HR_TO_SEC;  // update the volume
        Serial.println(totalVolume, 4);
      }
    }

This rectangular method is reasonably accurate, depending on your application. If you want a better approximation, google "trapezoidal numerical integration" or "Simpson's method" if you want even better approximation.


body:
In a recent comment, you posted a link to a [forum thread][] with the
code for reading the sensor. You should have provided this information
up front, because it completely changes the problem. It appears that the
flow meter sends pulses at a frequency proportional to the volume flow,
and the code uses an interrupt to count the pulses over a specified
time.

TisteAndii's answer suggests you _integrate_ the flow readings to get a
volume. And that suggestion makes perfect sense given the limited
information he had available at the time. Now that we know how the flow
meter is read, it makes no sense anymore:

* the interrupt service routine counts a number of pulses that is
  proportional to the _total volume_ that has gone through the meter
* the linked code _differentiates_ that reading in order to get the flow
* you are now _integrating_ that flow in order to get the total volume.

Instead of doing an integration on top of a differentiation, you could
just convert the raw reading into a volume. Then you do not have to
worry about any approximations done while differentiating or
integrating.

In the forum thread it is stated:

> Pulse frequency (Hz) in Horizontal Test= 7.5Q, Q is flow rate in L/min.

Writing this in a more mathematically accurate form (i.e. with
unit-correctness) gives:

> _f_/Hz = 7.5 _Q_/(L/min)

where _f_ is the frequency and _Q_ the volume flow.

Given that 7.5 Hz⋅min = 450 pulses, the above equation can be rewritten as

> _f_ = 450 pulses/L × _Q_

or, in terms of integrated quantities:

> volume = (pulse count) / (450 pulses/L)

Here is an example code that just convert the pulse count to a volume:

    // Calibration constant of the flow meter.
    const float calibration = 1/450.0;  // 450 pulses per liter

    // How often to print the measured volume.
    const uint32_t print_interval = 1000;  // once per second

    // Number of pulses counted so far.
    volatile uint32_t pulse_count;

    // Count the pulses inside an ISR.
    void count_pulse() { pulse_count++; }

    // Return volume reading, optinally resetting the count to zero.
    float totalVolume(bool reset = false)
    {
        noInterrupts();
        uint32_t pulse_count_copy = pulse_count;
        if (reset) pulse_count = 0;
        interrupts();
        return pulse_count_copy * calibration;
    }

    void setup()
    {
        pinMode(2, INPUT_PULLUP);
        attachInterrupt(0, count_pulse, RISING);
        Serial.begin(9600);
    }

    void loop()
    {
        static uint32_t last_print;
        if (millis() - last_print >= print_interval) {
            last_print += print_interval;
            Serial.println(totalVolume());
        }
    }

Note that you may want to reset the count from time to time. I added an
optional parameter to `totalVolume()` for this purpose. If you never
reset the counter, it will overflow after approximately
9544 m3.

[forum thread]: http://forum.arduino.cc/index.php?topic=8548.0


message:
Serial communication with Python

I am trying to send integer from my Python program to Arduino MEGA.
If I send 1, the LED should turn on and If  I send 0 the LED should turn off.

I was able to write Python code correctly as I think. I have configure the port and made `serialWrite(val)` function for send data to Arduino only if data is changed.
This not a full program. It has while loop. So, it writes data to Arduino rapidly. I used `serialWrite(val)` function to prevent that.

But, the LED never turns off, if I send 0. It turns on only. What are the problems in my code?

    import serial as ser

    prt = ser.Serial(
    port='COM3',
    baudrate=9600,
    parity=ser.PARITY_NONE,
    stopbits=ser.STOPBITS_ONE,
    bytesize=ser.EIGHTBITS
    )

    preSerVal=0
    #function for send data..data will send only val is changed
    def serialWrite(val):
        global preSerVal
        if(not preSerVal == val):
            prt.write(str(val)+'\r\n')
            preSerVal=val

This is my Arduino program.

    void setup() {
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
    }
    byte incomingByte;

    void loop()
    {
      if (Serial.available() > 0) {
        incomingByte = Serial.read();
          if (incomingByte == '1') {
            digitalWrite(13, HIGH);
        } else if (incomingByte == '0') {
            digitalWrite(13, LOW);
        }
      }
    }

**UPDATE 1**

I write testing program like this.

Python code:

    import serial as ser
    import time

    preSerVal=0
    prt = ser.Serial(
    port='COM3',
    baudrate=9600,
    parity=ser.PARITY_NONE,
    stopbits=ser.STOPBITS_ONE,
    bytesize=ser.EIGHTBITS
    )
    def serialWrite(val):
        global preSerVal
        if(not preSerVal == val):
             prt.write(str(val)+'\r\n')
             preSerVal=val

    while 1:
       for i in range(0,10):
            serialWrite(0)
       time.sleep(1)
       for i in range(0,10):
            serialWrite(1)

Arduino code:

    void setup() {
     Serial.begin(9600);
     pinMode(13, OUTPUT);
     digitalWrite(13, LOW);
    }
    byte incomingByte;

    void loop()
    {
      if (Serial.available() > 0) {
        incomingByte = Serial.read();
      if (incomingByte == '1') {
        digitalWrite(13, HIGH);
      } else if (incomingByte == '0') {
        digitalWrite(13, LOW);
      }
     }
    }

This code gives this result.
see the video bellow:

https://www.youtube.com/watch?v=utC4vo8YDVU&list=PLM5AA5oFchgC25da44Q2X900pz0eojSQJ&index=1

**UPDATE 2**

This is a piece of code..it sends 0..i checked it.

    try:
        circles = np.uint16(np.around(circles))
        for i in circles[0,:]:
            houghCenter=(i[0],i[1])
            cv2.circle(src,houghCenter,i[2],(0,255,0),2)
            cv2.circle(src,houghCenter,2,(0,255,255),1)
            cv2.circle(drawing,houghCenter,i[2],(0,255,0),2)
            cv2.circle(drawing,houghCenter,2,(0,255,255),1)
            #print (houghCenter,"   ",contourCenter)
            dx=math.fabs(houghCenter[0]-contourCenter[0])
            dy =math.fabs(houghCenter[1]-contourCenter[1])
            if (dx>diff and dy>diff):
                serialWrite(0)
            else:
                serialWrite(1)
    except Exception:
        serialWrite(0)

body:
You are missing a second time.sleep(1). That is why the first loop executes correctly and the the LED flashed faster. Without any time.sleep() at all, the LED is going OFF/ON so fast that you cannot see it happen (may be it's just not so bright as usually).

    while 1:
       for i in range(0,10):
            serialWrite(0)
       time.sleep(1)
       for i in range(0,10):
            serialWrite(1)
       time.sleep(1)


message:
Accelerometer fix values

I use Arduino Uno with an Accelerometer ADXL345-gy-291 (the full name of the ship) i did hook it up like this
[![enter image description here][1]][1]

Note I'm using SPI Communication, that was the right one to use in my case.
when I plug in my Arduino here what does my serial monitor give me
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/ecBxt.png
  [2]: https://i.stack.imgur.com/0xa4I.png
as you can see, it sends back fixed values no matter the movement of the ship is.
the code I use is :

    #include <SparkFun_ADXL345.h>
    ADXL345 adxl = ADXL345(10);

    void setup(){

      Serial.begin(9600);
      Serial.println("SparkFun ADXL345 Accelerometer Hook Up Guide Example");
      Serial.println();
      adxl.powerOn();
      adxl.setRangeSetting(16);
      adxl.setSpiBit(0);
      adxl.setActivityXYZ(1, 0, 0);
      adxl.setActivityThreshold(75);
      adxl.setInactivityXYZ(1, 0, 0);
      adxl.setInactivityThreshold(75);
      adxl.setTimeInactivity(10);
      adxl.setTapDetectionOnXYZ(0, 0, 1);
      adxl.setTapThreshold(50);
      adxl.setTapDuration(15);
      adxl.setDoubleTapLatency(80);
      adxl.setDoubleTapWindow(200);
      adxl.setFreeFallThreshold(7);
      adxl.setFreeFallDuration(30);
      adxl.InactivityINT(1);
      adxl.ActivityINT(1);
      adxl.FreeFallINT(1);
      adxl.doubleTapINT(1);
      adxl.singleTapINT(1);
    }
    void loop(){
      int x,y,z;
      adxl.readAccel(&x, &y, &z);
      Serial.print(x);
      Serial.print(", ");
      Serial.print(y);
      Serial.print(", ");
      Serial.println(z);
      ADXL_ISR();
    }
    void ADXL_ISR() {
      byte interrupts = adxl.getInterruptSource();

      if(adxl.triggered(interrupts, ADXL345_FREE_FALL)){
        Serial.println("*** FREE FALL ***");
      }

      if(adxl.triggered(interrupts, ADXL345_INACTIVITY)){
        Serial.println("*** INACTIVITY ***");
      }

      if(adxl.triggered(interrupts, ADXL345_ACTIVITY)){
        Serial.println("*** ACTIVITY ***");
      }

      if(adxl.triggered(interrupts, ADXL345_DOUBLE_TAP)){
        Serial.println("*** DOUBLE TAP ***");
      }

      if(adxl.triggered(interrupts, ADXL345_SINGLE_TAP)){
        Serial.println("*** TAP ***");
      }
    }

so I wonder what was the mistake I made there?

body:
You need to level-shift the Arduino's 5V signals to the module's I/O range of 1.7 - 3.6 V if you want to use SPI; that is, if you haven't damaged it already. I suggest you follow the tutorial [here][1] though. It employs I2C instead of SPI but is specific to your particular module. There are no level-shifters needed in this case. Simply connect VCC and CS to 3.3 V, the I2C pins to 3.3 V through 4.7k pull-ups and the GNDs together.

  [1]: http://forum.hobbycomponents.com/viewtopic.php?f=39&t=1568


message:
Interrupt and delay problems on Attiny 85

I wrote this code and uploaded it to attiny85:

     int hours = 2;
     int minutes = 4;
     static int MINUTES_COUNT_BIT = 5;
     static int HOURS_COUNT_BIT = 3;
     #define button 2
    void setup() {
      pinMode(3,OUTPUT);
      pinMode(4,OUTPUT);
      pinMode(button,INPUT);

      attachInterrupt(0,pin_ISR,CHANGE);

    }

    void loop() {

      // put your main code here, to run repeatedly:

    }

    void pin_ISR(){
        if(digitalRead(button)==LOW){
          for(int i = HOURS_COUNT_BIT;i>=0;i--){
          byte act_bit = bitRead(hours,i);

          switch(act_bit){
            case 0:
              digitalWrite(3,HIGH);
              delay(1000);
              digitalWrite(3,LOW);
              delay(1000);
              break;
            case 1:
              digitalWrite(4,HIGH);
              delay(1000);
              digitalWrite(4,LOW);
              delay(1000);

              break;
            }

        }
      }

      }

When I click button it lights up LEDs but it is so much faster than 500 milliseconds it looks like that:
https://drive.google.com/open?id=0ByeWvrEgy2gRNUp3MDNxQTAxd2c
Please help

body:
In short:

* Arduino `delay()` is relying on `millis()`.
* The `millis()` function is  updated by timer `ISR`.
* `ISR` handler blocks all other ISRs by disabling global interrupts.
* No update for `millis` results into deadlock in `delay` if you use it in another `ISR`

And recommendation for ISRs? **Do it as short as possible!** Set some volatile flag and do the action later outside of ISR.


message:
ATTiny85 I2C LCD

My setup is as follows:

 - Arduino IDE 1.6.11
 - Arduino Pro Mini as ISP
 - ATTiny85 1602A LCD with I2C board

The libraries I use are:

 - TinyWireM (source: https://github.com/adafruit/TinyWireM)
 - LiquidCrystal_I2C (modified for ATTiny) (source: http://playground.arduino.cc/Code/USIi2c)

The Sketch I use to test with:

    #include <TinyWireM.h>
    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x3F,16,2);  // set address & 16 chars / 2 lines

    void setup()
    {

      TinyWireM.begin();                    // initialize I2C lib
      lcd.init();                           // initialize the lcd
      lcd.backlight();
      lcd.clear();  // Print a message to the LCD.
    }

    void loop()
    {
      lcd.setCursor(0, 0);
      lcd.print("Hello World on Attiny85");
      delay(2000);
    }

The address is 0x3F, I found this using the scanner sketch, I also tested the LCD using the Arduino Pro Mini directly, it works fine.

The result of this setup is a single line of black blocks. My guess is that the initialization failed in some way. I have tried some things to make it work:

 - Pull-ups on SDA and SCL
 - Isolated from Arduino with regulated power supply
 - Setting contract with the pot meter on the back
 - reinstall of PC
 - reinstall of Arduino IDE
 - 1MHz, 8Mhz, TinyCore default and High-Low Tech
 - Replaced FTDI
 - Replaced Tiny85
 - Replaced LCD
 - Replaced Arduino Pro Mini

Some pictures:

[![back of the display][1]][1]

[![the blocks][2]][2]

[![connections][3]][3]

[EDIT]

**Final sketch:**

    #include <TinyWireM.h>                  // I2C Master lib for ATTinys which use USI
    // #include <LiquidCrystal_I2C.h>
    #include "LiquidCrystal_attiny.h"
    LiquidCrystal_I2C lcd(0x27,16,2);

    void setup() {

      // Now set up the LCD
      //lcd.begin(16,2);               // initialize the lcd
      pinMode(4, OUTPUT);
      lcd.init();
      lcd.backlight();
      lcd.home ();                   // go home
      lcd.print("Weatherstation");
      lcd.setCursor ( 0, 1 ); // go to position
      lcd.print("BMP180");
      delay(2000);
    }
    void loop() {
      digitalWrite(4, HIGH);
      delay(100);
      digitalWrite(4, LOW);
      delay(100);
    }

  [1]: https://i.stack.imgur.com/GZePC.jpg
  [2]: https://i.stack.imgur.com/hTfyz.jpg
  [3]: https://i.stack.imgur.com/DysXQ.jpg

body:
After hours of Googling, I found [a blog post][1] by Dimitris Platis where he describes using an ATTiny85 with I2C LCD. I emailed the guy and he replied with a link to his LCD I2C ATTiny library on GitHub. Using this library with the TinyWireM and the right core, it instantly worked.

My final setup is with a 4.7K resistor on SDA and SCL, I will add the final sketch in the original post under [EDIT]. This adventure took me two weeks so I hope it helps someone else some day.

LCD library used: https://github.com/platisd/ATtiny85-LCD-library
TinyWireM used: https://github.com/adafruit/TinyWireM
Core used: https://github.com/vprimachenko/ArduinoTiny

  [1]: https://platis.solutions/blog/2015/03/22/diy-interactive-name-tag/


body:
It doesn't look like you have an Arduino Pro Mini. I2C lines on a Pro Mini are on pins A4 for SDA and A5 for SCL and those 2 pins are placed at an odd location - check picture.

Hope I was helpful :)

[![Arduino Pro Mini pinout][1]][1]

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


body: I've spent an hour doing this problem and searched a lot. If you still didn't find the solution by doing this. Pls try to reduce the clock speed from `Internal 8 MHz` to `Internal 1MHz`. That way it works mine.


message:
Prevent 5V output on Arduino Nano 5V pin

I just made an addressable RGB LED strip controller but im concerned about if I'm going to break the thing.

I know it sounds vague so let me elaborate: there is an external power supply connected to my 5V pin and the LED strips positive so it powers both the strip and Arduino, but I also have my Arduino connected to my PC at all times. So I'm concerned about IF my power supply is for some reason not connected the Arduino will supply power on its own.

Is there a way to prevent 5V pin from outputting 5V, so it only accepts 5V

EDIT:
There are cases when the USB isn't connected so I need the 5V to be connected at all times, if its still vague then is there a way to only use data on USB and disregard the power?

body:
A simple diode is all you need. The USB power already goes through a diode, so another diode the same will create a "highest voltage wins" situation.

That is, if the voltage provided by the USB port is higher than the voltage you provide on the +5V pin (after the diode's forward voltage drop) then the USB port will power the nano. If the voltage on the +5V pin is higher (after the diode's voltage drop) than the USB then the voltage on the +5V pin will power the nano.

No power will flow out of the 5V pin to your LED strip because the diode is in the way.

Connect the 5V external power to the *anode* of the diode, and the 5V pin of the Arduino to the *cathode* of the diode. The cathode is generally the end of the diode with the stripe.  Make sure the diode can pass enough current to power the Arduino when the USB is un-powered. The 1N4001 is a popular choice and very easy to get hold of.

That choice of diode also has a higher forward voltage drop than the on-board USB diode (0.7V as opposed to about 0.4V), so the USB will generally be chosen by default when connected and powered up, which is as it should be for a bus-powered device.


message:
Connect an Arduino directly to RGB LED strip

I am totally new in this area. I have an Arduino mega 2560 and I have this LED RGB [Strips][1]. I would like to know if there is any way of connecting the Strips directly to the arduino. The strip has already solded 4 cables:

- one cable on 12V
- one cable on G
- one cable or R
- one cable on B

I don't have additional equipment. Also, I can't find anything online which uses the same type of strips as mine. Many thanks.

  [1]: https://www.amazon.co.uk/gp/product/B00XBHW0YS/ref=s9_simh_gw_g201_i2_r?ie=UTF8&fpl=fresh&pf_rd_m=A3P5ROKL5A1OLE&pf_rd_s=&pf_rd_r=565KNQFHRJ455NFM59T2&pf_rd_t=36701&pf_rd_p=026d359a-cb34-4790-9249-ec9f152ee8e2&pf_rd_i=desktop

body:
No. Two reasons:

1. The Arduino can only supply about 40 mA per pin max. Your LEDs will require about 1000 mA or so per channel (based on the 3 A PSU supplied with the unit).
2. The LEDs are individually addressed and codes have to be transmitted to them. This requires code to be written for the micro and an interface to the data line.

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

_Figure 1. The IR controller._

The IR controller supplied with the kit interfaces the power and provides the data signal to the strip.

The simplest way to control from your micro is to fit it with an IR (infra-red) LED and transmit the codes to the IR controller. This method also makes it almost impossible for you to damage your micro or the LED strip as the only connection between them will be by infra-red light.

Someone has probably figured this out already and you may find the complete code for an Arduino in a web search.

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


body:
Those LED strips are multiple parallel chains of 3 LEDs in series, with a 150Ω resistor for each chain.  The chains are arranged as common anode, and the chains are grouped into the three colours for the cathodes.

You require a power supply with enough current to supply all the LEDs (such as the 3A one supplied in the package).

Further, you require a method of switching each of the three channels, such as n-channel MOSFETs, which can handle enough current for each channel (one MOSFET per channel) - that is, 1A per channel if the whole strip takes 3A (but you can "derate" it by providing capacity for more current which helps alleviate some heat dissipation problems).

As long as the MOSFETs are logic level (such as the IRLxxx series) you can then switch them directly using the PWM outputs of the Arduino.


body:
  https://www.amazon.com/Channels-DMX-512-Decoder-Converter-Light/dp/B0083RBGJG or 3 power FETs and https://www.amazon.com/Power-Adapter-Transformers-Supply-Output/dp/B00DKSI0S8/ref=pd_lpo_328_bs_t_2?ie=UTF8&psc=1&refRID=SF0CXGBQYRBBRAQT2FN1

You can use the logic level ports to drive Logic level power MoSFET switches or use a RS85 IC to communicate to a DMX-512 interface special effects driver to RGB.

Other options include
Use 5A PWM 3channel dimmer purchased on line with 12V- 14.5Vmax PSU >40W per 5m reel string .

e.g. Laptop universal 65W charger ($30) with 14V -16V setting. and long AWG18 wire with 1-2V drop

(comments)

- You start by improving your question with details on what you want to do with the interface.
- if you want guidance shopping for a LED driver , just say so or ask for details, it's not hard


body:
No. there is no way to connect those directly.

You can use Solid state relays (SSR) for this.
I did it before and was able to make different colors.

Connect an external 12v directly 12V pin in srips.

Use SSR to connect from GPIO to LED R G and B pins


message:
Code Optimisation

I have tried fading the RGB Led with different colour format and sequence.
Working of Code :-

 - When value of number is 1, the Red LED fades gradually and glow up with the delay interval of 10ms with fade amount 5.
 - When value of number is 2, the Green LED works as above.
 - The change of state from Red to green takes 4 seconds.

Blue Led Code can also be added to this and various other colour combinations can be made, which will complex the code and add up difficulty is debugging and finding errors because every combination should have different name for fading so that it doesn't conflict with other combinations.

Here is my code. However, I need some suggestions regarding quality of my code. Is it the efficient way to do code. How can I improve the code. Any constructive suggestions would be of great help.

    int RED_LED = 12;           // the PWM pin the LED is attached to
    int BLUE_LED = 14;
    int GREEN_LED = 15;

    int RedLedBrightness = 0;    // how bright the LED is
    int GreenLedBrightness = 0;    // how bright the LED is

    int RedFadeAmount = 5;
    int GreenFadeAmount = 5;

    unsigned long previousMillis = 0;
    const long interval = 10;

    unsigned long previousMillis2 = 0;
    const long interval2 = 4000;

    int j = 0;

    void setup()
    {
      pinMode(RED_LED, OUTPUT);
      pinMode(BLUE_LED, OUTPUT);
      pinMode(GREEN_LED, OUTPUT);

      Serial.begin(115200)
    }

    void loop()
    {
        if (millis() - previousMillis2 >= interval2)
        {
         previousMillis2 = millis();

        j += 1;
        if (j > 2)
        {
            j = 1;
        }
        Serial.print("\n");
        Serial.println(j);
       }
        SpecialFunction(j);
    }

    void SpecialFunction(int Number)
    {
      if (millis() - previousMillis >= interval)
      {
        previousMillis = millis();

        if (Number == 1)
        {
          RedGradualChange();
        }

        else if (Number == 2)
        {
          GreenGradualChange();
        }
      }
    }

    void RedGradualChange(void)
    {
      analogWrite(GREEN_LED, 0);

      GreenLedBrightness = 0;    // how bright the LED
      GreenFadeAmount = 5;

      analogWrite(RED_LED, RedLedBrightness);
      RedLedBrightness = RedLedBrightness + RedFadeAmount;

      if (RedLedBrightness <= 0 || RedLedBrightness >= 1020)
      {
        RedFadeAmount = -RedFadeAmount;
      }
    }

    void GreenGradualChange(void)
    {
      analogWrite(RED_LED, 0);

      RedLedBrightness = 0;
      RedFadeAmount = 5;

      analogWrite(GREEN_LED, GreenLedBrightness);
      GreenLedBrightness = GreenLedBrightness + GreenFadeAmount;

      if (GreenLedBrightness <= 0 || GreenLedBrightness >= 1020)
      {
        GreenFadeAmount = -GreenFadeAmount;
      }
    }

body:
Without deciphering what all those functions are supposed to do, I can see a few fundamental flaws and inefficiencies:

1. Don't use string - especially if you're only then using it to convert into a char array. Just use the char array.
2. You're storing a number in a char array then comparing it to string constants. What is wrong with dealing with just numbers in the first place...?
3. This bit is wrong: `if (incomingByte = '#')` - you have an assignment (`=`) instead of a comparison (`==`) so it will always be true.
4. If you fix point 3 the rest of the code won't work, since your string will now always have `#` at the end (`3#` for instance) and the comparison against `3` (for example) will fail.

You should learn more about how to input values through serial:

* https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

----

For your fading code there is a lot of redundancy in there. Personally I would use a *bitfield* indicating which LEDs are to fade and which aren't.

Basically you have a single value and OR together bits within it to indicate the enabled LEDs.  For instance, assign the value `1` to red, `2` to green and `4` to blue. These correspond to `0b001`, `0b010` and `0b100` respectively.

When the state is changed, either by your loop or by an external serial signal, you reset all three colour brightnesses to 0 (to keep them synchronised) and set the right bits in the bitfield for the colours you want fading. For instance, for red you set the bitfield to 1. For cyan you set it to 6 (0b110).  Then in your processing loop you just fade the colours that are enabled, and write all three values (the colour that isn't enabled will already be 0).  This also has a side-effect that you now already have numbers assigned to the colours:

    0 = 0b000 = All off
    1 = 0b001 = Red
    2 = 0b010 = Green
    3 = 0b011 = Yellow
    4 = 0b100 = Blue
    5 = 0b101 = Magenta
    6 = 0b110 = Cyan
    7 = 0b111 = White

In fact, since all the colours are fading together, you don't even need separate values for each colour - just one global brightness value.

Some code (untested) for you:

    #define RED   0b001
    #define GREEN 0b010
    #define BLUE  0b100

    int brightness = 0;
    uint8_t enabled = 1;
    int fadeAmount = 5;

    const uint8_t RED_LED = 12;
    const uint8_t BLUE_LED = 14;
    const uint8_t GREEN_LED = 15;

    unsigned long previousMillis = 0;
    const long interval = 10;

    unsigned long previousMillis2 = 0;
    const long interval2 = 4000;

    void setup() {
      pinMode(RED_LED, OUTPUT);
      pinMode(BLUE_LED, OUTPUT);
      pinMode(GREEN_LED, OUTPUT);

      Serial.begin(115200);
    }

    void loop()
    {
        if (millis() - previousMillis2 >= interval2) {
            previousMillis2 = millis();
            enabled ++;
            if (enabled >= 8) enabled = 1;
            Serial.println(enabled);
        }

        if (millis() - previousMillis >= interval) {
            previousMillis = millis();
            if (enabled & RED) {
                analogWrite(RED_LED, brightness);
            } else {
                analogWrite(RED_LED, 0);
            }
            if (enabled & GREEN) {
                analogWrite(GREEN_LED, brightness);
            } else {
                analogWrite(GREEN_LED, 0);
            }
            if (enabled & BLUE) {
                analogWrite(BLUE_LED, brightness);
            } else {
                analogWrite(BLUE_LED, 0);
            }
            brightness += fadeAmount;
            if (brightness > 1023) {
                brightness = 1023;
                fadeAmount = -fadeAmount;
            } else if (brightness < 0) {
                brightness = 0;
                fadeAmount = -fadeAmount;
            }
        }
    }


message:
ESP8266 12e Arduino IDE outputs garbage values on serial monitor

I recently started using the [ESP8266 12E][1] <sup>(Amazon link)</sup> and hooked the board up to the Arduino IDE.

When trying to run any of the example sketches, all sketches compile and upload correctly. The blink sketch correctly causes the LED to blink, however, in the serial monitor a varying and large quantity of junk characters appear:

[![screenshot][2]][2]

The first thing I investigated was of course the baud rate. Online, documentation for the ESP8266 indicate 115200 as the correct baud rate, but on the bottom of the device, the baud rate is listed as 9600.

The junk characters, of course, appear whether the baud rate is 9600 or 115200. Using trial-and-error, I tried each other option. I've also tried several USB to micro-USB (c) cables. They're the same ones I use to charge my phone - is that the issue?

Am I missing something simple here? I searched each of the other Stack Exchange questions about garbage serial monitor values and they all seemed to indicate that the baud rate was the culprit, or that the CL / NR values needed to be changed. Experimentation with these did not result in removing the characters.

 [1]: https://www.amazon.com/gp/product/B010O1G1ES/ref=ask_ql_qh_dp_hza
 [2]: https://i.stack.imgur.com/HYlPl.png

body:
The baud rate you specify in your program and the baud rate in the serial monitor *must* match. The ESP8266 outputs a boot message at its own baud rate (varies from model to model - try 57600) before it executes your sketch.

For example:

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

You can choose any (within reason) baud rate in your program as long as you also choose the same baud rate in whatever is communicating with it (such as the serial monitor in the IDE). If you want to see the boot messages then the serial monitor will have to be set to the right baud rate.

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


body:
I had what I think is the same problem you did.  I posted my solution to it here:

[Link to my solution][1]

It seems that the ESP can upload code at 115200, but it can't talk to the serial monitor at that baud rate.  The solution is to programatically change the baud rate within your sketch.  The change in baud rate doesn't 'stick'.  You have to include it in your sketch so it is set every time the sketch is run.

Hope that helps.

  [1]: https://arduino.stackexchange.com/questions/47832/serial-monitor-not-properly-interpreting-data-from-my-nodemcu-v3/47843#47843


message:
Getting the highest value from analog reading?

I am doing a project using an FSR (Force Sensitive Resistor), I'm currently reading values with no problem every 100milis. I want to output via Serial.print the highest value, I've read.

I am having a hard time doing so. The project is use to "measure" the strength some projectiles hit the sensor. I want to get the highest value.

This is the code I have until now.

    int fsrPin = 0;     // the FSR and 10K pulldown are connected to a0
    int fsrReading;     // the analog reading from the FSR resistor divider
    void setup(void) {
      // We'll send debugging information via the Serial monitor
      Serial.begin(9600);
    }

    void loop(void) {
      fsrReading = analogRead(fsrPin);

      Serial.print("Analog reading = ");
      Serial.println(fsrReading);     // the raw analog reading

      delay(100);
    }

body:
You don't want to delay ever. Instead you want to change your thinking to "X miliseconds have passed, time to print and reset":

    int maxval = 0;
    uint32_t lastSample = 0;

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

    void loop() {
        if (millis() - lastSample > 100) { // Every 100ms:
            lastSample = millis();
            Serial.println(maxVal);
            maxVal = 0;
        }
        int reading = analogRead(0);
        if (reading > maxVal) {
            maxVal = reading;
        }
    }

Every 100ms it will print the maximum analog value read during the past 100ms.

You can replace the 100ms with any other value you choose, or even with a check to see if a button has been pressed, in which case you get the maximum reading since the last time the button was pressed:

    // global
    bool lastButtonValue = HIGH;

    // in loop()
    if (digitalRead(3) != lastButtonValue) {
        lastButtonValue = digitalRead(3);
        if (lastButtonValue == LOW) {
            // ... do the print and reset
        }
    }


message:
From Wiring to pure C

I'm using the Teensy 2.0 (atmega32u4) and decided to switch from Arduino IDE with Wiring to pure C. I think it's much more useful to master programming microcontrollers on that level. Wiring seems to be quite limited at some point.

It was really easy to use some basic libraries such as _avr/io_, or _util/delay_ and write simple programs like "arduino hello world".

My problem comes with more complex tasks such as acting as usb mouse. On http://pjrc.com are references just to use with arduino ide/wiring. I couldn't find anything useful on google. Is there any good reference for pure C programming tennsy/arduino and/or using libraries such as "usb_mouse.h" (from pjrc.com) with pure C?

----------

**EDIT 1**

Let me add some details (based of @st2000 answer).. Yes, Tennsy (and Arduino) are microcontrollers, not microprocessors. Programming avr chips in pure C doesn't require so much work as programming microprocessors. This is the simplest avr C program I could come with (typical blinky):

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

    int main(void) {
            (CLKPR = 0x80, CLKPR = 0x00);
            DDRD |= (1<<6);
            PORTD &= ~(1<<6);

            int sviti = 0;

            while (1) {
                    if (sviti)
                            PORTD |= (1<<6);
                    else
                            PORTD &= ~(1<<6);
                    sviti ^= 1;
                    _delay_ms(40000);
            }
    }

As you can see (@st2000), there are no dozens of setting up registers. It does not require any expensive equipment to upload resultant .HEX file - for teensy the only thing you need is a USB cable.

If you want a concrete example, I want to use [this library](http://www.pjrc.com/teensy/usb_mouse.html) with pure C, but it's obviously meant for wiring and arduino IDE primary. So how to use this library with pure C? And back to my main question, how to generally use libraries of this kind with pure C avr programming?

body:
Refer to the actual processors used on the platforms to find reference material for ordinary C or C++ programming.  There are different processors used on various Arduino boards.  Be aware that this approach normally requires programming hardware which range from a few dollars to hundreds of dollars.  Also be aware that "[bare metal programming][1]" requires the programmer to setup the processor's resources of interest.  This normally involves setting dozens (as in the Arduino Uno AVR processors) if not thousands (as in Arduino Zero's ARM processors) of registers which can deal with everything from the processor's clock to interrupt vectors.

USB programming is very complex.  Consider the complete description of RS232 could be contained in a white paper.  The equivalent for USB would be at least a book.  To simplify your efforts, we can eliminate all USB Host features as a mouse is a peripheral or USB Device.  Further, you will probably want to limit your USB Device to a USB HID or Human Interface Device.  This allows most OSs to easily recognize and use the mouse as the HID definition is more complete / restrictive. Also note, embedded processors which happen to have a USB port usually only support USB Devices as USB Host requires additional features & resources.  Now that the scope of USB support has been narrowed, you can start searching through the different processor's libraries for what you need to create a USB HID Mouse.

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


body:
> And back to my main question, how to generally use libraries of this kind with pure C avr programming?

just as how you would write under arduino ide -> arduino ide is nothing but pure c/c++ plus a set of canned libraries. so what you are trying to do is no different from what you are doing with arduino right now, maybe with your own libraries or libraries from folks other than the arduino folks.

nothing magic about going in "pure c".


message:
Arduino or XBee unique identifier?

Is there anything built into the Arduino Uno or the XBee Pro 2 radio module that I can poll within my Arduino script to act as a unique identifier? Mac address or otherwise? If anyone has a code snippet that can do this it'd be extremely appreciated.

Currently my Arduino nodes are broadcasting only to my node.js server, but my server is broadcasting to all the nodes, so if they're all waiting to be assigned an identifier number through the handshake function I wrote, they all receive the same one. If I stagger powering them up this is avoided and they each get a unique ID, but I hope there exists a cleaner solution.

body:
When programming the Uno's, you could write identifying values into particular EEPROM bytes.  To automate the process, write a development-system program to produce serial-numbered HEX files, with the serial number counting up each time the program runs.

For example, if you store IDs into byte 0x1E of EEPROM, the serial number file would look as follows when the serial number is 0x23:

    :01001E0023BE
    :00000001FF

The first line in the above file says 01 bytes of payload, stored at address 001E, record type 00 (data), payload byte 23, checksum BE.   See [wikipedia's Intel HEX article](https://en.wikipedia.org/wiki/Intel_HEX) for further explanation of HEX file format.  In brief, each time the serial number byte goes up by one, the checksum byte goes down by one.

To program a serial number byte into EEPROM from a file called `SNfile.hex`, issue a command like the following.

    avrdude -p atmega328p -c arduino -P /dev/ttyUSB1 -b57600 -U eeprom:w:SNfile.hex:i

See the `avrdude` manpage for explanation.

In your sketch, use [EEPROM.read(address)](https://www.arduino.cc/en/Reference/EEPROMRead) to read a unit's serial number.  For example:

    #include <EEPROM.h>
    byte mySN = EEPROM.read(0x1E);

[Note, regarding your question about  “anything built in... to act as a unique identifier”, I once spent quite a while looking for such a thing on Uno, Nano, and Mega2560 Arduinos, and found nothing.  I haven't looked at XBee radio modules for such data.]


message:
Generating analog signals

is there a way to make the Arduino act as a voltage source, by generating sinusoidal, triangular and other kinds of signals? If so, can it be done using LabVIEW? (I've already managed reading analog signals using VISA)

Thank you!

body:
The Due (and similar SAM based boards) have a DAC built in which can be set to different voltages (I forget the range off hand, maybe 0-Vcc at 12-bit resolution). Change that voltage fast enough, and you have a waveform.

Other Arduinos have PWM outputs which, when filtered through a low-pass filter, give a voltage proportional to the duty cycle of the PWM. Again, change the duty cycle fast enough and you have a waveform (limited by the *carrier frequency* of the PWM).

Can you do it from LabVIEW? Who knows? I have never used it.


message:
OnKeyPress in a arduino

So, I have 3 buttons to a arduino.
I want to detect the button press on the 3 of them.

For that, i've created a function:

    int OnKeyPress (int port) {

   int  LastState, BeginState, r;
   r = 0;

   BeginState = digitalRead(port);

   if (BeginState != LastState) {
    if (BeginState == 1) r = 1 ;
   }

   delay(5);
   LastState = BeginState;
   return r;
    }

   I want to instantiate 3 instances of this code, separately and they have to retain this variables `int  LastState, BeginState, r;` for each button, and the next time the function runs on the loop, the variables are the same of when they ran last time.

Just, how?

body:
This is an ordinary method (function) which can not be instantiated. It is necessary to write a class with 1 or more methods in it in order to instantiate multiple copies of that class and the method(s) with in that class.

The integers "LastState", "BeginState" and "r" only have scope within the method and will not survive after returning from the method.  There are several approaches to preserve these variables from one call to the next.  They can be declared as static integers.  Or they can be defined globally.

It appears you are recreating the existing [Bounce library][1].  I encourage you to continue if you are learning.  However, you may want to look at the Bounce library's [code][2] for guidance.

  [1]: http://playground.arduino.cc/Code/Bounce
  [2]: https://github.com/thomasfredericks/Bounce2


message:
How to improve date-time control from RTC?

I want to run cameras at a remote site from external batteries as long as possible. I need power-miser Arduino to switch battery power on/off at set intervals (e.g. 5 min) during daytime only. I am a beginner with Arduino and electronics.

Have set up 'breadboard' arduino with mosfet module for switching the power supply and RTC module, both from Freetronics (http://www.freetronics.com.au/collections/modules/products/real-time-clock-rtc-module#.V-i-S8knuPs). Following their recommendation I'm using RTC library here: http://rweather.github.io/arduinolibs/index.html

I need to refine the crude hour-based script below. Weatherley library returns separate objects e.g date.day, time.hour etc. Is there a simple way to convert to date-time object? Then calculate sunrise and sunset times based on latitude?

      #include <JeeLib.h> //  power saving library
      ISR(WDT_vect) { Sleepy::watchdogEvent(); } // Setup jeelip watchdog
      #include <SoftI2C.h> // rweather lib for RTC module
      #include <DS3232RTC.h> //rweather lib for RTC module
      SoftI2C i2c(A4, A5); // assign pins to SDA and SCL
      DS3232RTC rtc(i2c);
      RTCTime time;
      int gatePin = 12;   //  mosfet Gate connected to digital pin
      int startHour = 6; // want to replace with sunrise time
      int endHour = 19; // want to replace with sunset time

    void setup()
    {
     pinMode(gatePin, OUTPUT);   //  output pin for mosfet module
    }

    void loop()
    { // main loop starts here
      rtc.readTime(&time);  //get current time
      if (time.hour >= startHour && time.hour < endHour) // check daytime
      {   // if condition begins here
          while(time.hour < endHour ) // daytime operating period

          {   //  while loop (day) begins here
          digitalWrite(gatePin, HIGH);   // turn on gate for power supply
          Serial.flush(); //needed before sleepy
          Sleepy::loseSomeTime(30000); // low power wait
          digitalWrite(gatePin, LOW);    // turn off gate for power supply
          Serial.flush(); // needed before sleepy
          for (int i=0; i <= 3; i++){
            Sleepy::loseSomeTime(65000); // low power wait
            } // end for loop
          rtc.readTime(&time);
          } // end while loop (day)
          } //  if condition (daytime) ends here
    else
      { // else condition (night time) starts here
        while (time.hour >= endHour || time.hour < startHour )
        { // while loop (night) begins here
        for (int i=0; i <= 59; i++){
        Serial.flush(); // needed before sleepy
        Sleepy::loseSomeTime(65000); // low power wait
        } // end for loop
        rtc.readTime(&time);
        } // while loop (night) ends here
    // need to refine timing else hour-long wait periods can run past the end of night period
      } // else condition (night) ends here
    } //  main loop ends here

I will be very grateful for advice, many thanks in advance!

EDIT: Part of my original question could be answered - see below about time-date format *without* using RTC. Issues with RTC appear harder than I expected. I think they will need a new question later.

body:
> Is there a simple way to convert to date-time object?

Not with this library. But you can find [other][Christensen]
[libraries][Tecsmith] supporting the DS3232 which work with the [Arduino
Time library][]. This time library provides both the date and time in a
single object, either:

* a `time_t`, which is just the number of seconds elapsed since a
  standard “epoch”
* a `tmElements_t` struct, which has the date and time broken into
  separate elements (year, month, day, hour...).

> Then calculate sunrise and sunset times based on latitude?

There are quite a few algorithms describes on the Web for that. The more
accurate ones are also the more complex.

> `#include <SoftI2C.h>`

Doesn't your Arduino have a hardware I2C port? That would be more
efficient than software emulation.

> `Serial.flush(); //needed before sleepy`

It's only needed if you are actually using the serial port.

**Edit**: I saw on your [other question][] that you have been bitten by
an incompatibility between the Arduino Time library and the file
`time.h` from avr-libc. Now I just noticed that avr-libc includes the
functions [`sun_rise()` and `sun_set()`][sun_rise] that you may find
handy. Not sure they will play well with the Arduino time libraries
though. One possible incompatibility is the fact that they use different
epochs for defining `time_t` (year 1970 v.s. 2000).

[Christensen]: https://github.com/JChristensen/DS3232RTC
[Tecsmith]: https://github.com/Tecsmith/DS3232RTC
[Arduino Time library]: https://github.com/PaulStoffregen/Time
[other question]: https://arduino.stackexchange.com/q/29600
[sun_rise]: http://www.nongnu.org/avr-libc/user-manual/group__avr__time.html#ga21a491a92bce972d041e2194b4577943


body:
I hope I am allowed to summarise progress. Edgar Bonet's answer above pointed me in the right direction regarding date-time format and I want to 'accept' that answer, although it did not resolve my difficulties with RTC. I need to ask a new question about RTC later.

Using the Time library Edgar Bonet recommended, I managed to set and change date-time format, and calculate duration between date-time instances. I hope my example below could perhaps be useful for other beginners. If anyone has suggestions to improve this example, please add them.

        #include <TimeLib.h> // https://github.com/PaulStoffregen/Time
        time_t tstart;

        void setup()  {
        Serial.begin(9600);
        // assume no RTC available therefore set date-time in this sketch
        // when serial monitor opens, date-time will be set as follows
        setTime(8,30,0,17,10,2016); // (hr,min,sec,day,mnth,yr);
        tstart = now();
        Serial.print("Started at: ");
        digitalClockDisplay();
        Serial.println();
        }

        void loop(){
        Serial.println("Waiting...");
        delay(20000 + random(500, 5000) );
        Serial.println();
        time_t tnow = now();
        Serial.print("Now it is: ");
        digitalClockDisplay();
        time_t duration = tnow - tstart;
        Serial.print("Duration since start: ");
        showDuration(duration);
        Serial.println();
        Serial.println();
        }

        // function to print current date-time
        // modified from example in TimeLib
        void digitalClockDisplay(){
          Serial.print("Date: ");
          Serial.print(day());
          Serial.print("-");
          Serial.print(month());
          Serial.print("-");
          Serial.print(year());
          Serial.print("  Time: ");
          Serial.print(hour());
          printDigits(minute());
          printDigits(second());
          Serial.println();
        }
        // utility function from TimeLib
        // to print leading zeros
        void printDigits(int digits){
          Serial.print(":");
          if(digits < 10)
            Serial.print('0');
          Serial.print(digits);
        }

        // function from example TimeRTCLog
        void showDuration(time_t duration){
        // prints the duration in days, hours, minutes and seconds
          if(duration >= SECS_PER_DAY){
             Serial.print(duration / SECS_PER_DAY);
             Serial.print(" day(s) ");
             duration = duration % SECS_PER_DAY;
          }
          if(duration >= SECS_PER_HOUR){
             Serial.print(duration / SECS_PER_HOUR);
             Serial.print(" hour(s) ");
             duration = duration % SECS_PER_HOUR;
          }
          if(duration >= SECS_PER_MIN){
             Serial.print(duration / SECS_PER_MIN);
             Serial.print(" minute(s) ");
             duration = duration % SECS_PER_MIN;
          }
          Serial.print(duration);
          Serial.print(" second(s) ");
        }


message:
How do I turn off a 12V 3A RGB LED strip?

I'm trying to understand how to control an RGB LED strip, I set up all the `TIP120` (because I could get my hands on an n-channel mosfet), if I power everything in this way I can change colours and everything:
[![enter image description here][1]][1]

but now I'm facing a dilemma now, whats the correct way to manage to switch my power strip ON/OFF based on an input from a pir sensor? I mean, how can I handle 12V 3A (requested by my led strip), how do I correctly wire my Arduino up in order to make it switch the LED strip ON/OFF?

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

body: That's pretty simple: when you turn off all the colours you are actually turning off the entire strip with very minimum leakage current in each of the three FETs.


message:
Difference between Wire.setClock() method and TWBR method for changing I2C Frequency

I want to change the `I2C` frequency of my Arduino Mega 2560. I did find two methods. One method is to change the `TWBR` variable after `Wire.begin()`. The other one is to use `Wire.setClock()` after `Wire.begin()`.

Whats the difference between the 2 methods? which one is better? Can I set any `I2C` frequency I want?

body:
They are both one and the same. One is easier to remember though (I'll let you work out which).

`Wire.setClock(frequency)` just (ultimately) does:

    TWBR = ((F_CPU / frequency) - 16) / 2;

You can set any frequency that ends up with that formula generating an integer between 0 and 255.


body:
> Whats the difference between the 2 methods?

The difference is that one is more portable than the other. The "direct register set" will not work very well on an Arduino Due.

There is no speed or foot-print advantage with the "direct register set" as this is often only done once in the setup of the sketch.

> Which one is better?

If better is portable, maintainable, readable, etc then the answer is simple - use the API and not "direct register set".

> Can I set any I2C frequency I want?

No - obviously there are some restrictions. First, the CPU frequency is scaled so it cannot generate all possible frequencies. Second, the I2C device(s) and bus will set restrictions on the maximum frequency. Longer wires and several devices will add capacity and require lower frequency. Also the device with the lowest frequency puts an upper limit. Always check the data sheets for the I2C devices.

Cheers!


message:
How do I see underlying code and definitions inside Arduino IDE on MacOS X El Capitan

I'm a newbie to Arduino so please excuse the easy question and guide me to the appropriate sources or forums.  I just bought an Arduino Uno Starter Kit that comes with the "Arduino Projects Book" by Scott Fitzgerald et al and I'm happily working my way through the projects.  I downloaded the Arduino IDE (version 1.7.10) onto my mac and am turning on lights, etc.  However, I'd like to see the underlying code.  For example, I use the code "digitalWrite" to turn off/on LEDs.  I'd like to see the code for this.  I can imagine that it's just a write of 1 or 0 to a particular memory address, but I'd still like to see it.  I was hoping there was a right-click->"Go To Definition", but I don't see it. I downloaded the Arduino IDE to my Downloads folder and run it just from there. It's called Arduino.app.   I don't see a folder with .c and .h files as suggested in this post:  https://arduino.stackexchange.com/questions/17797/arduino-ide-underlying-code-and-libraries  Maybe I'm missing them?

Also, is it possible to set a breakpoint?

Again, sorry if these are "obvious" questions.  And I did look at the Arduino site without any success.

Thanks,

Dave

body:
The simplest way is to look at the source on Github:

* https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/cores/arduino

Can you set a breakpoint? No. The Arduino IDE and the bootloader don't support such functionality. To do that you need a real IDE (like Atmel Studio) and a hardware debugger.


message:
My computer dose not recognise my Arduino Uno

I had never used Arduino before. When I tried to interface my new Arduino Uno board to my computer, the computer failed to recognize the board.

Why isn't the board interfaced successfully? How should I troubleshoot that problem?

body: Majenko is probably right.  If it is a clone Arduino board you will need to install some CH340 drivers.  If it's an authentic board I would return it as it should work out of the box with the Arduino IDE.


message:
Ramping a stepper motor

I at the moment trying smoothly move a stepper motor. The problem with the stepper motor, is that it makes a high pitch noise while it moves, or sometime a crackling noise from the motor.

So i tried ramping up the frequency of the step signal, which seemed to help a bit but not perfect. Then I tried micro stepping rather than  full stepping, which also helped a bit but still, the noise is very clear.

The motor I am using is a [PK244-01A][1]
And the driver it is connected to is [this one][2]

I am not at all sure if the ramping I do is either too steep, or completely  incorrect, but here is the code that controls the motor.

    void stepper_motor::step_pwm()
    {

        digitalWrite(en_pin,HIGH);

        delay(0.005);

        digitalWrite(dir_pin,HIGH);
        //LOW  - Move towards the sensor
        //HIGH -  Move away from the sensor

        delay(0.005);
        int increment = 0;
        int step_count = 0;
        while(step_count <= max_step)
        {
          digitalWrite(step_pin,LOW);
          delayMicroseconds(2000);
          digitalWrite(step_pin,HIGH);
          delayMicroseconds(2000-increment);
          step_count++;

          if(step_count >= 1)
          {
            increment++;
            step_count = 0;
          }
        }

    }

  Anything I could do to make the noise of the motor less significant?

  [1]: https://www.orientalmotor.co.in/products/st/list/detail/?product_name=PK244-01A&brand_tbl_code=ST&series_code=G000&type_code=Unipolar 6 lead wires&type=Standard Type
  [2]: http://www.sainsmart.com/zen/documents/20-019-201/ST330  Stepper Motor Driver Board User Manual.pdf

body:
I had a similar issue once before. It actually matters a lot to properly ramp up your stepper motor. Especially under load if you ramp up too steep you can loose steps.

Since you are already using the arduino environment I suggest you could use the [AccelStepper][1] library.

I lets you set the acceleration and max. speed parameters nicely and uses a properly calculated ramp.

  [1]: http://www.airspayce.com/mikem/arduino/AccelStepper/


body: You need to be using the adjusted delay for both the high and the low part of the signal.  Also, what happens when the variable "increment" is larger than 2000?  Nothing good, for certain.  I'd personally like to be able to delay by a negative number and undo some things that are already done, but I don't think yoz can turn back time using an Arduino.