body:
I was looking into `ATmega32u4` datasheet to configure the `SPI`, and there is initialization snippet for data transmission.

    void SPI_MasterTransmit(char cData)
    {
        /* Start transmission */
        SPDR = cData;
        /* Wait for transmission complete */
        while(!(SPSR & (1<<SPIF)));
    }

What I didn't quite get is the last line of the snippet with the while condition to check the state of the `SPIF` bit in `SPSR` register.

What I think I understand that it means, if `SPIF` bit with the a conditional value of 1 which would be in the ALU for comparing it with the actual bit state in `SPSR`. If this is true with & bitwise operator which would be true if the actual bit in the `SPSR` is set with the given value (`1 << SPIF`).

My questions:

1. Am I understanding it right?
2. What this line actually means?
3. I have removed the semicolon at the end of the line and it compiled OK! Is what I did OK?

title: While condition with & bitwise of PINx read

Answers: 1

body:
SPI transmitt is started by writing one Byte into `SPDR`. And this code won't return from `SPI_MasterTransmit` function before it's complete. Transmitt completition is anounced by setting SPIF by hardware (and if SPI interrupt and global interrupts are enabled, it'll run also ISR and clear that flag).

If you write into `SPDR` before transmission is completed you'll corrupt current "transaction", so you have to wait until it's complete before another write.

Bitwise & is used for bit masking. Bits in the result are set if bits at corresponding positions in arguments are both set:

    0b00110011
             &
    0b00100001
            ==
    0b00100001

So if bit at position SPIF is not set, it will loop again and when it's set, it exits the loop, as there is inverted logic.

    ( SPSR     & (1<<SPIF))                    !(SPRS &(1<<SPIF))
    0b0xxxxxxx & 0b10000000 == 0b00000000  =>  !0b00000000 == true
    0b1xxxxxxx & 0b10000000 == 0b10000000  =>  !0b10000000 == false


body: I started to work with AWS IoT today, which offers a MQTT based connection to their web service. They officially only have a demo for the Arduino Yún, which is rather expensive. Has someone managed to get it running (e.g. with a NodeMCU with a ESP8266)?

title: Is there a library to use Amazon IoT services on any Arduino?

Answers: 1

body:
You can try the AWS IoT Embedded C SDK, that is for more general devices.
Other Arduinos requires a crypto library and a device powerful enough, maybe PI, to support the authentication process...
At this time they have no crypto library like the YUN SDK, for other Arduinos...

[Try it...][1]

  [1]: https://github.com/aws/aws-iot-device-sdk-embedded-C/blob/master/README.md


body:
The error message is:

> avrdude: AVR device initialized and ready to accept instructions
avrdude: Device signature = 0x1e950f
avrdude: Expected signature for ATmega32U4 is 1E 95 87
Double check chip, or use -F to override this check.

This error message is thrown when I attempt to upload any program to the Yun shield through an Arduino Bridge between the Uno and Yun shield with the Uno’s ATMega32 shorted into reset mode.
Any advice on how to get this working? Thanks.

title: How do I program my Arduino Yun Shield when I keep getting this AVRDUDE error message?

Answers: 2

body:
Apparently there is no `ATMega32U4` on that board but `ATmega328P` according to the signature `0x1e950f`.

Anyway, you may have to change or add new board with correct MCU setting.

Now I can see the difference between Yun and Yun shield. Shield can be connected to any Arduino board and Yun is similar like Shield + Leonardo.

I've found board definition for Arduino UNO:

    unoyun.name=Arduino Uno -- Dragino Yún
    unoyun.upload.via_ssh=true

    unoyun.vid.0=0x2341
    unoyun.pid.0=0x0043
    unoyun.vid.1=0x2341
    unoyun.pid.1=0x0001
    unoyun.upload.tool=avrdude
    unoyun.upload.protocol=arduino
    unoyun.upload.maximum_size=32256
    unoyun.upload.maximum_data_size=2048
    unoyun.upload.speed=57600
    unoyun.upload.disable_flushing=true
    unoyun.upload.use_1200bps_touch=true
    unoyun.upload.wait_for_upload_port=true

    unoyun.bootloader.tool=avrdude
    unoyun.bootloader.low_fuses=0xff
    unoyun.bootloader.high_fuses=0xde
    unoyun.bootloader.extended_fuses=0x05
    unoyun.bootloader.file=optiboot/optiboot_atmega328.hex
    unoyun.bootloader.unlock_bits=0x3F
    unoyun.bootloader.lock_bits=0x0F

    unoyun.build.mcu=atmega328p
    unoyun.build.f_cpu=16000000L
    unoyun.build.board=AVR_YUN
    unoyun.build.core=arduino
    unoyun.build.variant=standard

More info about it here: [https://www.arduino.cc/en/Guide/ArduinoYunShield][1] or similar product [http://wiki.dragino.com/index.php?title=Yun_Shield][2]

  [1]: https://www.arduino.cc/en/Guide/ArduinoYunShield
  [2]: http://wiki.dragino.com/index.php?title=Yun_Shield

body:
Make sure the board selected in the *Yun Shield* is the correct one (in this case *Arduino UNO*).

Steps for selecting the board on the Yun Shield
------------------------------------------------

 1. In your web browser load the *Yun Shield* page and log in (how to do this is described in the [Quick Start Guide][2]).
 2. Click on the SENSORS menu button.
 3. Under *Arduino Board Type* select the correct one.
 4. Click on the *CONFIGURE & RESTART MCU* button to apply settings.
 5. Maybe manual restart of the board would be needed (power unplug).

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

  [1]: http://wiki.dragino.com/index.php?title=Yun_Shield#Connect_to_Arduino_Uno
  [2]: http://www.dragino.com/downloads/downloads/YunShield/YUN_SHIELD_QUICK_START_GUIDE_v1.0.pdf
  [3]: https://i.stack.imgur.com/vutkA.gif


body:
I've got a 5 meter LED strip connected to a breadboard as such

12V Supply
----------

(+) -> (+) on breadboard rail

(-) -> ground on breadboard rail

Arduino (Wemos D1, all pins w/ PWM)
----------

pin7 -> gate(1st MOSFET)

pin8 -> gate(2nd MOSFET)

pin9 -> gate(3rd MOSFET)

GND -> ground on breadboard rail

MOSFETs (IRLB3034 equivalent)
----------

Gates (already explained)

Drain(1st MOSFET) -> Red line on WS2812 strip

Drain(2nd MOSFET) -> Green line on WS2812 strip

Drain(3rd MOSFET) -> Blue line on WS2812 strip

Source(all MOSFETs) -> (-) on breadboard

And despite this, when I run an extremely simple program such as this, I get white light (all being lit up), and can never individually address a color. I can write all to 0 and will still have a white light, same with writing all to 255, and same again with writing one or two to 255 and the remainder to 0.

    int redPin = 7;
    int bluePin = 8;
    int greenPin = 9;

    void setup() {

    }

    void loop() {
      analogWrite(redPin, 255);
      analogWrite(bluePin, 0);
      analogWrite(greenPin, 0);

    }

I'm thinking my AliExpress board may just be faulty, advertising PWM on every pin when that is not the case, or I may have selected the wrong MOSFETs for this application. Using this identical setup (same breadboard, same MOSFETs) with my Raspberry Pi 2B I was able to change the color of the lights.

Hoping someone here has worked with the Wemos D1 and can help. The documentation on this board seems to indicate that everything should be working, but it is not. I have two boards (same seller) and can confirm that it works with neither.

title: Unable to analogWrite to MOSFET properly (IRLB3034)

Answers: 1

body:
Unfortunately the WS2812 LEDs color is set by powering it up and sending data to it. This means that you don't need the FETs at all.

Sparkfun have a really good walkthrough for hooking up and controlling these LEDs:
[WS2812 Breakout Hookup Guide][1]

To achieve what you set out to do (ie controlling the color with the FETs) you will need a different analog LED strip (such as [this][2]). Adafruit have a really good walkthrough for hooking up and controlling the LEDs in this fashion.
[Controlling Analog RGB LED Strips][3]

  [1]: https://learn.sparkfun.com/tutorials/ws2812-breakout-hookup-guide/all
  [2]: https://www.adafruit.com/products/285?&main_page=product_info&cPath=37&products_id=285
  [3]: https://learn.adafruit.com/rgb-led-strips?view=all


body:
I'm building a base class that creates color patterns using FastLed's CRGB structure. I use the base class as inheritance for another more specific class that modifies a vector of *colors* (`Pixels[]`) and at some point I want to pass the color of a specific element from my class to the main sketch. But i'm having some issues with it, since the content of **`Pixels[]`** doesn't seem to match what I actually write in there.

Pattern.h:

 class Pattern
 {
  public:
  CRGB PixelAt(int idx);
  CRGB Pixels[6];
 }

Pattern.cpp:

 CRGB Pattern::PixelAt(int idx)
 {
   // safety check
   if (idx >= 0 && idx < NumLeds)
   {
     return Pixels[idx];
   }
   else
   {
     Serial.print("Index out of bounds: "); Serial.println(idx);
     return CRGB::Black;
   }
 }

TestPattern.h:

 class TestPattern : public Pattern {
  void Tick(unsigned long millis);
 }

TestPattern.cpp:

 void TestPattern::Tick(unsigned long millis)
 {
     for (int p = 0 ; p < NumLeds ; p++)
     {
       Pixels[p]=CRGB::Blue;
     }
 }

Main Sketch:

 for (int p = 0; p < NUM_PATTERNS; p++)
    {
      // update pattern
      ledPatterns[p].Tick(millis());

      if (ledPatterns[p].Status == Enabled)
      {
        // sum the values of the pixels
        for (int l = 0; l < NUM_LEDS; l++) {
          leds[l] += ledPatterns[p].PixelAt(l);
        }
      }
    }

I'm skipping parts of the code to make it easier to read, but I think with this much you should be able to help me make it work. I'm still getting acquainted with C and pointers, which is where I think the problem lies.

So how should I declare and use **`Pixels[]`** so that the Main Sketch, the base class and the inherited class all have consistent information?

title: Pass custom element of an array from an inherited class to main sketch

Answers: 1

body:
After reading comments i got some more clues where to search and indeed the problem was somewhat in the inheritance and how i was calling the functions. This post helped me [find the problem][1].

I forgot to post the piece of code where i was creating the patterns in the Main Sketch, this is how it was initially:

    Pattern ledPatterns[NUM_PATTERNS];
    ledPatterns[0] = TestPattern(NUM_LEDS, "Test Pattern 1", TestPat, 0, 0);
    ledPatterns[1] = TestPattern(NUM_LEDS, "Test Pattern 2", TestPat, 0, 1);

    ...
    ledPatterns[p].Tick(millis());
    ...

When i later called `ledPatterns.Tick` (the function that modifies the values, the function actually being called was the parent and not the child. Thus the unexpected result.

This is how i should have been initializing the patterns, since they are inherited:

    Pattern* ledPatterns[NUM_PATTERNS];
    ledPatterns[0] = new TestPattern(NUM_LEDS, "Test Pattern 1", TestPat, 0, 0);
    ledPatterns[1] = new TestPattern(NUM_LEDS, "Test Pattern 2", TestPat, 0, 1);

    ...
    ledPatterns[p]->Tick(millis());
    ...

Sorry for the huge confusion, i thought the problem was in a completely different part of the code

  [1]: https://stackoverflow.com/questions/34681286/why-is-a-virtual-function-of-child-class-not-called


body:
In my project work, I have 3 robots with their own Arduino boards. Each robot has Infra Red Sensors, whose values I can read using its corresponding Arduino. The main thing however is that each robot must have every other Robots' values. Can anyone suggest me a suitable strategy? I tried using the Processing Software, using which I am able to read all the values from all the robots but sending them back to the robots is turning out to be a problem! It says ports are busy!
Any help would be great!

title: Multi Agent Systems

Answers: 0


body:
I'm trying to read a -10 to +10V analog signal on my Arduino Mega (2560). I've been using a voltage divider to obtain a -5V to +5V signal (with two 10kOhm resistors), which used to work just fine.
I'm wondering if this -5V signal can damage the Analog Input pins of the Mega ?

Thank you in advance for your time !

title: Analog read negative voltage inbuilt protection

Answers: 2

body:
All the IO pins contain a pair of clamping diodes to protect against over-voltage and negative-voltage situations:

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

As long as the current flowing through one of those diodes doesn't exceed its maximum forward current all will be well and the Arduino won't be damaged. If too much current flows then you will damage the pin.

Since you have 10KΩ resistors, at -5V the maximum current that could flow (assuming a 0.7V drop on the diode) would be (-5 + 0.7) / (10,000 / 2) = -860µA (negative because it's flowing backwards out of the pin from ground to your negative voltage source, not into the pin to ground).

Unfortunately the datasheet doesn't provide a current limit specification for those diodes, but I would expect such a small amount of current to be safe enough.

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

body:
Current through the clamping diodes shouldn't be more than 1mA according to Atmel's [Zero Cross Detection Application Note (AVR182)][1].

EDIT: As Edgar Bonet pointed out you have current about `(-5+0.5)/(10000/2) = 0.9mA` (tested) in the worst case, there is not much space for mistakes.

  [1]: http://www.atmel.com/images/doc2508.pdf


body:
I'm trying to read data from an Arduino Uno I2C slave via `Wire.requestFrom()` on an Arduino Uno master. The slave's onRequest handler is simply:
<!-- language-all: lang-cpp -->

    void I2C_Send()
    {

      byte myArray[4];

      myArray[0] = lowByte(acount);
      myArray[1] = highByte(acount);
      myArray[2] = lowByte(bcount);
      myArray[3] = highByte(bcount);

      Wire.write(myArray, 4);

    }

It seems to work fine for a few iterations, but eventually something happens and the master's `requestFrom()` call hangs indefinitely. What's causing this and how do I prevent it?

I've tried setting various levels of timeout with `Wire.setTimeout(x);` but that has no effect.

title: How to prevent Wire.requestFrom from hanging?

Answers: 0


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

title: Receive data from multiple wireless sensors simultaneously

Answers: 1

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.


body:
I'm working on a prototype which uses the RedBearLabs Blend Micro with the NSC's nrf8001 ble chip, but have ran into a problem that I'm not sure how to solve.

I have two tactile buttons connected to the input pins on the Blend Micro, which are used to increase or decrease counters (integers) in my sketch that is in turn displayed on a OLED screen. When I use these buttons to manipulate the counter in offline mode (meaning that the bluetooth is not connected) I can repeatedly press the buttons very quickly and the counter is increased with every push - but when I connect to my phone and try to push the buttons with high frequency (>1-2 per second) the program is not able to react to every button interaction, causing only every second or third click to be registered.

The only thing that I do differently when I am connected is that I'm sending 5 bytes using "ble_write" (part of the RBL nrf8001 library), which seem to cause this delay resulting in missed clicks. Even sending one byte using "ble_write(X)" seem to slow down the sketch so much that this phenomena occurs.

Do any of you had similar problems and possible ways to solve this? I've been considering batching clicks together until I reach a certain amount and then send them at all once - this however may risk that a button is being pressed at the same time as the ble_write is executed, causing missed click.

Offline click looks like this:

    if(digitalRead(A4)) {
    while (digitalRead(A4)) {        }
    offlineIn++;
    localIn++;
    totCount++;
    sleepTimer = 0;
      }

And the online like this:

    if (digitalRead(A4)) {
      while (digitalRead(A4)) {        }
      totCount++;
      localIn++;
      sleepTimer = 0;
      ble_write('0');
      ble_write('0');
      ble_write('0');
      ble_write('1');
      ble_write('1');
    }

Thanks!

title: ble_write slows down my sketch causing problems (Blend Micro & NRF8001)

Answers: 1

body: I've solved it by overclocking my blend micro to 16mhz (done in the Arduino IDE). Not a perfect solution but works. :)


body: I have two Arduino boards which I've attached XBee radio boards to. One is to send data via `Serial.write(num)`, where `num` is an integer. The other is receiving that integer via `Serial.read`. However, when I have both units running, nothing is ever received by the receiving unit. I've tried switching the receiving unit radio board to the USB mode so that I can use the serial monitor to send data to the unit. I've tried sending bytes `01111110`, as well as integers such as `77`. Nothing ever gets read from the serial monitor. I've downloaded XCTU, but it cannot find either of the radios. What can I do?

title: No connection with XBee radios on Arduino board

Answers: 0


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

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

Answers: 1

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.


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

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

Answers: 1

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.


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

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

Answers: 3

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!


body:
I downloaded the zip file of the FFT library from the below link

http://wiki.openmusiclabs.com/wiki/ArduinoFFT

and it now as I implement the example codes, it gives out a message which says
"Error compiling for Mega or Mega2560".
I have an Arduino Mega2560 and I want to know how to use this library for my board for frequency analysis of sound. Any help on this will be much appreciated.

title: Arduino FFT library - Open Music Labs installation help

Answers: 0


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

title: Arduino Mega 2560 + ESP8266 Problem with GET Request

Answers: 3

body:
Try changing:

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

    Serial2.write("AT+CWMODE=1\r\n");
to:

    Serial2.write("AT+CWMODE=2\r\n");
or:

    Serial2.write("AT+CWMODE=3\r\n");

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?


body:
A few days ago I encountered memory problems (SRAM shortage) on my Arduino. I've read a lot and fixed the problem, now I have around 900 bytes free in SRAM. However, I still have difficulties understanding and using `progmem`.

The user is allowed to create up to 10 programs (a program in my case is just some object storing the user's preferences). As I don't want to run out of SRAM, I planned to store them in `PROGMEM`.

Consider the following class:
<!-- language-all: lang-cpp -->

    #define MAX_PROGRAMS 10
    #define MAX_PREFS 10

    class Program
    {
      public:
        Program(String name, Preference* prefs[]); // ctor

        String getName();
        static byte getNoOfPrograms();
        static Program* getProgram(byte idx);

      private:
        const String _name;
        static int _programCtr;

        Preference* _preferences[MAX_PREFS];
        static Program* _programs[MAX_PROGRAMS];
    };

One notices that a program can store up to 10 preferences, hence, if the user decides to make 10 programs, each with 10 different preferences, we will definitely run out of SRAM.

**Therefore, can I store instances of the above `Program` class in PROGMEM if I define them as below?**

    const Program* const pgm PROGMEM = new Program(F("Test"), ...);
    // ...
    delete pgm;

*I presume this is possible since the whole object is `const` and could never be changed. I actually tried this and had no compiler errors, however, I was stumbled by the fact that the above two lines of code use 22 bytes of SRAM, when I expected it not to use any.*

In my case, **would it be better not to store the whole object in `progmem` but only its constant fields, and do the same for all constants in `Preference` ?** (i.e. change `const String _name` to `const char name[] PROGMEM;` etc.)

title: Writing objects to PROGMEM

Answers: 0


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

title: How to find gain for this device?

Answers: 1

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/).


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

Answers: 3

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


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

title: writing and uploading sketch as cpp file

Answers: 1

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


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

title: Results for GP2Y1010AU0F Dust Sensor

Answers: 1

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.


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

title: How to control MKR1000 from outside your local network

Answers: 2

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.


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

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

Answers: 3

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.


body:
I am working on a project and need alot of toggle buttons to control various things around the house. I connected 5 [MuxShield 2](http://mayhewlabs.com/products/mux-shield-2)'s to my Arduino Mega. The first two will serve as inputs and the last two will serve as outputs.
The problem is when I try to loop over all the outputs (connected to LED's for now) to turn them on/off, only the first 3 rows work as expected. The LED's turn on one by one, but when the loop reaches a row number which it has already looped over on another multiplexer the LED's turn on all at once.

I think it has something to do with the arrays in the MuxShield library being shared across all multiplexers and therefor breaking all signals the second time it gets used but I'm not sure.
It's not that much code but, too much to post here so I uploaded it to [GitHub](https://github.com/jochim-van-dijck/Arduino).

If someone could please look over it and point me in the right direction, I'd greatly appreciate it. Thanks.

title: Multiple MuxShield 2's connected to a single Arduino Mega

Answers: 0


body:
I connected all the pins as in datasheet, except `ch_pd`.
But when I connect `ch_pd` to 3.3 V , the red light on `esp8266` goes dim. I used 3.3 V, 250 mA power supply. What is the reason for this?

title: Esp8266 not working

Answers: 0


body:
I am having issues with interfacing my stepper motor, connected to a control board being [this one][1]

Due to some reason I am not able to move it, unless I remove the enable signal. I can change the direction either unless I manually change by either plug it or `unplug` it. If codewise change the state of the `dir_pin`,would the motor keep spinning in the same direction.

The control board need has a timing diagram, specifying when the `en`, and `dir` signal should be enabled.

[![Timing diagram of the controlboard][2]][2]

  [1]: http://www.sainsmart.com/zen/documents/20-019-201/ST330  Stepper Motor Driver Board User Manual.pdf
  [2]: https://i.stack.imgur.com/WC5TB.png

the code I am using to interface it is as below:

stepper_motor.cpp:

    #include "stepper_motor.h"

    stepper_motor::stepper_motor()
    {
      pinMode(BUILTIN_LED,OUTPUT);
      pinMode(step_pin,OUTPUT);
      pinMode(dir_pin,OUTPUT);
      pinMode(en_pin,OUTPUT);

      alive_bool = true;
      position_bool = false;
      step_count = 0;
    }

    void stepper_motor::alive()
    {
      if(alive_bool == true)
      {
        digitalWrite(BUILTIN_LED,HIGH);
        alive_bool = false;
        delay(2000);
      }
      else if(alive_bool == false)
      {
        digitalWrite(BUILTIN_LED,LOW);
        alive_bool = true;
        delay(2000);
      }
    }

    void stepper_motor::step_pwm()
    {

        digitalWrite(en_pin,HIGH);

        delay(0.005);

        digitalWrite(dir_pin,LOW);

        delay(0.005);

        while(1)
        {
          digitalWrite(step_pin,LOW);
          delay(1);
          digitalWrite(step_pin,HIGH);
          delay(1);
        }

    }

stepper_motor.h

    /* Class: stepper_motor
     * Info: contains the setup, and primary interface to control
     * the stepper motor
     *
     * stepper_motor(): constructor -  setup the connection to the control board
     * void step_pwm():  Moves the tilt - uses the bool to determine the direction.
     * bool alive_bool: Is either high (1) or low (0), used for the alive void.
     */

    #ifndef stepper_motor_h
    #define stepper_motor_h

    #include "Arduino.h"
    #include "pins_arduino.h"

    #define step_pin  D1
    #define dir_pin   D2
    #define en_pin    D3
    #define max_step  200

     class stepper_motor
    {
      public:
        stepper_motor();
        void alive();
        void step_pwm();
      private:
        bool alive_bool;
        bool position_bool;
        int step_count;
    };

    #endif

main:

    #include "stepper_motor.h"

    stepper_motor motor;
    int state = 0;
    void setup() {
      // put your setup code here, to run once:
    }

    void loop() {

          motor.step_pwm();
    }

The motor moves, so the step signal seem to be correct.
But enable and dir seem to incorrect, or are pretty sure that they are.

So what is wrong with those signal? do they not follow the required timing?

title: Interfacing a stepper motor with arduino

Answers: 0


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

title: How to Factory reset ESP8266?

Answers: 2

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


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

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

Answers: 2

body:
jumper reset -> ground and rx -> tx (with power disconnected)
connect power, open serial monitor in arduino ide and type anything in and input. if the serial monitor echoes what you typed in, then your connection is good and you should look elsewhere for problems.

Found this solution on the arduino.cc community site.

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


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

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

Answers: 3

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


body:
Using nano clone as an ISP on a breadboard- as shown here - http://www.martyncurrey.com/arduino-nano-as-an-isp-programmer/

Previously, it worked great.  However, recently, chips that I have bootloaded and programmed have, when added to the breadboard for reprogramming, caused the USB connection to drop.  The heartbeat LED on the nano also dims slightly which makes me wonder if it's a power issue?

Either way, this means that I can't program the chip.

Does anyone know how to fix this?  The breadboard circuit will happily program new chips.

The programs on the chips that aren't working often include blink on pin 19 on the DIP chip (D13) - and when I disconnect the link from this to D13 on nano, the USB connection is restored.

But otherwise I am very confused, have got about 7 chips with the same issue and would be great to fix it.

Ideas?  Thanks

title: Can't reprogram atmega328p chips using nano as ISP

Answers: 0


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

title: Serial communication with Python

Answers: 1

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)


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

title: Accelerometer fix values

Answers: 1

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


body:
I am having problems with I2C communications between my Dragino Yun and an Arduino UNO R3.

I can have the Dragino request data (using `Wire.onRequest` on UNO) from the UNO and it works great, however, when I have the UNO sending and the Dragino using `Wire.onReceive` it's not picking up any data!?

What are the SDA and SCL pins on the Dragino? Are they the same as the UNO? Are there any specific difficulties involved for this setup?

title: I2C between Yun Shield (Dragino) and UNO R3 problem

Answers: 0


body:
I created a few Arduino-XBee temperature sensor nodes that send data to another XBee node.js server. I'm running into a few issues trying to write a function to initiate a handshake and receive an identifier number to start sending data (so its scalable rather than hard-coded on each) while the receiver is already communicating with pre-established nodes.

The first issue I'm having is that the Arduino nodes do not seem to start from the beginning of their code when I unplug them and then reapply power. They already think they have their identifier number if another node is running, and I have to push the reset button on them to get them to run their code fresh and establish their own handshake ID. Is there anything I can put in the code or a way that I can easily modify the circuitry to make them actually reset and start fresh when they lose power?

The circuitry I'm using is a basic thermistor voltage-divider, XBee module, and 5V battery pack. Here's what I've got so far for the code on the Arduino side:

    #include <SoftwareSerial.h>
    #include <math.h>

    // Global variables
    int AnalogPin = A2; // has much less jumpy readings than A0 (maybe A0 slightly damage from overuse)
    float V_source = 4.90; // measured
    SoftwareSerial XBee(2,3); // RX, TX
    String identifier = "";
    int receivedID = 0;

    // Calculate thermistor voltage
    float Voltage(float RawADC) {
      float meter_calibration = 0; // don't seem to need, matches my multimeter exactly
      float V_therm = (V_source * RawADC) / 1024.0;
      V_therm += meter_calibration;
      return V_therm;
    }

    // Calculate thermistor resistance
    // sometimes a bit off what voltage divider eq says it should be (probably due to input impedance of ADC)
    float Thermistor(float V_therm) {
      float resistance_calibration = 25; // possibly small breadboard/wires resistance
      float R_known = 560 + resistance_calibration; // measured (1% tol resistor)
      float R_therm =  ((R_known * V_therm) / (V_source - V_therm));
      return R_therm;
    }

    // Base conversion
    float log2(float num) {
      return (log(num) / log(2));
    }

    // Calculate temperature
    float Temperature(float R_therm) {
      float A = 0.0164872;
      float B = -0.00158538;
      float C = 0.0000033813;
      float temp_K = 1 / (A + B*log2(R_therm) + C*pow(log2(R_therm),3));
      return temp_K;
    }

    // Convert to Celsius or Fahrenheit
    float ConvertTemp(float temp_K, char T) {
      if (T == 'C')
        return (temp_K - 273.15);
      else if (T == 'F')
        return (temp_K * 1.8 - 459.67);
    }

    // Setup
    void setup() {
      int idStart = 0;
      receivedID = 0;
      Serial.begin(9600);
      pinMode(AnalogPin, INPUT);
      XBee.begin(9600);
      for (int i=0; i<100; i++) {
        Serial.print("\n");
      }
      Serial.println("Broadcasting...");
    }

    // Main
    void loop() {
      delay(1000);

      // Initiate handshake
      if (identifier == "") {
          XBee.print("BROADCASTING"); // ascii text
          XBee.write("\n");  // binary data
      }
      delay(3000);

      // Receive buffer, check for and confirm ID
      if (XBee.available() && (identifier == "")) {
        String msg = "";
        char r = XBee.read();

    /*
        // Error checking for first-only numeric ID (testing)
        msg = msg + r;
        String intString = "";
        int intStart = 0;
        int i = 0;
        while (intStart != 2 && i < msg.length()) {
          if (intStart == 0) {
            if (isDigit(msg[i])) {
                  intString += msg[i];
                  intStart = 1;
               }
          }
          else if (intStart == 1) {
            if (isDigit(msg[i])) {
                  intString += msg[i];
                  intStart = 1;
               }
          }
          else if (!isDigit(msg[i])) {
            intStart = 2;
          }
          i++;
        }
        Serial.print("testing: ");
        Serial.println(intString);
        identifier = intString;
    */

        identifier = r;
      }

      // handshake established
      if ((identifier != "") && (receivedID == 0)) {
        Serial.println();
        Serial.print("RECEIVED IDENTIFIER: ");
        Serial.println(identifier);
        Serial.println();
        receivedID = 1;
      }

      // Calculate and send temperature along with identifier
      while (receivedID == 1) {
            // ADC and V_therm values
        /* Good to get two or more analog readings and discard the first or take the average
        apparently analog pins are multiplexed so this gives it time to settle */
        float RawADC_1 = analogRead(AnalogPin); // toss 1
        float RawADC_2 = analogRead(AnalogPin); // average 2,3
        float RawADC_3 = analogRead(AnalogPin);
        float RawADC_avg = (RawADC_2 + RawADC_3) / 2.00;
        Serial.print("Raw ADC value: ");
        Serial.println(RawADC_avg);
        float V_therm = Voltage(RawADC_avg);
        Serial.print("Voltage across thermistor: ");
        Serial.println(V_therm);

        // Thermistor resistance
        float R_therm = Thermistor(V_therm);
        Serial.print("Resistance of thermistor: ");
        Serial.println(R_therm);

        // Temperature in Kelvin, Celsius, Fahrenheit
        float temp_K = Temperature(R_therm);
        Serial.print(temp_K);
        Serial.print("K   ");
        float temp_C = ConvertTemp(temp_K, 'C');
        float temp_F = ConvertTemp(temp_K, 'F');
        Serial.print(temp_C);
        Serial.print("C   ");
        Serial.print(temp_F);
        Serial.println("F   ");

        // XBee
        String mytemp = String(temp_F);
        String msg = String(identifier + " " + mytemp);
        XBee.print(msg); // ascii text
        XBee.write("\n");  // binary data
        Serial.print("Message sent to XBee: ");
        Serial.println(msg);
        Serial.println();

        delay(2000);
      }

    }

title: Arduino code not starting at beginning after poweroff

Answers: 0


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

title: Interrupt and delay problems on Attiny 85

Answers: 1

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.


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

title: ATTiny85 I2C LCD

Answers: 3

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.