message:
How do you convert PCM to PWM?

I'm a beginner and I've been developing my own library for a wave player. so far I have the SD card installed and OLED and rotary encoder all connected. I've successfully read the wave chunk and it's data(16bit and 44.1KHz). My question is that the data in wave file is PCM and I wish to play is using 16bit PWM and so how do I convert PCM to PWM?

body:
There is no such thing as a PCM file. PCM is completely erroneously used to describe an uncompressed digital audio file. What it actually means is "A file which contains data that can be fed directly to a PCM device without any form of intermediate conversion".

What you have in a "PCM" WAV file is just raw sample data. After your header (usually 44 bytes) you just have 16-bit values representing your sample points, with the two channels interleaved one after the other.

Since PCM is a linear audio representation, the sample data it expects is a simple linear representation of the audio (unlike µLaw or A-law) and with no compression (such as MP3 or FLAC). And that is the exact same data that PWM expects since it too is a simple linear output.

However, none of that matters, because the Arduino simply isn't powerful enough to play your file. Maybe a smaller one (8kHz, mono, 8-bit) would be playable, but not yours. The numbers just don't add up.

There is a [PCMAudio](http://playground.arduino.cc/Code/PCMAudio) example available, but it only works from audio embedded within your program.

There is also a [TMRpcm](https://github.com/TMRh20/TMRpcm) library available which plays from SD card, but is limited to 8-bit mono, though it can supposedly do up to 32kHz sample rate (though I wouldn't want to try doing anything else at all at that rate).

You would be better off using a system more geared towards audio - something with an I2S CODEC chip attached would be the best solution.


sender: user

message:
Is it possible to program/flash ESP8266MOD(07) With Arduino UNO

i am new to ESp and yesterday i received my **ESP8266MOD**, i don't have FTDi connector with me right now(it's on the way).

**Is it possible to flash ESP with Arduino UNO?**

Regards,
Ben

sender: assistant

body:
I think it is possible. You can use the Arduino Uno 's Rx and Tx lines, but maybe you will need to have a voltage divider resistor arrangement to step down the 5V UART lines from the Uno to the 3.3V needed by the ESP, otherwise you risk damaging the ESP.

The basic approach to flash a ESP is described by several web sources and instructables, such this one [Getting started with the ESP8266 ESP-12](http://www.instructables.com/id/Getting-Started-with-the-ESP8266-ESP-12/) (there is also one section how to flash with an Arduino Uno).


body:
Yes you can.

Take a look at [this detailed guide](https://tttapa.github.io/Pages/Arduino/ESP8266/Flashing/Flashing-With-an-Arduino.html).

The most important thing to keep in mind is that you have to connect from the ATmega16U2's perspective, so you have to swap RX and TX:
[![enter image description here][1]][1]

You'll probably want some buttons to facilitate the flashing process:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/Rj6FV.png
  [2]: https://i.stack.imgur.com/mtLtN.png


message:
SdFat initialization blocks HC-SR04

I appreciate the help of this forum very much and it`s my first time to ask you experts befor driving crazy...

ArduinoUno and SDcard-BreakOutboard and DistanceSensor HC-SR04 are not working well together. The problem - as far as I found out - is in this statement:

    if (!sd.begin(sdChipSelect) || !file.open("DATALOG.TXT", O_CREAT | O_WRITE | O_APPEND)) {
    // Replace this with something for your app.
    Serial.println(F("SD problem"));
    //while(1);
    }

When it is erased the distance sensor works perfectly, if it is in place it shows 0 cm (and that for days! ;-) ). I read something that SdFat ist doing something with Pin10 but also putting it on OUTPUT - HIGH or LOW didn't do the trick. Any ideas?

Kind regards

Rob

The "minimal" code:

    /*
    SD card datalogger

    This example shows how to log data
    to an SD card using the SdFat library.

    The circuit:
    * analog sensors on analog ins 0, 1, and 2
    * SD card attached to SPI bus as follows:
    ** MOSI - pin 11
    ** MISO - pin 12
    ** CLK - pin 13
    ** CS - pin 7 (for MKRZero SD: SDCARD_SS_PIN)
    */
    #include <SdFat.h>
    const uint8_t sdChipSelect = 7;
    // SD file system.
    SdFat sd;
    // Log file.
    SdFile file;

    // Hook up HC-SR04 with Trig to Arduino Pin 9, Echo to Arduino pin 10
    // Maximum Distance is 400 cm
    unsigned long echo = 10;
    int ultraSoundSignal = 9; // Ultrasound signal pin
    unsigned long ultrasoundValue = 0;

    void setup() {
    // Serial Port
    Serial.begin(9600);
    // Pin 9 = TriggerPin
    pinMode(ultraSoundSignal,OUTPUT);

    // Initialize the SD and create or open the data file for append.
    if (!sd.begin(sdChipSelect) || !file.open("DATALOG.TXT", O_CREAT | O_WRITE | O_APPEND)) {
    // Replace this with somthing for your app.
    Serial.println(F("SD problem"));
    //while(1);
    }
    Serial.println("card initialized.");
    delay(1000);
    }

    void loop() {
    Serial.println("Beginn");
    // Distanzmessung mit HC-SR04
    int x = 0;
    x = ping();
    Serial.print(x); Serial.println(" cm");
    delay(1000); //delay 1/4 seconds.
    }

    unsigned long ping()
    {
      pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output
      digitalWrite(ultraSoundSignal, LOW); // Send low pulse
      delayMicroseconds(2); // Wait for 2 microseconds
      digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
      delayMicroseconds(5); // Wait for 5 microseconds
      digitalWrite(ultraSoundSignal, LOW); // Holdoff
      pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
      digitalWrite(ultraSoundSignal, HIGH); // Turn on pullup resistor
      // please note that pulseIn has a 1sec timeout, which may
      // not be desirable. Depending on your sensor specs, you
      // can likely bound the time like this -- marcmerlin
      // echo = pulseIn(ultraSoundSignal, HIGH, 38000)
      echo = pulseIn(ultraSoundSignal, HIGH,38000); //Listen for echo
      ultrasoundValue = (echo / 58.138);// * .39; //convert to CM then to         inches
      return ultrasoundValue;
    }

body:
Pin 10 is the SS pin for SPI. Since you are using SPI for the SD card pin 10 *must* be an output (for SPI to operate in master mode). Ideally you will use that pin as the SS (or CS, whatever you want to call it) for the SD card.

You can't use it as the echo input of an ultrasound range finder and use SPI.


message:
Measuring the speed of an object moving fast through air

I am new to arduino and am confused about how I would go about doing this: I want to attach a device to a small ball, that will move through the air at speed. The purpose of this device would be to determine the speed of this object as it moves through the air. My ball will always move in the same path because it will be shot out of a tennis ball shooter. My initial intuition would be to use an accelerometer to determine the acceleration at quarter second intervals and then multiply those values by a quarter of a second to obtain the change in speed and then add it to the sum of all the previous change in speed values (starting at 0).

Would this work? Is my reasoning correct? Are there any better solutions?

Thank You!

body:
You are proposing calculating velocity based on sampled acceleration.  Essentially taking the integral of the acceleration.  This is the first step in a process call [dead reckoning][1]. This is discussed in [this arduino.stackexchange.com answer][2].  In that answer there is a [link to a web page which implements dead reckoning using an Arduino][3]. You will find this equation on that web page:

    velocity(i) = velocity(i-1) + acceleration (i)

  [1]: https://en.wikipedia.org/wiki/Dead_reckoning
  [2]: https://arduino.stackexchange.com/questions/25529/detecting-distance-moved-by-accelerometer/25547#25547
  [3]: http://bluelemonlabs.blogspot.com/2013/07/blog-post.html


message:
DMX on the Arduino without additional driver chip

I recently saw [this video][1] where the creator controlled a DMX light via the Arduino. There he used the pins 3 and 4 for the data on the Arduino Duemilanove. As DMX library he used DmxSimple.

Based on my research DMX is RS-485 and for this there's a driver chip required.

So I have three questions about this:

1. Why do all sources I found say that there's a driver chip required when it seems to work without?

2. I got a Arduino Leonardo compatible device (Devduino). Is it possible to control DMX like stated above on this platform?

  [1]: https://www.youtube.com/watch?v=3Q4hLA7YM7c

body:
The physical layer of a DMX interface is based on [differential signaling][1] over an [RS485 link][2].  This is exactly what is said [here on the DMX Arduino.cc][3] page.

A differential signal (like RS485 or USB) can travel greater distances than signals which reference ground (like RS232, I2C or SPI).  This is because noise, which affect both sides of a differential signal, can be canceled out at the far end when one of the signals is inverted then added to the other by the differential receiver.

Connecting one side of a differential receiver to ground and driving the other side with logic level voltage is not recommended.  Even if it worked and did not cause harm to the transmitting processor nor the differential receiver the signal will likely be susceptible to undesirable noise.

RS485 is a ubiquitous standard and likely several easily sourced designs exist for the Arduino.

  [1]: https://en.wikipedia.org/wiki/Differential_signaling
  [2]: https://en.wikipedia.org/wiki/RS-485
  [3]: http://playground.arduino.cc/Learning/DMX


body:
It might be possible, actually. A differential signal **can** be produced via a standard Arduino, though there's still the 5V logic level to be concerned about. I am guessing that his lamp was capable of a 5V-swing signal (10V, all told), but this is not a guarantee, especially if the standard does not normally support this. In that sort of case, you trust that the manufacturer made the device sufficiently hardened/overengineered so that the higher voltages do not cause damage.

From watching the linked video, the signal wires are **both** attached to *GPIO pins* of the Arduino board. If one is pulled HIGH (5v) and the other LOW (Gnd), you produce a signal. The other differential signal is provided by swapping which pins are LOW and HIGH.

EDIT: That's a Duemilanove, NOT an Uno, so the outputs might be different. (Still, one of the newer 3v3 boards would probably be safer, if you are testing this). Further, if the wires are long enough, there might even be something of a voltage drop that makes it safe(er).

The end result then uses bit-banging to emulate a transceiver using this jury-rigged differential transmitter.


body:
RS485 or RS422 and consequently DMX use differential drivers at 5 volts.  This means that both lines are 0 to 5V nominally, with a (usually, depending on the cable used) 120 ohm resistor as a terminator on both ends.  A 3.3V signal might work, but barely.

perhaps sending the signal on one line and just 0V on the other might work sort-of, but I've never tried or even heard of that.

My guess would be that in this case they are using a bit-banged serial port modified to also control the other pin, but inverted.  Perhaps something could be done with a standard serial port on one pin, setting up an interrupt on that pin changing level, and using the ISR to check the level on the 'serial pin and invert it and set the other pin.  I think that would probably incur too much of a delay between the two pins, but perhaps not.  Strictly speaking, the delay between the two pins changing if it was bit-banged is probably out of spec for RS422/485, but might work anyway unless the baud rate was higher.

If you are going to use DMX, spend the $0.30 and buy a driver chip or a bit more and get a DMX shield.  I've seen DMX get screwed up by a whole lot less than the differential line being a bit out of sync.


message:
char array comparison

I'm having some issues dealing with strings in a small Arduino app.
I wonder why **this code works**:

    mqtt.setServer("192.168.1.42", port);

and this code doesn't:

    IPAddress ip = MDNS.queryHost(...);
    mqtt.setServer(ip.toString().c_str(), port);

Even when `strcmp` returns 0 when I compare both:

    strcmp(ip.toString().c_str(), "192.168.1.42"); // output = 0 => equality

I've also tried other alternatives, such as creating a `char` array, with no luck:

    String ipstr = ip.toString();
    char ipchar[ipstr.length() + 1];
    ipstr.toCharArray(ipchar, ipstr.length() + 1);

    mqtt.setServer(ipchar, port);

All alternatives compile, but the mqtt connection is never established later on. I must be missing something obvious because it works when I hardcode the "192.168.1.42" string.

body:
`PubSubClient::setServer(const char * domain, uint16_t port)` just saves the pointer, it doesn't copy the string (probably because it expects a static string literal).
([Source][1])
In your case, when `ip` goes out of scope, the pointer is no longer valid, so it won't work.

Just use the `PubSubClient::setServer(IPAddress ip, uint16_t port)` function instead.
([Source][2])

Always read the [API documentation][3], most libraries have one, even though it can be hard to find. The ReadMe and GitHub Wiki pages are a good place to start.
If that's insufficient (not uncommon for open source projects), read the [header files][4], which list all functions of the library.
If you still have doubts about what a function does, refer to the actual [implementation files][5].

  [1]: https://github.com/knolleary/pubsubclient/blob/f029640ee6365c58ebfe66ebf6bf1733d322f2ec/src/PubSubClient.cpp#L566
  [2]: https://github.com/knolleary/pubsubclient/blob/f029640ee6365c58ebfe66ebf6bf1733d322f2ec/src/PubSubClient.h#L118
  [3]: https://pubsubclient.knolleary.net/api.html#setserver
  [4]: https://github.com/knolleary/pubsubclient/blob/f029640ee6365c58ebfe66ebf6bf1733d322f2ec/src/PubSubClient.h
  [5]: https://github.com/knolleary/pubsubclient/blob/f029640ee6365c58ebfe66ebf6bf1733d322f2ec/src/PubSubClient.cpp


message:
How to drive SPI MAX7219 7-segment led module using MCP23S17 extender

I have used Nick Gammon's (MAX7219) and (bitBangedSPI) libraries to drive SPI 7-segment 8 digit led modules successfully from the Arduino Uno.  I would like to extend the number of Slave Select (CS) choices by using the MCP23S17 chip.  The Mcp23s17 libraries to use might be https://github.com/dreamcat4/Mcp23s17 or https://github.com/MajenkoLibraries/MCP23S17.  I have found the stackExchange entry https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino to be helpful and this entry to be helpful http://www.ermicro.com/blog/?p=1050, but all the examples just turn on LED lights, not digits of 7-segment led modules.

I realize I might have to modify the MAX7219 and bitBangedSPI libraries where the digitalWrite command is used.  However, I'm not sure how to modify or drive these 7-segement modules using the MCP23S17 chip.

A skeleton script to display PI selected on pin 6 on the Uno and address 0x0 of the MCP23S17 is shown below.  I would like to choose which pinout to utilize as well but am not sure how this would be coded.
[![enter image description here][1]][1]

    #include <SPI.h>
    #include <bitBangedSPI.h>
    #include <MAX7219.h>
    // Mcp23s17 library available from https://github.com/dreamcat4/Mcp23s17
    #include <Mcp23s17.h>

    // Wire up the SPI Interface common lines:
    // #define SPI_MOSI             7 //arduino   <->   SPI Master Out Slave In   -> SI  (Pin 13 on MCP23S17 DIP)
    // #define SPI_MISO   not used 12 //arduino   <->   SPI Master In Slave Out   -> SO  (Pin 14 on MCP23S17 DIP)
    // #define SPI_CLOCK            8 //arduino   <->   SPI Slave Clock Input     -> SCK (Pin 12 on MCP23S17 DIP)

    // Then choose any other free pin as the Slave Select (pin 10 if the default but doesn't have to be)
    #define MCP23S17_SLAVE_SELECT_PIN  6 //arduino   <->   SPI Slave Select           -> CS  (Pin 11 on MCP23S17 DIP)
    // MULTIPLE DEVICES
    // Up to 8 MCP23S17 devices can share the same SPI bus and slave select pins.
    // Assign each chip a unique 3-bit device address (by setting the A2,A1,A0 pins)
    // Then below, device address is optional 2nd parameter to the constructor fn...
    // MCP23S17 Mcp23s17_0 = MCP23S17(MCP23S17_SLAVE_SELECT_PIN,0x0);
    // ...
    // MCP23S17 Mcp23s17_7 = MCP23S17(MCP23S17_SLAVE_SELECT_PIN,0x7);

    // SINGLE DEVICE
    // Instantiate a single Mcp23s17 object
    MCP23S17 Mcp23s17_0 = MCP23S17(MCP23S17_SLAVE_SELECT_PIN,0x0);
    const byte chips = 1;
    static char outputBuffer[20]; // outputBuffer[] likely 2x the size it needs to be.

     // 1 chip, bit banged SPI on pins 6, 7, 8

    MAX7219 display(chips, 6, 7, 8);  // Chips / LOAD / DIN / CLK
    void setup()
    {
     // Set all pins to be outputs (by default they are all inputs)
     Mcp23s17_0.pinMode(OUTPUT);

     display.begin();
     display.setIntensity(1);
     float pi = PI;
     dtostrf(pi, 7, 7, outputBuffer);
     display.sendString(outputBuffer);

    }  // end of setup

    void loop() { }

An example of the 8-digit 7-segment display.  They are available on Amazon, Ebay, AliExpress etc. This one has 0.33 inch digits; other modules are 0.56 inch digits.

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

  [1]: https://i.stack.imgur.com/vzqGZ.jpg
  [2]: https://i.stack.imgur.com/hO8nC.jpg
  [3]: https://i.stack.imgur.com/4zU8L.jpg

body:
I'm not 100% on what you want to do but I have used both the chips you seem to want to do it with.

The MAX7219 can control 8 7Segment displays.
I don't remember it being an SPI device, you just set the pattern you want in the registers and off it goes.  (It could be that is used such a high level abstraction that I didn't realise it was SPI)

The IOX chip you are referring to is quite similar in behaviour, you setup the registers and away it goes.

On the surface it appears you can do what you want, but I suspect you will hit timing issues unless you want very static displays (maybe < 1FPS).  The time it takes you to establish the correct settings on the IOX chips will be the limiting factor.

You might want to look at the I2C version of the IOX which will require just 2 pins to connect to up to 7 ICs.

Alternatively use a network of microprocessors to each drive the maximum number of MAX7219s that they can, such as Nanos, ESP8266-12/NodeMCU, etc.


body:
The MAX7219 chip is designed to be daisy chained -- connect Dout to the Din of the next MAX7219 (see the No-op Register section in the [data sheet][1]). I'm not sure if there is a limit to the number that can be daisy chained.

In fact Nick Gammon's library appears to support this.  The "chips" parameter is the number of daisy chained MAX7219s.

The MAX7219 is does not use SPI. As I understand it the SPI/bitBangedSPI libraries are used as a convenient way to send the data bits with a synchronized clock.

  [1]: https://www.sparkfun.com/datasheets/Components/General/COM-09622-MAX7219-MAX7221.pdf


body: Just daisy chain the MAX7219s as already mentioned. I use SPI directly with the chip all time, it works great with the default modes - 4 MHz clock, Mode 0, MSBFIRST.  Many libraries use software SPI to talk to it, which I think is just a waste of the SPI hardware in the '328P family of chips.


message:
I want a code for 6 LDR/LED pair

Each LDR is connected to one LED because I am doing a parking lot model. I have tried but with no luck. Help!

        int ledPin = 11;
    int sensorInput = A0;

    boolean ledIsOn = false;

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

    void loop() {
      int lightLevel = analogRead(A0);

      if (ledIsOn) {
        if (lightLevel > 600) {
          ledIsOn = false;
        }
      } else {
        if (lightLevel < 400) {
          ledIsOn = true;
        }
      }

      digitalWrite(ledPin, ledIsOn);

      Serial.println(lightLevel);
    }

*this is the code for one LED to one LDR Sensor but I cannot make the 6 led to 6 ldr

and I did this code for 6 LDR

    #define pin_size 6
    const int pin[pin_size] = { A0, A1, A2, A3, A4, A5};

    void setup() {

      Serial.begin(9600);

    }

    void loop() {
      for (int i = 0 ; i < pin_size; i++) {
        Serial.print(analogRead(pin[i]));
        Serial.print(" - ");
        Serial.print(i);
        Serial.print("  |  ");

      }
      Serial.print("\n");
      delay(1000);

    }

body:
You need to convert all the regular variables to arrays. The loop through each index and run the the same as before for each index.

    const int pin_size 6
    int ledPins[] = {3, 4, 5, 6, 7, 8};
    int sensorPins[] = {A0, A1, A2, A3, A4, A5};
    boolean ledIsOn[] = {false, false, false, false, false, false};

    void setup() {
      for (int i = 0 ; i < pin_size; i++) {
        pinMode(ledPins[i], OUTPUT);
      }
      Serial.begin(9600);
    }

    void loop() {
      for (int i = 0 ; i < pin_size; i++) {
        int lightLevel = analogRead(sensorPins[i]);

        if (ledIsOn[i]) {
          if (lightLevel > 600) {
            ledIsOn[i] = false;
          }
        } else {
          if (lightLevel < 400) {
            ledIsOn[i] = true;
          }
        }

        digitalWrite(ledPins[i], ledIsOn[i]);

        Serial.println(lightLevel);
      }
    }


message:
Timer2 Compare Interrupt not working as expected

To get this out of the way first: I have already looked at ["Timer2 does not work as it should"](https://arduino.stackexchange.com/questions/830/timer2-does-not-work-as-it-should) and ["Timer2 “Clear OC2B on Compare Match” not working as expected in CTC mode"](https://arduino.stackexchange.com/questions/30507/timer2-clear-oc2b-on-compare-match-not-working-as-expected-in-ctc-mode) but have not found the answers there very useful.

Now on to my problem:

I'm trying to use the Timer2 in CTC mode to have an interrupt every 500us. For this, I have the following code:

    #include "TimerTwo.h"

    TimerTwo Timer2;

    ISR(TIMER2_COMPA_vect) { //ISR on Compare Match A
      Timer2.isrCallback();
    }

    void TimerTwo::initialize() {
      cli();
      TCCR2A = 0;// set entire TCCR2A register to 0
      TCCR2B = 0;// same for TCCR2B
      TCNT2  = 0;//initialize counter value to 0

      // set compare match register for 2khz increments
      OCR2A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)

      // turn on CTC mode
      TCCR2A |= _BV(WGM21);

      // Set CS22 bit for 64 prescaler
      TCCR2B |=  _BV(CS22);

      // enable timer compare interrupt
      TIMSK2 |= _BV(OCIE2A);
      sei();
    }

    void TimerTwo::attachInterrupt(void (*isr)()) {
      TIMSK2 |= _BV(OCIE2A);
      isrCallback = isr;
    }

    void TimerTwo::detachInterrupt() {
      TIMSK2 &= ~_BV(OCIE2A);
      isrCallback = nullptr;
    }

and

    #ifndef TIMERTWO_H
    #define TIMERTWO_H

    #include <Arduino.h>

    class TimerTwo
    {
      public: //methods
        void initialize();
        void attachInterrupt(void (*isr)());
        void detachInterrupt();
        void (*isrCallback)();
    };

    extern TimerTwo Timer2;

    #endif

It was inspired by the TimerOne library.

However, when I measure the period at the output pin (which I have attached inside some other code) I only get a period of 1ms. Even if I set `ORC2A` to 63, this fact doesn't change.

I have the constructor of this called inside my `setup()` so the registers should not be overwritten by the wiring.c.

I have also looked at the [datasheet of the ATmega328p](http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf#G1.1920802) and checked that all registers are set correctly.

Thanks in advance for your help. If you need any further information, let me know.

body:
So you're right that CTC is acting weird. I've noticed this few years ago too on different board, but I've always suspected asychronous mode (I've added 32k RTC Xtal on Arduino Mega).

However Fast PWM mode with `OCR2A` as a `TOP` value seems to be working:

    class TimerTwo
    {
      public: //methods
        void initialize();
        void attachInterrupt(void (*isr)());
        void detachInterrupt();
        void (*isrCallback)() = nullptr;
    };

    TimerTwo Timer2;

    ISR(TIMER2_COMPA_vect) { //ISR on Compare Match A
      Timer2.isrCallback();
    }

    void TimerTwo::initialize() {
      cli();

      OCR2A = 124;                        // = (16*10^6) / (2000*64) - 1 (must be <256)
      TCCR2A = _BV(WGM21) | _BV(WGM20);   // turn on fast PWM mode with top in OCR2A
      TCCR2B = _BV(WGM22) | _BV(CS22);    // Set CS22 bit for 64 prescaler
      TCNT2  = 0;                         // initialize counter value to 0

      sei();
    }

    void TimerTwo::attachInterrupt(void (*isr)()) {
      isrCallback = isr;
      TIMSK2 |= _BV(OCIE2A);
    }

    void TimerTwo::detachInterrupt() {
      TIMSK2 &= ~_BV(OCIE2A);
      isrCallback = nullptr;
    }

    volatile uint32_t counter = 0;
    void isrHandler() {
      ++counter;
    }

    void setup() {
      Serial.begin(115200);
      Timer2.initialize();
      Timer2.attachInterrupt(&isrHandler);
    }

    void loop() {
        static uint32_t counter_old = 0;
        Serial.println(counter - counter_old);
        counter_old = counter;
        delay(500);
    }

EDIT: Ok, so after some digging on [this issue][1] I've found that setting CTC mode might cause OCR2A corruption (I guess?) . It seems to be working if you reorder the settings to:

      TCCR2B = 0;          // stop the timer and reset WGM22
      TCCR2A = _BV(WGM21); // turn on CTC mode with top in OCR2A
      OCR2A  = 124;        // = (16*10^6) / (2000*64) - 1 (must be <256)
      TCNT2  = 0;          //initialize counter value to 0
      TCCR2B = _BV(CS22);  // Set CS22 bit for 64 prescaler (for starting the timer)

  [1]: https://www.avrfreaks.net/forum/issue-timer2-ctc-mode-arduino-uno-board


message:
Arduino Modbus RTU VFD control

I need help with this code:

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

    /**
    *  Modbus master example 1:
    *  The purpose of this example is to query an array of data
    *  from an external Modbus slave device.
    *  The link media can be USB or RS232.
    *
    *  Recommended Modbus slave:
    *  diagslave http://www.modbusdriver.com/diagslave.html
    *
    *  In a Linux box, run
    *  "./diagslave /dev/ttyUSB0 -b 19200 -d 8 -s 1 -p none -m rtu -a 1"
    * This is:
    * serial port /dev/ttyUSB0 at 19200 baud 8N1
    * RTU mode and address @1
    */

    #include <ModbusRtu.h>

    // data array for modbus network sharing
    uint16_t au16data[16];
    uint8_t u8state;

    /**
    *  Modbus object declaration
    *  u8id : node id = 0 for master, = 1..247 for slave
    *  u8serno : serial port (use 0 for Serial)
    *  u8txenpin : 0 for RS-232 and USB-FTDI
    *               or any pin number > 1 for RS-485
    */
    Modbus master(0,0,2); // this is master and RS-232 or USB-FTDI, PIN 9 PARA INDICAR QUE TRASMITO

    /**
    * This is an structe which contains a query to an slave device
    */
    modbus_t telegram;

    unsigned long u32wait;

    void setup() {
     master.begin( 9600 ); // baud-rate at 19200
     master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
     u32wait = millis() + 1000;
     u8state = 0;
    }

    void loop() {
     switch( u8state ) {
     case 0:
       if (millis() > u32wait) u8state++; // wait state
       break;
     case 1:
       telegram.u8id = 1; // slave address
       telegram.u8fct = 5; // function code (this one is registers read)
       telegram.u16RegAdd = 0; // start address in slave
       telegram.u16CoilsNo = 2; // number of elements (coils or registers) to read
       //telegram.au16reg = au16data; // pointer to a memory array in the Arduino

       // PARA EL VARIADOR OMRON MX1: MODBUS RTU 01 05 00 00 FF 00 -> START
       // 01 -> SLAVE (VFD OMRON)
       // 05 -> WRITE COIL
       //  00 00 -> ADDRESS COIL
       // FF 00 -> VALUES TO WRITE IN COIL FOR RUN

       telegram.au16reg[0] = 0;
       telegram.au16reg[1] = 0;
       telegram.au16reg[2] = 0;
       telegram.au16reg[3] = 0;
       telegram.au16reg[4] = 0;
       telegram.au16reg[5] = 0;
       telegram.au16reg[6] = 0;
       telegram.au16reg[7] = 0;

       telegram.au16reg[8] = 1;
       telegram.au16reg[9] = 1;
       telegram.au16reg[10] = 1;
       telegram.au16reg[11] = 1;
       telegram.au16reg[12] = 1;
       telegram.au16reg[13] = 1;
       telegram.au16reg[14] = 1;
       telegram.au16reg[15] = 1;

       master.query( telegram ); // send query (only once)
       delay(3500);

       telegram.u8id = 1; // slave address
       telegram.u8fct = 6; // function code (this one is registers read)
       telegram.u16RegAdd = 1; // start address in slave
       telegram.u16CoilsNo = 4; // number of elements (coils or registers) to read
       //telegram.au16reg = au16data; // pointer to a memory array in the Arduino
       //telegram.au16reg = 0000000111110100;

       // PARA EL VARIADOR OMRON MX1: MODBUS RTU 01 06 00 01 01 F4 -> CHANGE FQ
       // 01 -> SLAVE (VFD OMRON)
       // 06 -> WRITE IN REGISTE
       // 00 01 -> REGISTER ADDRESS
       // 01 F4 -> VALUE TO WRITE IN THE REGISTER TO CHANGE THE MOTOR FREQUENCY

       telegram.au16reg[0] = 0;
       telegram.au16reg[1] = 0;
       telegram.au16reg[2] = 0;
       telegram.au16reg[3] = 0;
       telegram.au16reg[4] = 0;
       telegram.au16reg[5] = 0;
       telegram.au16reg[6] = 0;
       telegram.au16reg[7] = 1;

       telegram.au16reg[8] = 1;
       telegram.au16reg[9] = 1;
       telegram.au16reg[10] = 1;
       telegram.au16reg[11] = 1;
       telegram.au16reg[12] = 0;
       telegram.au16reg[13] = 1;
       telegram.au16reg[14] = 0;
       telegram.au16reg[15] = 0;

       master.query( telegram ); // send query (only once)
       delay(3500);
       telegram.u8id = 1; // slave address
       telegram.u8fct = 5; // function code (this one is registers read)
       telegram.u16RegAdd = 1; // start address in slave
       telegram.u16CoilsNo = 2; // number of elements (coils or registers) to read
       //telegram.au16reg = au16data; // pointer to a memory array in the Arduino

       // PARA EL VARIADOR OMRON MX1: MODBUS RTU 01 05 00 00 00 00 -> STOP
       // 01 -> ESCLAVO (VARIADOR OMRON)
       // 05 -> ESCRIBIR EN UNA BOBINA
       // 00 00 -> DIRECCION DE LA BOBINA
       // 00 00 -> VALOR A ESCRIBIR EN LA BOBINA PARA STOP

       telegram.au16reg[0] = 0;
       telegram.au16reg[1] = 0;
       telegram.au16reg[2] = 0;
       telegram.au16reg[3] = 0;
       telegram.au16reg[4] = 0;
       telegram.au16reg[5] = 0;
       telegram.au16reg[6] = 0;
       telegram.au16reg[7] = 0;
       telegram.au16reg[8] = 0;
       telegram.au16reg[9] = 0;
       telegram.au16reg[10] = 0;
       telegram.au16reg[11] = 0;
       telegram.au16reg[12] = 0;
       telegram.au16reg[13] = 0;
       telegram.au16reg[14] = 0;
       telegram.au16reg[15] = 0;
       master.query( telegram ); // send query (only once)
       delay(3500);
       u8state++;
       break;
     case 2:
       master.poll(); // check incoming messages
       if (master.getState() == COM_IDLE) {
         u8state = 0;
         u32wait = millis() + 100;
       }
       break;
     }
    }

I've managed to send RUN command to VFD but i can't (so far) send the change frequency command "01 06 00 01 01 F4" + CRC check.

When I connect logic analyzer with modbus rtu decoder, it shows "Device ID:'1' Function Write single coil ('5') Addr: '0' value: '65280' Chksum: '14988'.

The problem is that it pass only 1 telegram (array of packets) for command "RUN" but no the two others. Any help will be appreciated.

This is the link for VFD Omron MX: https://industrial.omron.us/en/media/I570-E2-02B_3G3MX2_UsersManual_tcm849-112721.pdf

TIA

body:
You should update the comments and remove unused settings like the count fields for request with one value (function 5 and 6).

au16reg are the data to be send. ignore the binary format from the example.

To send a value of the coil or register set the value to telegram.au16reg[0].

For the Modbus message protocol see for example [the Wikipedia article][1].

  [1]: https://en.wikipedia.org/wiki/Modbus#Supported_function_codes


message:
Using Teensy 3.5 (Arduino) to produce USB and Hardware MIDI messages simultaneously. Help?

Currently trying to get a teensy 3.5 to spam a series of notes in a loop over USB and hardware serial, which I am pretty sure it can do.

I have a MIDI circuit set up as per the specifications here:
https://www.pjrc.com/teensy/td_libs_MIDI.html
And currently have it booping a looping grouping of notes through massive embedded in ableton over a 5 PIN DIN circuit feeding into a generic MIDI 5 Pin DIN -> USB converter.

     #include <MIDI.h>

    #define HWSerial Serial1
    MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
    const int channel = 1;

    void setup() {

      HWSerial.begin(9600);
      MIDI.begin();
    }

    void loop() {
      int note;
      for (note=10; note <= 127; note++) {
        MIDI.sendNoteOn(note, 100, channel);
        delay(200);
        MIDI.sendNoteOff(note, 100, channel);
      }
      delay(2000);
    }

I am lead to believe that when working with the USB serial output on the teensy you simply refer to the port as 'Serial' and for the others it's 'Serial1', 'Serial2', and so on.

I have tried using serial in place of the arguments within MIDI_CREATE_INSTANCE
and also tried using MIDI_CREATE_DEFAULT_INSTANCE which should do this setup on the default serial port, which I assume is USB? (This worked fine on my arduino mega setup where I was using the 16u2 chip as a serial -> USB midi converter as per this method: https://github.com/ddiakopoulos/hiduino)

I'm just a little stumped as I have managed to get the code to compile using default instance and it appears as a midi device in windows device manager and also in ableton when I set USB Type: Serial + MIDI from arduinos tools dropdown box but does not output any notes :(

Can anyone help me get this working?

I'm currently toying with:

        #include <MIDI.h>

    const int channel = 1;

    void setup()
    {

    }

    void loop()
    {
      int note;
      for (note=20; note <= 63; note++) // Range was changed from 10:127 to save eardrums.
      {
        usbMIDI.sendNoteOn(note, 100, channel);
        delay(200);
        usbMIDI.sendNoteOff(note, 100, channel);
      }
      delay(2000);
    }

but get

        C:\Users\Jamie\AppData\Local\Temp\arduino_build_144363/..\arduino_cache_283435\core\core_teensy_avr_teensy35_usb_serialmidi,speed_120,opt_o2std,keys_en-us_4939f5412a75a8560acb0f9e98268f02.a(pins_teensy.c.o): In function `_init_Teensyduino_internal_':

    C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3/pins_teensy.c:582: undefined reference to `analog_init'

    collect2.exe: error: ld returned 1 exit status

    Error compiling for board Teensy 3.5.

and if I try inluding 'usbMIDI' I get

    F:\GigaTech\MMMM_Beta_Code\debug\TeensyUSBMIDILoopTest\TeensyUSBMIDILoopTest.ino:1:21: fatal error: usbMIDI.h: No such file or directory

    compilation terminated.

    Error compiling for board Teensy 3.5.

although midiUSB is definitely installed :S

----------------------------------------------------------------------------
------------------------------C O N T I N U E D ----------------------------
----------------------------------------------------------------------------

Ok so I now have a working sketch for both USB and Hardware MIDI comms but I can't seem to get them to work simultaneously.
My code for the hardware is as shown above, and the USB method is below:

     #include <MIDI.h>

    MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
    const int channel = 1;

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

    void loop() {
      int note;
      for (note=10; note <= 127; note++)
      {
        usbMIDI.sendNoteOn(note, 100, channel);
        delay(200);
        usbMIDI.sendNoteOff(note, 100, channel);
      }
      delay(2000);
    }

I sort of assumed it would be possible to do something like this:

     #include <MIDI.h>

    #define HWSerial Serial1
    MIDI_CREATE_INSTANCE(HardwareSerial, Serial, MIDI); // 5 Pin DIN Out
    const int channel = 1;

    void setup()
    {
      HWSerial.begin(9600);
      MIDI.begin();
    }

    void loop() {
      int note;
      for (note=20; note <= 63; note++) // Range was changed from 10:127 to save eardrums.
      {
        usbMIDI.sendNoteOn(note, 100, channel);
        MIDI.sendNoteOn(note, 100, channel);
        delay(200);
        usbMIDI.sendNoteOff(note, 100, channel);
        MIDI.sendNoteOff(note, 100, channel);
      }
      delay(2000);
    }

But It doesn't seem to work.
The code compiles and uploads just fine, however, ableton only sees MIDI messages coming over the teensy usb port and not through my MIDI receiver.
I wondered if this is because the two are both being routed to my PC via a usb port but this shouldn't be a problem surely.
I have also tried assigning the USB and hardware MIDI sends to different channels but to no avail.

I would love to get these both working simultaneously.

body:
Just use [usbMidi][1].

    #include <MIDI.h>

    MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
    const int channel = 1;

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

    void loop() {
      int note;
      for (note=10; note <= 127; note++) {
        MIDI.sendNoteOn(note, 100, channel);
        usbMIDI.sendNoteOn(note, 100, channel);
        delay(200);
        MIDI.sendNoteOff(note, 100, channel);
        usbMIDI.sendNoteOff(note, 100, channel);
      }
      delay(2000);
    }

  [1]: https://www.pjrc.com/teensy/td_midi.html


body:
So I managed to get both working sumultaneously!

It seems that no declaration of a MIDI instance is necessary for teensy MIDI over USB, and I had a small error in my code, Said function declaration should read 'Serial1' not 'Serial'.

Working code is below! :)

    #include <MIDI.h>

    #define HWSerial Serial1
    MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI); // 5 Pin DIN Out
    const int HWChannel = 2;
    const int USBChannel = 1;

    void setup()
    {
      HWSerial.begin(9600);
      MIDI.begin();
    }

    void loop() {
      int note;
      for (note=20; note <= 63; note++) // Range was changed from 10:127 to save eardrums.
      {
        usbMIDI.sendNoteOn(note, 100, USBChannel);
        MIDI.sendNoteOn(note, 100, HWChannel);
        delay(200);
        usbMIDI.sendNoteOff(note, 100, USBChannel);
        MIDI.sendNoteOff(note, 100, HWChannel);
      }
      delay(2000);
    }


message:
Digital selection for gain control not working instead showing 0

I am making a device which will have a button to measure the input and another button to reset and the inputs are variable analog values(0 to 5v) and output is a ratio of two analog input voltages. It also has a selection keys(two buttons) for four selections(like gain eg. if key1 == LOW key 2 == LOW then J = 1 and likewise)
but the problem is when i am multiplying j with it the output shows zero if I multiply numbers like 1,2,3etc without using j then the ratio value gets multiplied.

here is the code

        void setup() // put your setup code here, to run once:
        {
          Serial.begin(9600);
          pinMode( K1, INPUT );
          pinMode( K2, INPUT );
          pinMode( MeasureButton, INPUT );
          pinMode( ResetButton, INPUT );
          dsp.begin(20, 4);
          current = millis();
        }

        void loop()
        {

          while(current < wait)
          {
          Serial.println("INITIALIZING");
          delay(1000);
          current = millis();
          }
          Serial.println("                   ");
          delay(1000);
          Serial.println(" READY TO MEASURE ");
          delay(2000);
          while (digitalRead(MeasureButton) == LOW)
          {
            if(K1 == LOW && K2 == LOW)
            {J = 1; // SOMETHING VALUE
            showMessage1();
            i = 0;
            delay(1000);
            }if(K1 == LOW && K2 == HIGH)
            J= 2; // SOMETHING VALUE
            showMessage1();
            i = 0;
            delay(1000);
            if(K1 == HIGH && K2 == LOW )
            J= 3; // SOMETHING VALUE
            showMessage1();
            i = 0;
            delay(1000);
            if(K1 == HIGH && K2 == HIGH )
            J= 4; // SOMETHING VALUE
            showMessage1();
            i = 0;
            delay(1000);

          }
          while (digitalRead(ResetButton) == HIGH)
          {
          dsp.setCursor(1,0);
          dsp.print("                   ");
          Serial.println("                   ");
          delay(1000);
          dsp.setCursor(1,0);
          dsp.print("RESETED");
          Serial.println("RESETED");
          delay(1000);
          }
    while (digitalRead(ResetButton) == LOW)
          {
          dsp.setCursor(1,0);
          dsp.print("                   ");
          Serial.println("                   ");
          delay(1000);
          dsp.setCursor(1,0);
          dsp.print("PRESS MEASURE");
          Serial.println("PRESS MEASURE");
          delay(1000);
          }
        }

        void showMessage1()
        {
           while(i<5)
            {
            A = analogRead(A0);
            B = analogRead(A1);
            C = analogRead(A2);
            D = analogRead(A3);
            N = analogRead(A4);
            W1 = (A/N)*J;        // J is another variable whose value is dependent on K selection values
            W2 = (B/N)*J;        // J is another variable whose value is dependent on K selection values
            W3 = (C/N)*J;        // J is another variable whose value is dependent on K selection values
            W4 = (D/A)*J;        // J is another variable whose value is dependent on K selection values

            sumW1 = sumW1 + W1;
            sumW2 = sumW2 + W2;
            sumW3 = sumW3 + W3;
            sumW4 = sumW4 + W4;
            i++;
          }
            Serial.print("W1-");
            Serial.print(sumW1);
            Serial.print("W2-");
            Serial.println(sumW2);
            Serial.print("W3-");
            Serial.print(sumW2);
            Serial.print("W4-");
            Serial.println(sumW4);
            sumW1 = 0;
            sumW2 = 0;
            sumW3 = 0;
            sumW4 = 0;
        }

body:
      pinMode( K1, INPUT );

with

        if(K1 == LOW && K2 == LOW)

makes no sense. `K1` is a pin number. `LOW` is a macro for `0` (`HIGH` for `1`). You are comparing a static pin number against a static number.

If `K1` is not equal to 0, the inner part of that if statement can never be reached.

What you meant to do was "if the voltage at the pin K1 is low". For that you need to read out the current value of the pin and check it.

For that you must replace your `if(K1 == LOW)` type statements to `if( digitalRead(K1) == LOW)`.

I'd also like to mention that you must have a pull-up on your buttons for this "LOW"/"HIGH" logic to work. Either externally, or use `INPUT_PULLUP` instead of `INPUT` in `pinMode`.


message:
Why the LED freezes? when I am adding a delay?

I am new into arduino and stuff. So i was playing around with the pull up resistor. It worked fine but the problem rised when I used a delay to turn the led on for few seconds before it gets back to low state it stopped working when I pressed the switch multiple times it may work sometimes but maximum time it is not working

***here is the code***

    const int buttonPin = 4;
    const int ledPin =  12;
    int buttonState = 0;

    void setup() {
          pinMode(ledPin, OUTPUT);
          pinMode(buttonPin, INPUT_PULLUP);
    }

    void loop() {
            buttonState = digitalRead(buttonPin);
          if (buttonState == LOW)
      {
        digitalWrite(ledPin, HIGH);
        delay(5000);
      } else
      {
        digitalWrite(ledPin, LOW);
        delay(5000);
      }
    }

body:
Your Arduino does nothing during the delay(5000). So pressing the button during the 5000 mSec that the led is off won't do anything. Or you must be very lucky to press the button in the very small time between one loop and the next.

I learned a lot about timing and delays with this tutorial: [Blink Without Delay][1]

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


message:
Will analog servo work with Arduino servo library?

I ordered some cheap servos from Amazon before I noticed that there seemed to be two different kinds (digital & analog).

Mine are Tower Pro SG90 Analog ([http://www.towerpro.com.tw/product/sg90-analog/][1])

I was trying to get mine to work with an extremely simple sample code (below) using the Arduino Servo library (using digital pin 3) and I was experiencing the jitters.

I read over the solutions at : [https://electronics.stackexchange.com/questions/77502/is-there-a-way-to-stop-servos-from-shaking][2]

While reading that I learned that there is also a *digital* flavor of the servo:
[http://www.towerpro.com.tw/product/sg90-7/][3]

I'm wondering if that is part of the problem I'm seeing with the servo jittering.  I haven't seen this addressed elsewhere.

**My questions are:**

 1. Are those servos even different? Maybe that is just a marketing
    thing??
 2. Do I need to switch to using an analog pin for the servo data
        connection?
 3. Is it even possible to use the Arduino Servo library for this
    purpose or do I need to use some *manual* code (like analogWrite()) **and** move the servo to an analog pin?
 4. Or, should it work completely fine and the jittering is just some
    unrelated problem?

Here's the simple code I'm using:

    #include <Servo.h>
    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 0;    // variable to store the servo position

    void setup() {
      myservo.attach(3);  // attaches the servo on pin 3 to the servo object
    }

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

  [1]: http://www.towerpro.com.tw/product/sg90-analog/
  [2]: https://electronics.stackexchange.com/questions/77502/is-there-a-way-to-stop-servos-from-shaking
  [3]: http://www.towerpro.com.tw/product/sg90-7/

body:
Jitter can be caused by a lack of power, in which case it will be an irregular pattern that leaves the servo in the wrong place or it can be caused by the increment commands not being sent to the servo smoothly enough.

Have you got enough power for the servo? Where is the power coming from, does this output match the datasheet?

This analog servo requires PWM, so is pin 3 of you board PWM capable?

How fast does you servo rotate?  At the moment you are saying 1degree every 15ms, I suspect that is too slow and that's why the arm is coming to a stop and then rotating again which is making it jitter.


body:
There's a [discussion here][1] about the difference. The short answer is they both are commanded by a PWM signal but differ in the internal control circuitry that responds to it.

  [1]: https://www.rcgroups.com/forums/showthread.php?498802-Help-on-digial-servos&highlight=digital servo


message:
What's wrong with this code?

//Error message Arduino: 1.8.5 (Windows 10), Placa:"Arduino/Genuino Uno"

    Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

    (.text+0x0): multiple definition of `__vector_7'

    libraries\IRremote\IRremote.cpp.o (symbol from plugin):(.text+0x0): first defined here

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Erro ao compilar para a placa Arduino/Genuino Uno.

    Este relatório teria mais informação com a
    opção «Mostrar mensagens detalhadas durante a
    compilação» seleccionada nas Preferências.
    //

Code

    #include <IRremote.h>      //must copy IRremote library to arduino libraries
    #include <Servo.h>
    #define plus 0xFD10EF   //clockwise rotation button
    #define minus 0xFD50AF  //counter clockwise rotation button

    int RECV_PIN = 2;       //IR receiver pin
    Servo servo;
    int val;                //rotation angle
    bool cwRotation, ccwRotation;  //the states of rotation

    IRrecv irrecv(RECV_PIN);

    decode_results results;

    const int pinoledlar=10;
    int portaled4 = 12;
    int portaled3 = 8;
    int portaled2 = 11;
    #define pinopir 3
    int acionamento;
    const int sirene=7;
    int portaLDR = A5; //Porta analógica utilizada pelo LDR

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
      servo.attach(9);     //servo pin
      pinMode(pinoledlar,OUTPUT);
      pinMode(portaled2, OUTPUT);
      pinMode(portaled3, OUTPUT);
      pinMode(portaled4, OUTPUT);
      pinMode(pinopir,INPUT);
      pinMode(sirene,OUTPUT);
    }

    void loop()
    {
        acionamento=digitalRead(pinopir);
        if (irrecv.decode(&results))
        {
        Serial.println(results.value, HEX);
        irrecv.resume(); // Receive the next value

        if (results.value == plus)
        {
          cwRotation = !cwRotation;      //toggle the rotation value
          ccwRotation = false;         //no rotation in this direction
        }

        if (results.value == minus)
        {
          ccwRotation = !ccwRotation;   //toggle the rotation value
          cwRotation = false;            //no rotation in this direction
        }
        }
        if (cwRotation && (val != 175))
        {
        val++;                         //for colockwise button
        }
        if (ccwRotation && (val != 0))
        {
        val--;                         //for counter colockwise button
        }
        servo.write(val);
        delay(20);          //General speed

        if (acionamento==HIGH)//se detetar movimento
        {
        digitalWrite(pinoledlar,LOW);
        tone(sirene,440,1000);
        delay(1500);
        }
        else// senão detetar movimento
        {
        digitalWrite(pinoledlar,HIGH);
        noTone(sirene);
        delay(1500);

        int estado = analogRead(portaLDR);  //Lê o valor fornecido pelo LDR

        // Caso o valor lido na porta analógica seja maior do que
        // 800, acende o LED
        // Ajuste o valor abaixo de acordo com o seu circuito
        if (estado > 900)
        {
        digitalWrite(portaled2, HIGH);
        digitalWrite(portaled3, HIGH);
        digitalWrite(portaled4, HIGH);
        }
        else  //Caso contrário, apaga o led
        {
        digitalWrite(portaled2, LOW);
        digitalWrite(portaled3, LOW);
        digitalWrite(portaled4, LOW);
        }
    }
    }

body: You have a very common problem that is documented all over. You have two libraries, Servo and IRremote, that are both trying to use the same hardware timer. Do a little Google searching for possible fixes. You will need to either find a different Servo library or a different IRremote library.


message:
Using a channel relay

im using 4 channel relay to switch the motor pump.  but when the arduino output is high and i check first with led. the led behavior were high too but when i attached to the relay input IN1,  the relay were low.  its like reversed action(the arduino is high, but relay was low then when arduino output is low,  suddenly the relay was high.  i try to edit the code hoping if i set arduino output is low then relay will be high but its still the same,  its reversed.  arduino output is low but the relay become high.  is there any way to make the relay to become high when the digital output is high?

however.. i didnt have the the actual circuit act but im using the digital pin as the output and some switches.  the project im work on is the automatic aquarium pump and water change which is the pump will automatically refill the water actuated by the float switch and will automatically drain the water and refill the new water in certain time.

im using pin 13 as the output.. and the pin 1 as the input which is a switch
as in picture im using a led as a output. but as soon i change to the relay, it become what i just said at the above
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![enter image description here][4]][4]

  [1]: https://i.stack.imgur.com/y2CDQ.jpg
  [2]: https://i.stack.imgur.com/gH2Ky.jpg
  [3]: https://i.stack.imgur.com/IZEPA.jpg
  [4]: https://i.stack.imgur.com/7Yoi3.jpg

body:
First of all, you'll soon blow up that LED. (Or the Arduino if you're really unlucky.) You need a current limiting resistor.

Secondly, most relays have two switch contacts: normally closed (N.C.) and normally open (N.O.). If you want your device to be off, unless the Arduino turns on the relay, use the N.O. connection. If you want your device to be on, unless the Arduino turns on the relay, use the N.C. connection.
It looks like you need N.O.

N.b: 'closed' means on (i.e. the switch is closed and current is allowed to flow).

Finally, you seem to be using an external pull-up resistor for you switch, which is completely unnecessary: the Arduino has an internal pull-up resistor on every digital pin that you can enable using `pinMode(pin, INPUT_PULLUP)`.

**Edit**: you didn't connect the relay to the button pin instead of the LED pin, did you?


message:
HM-10 Central mode starting a connection

I'm trying to issue a connection via HM-10 from arduino (rather than my phone).
However, I'm unable to start a connection from arduino using both AT+CON and AT+CONNL. When I try AT+CON I get `OK+CONNA` and when I use AT+CONNL I get `OK+CONNE`. Here's my code:

    #include <SoftwareSerial.h>
    SoftwareSerial bluetooth(8,9);

    void setup() {
      Serial.begin(115200);
      Serial.setTimeout(50);
      bluetooth.begin(115200); //open BLE connection
      bluetooth.setTimeout(50); //set timeout
      bluetooth.write("AT+ROLE1");
      //bluetooth.write("AT+ROLE0");
      delay(50);
      bluetooth.write("AT+NOTI1");
      delay(50);
      bluetooth.write("AT+CONC40BCB403020");
      delay(50);
      //bluetooth.write("AT+CONNL");
    }

    void loop() {
        while (bluetooth.available() > 0) {
          String response = bluetooth.readString();
          Serial.println(response);
        }
    }

The response that I get is:

    OK+Set:1
    OK+Set:1
    OK+CONNA

body: By now you've surely moved past this, but: I found that I had to try connecting multiple times in order to get a connection to complete.  Also, your timeout might need to be longer?


message:
How to show one thing in the serial monitor?

I am trying to make a device which has two push buttons and one analog input. At first the serial monitor will show INITIALIZING, then it will show ready to begin if the measured pin is pressed. Then only it will start to measure if again pressed, then it will show ****************************** and if the reset pin is pressed, it will show reset. If again pressed then ------------------------
but the problem is, it is showing

*************
----------
(analog value) at the same time.

This is my code.

    int sensor = A0;
    int A = 0;
    int resetPin = 3;
    int measurePin = 2;
    int resetstatus = 0;
    int measurestatus = 0;
    boolean flag1 = true;
    boolean flag2 = true;
    long current = 0;

    void setup() {
     Serial.begin (9600);
     pinMode (sensor, INPUT);
     pinMode (resetPin, INPUT_PULLUP);
     pinMode (measurePin, INPUT_PULLUP);
     current = millis ();
    }

    void loop() {
     while (current < 3000) {
      Serial.println ("INITIALIZING");
      current = millis ();
      delay (200);
     }
     Serial.println ("Ready to begin");
     delay (200);
     resetstatus = digitalRead (resetPin);
     measurestatus = digitalRead (measurePin);
     if (resetstatus == LOW) {
      flag1 = !flag1;
      delay (50);
     }
     if (flag1 == HIGH) {
      delay (50);
      reset ();
     }
     if (flag1 == LOW) {
      Serial.println ("------------------------------------");
     }
     delay (100);
     if (measurestatus == LOW) {
      flag2 = !flag2;
      delay (50);
     }
     if (flag2 == HIGH) {
      delay (50);
      measure ();
     }
     if (flag2 == LOW) {
      Serial.println ("***********************************");
      digitalWrite (13, LOW);
     }
     delay (100);
    }

    void measure() {
     A = analogRead (sensor);
     Serial.println (A);
     digitalWrite (13, HIGH);
    }

    void reset() {
     Serial.println ("reset");
    }

body:
You have declare flag1 and flag2 as Boolean values but then you are looking to see if they are HIGH or LOW.  Bools are either true or false.  However because of the quirks of C++ this will probably work, if High and low are 1 and 0, its just bad style.

When you have this bit of code:

    if (flag2 == HIGH)
    {
        delay (50);
        measure ();
    }
    if (flag2 == LOW)
    {
        Serial.println ("***********************************");
        digitalWrite (13, LOW);
    }

You could use an else statement instead, i.e.

    if (flag2 == true) // Corrected to true
    {
        delay (50);
        measure ();
    }
    else
    {
        Serial.println ("***********************************");
        digitalWrite (13, LOW);
    }


message:
Arduino Wall Wart and Relay Board Power Supply

I am relatively new to Arduino, and have been doing a project to trigger an LED/alarm when movement is detected to be over a certain threshold value. I am using an Arduino Uno, an LED/buzzer (https://www.adafruit.com/product/2994), an MPU-6050 (https://playground.arduino.cc/Main/MPU-6050), and a 4 channel relay board (http://www.seeedstudio.com/blog/2013/02/28/shield-evolution-flexible-add-ons-for-arduino/relay-shield/ - sorry it's not very descriptive).

The LED/buzzer needs a 12V DC power supply, and I am using a wall wart to supply it. I am wondering how I am supposed to hook everything up - everything online tells me that the LED needs to be connected not only to the relay board, but to a power supply as well. However, my power supply is to the Arduino itself.

Based on the following picture, I would think that I would need to take the ground wire of the LED to the power source itself, then connect the power source to the relay board Common input.

[![This is not my project - I am simply looking at how the power is connected][1]][1]

Here is the circuit without the external power, using a small LED:

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

And here is the current setup (note that the cables were initially shifted over by 1 on the analog input, but I have fixed that since):

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

Is there a way to use the wall wart as the power supply? Do I even need the relay board?

  [1]: https://i.stack.imgur.com/G7Ym3.png
  [2]: https://i.stack.imgur.com/DXHXR.jpg
  [3]: https://i.stack.imgur.com/RvXDY.jpg

body:
You will need the relay board.  The Arduino output 5V and so you can't use it to directly power the 12V half of the circuit.

If you can split the power from the wall wart so it powers the 12V circuit and the barrel connector on the Arduino then that should work.  If you can, then you will need to ensure that the 0v of the Arduino and the 12v circuit are tied together, otherwise the two halves of the circuit will be using different versions of 0V and you will get interesting results.

If you want to use the setup in your second picture then no you don't need the relay board, but that's only because the whole circuit is 5V.

"How do you split the power?" I hear you say, "do I need any extra hardware?"

That depends, how attached are you to your wall wart's cable?  The way I have done it is to ***UNPLUG*** the wall wart, cut the cable in "half", strip a cm of each wire and plug both ends of it into two empty rows on you bread board.  Then use jumper wires to take an additional feed off to the 12V circuit.

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

**CAUTION** Ensure you get the polarity of the wires the right way around.  You can test this with a volt metre.  I suggest red electrical tape to mark the +ve wire.

**IF YOU ARE NOT CONFIDENT DON'T DO IT!**

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


message:
RGB LED strip inverted PWM

This bug/stupidity-of-myself/problem is killing me:
I'm have created an RGB strip controller that cycles through the additive-rgb-color spectrum while turning a potentiometer.

I have a pot hooked up to my Arduino Nano v3 (from AZ-Delivery, not official Arduino). Then I have an RGB amplifier hooked up to the Arduino with each phase (R, G, B, V+) and to an external power supply (12V by 2A max).

I shortened my program and removed all the value-to-colour-conversion because that has nothing to do with the problem:

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

    void loop() {
        ColorVal = analogRead(pinPot); //read value of color poti
        ColorByte = map(ColorVal, 0, 1023, 0, 255); //Scales 0-1023 to 0-255

        // potvalue to color conversion
        // ...

        // write via PWM to LED
        analogWrite(pinR, R);
        analogWrite(pinG, G);
        analogWrite(pinB, B);
    }

**My problem:** Theoretically you would expect the system to show white when all variables (R, G and B) are set to 255. However, it behaves the other way around. When all values are set to 255 it's off and vice versa. Another example: When R = 255 and G = 0 and B = 0 Green and Blue are lighting and Red is off.

I thought this has to do with polarity or something but I cannot seem to find it out.

body:
The RGB LED strip has a common anode (V+). When you put 12 V on R, G or B, the LEDs have 12 V on both sides, so there is no voltage across it and no current.

And if you put 0 V, they have 12 V across it and light up.

To fix it, just invert the PWM value in your code:

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

    analogWrite(255-pinR, R);
    analogWrite(255-pinG, G);
    analogWrite(255-pinB, B);


message:
Relay Board making Output Signal Weak

I am using an Arduino Uno and Relay Shield (http://www.seeedstudio.com/blog/2013/02/28/shield-evolution-flexible-add-ons-for-arduino/relay-shield/), and using a code similar to the Teapot Demo, in which an LED blinks when movement is detected. When I connect the shield, the LED blinks at the normal brightness when uploading the code, but blinks extraordinarily dimly when indicating movement. This is both the external and internal LED display for the Arduino.

This is my current setup:

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

I think it must be a code issue because the LED clearly has the ability to blink on and off normally.
Any suggestions as to what is wrong or what I should do?

Below is my code:

    #include "I2Cdev.h"
    #include "MPU6050_6Axis_MotionApps20.h"
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif
    MPU6050 mpu;
    // uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
    // components with gravity removed. This acceleration reference frame is
    // not compensated for orientation, so +X is always +X according to the
    // sensor, just without the effects of gravity. If you want acceleration
    // compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
    #define OUTPUT_READABLE_REALACCEL

    // uncomment "OUTPUT_TEAPOT" if you want output that matches the
    // format used for the InvenSense teapot demo
    #define OUTPUT_TEAPOT

    //----------------------------------------------------------------------------------------------

    const int LED_PIN = 13; // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    const int buzzerPin = 12;

    bool blinkState = false;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    // packet structure for InvenSense teapot demo
    uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

    // ================================================================
    // ===               INTERRUPT DETECTION ROUTINE                ===
    // ================================================================

    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }

    // ================================================================
    // ===                      INITIAL SETUP                       ===
    // ================================================================

    void setup() {
        // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        // initialize serial communication
        // (115200 chosen because it is required for Teapot Demo output, but it's
        // really up to you depending on your project)
        Serial.begin(115200); // this is a "Baud" rate
        while (!Serial); // wait for Leonardo enumeration, others continue immediately

        // initialize device
        Serial.println(F("Initializing I2C devices..."));
        mpu.initialize();

        // verify connection
        Serial.println(F("Testing device connections..."));
        Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

        // wait for ready
        Serial.println(F("\nSend any character to begin DMP programming and demo: "));
        while (Serial.available() && Serial.read()); // empty buffer
        while (!Serial.available());                 // wait for data
        while (Serial.available() && Serial.read()); // empty buffer again

        // load and configure the DMP
        Serial.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        // supply your own gyro offsets here, scaled for min sensitivity
        mpu.setXGyroOffset(220);
        mpu.setYGyroOffset(76);
        mpu.setZGyroOffset(-85);
        mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

        // make sure it worked (returns 0 if so)
        if (devStatus == 0) {
            // turn on the DMP, now that it's ready
            Serial.println(F("Enabling DMP..."));
            mpu.setDMPEnabled(true);

            // enable Arduino interrupt detection
            Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
            attachInterrupt(0, dmpDataReady, RISING);
            mpuIntStatus = mpu.getIntStatus();

            // set our DMP Ready flag so the main loop() function knows it's okay to use it
            Serial.println(F("DMP ready! Waiting for first interrupt..."));
            dmpReady = true;

            // get expected DMP packet size for later comparison
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {
            // ERROR!
            // 1 = initial memory load failed
            // 2 = DMP configuration updates failed
            // (if it's going to break, usually the code will be 1)
            Serial.print(F("DMP Initialization failed (code "));
            Serial.print(devStatus);
            Serial.println(F(")"));
        }

        // configure LED for output
        pinMode(LED_PIN, INPUT);
        pinMode(buzzerPin, INPUT);
    }

    // ================================================================
    // ===                    MAIN PROGRAM LOOP                     ===
    // ================================================================

    void loop() {
        // if programming failed, don't try to do anything
        if (!dmpReady) return;

        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {
            // other program behavior stuff here
        }

        // reset interrupt flag and get INT_STATUS byte
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();

        // get current FIFO count
        fifoCount = mpu.getFIFOCount();

        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
            // reset so we can continue cleanly
            mpu.resetFIFO();
            Serial.println(F("FIFO overflow!"));

        // otherwise, check for DMP data ready interrupt (this should happen frequently)
        } else if (mpuIntStatus & 0x02) {
            // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

            // read a packet from FIFO
            mpu.getFIFOBytes(fifoBuffer, packetSize);

            // track FIFO count here in case there is > 1 packet available
            // (this lets us immediately read more without waiting for an interrupt)
            fifoCount -= packetSize;

            #ifdef OUTPUT_READABLE_REALACCEL
                // display real acceleration, adjusted to remove gravity
                int Mag;
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetAccel(&aa, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                Serial.print("areal\t");
                Serial.print(aaReal.x);
                Serial.print("\t");
                Serial.print(aaReal.y);
                Serial.print("\n");
                Mag = sqrt((aaReal.x*aaReal.x) + (aaReal.y*aaReal.y));
                Serial.print("Accel. Mag. is ");
                Serial.print(Mag);
    //            Serial.print("\t");
    //            Serial.println(aaReal.z);
            #endif

            #ifdef OUTPUT_TEAPOT
                // display quaternion values in InvenSense Teapot demo format:
                teapotPacket[2] = fifoBuffer[0];
                teapotPacket[3] = fifoBuffer[1];
                teapotPacket[4] = fifoBuffer[4];
                teapotPacket[5] = fifoBuffer[5];
                teapotPacket[6] = fifoBuffer[8];
                teapotPacket[7] = fifoBuffer[9];
                teapotPacket[8] = fifoBuffer[12];
                teapotPacket[9] = fifoBuffer[13];
                Serial.write(teapotPacket, 14);
                teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
            #endif

            // blink LED and sound buzzer to indicate activity
            if (Mag > 120) {
              blinkState = !blinkState;
              digitalWrite(LED_PIN, blinkState);
    //          delay(1000);
              tone(buzzerPin, 100);
            }
            else if (Mag <= 120) {
              digitalWrite(LED_PIN, LOW);
              noTone(buzzerPin);
            }

        }
    }

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

body:
Without seeing your code, it is hard to tell you directly what the problems is. If you can, please post your code.

Based on the information in your question, I can see two possible causes for this.

Firstly, it could be that there isn't enough power from your supply to power everything. So when the Arduino tries to turn on the relay, it doesn't have enough grunt and the voltage drops too low and the Arduino resets, de-energising the relay. This happens many times a second and shows up as a dull LED.

This can be proven by disconnecting the relay from the Arduino output. Run the sketch again, and if everything works at full brightness without the relay connected, then it is almost certainly not enough power.

My second theory is that it is a bug in your code. Some cycles it detects movement and so it turns the LED on.  Others cycles it doesn't detect a change in movement so it turns the LED off. This happens many thousand times a second. It would be visible on an oscilloscope if you have one.

The simple thing you could do for this scenario is to add a delay (eg `delay(1000);`) straight after the LED is turned on when movement is detected. This should leave the LED on for at least a second after movement is detected.


message:
How to add additional millisecond delay to microsecond delay generator

I am trying to make a delay generator. I already found an excellent example in [https://arduino.stackexchange.com/questions/34991/generating-a-short-pulse-after-a-delay][1] that works in the range from ~5-32767 microseconds (it is limited by a 16 bit microsecond counter divided by 2).

How would I go about extending that range into the millisecond range (say up to 1s or so)? Since this example is interrupt-based, adding delay() statements do not really seem to work.

I have also tried changing the timer prescaler, but then the jitter is also scaled up in an unacceptable way.

This is the code I have now. Send commands via the arduino serial console, D500 for 500µs delay, L100 for a 100µs long pulse. Letters M and N change the prescaler.

    uint16_t pulse_delay = 10; //half-microseconds
    uint16_t pulse_length = 10;
    String inputString = "";         // a string to hold incoming data
    boolean stringComplete = false;  // whether the string is complete
    long read_value = 0;
    long ms_delay = 0;

    void printvals() {
      Serial.print(F("Delay: "));
      Serial.print(pulse_delay / 2);
      Serial.println(F(" µs"));
      Serial.print(F("Length: "));
      Serial.print(pulse_length / 2);
      Serial.println(F(" µs"));
    }
    long getcommandvalue(String inputstring) {
      inputString.remove(0,1);
      return inputString.toInt();
    }
    void setup(){
      pinMode(8, INPUT);
      pinMode(9, OUTPUT);
      TCCR1A = 0;
      TCCR1B = _BV(ICNC1)  //input capture noise cancel
       | _BV(ICES1) //positive edge
       | _BV(CS11); // /8 prescaler
      TIMSK1 = _BV(ICIE1); //enable input capture interrupt
      Serial.begin(9600);
      inputString.reserve(200);
      Serial.println(F("RDY"));
      printvals();
    }
    void loop(){
      if (stringComplete) {
       switch(inputString.charAt(0)) {
      case 10: //\n (Newline; Line Feed)
        // previous line ending was CRLF, so now LF was carried to the next string
        break;
      case 63: //?
        //print current vales
        printvals();
        break;
      case 68: //D (Delay)
        read_value = getcommandvalue(inputString);
        if (read_value >= 1) {
       pulse_delay = 2 * read_value;
       printvals();
        }
        break;
      case 76: //L (Length)
        read_value = getcommandvalue(inputString);
        if (read_value >= 1) {
       pulse_length = 2 * read_value;
       printvals();
        }
        break;
      case 77: //M (additional prescaling)
        TCCR1B = _BV(ICNC1)  //input capture noise cancel
       | _BV(ICES1) //positive edge
       | _BV(CS10) // 64 prescaler
       | _BV(CS11); // /8 prescaler
        break;
      case 78: //N (8x prescaling)
        TCCR1B = _BV(ICNC1)  //input capture noise cancel
       | _BV(ICES1) //positive edge
         | _BV(CS11); // /8 prescaler
        break;
      case 79: //O
        ms_delay = getcommandvalue(inputString);
        // I don't know where to execute this ms_delay
        break;
       }
       inputString = "";
       stringComplete = false;
      }
    }

    void serialEvent() {
      while (Serial.available()) {
     // get the new byte:
     char inChar = (char)Serial.read();
     // add it to the inputString:Z
     inputString += inChar;
     // if the incoming character is a newline, set a flag
     // so the main loop can do something about it:
     if ((inChar == '\n') or (inChar == '\r')) {
       stringComplete = true;
     }
      }
    }

    ISR(TIMER1_CAPT_vect){
      TCCR1A = _BV(COM1A0) | _BV(COM1A1); //set OC1A on match
      TIFR1 = _BV(OCF1A);  // clear interrutp flag
      TIMSK1 |= _BV(OCIE1A); //enable match interrupt
      OCR1A = pulse_delay; //pulse begin time

      TCNT1 = TCNT1 - ICR1; //TCNT1 now contains time since input pulse, even if
          //the interrupt isn't run immediately
    }
    ISR(TIMER1_COMPA_vect){
      TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
      TCCR1A = _BV(COM1A1); //clear OC1A on match
      OCR1A = pulse_delay + pulse_length;
    }

  [1]: https://arduino.stackexchange.com/questions/34991/generating-a-short-pulse-after-a-delay

body:
You could count timer compare matches.  The following illustrates the principle, maybe not accurate as written but I am sure the counter loop will be precise enough for your needs, considering you want to use an Arduino.  Depending on the time resolution you want, you may be able to run other code while the software counter is active.

The following can count to several seconds, depending on values of `OCR1A` and `counter_target`.

    unsigned int state, pulse_delay;
    byte counter[3]={0,0,0}; // 24 bit counter, you can make it longer in principle

    byte counter_target[3]={0,0,0}; // defines length of delay you want

    void setup(){
    state=0;
    TCCR1A=0;
    TCCR1B=0;
    }

    void loop(){
    switch (state){
    case 0: // idle state machine // you other code here
    counter_target[0]=0; // For example
    counter_target[1]=0;
    counter_target[2]=1; // corresponds to (1+65536)*pulse_delay/clock_scaler
    // when you are ready to start counting
    state=1;
    break;

    case 1: // setup timer
    counter[0]=0; // Zero the 24-bit counter
    counter[1]=0;
    counter[2]=0;
    OCR1A = pulse_delay; // number of pulses to count = 1+OCR1A
    OCR1B = OCR1A+1;
    ICR1  = OCR1A+1;    // Just to make sure these don't cause compare match
    TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
    state=2;
    TCCR1A = B00000011; // Fast PWM mode 15 on UNO, OCR1A=TOP
    TCCR1B = B00011001; // Clock prescaler 1
    break;

    case 2: // Counting up
    loop_until_bit_is_set(TIFR1,OCF1A);
    TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
    counter[0]+=1; // Increment counter by 1
    if(counter[0]==0x00){counter[1]+=1;
    if(counter[1]==0x00){counter[2]+=1;}} // etc

    if(counter[0]==counter_target[0] && counter[1]==counter_target[1] && counter[2]==counter_target[2]){state=0;}  // Check if we have reached the target delay
    break;

    }
    }


message:
analogRead always returns 1023 - Arduino Mega 2560

I have connected an FSR (Force Sensitive Resistor) to **[![Arduino Mega 2560][1]][1]** as per image(edited name for avoiding mismatch). When I measure the voltage b/w two pins of fsr, voltage changing as per pressure applied. But analogRead always returns **1023**. But my another Mega works good with same code and configurations. Can someone guide me to correct it. Thanks in advance.
<!-- language-all: lang-cpp -->

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

    void loop() {
      int num1 = analogRead(A15);
      Serial.println(num1);
      delay(1500);
    }

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

body:
It sounds like your Arduino Mega 2560 is broken.

> If mega a works and mega b doesn't with the same circuit then mega b must be broken. – Majenko

You can confirm this theory by creating a voltage divider circuit (or use a potentiometer as a voltage divider) and get your Arduino Mega to read that in. It is good practice to measure the voltage using a multi-meter as well. This will help you verify that the voltage read in correspond with the voltage measured and will also help so you do not go over-voltage.

If you are constantly getting `1023` then change it to another analog input. If that still does not work, then try the other Arduino Mega.


body:
I had a similar problem when I ported my code from an Arduino Due to an Arduino Mega. I was able to solve this problem by adding the following call in the setup function.

    analogReference(DEFAULT);

It seems that in some other Arduinos, the analog reference will be selected automatically, but at least the Arduino Mega needs it.


body: I had the same problem when simulating a similar circuit in proteus software. I was able to solve it by supplying power with an external dc input terminal to the arduino board 5v pin.


message:
Combining two different coding program into one sketch

Im working on project that uses a relay module,arduino atmega328 and a 2 motor 12vdc. based on coding i give, the first code is the motor 1 will run based on the input switch. and the second code the motor will run based on the delay time. what im doing is, im going to combine these two coding into one sketch hoping these two coding will run together. but im confused on how to combine.

    `int motorPin = 10; // pin that turns on the motor
    int blinkPin = 9; // pin that turns on the LED
    int watertime = 5; // how long to water in seconds
    int waittime = 60; // how long to wait between watering, in minutes

    void setup()
    {
      pinMode(motorPin, OUTPUT);
      pinMode(blinkPin, OUTPUT); // set pin 13 to an output so we can use it to turn on the LED
    }

    void loop()
    {
      digitalWrite(motorPin, HIGH); // turn on the motor
      digitalWrite(blinkPin, HIGH); // turn on the LED
      delay(watertime*3000);        // multiply by 1000 to translate seconds to milliseconds

      digitalWrite(motorPin, LOW);  // turn off the motor
      digitalWrite(blinkPin, LOW);  // turn off the LED
      delay(waittime*6000);        // multiply by 60000 to translate minutes to milliseconds
    }`

this is the coding to run the motor by using delay time

    const int buttonPin = 2;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin

    // variables will change:
    int buttonState = 0;         // variable for reading the pushbutton status

    void setup() {
      // initialize the LED pin as an output:
      pinMode(ledPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
    }

    void loop() {
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);

      // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
      if (buttonState == LOW) {
        // turn LED on:
        digitalWrite(ledPin, LOW);
      } else {
        // turn LED off:
        digitalWrite(ledPin, HIGH);
      }
    }

this is the code which the motor will run based on the switch

for now, i dont have idea on how to combine these two coding.

the idea of my project is when switch is LOW(pin 3)  the Motor 1(pin 13) will HIGH until the switch is HIGH, the motor 1 will be LOW and stop.  At the same time,  there will be time delay for 10 second and the Motor 2 (pin 10)will active soon after switch is LOW and delaying time for 10 seconds and the Motor 2 will be active with time for 25 second  and stop and the next active for another 60 minutes

body:
The simplest way of combining two programs is this:

1. Copy the content of the two programs into a single new .ino (program) file
2. Rename the first setup function `setup_one`
3. Rename the first loop function `loop_one`
4. Rename the other setup and loop functions `setup_two` and `loop_two`
5. Add the following code to the bottom of that file.

Code:

    void setup()
    {
      setup_one();
      setupr_two();
    }
    void loop ()
    {
      loop_one();
      loop_two();
    }

This is a very simplistic approach and it won't work for all cases.  It will work in this case, but you will find it will do program one then program two.  It will work because your constants don't clash (at the top of the program) you aren't using the same pin in the different programs, etc.

You need to learn what the code does though to really merge the programs, you will see better ways of doing it.  The best way to learn is to right down, in your native language, what each line of code does, so in the case of program one:

    turn on the motor
    turn on the LED
    wait for 'watertime' seconds
    turn off the motor
    turn off the LED
    wait for 'waittime' minutes

For program 2:

      read the state of the pushbutton value:
      If the button is in state low
        Turn off the LED -- Not sure  this might be on
      else
        Turn on the LED -- Not sure this might be off

Hopefully you should recognise those descriptions (they are the comments) and when you read through the descriptions you will realise why the code you put together using the above method "doesn't work".  It does, you just need to wait for 'waittime' minutes before you get a few microseconds to press the button.

If you want the motor to respond to the button then rearrange the natural language description to do what you want and then replace the English with the code and you should have a program that is close to working.  (Hopefully)


message:
Limiting Data Output Frequency from ADXL345

I have a working ADXL345 connected to an Arduino UNO, I need to limit the rate at which the ADXL345 takes in readings. I am using the SparkFun library for this sensor. I have read about the delay function and it works in the loop function but I was wondering if there might be a better way that is much more efficient?

body:
Everytime you get a value from the sensor (for example with `getX()` or others) the library communicates with the sensor over I2C or SPI. So you can limit the usage of these function in your sketch. One way is with using `delay()`, but this is considered unefficient in most cases, since you are basically busy waiting during execution of `delay()`. You will not be able to do anything else in the future during this time span (if you want to add functionality to your device).

It's better to use non-blocking code, that only checks, if it is time to do something and if not going further through the program. Image like you yourself would bake a pizza. You would not stare at the clock for 20 min, until the time is up. You would periodically check, if the time has come to take the pizza out.

You can achieve this on an Arduino with use of the `millis()` function, which returns the number of milliseconds since the last powerup/reset. (Note that it overflows after about 50 days). There are plenty of tutorials for that out there. You can start with the `BlinkWithoutDelay` example from the Arduino IDE, which perfectly shows, how this is to be coded.

Note: If you are using the sensor with a battery, then you might want to limit its power usage. For this the library can set the corresponding registers in the sensor to set the datarate in the sensor (The rate at which the data in the sensor is updated). A smaller rate will lower the power consumption. So you can set the rate at about the rate of the reading in your sketch.


message:
maintain state of a channel cd74hc4067

I have this code to change channels.

    void setMuxChannel(byte channel) {
       digitalWrite(muxS0, bitRead(channel, 0));
       digitalWrite(muxS1, bitRead(channel, 1));
       digitalWrite(muxS2, bitRead(channel, 2));
       digitalWrite(muxS3, bitRead(channel, 3));
    }

I have this code to write a value in a channels, but when I change to a new channel, the previous channel returns to LOW.
I want to turn on LEDs using multiplexer, however the LEDs do not stay on since the channel they are connected to does not keep its value.

      setMuxChannel(1);
      digitalWrite (muxSIG,a);
      delay(5);
      setMuxChannel(2);
      digitalWrite (muxSIG,b);
      delay(5);
      setMuxChannel(3);
      digitalWrite (muxSIG,c);
      delay(5);
      setMuxChannel(4);
      digitalWrite (muxSIG,d);

body:
The whole point of a multiplexer is to only connect ONE channel at a time to the input. It is designed to send many different signals through one wire by time sharing. Normally data in some form is send, and not the direct control current of a simple load. So you will not be able to drive more than one channel at a given time.

You can cycle very fast through the channels to let it seem, as if the LEDs were on simultaneously, but this will decrease their light intensity.

If you just want to drive some LEDs without using too mich of the IO pins, you should follow Majenkos comment and use a shift register instead. They can drive all outputs at the same time if wanted. Also often they can be daisy-chained to simply controlling multiple shift registers through a single output of the Arduino.


message:
Multiple #ifndef vs. single one #endif

My question is connected with the issue as linked:
https://arduino.stackexchange.com/questions/36234/is-there-any-good-working-modbus-tcp-master-library-available-for-arduino

An example of Modbus TCP master library as suggested in the post above. A part of ModbusTCP.h file:

    #ifndef Modbus_TCPIP_h
    #define Modbus_TCPIP_h

    #ifndef WIZNET_W5100
    #define WIZNET_W5100  0       /**< define 1 if  WIZNET W5100 IC is used, otherwise 0 */
    #ifndef ENC28J60
    #define ENC28J60      1       /**< define 1 if  ENC28J60 IC is used, otherwise 0     */
    #ifndef ESP8266
    #define ESP8266       0

    //...The entire code of the header

    #endif // Just a single one occurence of the #endif in the last line of the header code! 8-|

When I've run the compilation of it in my Arduino IDE, I've got an error as follows: unterminated #ifndef. Mentioned error has a four ocurrences in the error log and it is linked to: Modbus_TCPIP_h, WIZNET_W5100 and ENC28J60.

What should be modified in the header file?

body:
The code is missing "#endif". Should look something like this:

    #ifndef WIZNET_W5100
    #define WIZNET_W5100  0       /**< define 1 if  WIZNET W5100 IC is used, otherwise 0 */
    #endif
    #ifndef ENC28J60
    #define ENC28J60      1       /**< define 1 if  ENC28J60 IC is used, otherwise 0     */
    #endif
    #ifndef ESP8266
    #define ESP8266       0
    #endif

Cheers!