body:
I am working on a project to blow air gently through a number of pipes and variable speed. I would like to use a standard PC case fan and have control of whether the fans are on/off and also what speed they spin at. My hope is to attach temperature sensors later and eventually blow are depending on the temperature.

It appears that PC fans on 3-wire and 4-wire systems provide variable speed by changing input voltage ranging from 3-12V  (linear voltage regulator) or with PWM set to 3.3V or 5V. Furthermore, it looks like inexpensive products exist to split/copy a single signal to multiple fans (see [here][1]).

I am hoping to control 4-8 fan speeds, as independently as possible while using as simple/standard a case fan as possible. What is the best way to drive PC case fans using the Arduino?

Reference: https://en.wikipedia.org/wiki/Computer_fan_control

  [1]: https://www.newegg.com/Product/Product.aspx?Item=N82E16882422018

title: PC Fan Speed Control

Answers: 1

body:
To put the comments into an answer:

You can drive most PC fans (which have at least 3 pins) with any PWM source and change their speed through the duty cycle. The Arduino Uno itself has 6 PWM channels. If you want to control more fans, you have to use an extra chip, that provides PWM. You can use the [breakout board from Adafruit][1], but also any other external PWM chip (they are often marked as servo drivers, since servos use PWM signal too).

The speed of most fans can also be changed through providing a different input voltage, but this is not intended for direct variation. Instead this is normally used to set the speed interval, in which the fan should run. For example some PC fans have extra adapters, which lower the supply voltage to let them run more silent. For short term variation you should definitely use PWM. If your fans are too fast at their nominal voltage, you can provide them with a lower voltage permanently.

As dandavis pointed out, the 4th pin is usually connected to a feedback loop. They provide a defined number of pulses per full rotation, so that you can really measure the speed, instead of just estimating. When you don't need this functionality both kinds of fans (3 pin or 4 pin) are good for you.

  [1]: https://www.adafruit.com/product/815


body:
I have an uno r3 clone in an enclosure and one [of these][1] usb ports on the enclosure.

It's pretty tight in there so I was wondering if there was a way to bypass the usb port on the board and plug it in directly to the pins.

So do something like plug the usb into the outer port on the enclosure and then cut off the usb end and plug the wires directly into the board rather than using the onboard arduino usb port.

The group of 4 just above the i2c seems promising but couldn't find much on it.

Thanks for your help.

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

  [1]: http://cpc.farnell.com/cliff-electronic-components/cp30111/gender-changer-xlr-shell-usb-b/dp/CN19602?CMP=TREML007-005
  [2]: https://i.stack.imgur.com/net5y.jpg

title: wire up usb to pins rather than on board usb socket

Answers: 2

body: You will have to (optionally) desolder the existing USB socket and solder the wires to the pins where that socket was on the board. It connects directly to the pins of the CH340G surface mount chip (rectangular one by the USB socket) and soldering wires to those pins would be tricky.

body:
The USB actually goes through the 16 pin chip that will translate the USB to serial to the RX and TX pins. None of the external sockets or plated through holes are connected to the data lines of the USB port.

You are better off soldering the wire to the pins on the connector itself. Or try and find a proper wire with the correct connectors.


body:
I am working with 2 identical (Arduino) [Adafruit Feather M0 Bluefruit LE][1]s. Only one of them can connect to a Universal Windows Platform [app][2] running on a  Windows 10 machine. The other connection fails with [Unreachable][3] status.

I am only trying to connect with one MCU at one time. Both MCUs are loaded with the same program which resets the Bluetooth Unit. Both MCUs can connect to an Android app. Neither board appear damaged.

Why could a UWP app be able to connect to one board but not another?

  [1]: https://www.adafruit.com/product/2995
  [2]: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BluetoothLE
  [3]: http://GattCommunicationStatus

title: why of 2 identical micro-controllers, only one can connect to a given device?

Answers: 1

body:
Other than a software issue, there is no reason it shouldn't work. Only thing may be identical Bluetooth names or ids. Clear the device from windows and try again.

I have some cheap Bluetooth obd 2 readers that all use the same Bluetooth mac address and name. I have to delete one from my android phone before adding the new one to connect to it.


body:
I am looking to make indicator lights for my computer to indicate things such as system load, IO usage, et cetera, using an Arduino and NeoPixels.  I would like to just plug it into my computer, and have some custom software connect to it and send it the data it needs as my computer runs.

The part I am having trouble with is figuring out how to connect the Arduino to the computer in a way that is consistent in the long term.

I have had issues with the Arduino switching which /dev/ttyAMC* port it is assigned, so I looked for options other than the USB serial.  The only other way seems to be USB, as that is the only common general purpose port these days.

This is where my problem lies.  People don't seem to be doing this sort of thing, or at least they don't post about it.

The Teensy can act as a USB HID, but the [raw HID][1] feature hasn't been updated in almost a decade, the host side code is based on deprecated libraries, and it seems oriented more for Teensy to computer transfers.

There doesn't seem to be any consumer level USB interface chips available, either.

I found [V-USB][2], which seems like a solution to my problems, in fact someone even used it to do [basically what I want to do][3].  However, I would still need to learn the library.

----------

So, my question is what is the recommended way of interfacing between a computer and Arduino in the long term?  Is USB support really necessary, or have I just overthought the entire thing?

  [1]: https://www.pjrc.com/teensy/rawhid.html
  [2]: https://www.obdev.at/products/vusb/index.html
  [3]: http://www.jers.net/ledload/

title: Long term connection between Arduino and computer

Answers: 1

body:
I think the easiest option may be to keep the USB (ACM) link, so you
don't have to do anything special on the Arduino, and try to figure out
a way to identify the correct device on the computer side.

On Linux, providing consistent device names for specific peripherals is
normally the job of udev. You could add your own udev rule to create a
symbolic link for your Arduino every time you plug it in. Then, your
custom software would always open `/dev/neopixel-monitor`, which would
be a symlink to the proper `/dev/ttyACMx` device.

Actually, you may not need write your own rule. I took a look at the
udev rules installed by default on my Ubuntu 16.04 and found a file
named `/lib/udev/rules.d/60-serial.rules` meant to populate the
`/dev/serial/by-path/` and `/dev/serial/by-id/` directories. Then I
plugged in my Arduino Uno R3 and saw the symlink
`/dev/serial/by-id/usb-Arduino__www.arduino.cc__0043_93140364233351E00101-if00`
automatically created, which right now points to `../../ttyACM0`. In
this name, `0043` is the USB device ID of the Uno, and the following
alphanumeric sequence looks like a serial number. The `if00` looks like
an interface number, <s>and may vary</s> (it won't, se Majenko's comment).
The link name should
be a good way to uniquely identify that particular Arduino.


body:
When I try to compile the following code in Arduino ,I get the error "expected initializer before 'void'".How can I get the code to work?

    const int LED = 9;
    const int BUTON = 2

    void setup() {
      pinMode (LED, OUTPUT);
      pinMode (BUTON, INPUT);
    }

    void loop() {
      if (digitalRead(BUTON) == HIGH);
      {
        digitalWrite(LED, HIGH);
      }
      else
      {
        digitalWrite(LED, LOW);
      }
    }

Answers: 1

body:
You are missing a semi-colon after `const int BUTON = 2`

Each expression should be terminated with a semi-colon.  Your code should look like this:

    const int LED = 9;
    const int BUTON = 2;

    void setup() {
      pinMode (LED, OUTPUT);
      pinMode (BUTON, INPUT);
    }

    void loop() {
      if (digitalRead(BUTON) == HIGH)
      {
        digitalWrite(LED, HIGH);
      }
      else
      {
        digitalWrite(LED, LOW);
      }
    }


body:
Imagine a collection of LEDs (Neopixel or otherwise) labeled 2 through 12. There may be more than 11 LEDs, so repeat numberings are allowed. I want a simple way to control them from a single Arduino *based on their label*. So e.g. I should be able to implement a function whose arguments are a label value and an RGB value, and which turns all LEDs of that label value to the given RGB value. Most importantly, the solution has to be order-independent; that is, I should be able to re-wire the LEDs (or equivalently, scramble around the hex labels) in any manner, and still have everything work without rewriting any code. (For context, my goal is to make a custom Settlers of Catan edition, where the labels on each hex light up when their die value is rolled.)

I know I can't just use Neopixels out of the box, since the addressing depends on the order in which they're wired. So I assume I need to hack together a way for each LED to "know" its label, wire them all in parallel, and then write a custom library to . But I have no idea how to get each LED to know its label without having an entire Arduino for each LED, which would take up way too much space. (I'd like to fit everything in roughly the volume of a typical Catan hex label; think 2-3 quarters stacked together.)

I'm fairly comfortable with Arduinos, but I'm an electronics noob. Is it possible to reprogram the Neopixel controller? Or is there a tiny logic board I can hook up to a Neopixel or dumb LED that would do the job? Anything else I'm missing?

title: How to control Neopixel LEDs in parallel?

Answers: 2

body:
The data wires of individually addressable LEDs of various descriptions are typically wired as a daisy chain, with each LED driver having input and output for the data (and clock). Each LED driver will then manipulate the signal it sends onward to trick the next LED into thinking it is the first in the chain.

Most libraries to drive them can easily have a few 100 LEDs it can driver at a time depending on available RAM.

body:
It will not be easy to “re-wire the LEDs [...] and still have everything
work without rewriting any code.” Those LEDs are not that smart, and the
only way to address them is by the order in which the color data is sent
through the data line.

What you can do, however, is write the code is such a way that rewiring
requires only a _minimal change_ in the code. I would use an array to
map the LED indices to their labels. Something like this:

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

    const uint16_t LED_COUNT = ...;

    // Map LED indices along the strip to hex labels.
    const uint8_t ledLabels[LED_COUNT] = {
        2, 2, 2, 2,  // LEDs 0 to 3 are labeled "2"
        8, 8, 8, 8,  // LEDs 4 to 7 are labeled "8"
        // etc...
    };

Then, assuming your LED strip is declared as follows:

    const uint8_t LED_STRIP_PIN = ...;
    Adafruit_NeoPixel ledStrip(LED_COUNT, LED_STRIP_PIN);

the “function whose arguments are a label value and an RGB value, and
which turns all LEDs of that label value to the given RGB value” can be
quite easily written:

    // Turn all the LEDs sharing that hex label to the given color.
    void setHexColor(uint8_t label, uint32_t color)
    {
        for (uint16_t n = 0; n < LED_COUNT; n++)
            if (ledLabels[n] == label)
                ledStrip.setPixelColor(n, color);
        ledStrip.show();
    }

Now, if you rewire the strip, you just need to update the `ledLabels`
array and recompile. If you can manage to send that information to your
Arduino while it's running (a serial connection, an IR link, an SD card
inserted in an appropriate socket, whatever...), then you could even
have a procedure where the Arduino updates the array itself. Obviously
the `const` qualifier should then be removed. But you now have to devise
a way to “tell” the Arduino about your wiring.


body:
I have developed my own development board using ATmega32U4. I want to bootload my ATmega32U4 and hence I used Arduino Uno to bootload it. I have given the connections as per
https://www.arduino.cc/en/Tutorial/ArduinoISP
 and I followed this instructions:

1. Open the ArduinoISP firmware (in Examples) to your Arduino board.

2. Select the items in the Tools > Board and Serial Port menus that correspond to the board you are using as the programmer (not the board being programmed).

3. Upload the ArduinoISP sketch.

4. Wire your Arduino boards..

5. Select the item in the Tools > Board menu that corresponds to the board on which you want to burn the bootloader (not the board that you're using as the programmer). See the board descriptions on the environment page for details.

6. Select the Arduino as ISP in the Tools>Programmer menu.

7. Use the Burn Bootloader command.

But I am getting the error message as

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
             Double check connections and try again, or use -F to override
             this check.

I am using 16Mhz crytsal oscillator along with 22pf

What might be the problem?

title: Problem in bootloading my ATmega32U4 chip

Answers: 1

body:
If you are developing your own board there are a number of things which can go wrong, although the problem is usually very simple and bootloading will be easy once you fix the bugs.

Possible hardware problems are:

 - You have bad solder joints / connections.  Even if you think the solder joints are good, try reflowing them again
 - ISP leads are too long - can lead to data corruption during bootloading
 - Pins are not correct.  E.g. are MOSI and MISO the correct way around?
 - Reset pin needs a pullup resistor

Most likely, you have some sort of hardware problem.  Post your board layout (or at least schematic) and we can look at it.  If you have a pro micro board to hand (if not, buy one one ebay or similar), try bootloading that and see whether your procedure works.


body:
I have a 4kHz pulse as trigger and I need two phase-shifted PWM output with divided frequency from arduino uno.

Now I've managed one PWM output using the following code:

    int cnt = 0;
    void setup() {
      pinMode(3, OUTPUT);
      pinMode(2, INPUT);
      attachInterrupt(digitalPinToInterrupt(2), rising_edge, RISING);
    }

    void loop() {

    }

    void rising_edge() {
      cnt = cnt + 1;
      if (cnt >= 4) {                           //divide by 8
        digitalWrite(3,(digitalRead(3)^1));
        cnt = 0;
      }
    }

As suggested by Majenko♦, I tried using Timer1 lib, but the phase shift is always 15us, regardless timer1 period.

    #include <TimerOne.h>

    int cnt = 0;

    void setup() {
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(2, INPUT);
      Timer1.initialize(10000);
      Timer1.attachInterrupt(ISP_T1);
      attachInterrupt(digitalPinToInterrupt(2), ISP_INTx, RISING);
    }

    void loop() {

    }

    void ISP_INTx() {
      cnt = cnt + 1;
      if (cnt >= 4) {
        digitalWrite(3,(digitalRead(3)^1));
        cnt = 0;
        Timer1.start();
      }
    }

    void ISP_T1() {
      digitalWrite(4,(digitalRead(4)^1));
      Timer1.stop();
    }

Shift should be arbitrary value between 0-1 x period (depends on divider)

Adjustable duty is preferred but not necessary.

title: generate two phase-shifted PWM pulses triggered by frequency-divided external signal with Arduino uno?

Answers: 2

body:
> If I understand correctly, it uses timer0 for interrupt and CPU for counting.

No, it doesn't. The interrupt is an interrupt. Timer0 is a timer.  At the moment you just have an *external* interrupt triggering an ISR which adds to a variable and toggles an output.

Timer0 is used to drive `millis()` and `delay()`.

What you need to do is set up a timer (*not* Timer0 since it's already reserved) which will time out with a period equal to the time difference of the phase shift.  Start it in your existing ISR (when the output is toggled), and in the timer's ISR stop the timer and toggle the second output (or set it the same as the 0° output).

You may find the [TimerOne](https://github.com/PaulStoffregen/TimerOne) library helpful for this.

body:
I think your first example is very close. What about:

    int cnt = 0;
    void setup() {
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(2, INPUT);
      attachInterrupt(digitalPinToInterrupt(2), rising_edge, RISING);
    }

    void loop() {

    }

    void rising_edge() {
      cnt = cnt + 1;
      if (cnt >= 4) {                           //divide by 8
        cnt = 0;
      }
      switch(cnt){
        case 0: digitalWrite(3,HIGH);break;
        case 1: digitalWrite(4,HIGH);break;
        case 2: digitalWrite(3,LOW);break;
        case 3: digitalWrite(4,LOW);break;
      }
    }

Assuming a uniform input frequency, pin 3 will be 90 degrees out of phase with pin 4. You could make this adjustable if you don't mind a larger divider by expanding the switch/case to eg 6 or 8 steps.

You could get more steps by triggering on rising and falling edges (although that may not give uniform phase if the incoming PWM is not at 50% duty cycle.


body:
I'm trying to determine the minimum value of pull resistor for Arduino Uno

The datasheets says for arduino; VOL = 0,4 for IOL = 20 mA. (VDD = 5V)

For formula for calculation of minimal pull-up is: Rmin=Vcc−0.4V/20mA = 4,6V / 20mA = 230 ohms.

But I saw that people use 0,4V for 3mA. Than the minimal value is 1,6K ohms.

So whats the minimum value of pull-up for arduino?

(also my slave has 0,4 Vol for 20 mA IOL)

title: Minimum value I2C-pull up resistor for arduino

Answers: 2

body:
I assume you want to work out the minimum value for a pullup resistor that will give a voltage below *VIL* for an IO pin in open-drain mode.

That is not a simple task, chiefly because you don't know the ON resistance (*RDSON*) of the low-side MOSFET in the chip.

It's possible to come up with a rough estimate ([see here](https://hackingmajenkoblog.wordpress.com/2017/03/20/what-exactly-is-a-gpio-pin/)) though.

With VIL of 1.5V and maximum current of 40mA that's an estimated theoretical resistance of 1.5/0.04 = 37.5Ω.

Note: this is just an estimate based on the *absolute maximum* and *DC Characteristics* values from the datasheet.

So if we take that value as actually true you can work out the upper half of a voltage divider that would result in 1.5V coming out. There's two ways of doing that - using the resistance or using the current.

Taking the resistance R1=R2(Vin/Vout-1), 37.5 x (5/1.5-1) = 87.5Ω.

If you want to do it with the current (40mA "absolute maximum"), then R=V/I = (5-1.5) / 0.04 = 87.5Ω.

However, that comes with a *big* caveat.  The IO pin, while it can, for short periods, sink 40mA, it's not designed to do that for long periods. For that 25mA is the *recommended* maximum. So a resistor should be chosen that keeps the current *below* 25mA.

Assuming 37.5Ω for the MOSFET resistance, and 25mA through it, that gives a voltage drop across it of 0.94V (well below *VIL*). The upper resistor in that divider would then be (5-0.94)/0.025=162.5Ω

So to sum up:

* The *absolute minimum* resistor would be 87.5Ω
* The *recommended minimum* resistor would be 162.5Ω
* The resistor you would choose to use would bear no real relationship to those values since you would normally choose something more sensible, like 3.3kΩ unless you wanted to run the I2C bus at insanely high speeds or with massive load capacitances.

You really don't need to know the theoretical minimum. You know the maximum already, and all you really need to know is "is the value I'd like to use safe for the IO pin" - i.e., does it draw less than 20mA?

For that you can ignore all the other values. All you care about is your resistance, the Vcc voltage, and the resultant current.

For instance, for a 900Ω resistor with 5V across it you get 5.6mA. You know for a fact that you can never have more than 5.6mA regardless of the resistance of the MOSFET - it can only go down from there.

5.6mA is below the recommended maximum of 20mA, so you're perfectly safe with that resistor.

body:
The full datasheet of the atmega328p can be found here: [https://www.microchip.com/wwwproducts/en/ATmega328P][1].
It is called "ATmega328/P AVR MCU with picoPower Technology Data Sheet".

In section "32.7 Two-Wire Serial Interface Characteristics" in table 32-10 on page 372 it shows different voltage levels for the input.

On page 110 it says: "*When the TWEN bit in TWCR is set (one) to enable the 2-wire Serial Interface, pin PC4 is disconnected from the port and becomes the Serial Data I/O pin for the 2-wire Serial Interface. In this mode, there is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation*".

I wrote here before that the i2c (the twi hardware inside the microcontroller) did not use the digital pin hardware. However, the i2c pins can still sink a lot of current. Thanks to @Berkay for noticing the same behaviour of the sink current as a normal digital pin.

According to the datasheet the atmega328p of the Arduino uno **might** not use the digital pin hardware for i2c. It is not known if the same mosfet circuit is used with the same (large) sink current. Perhaps the chip uses a similar mosfet circuit with added slew rate for the output and added spike filter for the input. Perhaps the same mosfet of the digital pin is used after all.

In the Arduino sketch, calling `Wire.begin` turns on the dedicated i2c hardware in the atmega328p chip. The sink current and voltage levels are according to the i2c specifications.
As you can see in the [i2c tutorial by Nick Gammon][2], the Arduino can sink more than 3 mA.

When the pullup resistors are too low, for example for a sink current of 4 mA, the Arduino uno can handle that, but the slave might not.

When all the pullup resistors are combined, the required sink current can be calculated. The maximum is 3 mA to meet the i2c specifications. To compensate for wire capacitance the i2c bus speed can be lowered.

The i2c bus is not ment to go into a cable, it is not ment for long wires. A cat6 cable is 46 pF/m. That means your 800 pF is for 17 meters cable? That is not what the i2c bus is for. It is for 17 centimeters. The rule of thumb is maximum 50 cm for a normal 100 kHz to 400 kHz i2c bus.

  [1]: https://www.microchip.com/wwwproducts/en/ATmega328P
  [2]: http://www.gammon.com.au/forum/?id=10896&reply=5#reply5


body:
I am building a small project that uses a pair of 8x8 LED matrix (driven by the MAX7219), a pair of SG90 servos, a HC-SR04 ultrasonic sensor, a 16x2 LCD (Hitachi HD44780 driver), some push buttons and all controlled with the Arduino Uno. All the components are powered using another usb port on my pc.

When I tried intergrating all the compenents, I noticed the LED matrix does not light up at all. I've decided to combine serveral basic code samples to test their interaction with eachother, where i noticed the use of `pinMode` to declare my pins for the push buttons will cause the LED matrix to stop working. Removing the section using `//` will get the led matrix(s) to work again.

Does anyone have any experience with this issue and can explain to me what causes this conflict? I've tried going through the LedControl documentation on the arduino page and I still could not understand what causes this issue.

    /*

    test build for debug

    log:

    LED Matrix : test code added, no issues
    LCD Display: test code added, no issues
    Sensor: test code added, serial clashed with LED Matrix. Working with disabled serial, Main build still not resolved.
    Servo: test code added, no issues
    Buttons: test code added, LED Matrix no longer light up. issue appears to be at the (pinMode) section when declaring buttons as inputs.

    */

    //buttons

    #include <Button.h>

    const int positiveButtonPin = A1;
     int positiveButtonState = LOW;

    const int negativeButtonPin = A2;
     int negativeButtonState = LOW;

    // servo library setup
    #include <Servo.h>
    Servo servo1;
    Servo servo2;

    // lcd setup
    #include <LiquidCrystal.h>
    const int rs = 12, en = 11, d4 = 10, d5 = 9, d6 = 8, d7 = 7;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

    //led matrix library setup
    #include "LedControl.h"
    LedControl lc=LedControl(2,1,0,2);  // Pins: DIN,CLK,CS, # of Display connected
    unsigned long delayTime=200;  // Delay between Frames

    // sensor setup
    const int trigPin = 6;
    const int echoPin = 5;
    long duration;
    int distance;

    // led matrix arrays (test with 2 formats)

    byte invader1a[] = {0x7C,0x7C,0x60,0x7C,0x7C,0x60,0x7C,0x7C};

    byte invader1b[] = {0x78,0x7C,0x66,0x66,0x66,0x66,0x7C,0x78};

    byte invader2a[] =
    {
      B00100100, // First frame of invader #2
      B00100100,
      B01111110,
      B11011011,
      B11111111,
      B11111111,
      B10100101,
      B00100100
    };

    byte invader2b[] =
    {
      B00100100, // Second frame of invader #2
      B10100101,
      B11111111,
      B11011011,
      B11111111,
      B01111110,
      B00100100,
      B01000010
    };

    void setup() {
      // put your setup code here, to run once:

    //button setup
    {
    //  pinMode(positiveButtonState, INPUT);                    //         <----------------- THIS CAUSES ISSUE WITH LED MATRIX
    //  pinMode(negativeButtonState, INPUT);
    }

    // servo setup
      servo1.attach(4);
      servo2.attach(3);

    //sensor serial test code
    // sensor setup
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
    //  Serial.begin(9600);                                         //     <----------------- THIS CAUSES ISSUE WITH LED MATRIX, DISABLED

        //led matrix setup
      lc.shutdown(0,false);  // Wake up displays
      lc.shutdown(1,false);
      lc.setIntensity(0,2);  // Set intensity levels
      lc.setIntensity(1,2);
      lc.clearDisplay(0);  // Clear Displays
      lc.clearDisplay(1);

        //lcd hello world code
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print("hello, world!");

    }

    //  Creating array strings

    void sinvader1a()
    {
      for (int i = 0; i < 8; i++)
      {
        lc.setRow(0,i,invader1a[i]);
      }
    }

    void sinvader1b()
    {
      for (int i = 0; i < 8; i++)
      {
        lc.setRow(0,i,invader1b[i]);
      }
    }

    void sinvader2a()
    {
      for (int i = 0; i < 8; i++)
      {
        lc.setRow(1,i,invader2a[i]);
      }
    }

    void sinvader2b()
    {
      for (int i = 0; i < 8; i++)
      {
        lc.setRow(1,i,invader2b[i]);
      }
    }

    void loop() {
      // put your main code here, to run repeatedly:

    //servo test code
        // servo attach
        servo1.attach(4);
        servo2.attach(3);

         servo1.write (120);  // change angle here below. adjust until it looks like it's looking at user
      servo2.write (90);
      delay(250);
      servo1.write (90);
      servo2.write (120);
      delay(250);
    // servo detach to reduce noise
    servo1.detach();
    servo2.detach();

    // led matrix test code
        sinvader1a();
        delay(delayTime);
        sinvader2a();
        delay(delayTime);

        sinvader1b();
        delay(delayTime);
        sinvader2b();
        delay(delayTime);

        //lcd hello world code
        // set the cursor to column 0, line 1
          // (note: line 1 is the second row, since counting begins with 0):
          lcd.setCursor(0, 1);
          // print the number of seconds since reset:
          lcd.print(millis() / 1000);

    //sensor test code
    // Clears the trigPin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance= duration*0.034/2;

    // no longer useful due to disabled serial
    /*
    if (distance<1000){
    Serial.print("Distance: ");
    Serial.println(distance);}
    else {}
    */

    }

title: Need help with using LED matrix with pushbuttons

Answers: 1

body:
It appears you are attempting to use the hardware UART for both talking to your MAX7221 or MAX7219:

    LedControl lc=LedControl(2,1,0,2);

And for talking to, maybe, the SDK's serial monitor:

    Serial.begin(9600);

There is only 1 UART on the Atmel processor used on an Arduino Uno.  Consider using a larger Arduino / processor where there are more UARTs on the processor.  Be aware that it may be necessary to re-write the library to use the alternative hardware on larger processors.

Also, there is an error in your code and it is causing you to think about it incorrectly:

The lines:

    pinMode(positiveButtonState, INPUT);
    pinMode(negativeButtonState, INPUT);

...interfere with the LED matrix because they are changing pin zero from a UART Receive to a GPIO Receive.  Likely you meant to type:

    pinMode(positiveButtonPin, INPUT);
    pinMode(negativeButtonPin, INPUT);


body:
For my final project on the university as a Systems Engineer, I'm working on a "electronic stethoscope", which is giving me a lot of headaches.

I bought a Adafruit Feather ESP32 Huzzah (https://learn.adafruit.com/adafruit-huzzah32-esp32-feather/overview) which has a dual core processor that works around 240 MHz of speed, it has support of wireless communication with Bluetooth classic (which is the one I'm using) and also works with the I2S protocol.

That is the reason why I bought an I2S MEMS Microphone SPH0645 (https://www.adafruit.com/product/3421), which according with its documentation works under 50Hz-15KHz.

As a first approach, I thought that it would be enough, but I'm getting a very slow sample rate that is around 800 samples per second. With these values, I can't reproduce any sound with the expected quality.

On the other hand, since the ESP32 has not a high level library to interact with I2S such as ArduinoSound I had to create my own code based on the specification (https://esp-idf.readthedocs.io/en/v2.0/api/peripherals/i2s.html).

My code on the Arduino IDE looks like this:

    #include "libraries/SmappioSound/SmappioSound.cpp"
    #include "BluetoothSerial.h"

    int *buffer;
    BluetoothSerial serialBT;
    int value = 0;
    int framesRead = 0;

    SmappioSound smappioSound(6835); //value for stabilization

    void setup() {
      // put your setup code here, to run once:

      pinMode(DATA_PIN, INPUT); // Supuestamente necesario para que no haya ruido
      serialBT.begin("smappio_PCM");
      Serial.begin(115200);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      smappioSound.begin(buffer);
    }

    void loop() {

      //gets the amount of bytes readed from the buffer.
      framesRead = smappioSound.read() / I2S_BITS_PER_SAMPLE_32BIT;

      for(int index = 0; index <= framesRead; index++)
      {

          value = smappioSound.getSampleValue(index);
          if(index % 2 == 0)
          {
              serialBT.print(String(value) + ",");
              Serial.println(value);
          }
      }
    }

The SmappioSound.h library is where the interaction with I2S occurs.
The configuration for i2S is the following:

    #pragma region // Sección de Configuración
      static const print_mode_t PRINT_MODE = BYTES;                                   // Tipo de impresión: BITS | BYTES | INTEGER | FULL_DETEAILED
      static const bool PRINT_BOTH_CHANNELS = false;                                    // Indica si imprime solo el "Canal 0" ó el "Canal 0" y el "Canal 1"
      static const int FRAMES_REQUESTED = 1;                                           // Parece relacionarse con la cantidad de buffers
      static const int TICKS_TO_WAIT = 0;                                            // Investigar
      static const i2s_bits_per_sample_t BITS_PER_SAMPLE = I2S_BITS_PER_SAMPLE_32BIT;   // Datasheet: 24. Ejemplo: 32.

      static const i2s_config_t SPH_CONFIG = {
        .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),                                            // El controlador es el Maestro y Recibe, el microfono es Esclavo y Transmite
        .sample_rate = 32000,                                                                           // Entre 32KHz y 64KHz (Datasheet)
        .bits_per_sample = BITS_PER_SAMPLE,
        .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,                                                   // El formato que usa el micrófono. No se encontró el Datasheet
        .communication_format = (i2s_comm_format_t) I2S_COMM_FORMAT_PCM,    //(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB) // Investigar
        //MSB: most significant byte -> BIG ENDIAN
        .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,                                                       // High interrupt priority (investigar)
        .dma_buf_count = 2,                                                                            // Cantidad de buffers, 128 max.
        .dma_buf_len = 32 * 2                                                                           // Tamaño de cada buffer
      };

    #pragma endregion Sección de Configuración

As you can see, I'm trying to get 32KHz as **sample rate** with **32 bit-depth** (not working for 16, and 24 bits), and I'm setting 115200 baud-rate in the Arduino IDE.

On the other hand, I created a .NET Winforms application that is receiving the generated PCM values over bluetooth 4.0. After 1 second is giving me only 693 samples which is very few.

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

**Can I reach at least 20KHz as sample rate with these hardware components? Do you see something wrong in my code?**

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

title: Increase sample rate in ESP32 board

Answers: 1

body:
Here's a few tips on optimization.

      for(int index = 0; index <= framesRead; index++)
      {

          value = smappioSound.getSampleValue(index);
          if(index % 2 == 0)
          {
              serialBT.print(String(value) + ",");
              Serial.println(value);
          }
      }

Doing

              serialBT.print(String(value) + ",");
              Serial.println(value);

is very wasteful. First of all you're debug-outputting every value as an ASCII string to `Serial`, second you're doing the same thing over `serialBT` with an additional `,`.

It's wasteful because:

* your baud rate is extremely low (115200 on `Serial`)
* converting every value to ASCII will induce an overhead

Your `int value` is 32 bits / 4 bytes which may take arbitrary values. Say the value is at its positive max at `0x7fffffff` = 214748364. Then transmitting the ASCII string will take 9 bytes (10 bytes for largest negative value), sending the raw binary value will *always* take 4 bytes. Thus you should always send your samples in raw binary format, not converted to an ASCII `String`.

At a wanted sampling rate of 32KHz with 32-bit values, you'd need an effective bit rate of 32000*32 = 1,024,000 Bits/s. Your `Serial` on which you are also printing every 2nd value, is on 115,200 bit/s (and you'd still have to account for the UART overhead, aka start and stop bits for every 8 data bits!).

Depending on the quality of the USB-UART converter on your board (FTDI, CP2102: good, CH340: bad), you can actually get to over 1 megabaud. The ESP32's UART periphal will allow you to set whatever clock divider you want to divide the 80 MHz APB clock ([source, chapter 13.3.2][1]). ESP-IDF has the `UART_BITRATE_MAX` defined to 5,000,000 ([source](https://github.com/espressif/esp-idf/blob/master/components/driver/include/driver/uart.h#L40)), and since Arduino-ESP32 derives from ESP-IDF, that should be possible there, too.

As I said, the USB-UART adapter between the ESP32 and your PC is critical. It has to support such a high speeds with a sufficiently large TX/RX buffer. The max baud rate of a CP2101 is 921600 ([source][2]), an FT232RL ([source][3]) up to 3 megabaud.

In general you don't want to give your sample values to the peripheral value-wise. Both your `Serial` and your `BluetoothSerial` have the possibility to enqueue a whole buffer at once ([source][4]). I don't know the real underlying implementation where the final samples will be stored (and held stable for a while) but you might just be able to do

    framesRead = smappioSound.read() / I2S_BITS_PER_SAMPLE_32BIT;
    serialBT.write((uint8_t*) buffer, framesRead * sizeof(int32_t));

to send the whole buffer at once. You'd also have to check how to handle or set the transmission speed on the bluetooth peripheral. I don't know much about the ESP32's BT / BLE radio to answer that.

Speed on a UART adapter could further be advanced to a non-blocking DMA backed variant. Since both I2S and the UART periphal support DMA transfers. Thus, the maximum transfer speed would be reachable.

Another posisbility would be to change the transission medium. You could have your ESP32 join a WiFi network and transmit its audio buffers via UDP or TCP to some server listening on the PC. I think however Bluetooth and UART (with the right tweaks) would also be possible.

  [1]: https://www.espressif.com/sites/default/files/documentation/esp32_technical_reference_manual_en.pdf
  [2]: https://www.silabs.com/documents/public/data-sheets/CP2102-9.pdf
  [3]: http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf
  [4]: https://github.com/espressif/arduino-esp32/blob/master/libraries/BluetoothSerial/src/BluetoothSerial.cpp#L238


body:
I am making a remotely controlled car for a project at Uni. The car is made from an Arduino Uno, a 2 motor driver and a Bluetooth transceiver. I have written some code for it, but it randomly stops after 2 or 3 loops.

Here is my code:

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

    #include "SoftwareSerial.h"

    typedef unsigned char u8;

    typedef struct {
      u8 right;
      u8 left;
    } speed;

    SoftwareSerial bluetooth(4, 2);

    const u8 RIGHT_MOTOR_PIN1 = 3;
    const u8 RIGHT_MOTOR_PIN2 = 5;
    const u8 LEFT_MOTOR_PIN1 = 6;
    const u8 LEFT_MOTOR_PIN2 = 9;

    const u8 MAX_SPEED = 0xFFU;
    const u8 HALF_SPEED = MAX_SPEED / 2;
    const u8 NO_SPEED = 0x0U;

    static u8 command = 0U;
    static speed potentialSpeed;
    static speed actualSpeed;

    void setup() {
      bluetooth.begin(115200);
      while (0U != bluetooth.available()) bluetooth.read();
      potentialSpeed.right = MAX_SPEED;
      potentialSpeed.left = MAX_SPEED;
      actualSpeed.right = NO_SPEED;
      actualSpeed.left = NO_SPEED;
    }

    void loop() {
      readCommand();
      {
        if (clockwise(command)) {
          if (0U == (command & 0xFEU)) {
            actualSpeed.right = - MAX_SPEED;
            actualSpeed.left = + MAX_SPEED;
          }
        } else if (counterclockwise(command)) {
          if (0U == (command & 0xFDU)) {
            actualSpeed.right = + MAX_SPEED;
            actualSpeed.left = - MAX_SPEED;
          }
        } else {
          if (right(command)) {
            potentialSpeed.right = HALF_SPEED;
          }
          if (left(command)) {
            potentialSpeed.left = HALF_SPEED;
          }
          if (forward(command)) {
            if (!backward(command)) {
              actualSpeed.right = + potentialSpeed.right;
              actualSpeed.left = + potentialSpeed.left;
            }
          } else if (backward(command)) {
            actualSpeed.right = - potentialSpeed.right;
            actualSpeed.left = - potentialSpeed.left;
          }
        }
        if (0U == command) {
          potentialSpeed.right = MAX_SPEED;
          potentialSpeed.left = MAX_SPEED;
          actualSpeed.right = NO_SPEED;
          actualSpeed.left = NO_SPEED;
        }
      }
      runAt(actualSpeed);
      delay(95);
    }

    void readCommand(void) {
      command = 0U;
      if (1U == bluetooth.available())
        command = bluetooth.read();
    }

    inline boolean clockwise(u8 command) {
      return (boolean)((command >> 0U) & 1U);
    }
    inline boolean counterclockwise(u8 command) {
      return (boolean)((command >> 1U) & 1U);
    }
    inline boolean right(u8 command) {
      return (boolean)((command >> 2U) & 1U);
    }
    inline boolean left(u8 command) {
      return (boolean)((command >> 3U) & 1U);
    }
    inline boolean forward(u8 command) {
      return (boolean)((command >> 4U) & 1U);
    }
    inline boolean backward(u8 command) {
      return (boolean)((command >> 5U) & 1U);
    }

    void runAt(speed Speed) {
      if (Speed.right > 0U) {
        analogWrite(RIGHT_MOTOR_PIN1, 0U);
        analogWrite(RIGHT_MOTOR_PIN2, Speed.right);
      } else {
        analogWrite(RIGHT_MOTOR_PIN1, (-(Speed.right)));
        analogWrite(RIGHT_MOTOR_PIN2, 0U);
      }
      if (Speed.left > 0U) {
        analogWrite(LEFT_MOTOR_PIN1, 0U);
        analogWrite(LEFT_MOTOR_PIN2, Speed.left);
      }
      else {
        analogWrite(LEFT_MOTOR_PIN1, (-(Speed.left)));
        analogWrite(LEFT_MOTOR_PIN2, 0U);
      }
    }

Could you please help me find the cause?
Also, I am unable to make it go backwards. Can that be related?

title: Arduino remote-controlled car stops after a few seconds

Answers: 1

body:
The problem was that the bluetooth module would receive bytes faster than the SoftwareSerial was able to read, so `bluetooth.available()` would return more than `1U` after a couple of loops. This was fixed by changing the following:

    void readCommand(void) {
      command = 0U;
      if (bluetooth.available()) {
        while(bluetooth.available() > 1U)
          bluetooth.read();
        command = bluetooth.read();
      }
    }

The 'make-it-run-backwards' problem was also solved, but was unrelated.


body:
I am building a clock with an Arduino.

Most clocks have a RTC module or some kind of RTC chip in order to get the time. I do not.

How do i replace this chip with software? Is there a C/C++ library equivalent to the Java library  `java.util.date`?

Can I run a Java program instead of a C program on my Arduino so I can use this Java library? I only know Java and have little experience with C/C++. I have looked into ways to program this clock in Java which I have had success with, but this is only in my computer, not in the Arduino.

title: Simulating a real time clock module with software

Answers: 2

body:
Having looked at you other question it seems you are trying to run before you can walk.  You may be a good java programmer, but you need to get your head around C++ before you go all in and build a clock.

To answer this question, yes there are ways to get software to keep time, but when you power it up, how do you know what the time is?  This is where having a RTC will help, there are plenty of bare ICs out there and even ones with libraries.

If you had a network then you could grab the header data from the network packets, but you are running this on a Mega, which seems an odd choice for something as simple as a network time clock, surly a nano would do, or an ESP8266.

These links will help you, but personally I think you need to break the problem down into smaller chunks.

https://www.arduino.cc/reference/en/

https://playground.arduino.cc/Code/Time

body:
> how do i replace [an RTC] chip with software?

You can't. An RTC is made of basically two things:

* a carefully trimmed crystal oscillator that has a very stable and well
  calibrated frequency
* some logic to count the oscillations and convert that to time and
  date.

The logic can be easily replaced by software, but the crystal cannot.
Any “pure software” solution you may find ultimately relies on counting
cycles of the system clock (the signal that clocks the whole
microcontroller). On most Arduinos, including the Uno, the system clock
is based on a [ceramic resonator][]. These are usually specified with
0.5% frequency tolerance, and they typically have a frequency offset of
about ±0.1%. That's a drift of ±44 minutes per month!

You can get better accuracy by calibrating your Arduino's clock, and
correcting by software the frequency offset you measure. However, the
frequency is not only off, it is also quite unstable, and very sensitive
to temperature variations. So even with calibration you end up with a
clock that is ridiculously bad compared with the cheapest quartz watch.

> is there a c++ library equivalent to the java library java.util.date?

I don't know Java, but there are C++ libraries available for managing
time. For example, you could initialize Paul Stoffregen's [TimeLib][] as
follows:

    setTime(hr,min,sec,day,mnth,yr);  // set initial time
    setSyncInterval(-1);  // pretend we don't need to resync

and then periodically query the time with `now()`. That should be all
you need to build a “proof of concept” of your clock: it will tell you
the time, but with an awfully bad long-term accuracy.

Note that, once you add an RTC or another good time source, you can add
a “time provider” to that library, keep the rest of your code unchanged,
and benefit from the accuracy of your new time source.

> Can i run a java program instead of a c program on my arduino [...]?

No, you can't. A Java runtime will never fit in your Arduino.

[ceramic resonator]: https://en.wikipedia.org/wiki/Ceramic_resonator

[TimeLib]: https://github.com/PaulStoffregen/Time


body:
I'm trying to optimize the communication (minimize wires) on a project where I can control a motor and toggle some 230V devices by using RS485 and I2C.

On this project, I'm using an Arduino (Mega) for the control panel (buttons, potmeters, LED segment display (I2C) etc.).

I'm using the RS485 protocol (Modbus RTU) to control an inverter by using a MAX485 TTL converter. Now I also have a relay board (8 channel) to be able to toggle some lightning and sound devices. Both the inverter and the relay board, as well as the power supply, are located in another box, which I call the power box. Between the control panel and the power box will be a cable.

[Control Panel (with arduino mega)] <--cable--> [power box (with inverter, 8 channel relay board and 230V devices)]

**I've got the following requirements:**

 - The cable should have a minimum amount of wires (5V, Ground, 485+(A) and 485-(B) for sure)
 - The total length of the cable varies from 1 to 3 meters.
 - The signal should be reliable.

Now the relay board uses 8 channels. I've bought an I2C expander (PCF8574) to minimize that to 2 wires (SDA, SCL).

I'm thinking of using the existing 485 lines to control the inverter AND the relay board. So no additional wires are required. But theoretically I can't get it to work. So before I try to invent it.

1. Can I do I2C communication over the RS485 as well somehow by putting another converter?

2. If you recommand to just go with 6 wires (power, RS485 and I2C), how reliable is my I2C line going to be on 3 meters? What pull-up values do you recommand? (24AWG wire in mind, but also using a close-by LED segment display, so 2 I2C devices on different distances). I've read posts saying:

>The rule of thumb is maximum 50 cm for a normal 100 kHz to 400 kHz I2C bus.

Or can I use some other protocol/trick? Either minimalize wires, or boost signal by a I2C buffer? (recommendations?)

title: How to make I2C work on RS485?

Answers: 1

body:
I2C and RS485 are such vastly different protocols with such vastly different signalling needs that they cannot share the same cables.

Further, I2C is not designed for connecting with long cables - it's meant for use between chips on a PCB.

The simplest "Arduino" solution would be to create a new RS485 device on your RS485 bus using another MAX485 and a small Arduino (micro, nano, etc) that responds to MODBUS RTU instructions and controls the relay board for you.


body:
I recently bought a mega 2560 to toy around with as a hobby. It's pretty fun so far, but I've recently gotten stuck while trying to use attachInterrupt with a button. I'm using the CHANGE mode, and have read the documentation pretty thoroughly ( I think ).

I've looked up multiple questions and tried to fix my setup and I still can't seem to make it work.

Here's my code:

    int buttonPin = 18;
    int ledPin1 = 11;
    int ledPin2 = 9;
    int ledPin3 = 5;

    int value = 0;

    void setup() {
      //declare inputs and outputs
      pinMode(buttonPin,INPUT_PULLUP);
      pinMode(ledPin1,OUTPUT);
      pinMode(ledPin2,OUTPUT);
      pinMode(ledPin3,OUTPUT);

      //create interrupt for button
      attachInterrupt(digitalPinToInterrupt(5),count,CHANGE);

      Serial.begin(9600);
    }

    void loop(){
      if(value == 0){ digitalWrite(ledPin1,HIGH);}
      else{ digitalWrite(ledPin1,LOW); }

      if(value == 1){ digitalWrite(ledPin2,HIGH);}
      else{ digitalWrite(ledPin2,LOW); }

      if(value == 2){ digitalWrite(ledPin3,HIGH);}
      else{ digitalWrite(ledPin3,LOW); }

      delay(500);
      Serial.print(digitalRead(buttonPin));

    }

    //count occurs when button is pressed
    void count(){
      //incremement a counter
      value++;
      //reset counter from 3 to 0
      if(value >= 2){ value = 0; }
    }

It's a pretty simple sketch. I'd attach a picture of my current setup but I don't really think It's needed. The button is indeed working as I'm debugging using serial.print().

If not clear, the objective of the sketch is to change the LED lit when the button is pressed. Currently, the variable value is stuck at 0.

title: attachInterrupt for mega 2560 not triggering

Answers: 1

body:
>     //create interrupt for button
    attachInterrupt(digitalPinToInterrupt(5),count,CHANGE);

The code does not match the comment.

    attachInterrupt(digitalPinToInterrupt(buttonPin),count,CHANGE);


body:
I recently purchased some inexpensive Nano boards, but they give an error signal and won't upload from my Mac with OSX High Sierra...  I am able to upload to Unos and Megas without issues.  I am selecting the correct board and the Atmega 328P and the dev/cu.bluetooth-incoming-port.I have also installed the CH341SER_MAC drivers using the H34X_INSTALL_V1.3 pkg. The error msg is as follows:  Can you help???

    /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc" -Wall -Wextra -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.elf" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/sketch/Blink.ino.cpp.o" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/core/core.a" "-L/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522" -lm
    "/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.elf" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.eep"
    "/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom  "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.elf" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.hex"
    Sketch uses 948 bytes (3%) of program storage space. Maximum is 30720 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.Bluetooth-Incoming-Port -b57600 -D -Uflash:w:/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.hex:i

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

             System wide configuration file is "/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/Users/daniellecomte/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/cu.Bluetooth-Incoming-Port
             Using Programmer              : arduino
             Overriding Baud Rate          : 57600
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
    Invalid library found in /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC: /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC
    Invalid library found in /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC: /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC

title: Uploading to a CH340 "Nano" board using a Mac with Osx High Sierra

Answers: 1

body:
If your clones come with a CH340G-chip you might proceed as follows:
Download the latest driver with Hi Sierra compatibility here: [Select Driver version 1.4 !!][1]

  [1]: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver
Install the driver by double clicking the downloaded file - the installation will stop, issuing an error message as it is an unsigned driver - but if you downloaded the driver via the GitHub link, it is ok. So open Tools, Security and you will be asked by OS X's security system if you want to install the driver anyway - YES!

After restarting your Mac connect your Nano clone and start a copy of the Arduino IDE. Assuming you got version 1.8.5: under Tools/Port you should see something like /dev/cu.wchusbserialXXX - select this port. Now update your board manager, close and restart the IDE again. Under Tools select  "Board: Arduino Nano" and "Processor: ATmega 328P (Old Bootloader)".

Now you should be ready to upload your sketch.

Background information:
Since January 2018 all original Nanos come with the Optiplex bootloader (which is also incorporated in other Arduinos like the Uno. Clones will most likely have the old bootloader pre-loaded, that's why the Processor selection must be set to ".... (Old Bootloader)".

Hope that helps to get along.


body:
I have decided to use NRF24L01+’s for my Arduino project for wireless communication. I am using the RF24 library by TMRh20 to talk back and forth.

Github Link: https://github.com/nRF24/RF24

I want to be able to send and receive data as fast as possible between the remote, and the receiver. After reading through the library I was able to create a some simple code that allowed the remote to transmit ~600 32-byte messages a second and the receiver was able to read ~490 messages a second.

Transmitter Loop Code:

`if (radio.available())
  { radio.read( &myData, sizeof(myData) ); }`

Receiver Loop Code:

`radio.write( &myData, sizeof(myData), 1);`

With this code however, the remote control cannot receive telemetry data back from the receiver. It is only a one way communication with no acknowledgments.

I have a few questions about wireless communication with the NRF24L01+. First, what is an acknowledgement? I understand it is a way for the transmitter to know that the receiver got the message, but what is being sent in the acknowledgment?

What is the difference between commands such as radio.write, radio.writefast, radio.startwrite, and radio.startwritefast. The RF24.h file has explnations of these commands but their desrciption does not make too much sense to me.

After doing some research, I found that to write, I must stop listening, write the message, and then start listening again for messages. The issue with this code is that the NRF is never listening long enough to receive a message (unless I add in a delay where it stays in RX mode). Is there anyway to keep a reading pipe open while writing and then pick it up from the FIFO when I am ready to read?

It seems that it is possible to write an ACK Payload, and this allows the NRF to transmit a message without leaving RX mode. Is this a possibility, and what is an ACK Payload?

What is the best practice for achieving the fastest speed two-way communication. Is it common practice to have two NRF’s and have one dedicated to listening and one dedicated to writing on each Arduino? Is there a good way to achieve high speed two-way communication rates with a single NRF?

title: Wireless Communication with NRF24L01+

Answers: 1

body:
firstly, the `radio.write` command is used for checking for the acknowledgement from the RX after the `FIFOs` are full for a single write. But `radio.writefast` will not wait for the acknowledgement from the RX and would continuously transmit the payload for a single write. Similarly for `radio.startwrite` and
`radio.startwritefast` commands.

Coming to the keeping the NRF in listening mode, even I haven't tried it before so I cannot suggest an exact solution for this problem. But as far as I know,  you can go for `writestart` command to keep the reading pipes open while you are sending. But I would personally suggest you to confirm this from datasheet again before experimenting.

For ACK payload, it depends upon the master unit controlling the `SPI communication` with the NRF chip and thus, by maintaining a mutual understanding between the RX and TX units, you can define the payload for acknowledgement signal as well.

Coming to best speed possibility, To increase speed, NRF has three speeds from which you can select the highest value available. Also see which `pipe/channel` works the best for you so that you can achieve the least number of lost packets.


body:
I just got an Arduino nano (from arduino.cc, not a knock-off), and have issues uploading sketches. It refuses to upload, with the error message "programmer is not responding".

Some searching led to an incorrect transfer baud rate. Indeed, the IDE (1.8.5) output before uploading displays "overriding baud rate: 57600", and the command line has a `-b57600` argument. By copying this command in a terminal and removing this parameter, the upload works. It also works with `-b115200`. All other values I tried do not work.

Is there a way to configure the IDE to use the correct baud rate ? I know I could use the command line, but that's not very practical, I would prefer to keep the _Integrated_ part of the IDE :).

title: Set avrdude transfer baud rate in Arduino IDE

Answers: 1

body:
Update the boards package for the AVR hardware. That will give you new options in the tools menu.

Then you should just select the right CPU variant.

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

From top to bottom those are 115200, 57600 and 19200 baud.

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


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

I use 2 gearbox motors with 2 wheels .. but if I try to run it, he can not walk straight. he always moves slightly to the right or to the left.

How i fix it ?

title: My "avoid car" can't move straight

Answers: 1

body:
Likely the two gearbox motors you have are running at slightly different speeds for the same voltage. This is probably within normal tolerances, given that you say it moves *slightly* to the right or left.

You can use PWM-capable pins for motor control so you can adjust how fast the motors turn. If you do this, you have a couple of paths you can take:

You can, through trial-and-error, lower the PWM value (`analogWrite(pin, speed)`) for the faster-turning motor so that they both turn at the same speed.

or

You can find some way to detect the actual rotational speed of each motor and do the calibration in real-time on the Arduino. This might mean adding new sensors such as rotary encoders (mechanical or optical), or light-break sensors, etc.


body:
[![][1]][1]
Hello, I apologise for being such a noob but can someone help with this.
I am having trouble working with this. When I insert the arduino's pins into my new usb host shield , there is no indication light and when I plugged my Xbox receiver into the shield it does not turn on as it would with my desktop. Any thoughts? Please post below

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

title: USB host shield help

Answers: 1

body:
Posting the clear photo is helpful because it shows the USB host board has the [following problem][1].

  [1]: https://esp8266-notes.blogspot.com/2017/08/defective-arduino-usb-host-shield-boards.html


body:
I'm trying to use momentary push buttons to switch bi color LED between RED and GREEN. I've got one working, but when I try to adapt the code for more buttons, it doesn't work. I'm just changing the buttonnumbers (which are defined).
It compiles and uploads without error.

    void loop() {
      byte currentButton1Status = digitalRead(button1);
      if (currentButton1Status == button1Status)
        lastEqualButtonTime = millis();
      else if ((millis() - lastEqualButtonTime) > debounceTimeMs)
      {
        lastEqualButtonTime = millis();
        button1Status = currentButton1Status;

        if (button1Status == LOW) {
          digitalWrite(17, !digitalRead(17));
          digitalWrite(16, !digitalRead(16));
        }
      }

      byte currentButton2Status = digitalRead(button2);
      if (currentButton2Status == button2Status)
        lastEqualButtonTime = millis();
      else if ((millis() - lastEqualButtonTime) > debounceTimeMs)
      {
        lastEqualButtonTime = millis();
        button2Status = currentButton2Status;

        if (button2Status == LOW) {
          digitalWrite(15, !digitalRead(15));
          digitalWrite(14, !digitalRead(14));
        }
      }
    }

title: currentbuttonstatus

Answers: 1

body: You've only said "... it doesn't work" which doesn't give much to go on, but the first thing I see that might contribute it not working as (I think) you expect it o, is only one `lastEqualButtonTime` variable for both buttons (is it a global? I don't see a definition). I think you'll need one for each.


body:
How can I declare an empty global array, to be initialized in setup?

What I would like to do is this:

    #include <ResponsiveAnalogRead.h>

    const size_t ANALOG_SIZE = 3;
    const int ANALOG_PINS[ANALOG_SIZE] = {A0,A1,A2};
    ResponsiveAnalogRead analog_reads[ANALOG_SIZE];

    void setup() {
      for(size_t i=0; i<ANALOG_SIZE; i++){
        analog_reads[i]=ResponsiveAnalogRead(ANALOG_PINS[i], true, 0.01);
      }
    }

But the error I get is:

    sketch_may29c:5: error: no matching function for call to 'ResponsiveAnalogRead::ResponsiveAnalogRead()'
     ResponsiveAnalogRead analog_reads[ANALOG_SIZE];

                                                  ^

Is it impossible to declare an empty array of a given size?

title: How can I initialize an array of objects in setup?

Answers: 3

body:
When you declare an array it will call the [default constructor][1] for the type. ResponsiveAnalogRead does not have a default constructor so it cannot initialize the entries in the array.

  [1]: http://en.cppreference.com/w/cpp/language/default_constructor

body:
As Craig wrote, the declaration of an class typed array will call the default constructor of the class, which is the one without any arguments. The class, that you use, does not provide a default constructor, since it needs it's parameters. You cannot do it this way.

But you can use dynamic allocation. In global scope only declare an array of pointers to `ResponsiveAnalogRead` objects:

    ResponsiveAnalogRead *analog_reads[ANALOG_SIZE];

This array only holds pointers, that can point to `ResponsiveAnalogRead` objects. The objects themselves are not created yet. In `setup()` you can then create the objects dynamically with the `new` statement:

    analog_reads[0] = new ResonsiveAnalogRead( input_parameters);

(Of course you have to replace `input_parameters` with all parameters, that the constructor needs). To call a member of the object, you can dereference it like this:

    analog_reads[0]->member_function();

If you don't know about pointers yet, you should google for a tutorial (there are plenty), so that you understand the principle behind them.

Important note: Dynamic allocations of memory geht written to the heap in RAM. Since the Arduino (especially the Atmega based ones) has only very limited RAM, dynamic allocations have to be handled with great care. You should not create and delete data often in your program, since this would make swiss cheese out of your heap. But allocating the memory only once in your program and never deleting it, will not be a problem, as long as you don't try to allocate too much memory.

body:
Craig already explained the reason of the error is the lack of a default
constructor, and chrisl suggested a reasonable alternative. I would like
to suggest two other alternatives.

## Static initialization

You state that you want to do the initialization in `setup()`, but you
don't explain _why_ you want that. I will guess that what you _really_
want is to have all those objects in array. The library page provides
this example showing how to statically initialize multiple instances:

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

    ResponsiveAnalogRead analogOne(A1, true);
    ResponsiveAnalogRead analogTwo(A2, true);

The problem with this example is that you don't have an array, so you
cannot loop through the instances. This problem, however, can be easily
fixed:

    const size_t ANALOG_SIZE = 3;
    ResponsiveAnalogRead analog_reads[ANALOG_SIZE] = {
        ResponsiveAnalogRead(A0, true),
        ResponsiveAnalogRead(A1, true),
        ResponsiveAnalogRead(A2, true)
    };

Note that you don't need the `ANALOG_PINS` array anymore. And you don't
need to pass `0.01` as the last argument to the constructor, as this is
the default value anyway. This would be my preferred solution: it is
simple enough and doesn't increase the number of lines of code.

## Patching the library

If you _really_ want to initialize the array in `setup()`, then you can
patch the file ResponsiveAnalogRead.h from the library:

1. Add default values to all the parameters of the constructor. For
   example:

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

    ResponsiveAnalogRead(int pin=0, bool sleepEnable=0, float snapMultiplier=0.01);

2. Add a method for setting the pin after initialization:

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

    void setPin(int newPin) { pin = newPin; pinMode(pin, INPUT); }

The first change will enable you to compile your code as-is. The second
change will allow you to update the objects in `setup()` rather than
overwriting them (which I don't find very elegant):

    for (size_t i = 0; i < ANALOG_SIZE; i++) {
        analog_reads[i].setPin(ANALOG_PINS[i]);
        analog_reads[i].enableSleep();
    }

Note that using the default constructor now has the side effect of
setting pin 0 to input. This should not be a big deal, as the
constructor is called before `setup()`, and all the IO pins are inputs
at this point. If you want nevertheless to void that side effect, then
set the default pin to `-1`, and patch the constructor to only configure
the pin if it's not `-1`.

Patching the library creates a maintenance burden though: you will have
to reapply the patch each time the library is updated. This may not be
that bad if you know how to `git rebase` or `git merge`, but ideally you
would want to get a pull request accepted by the original maintainer.

**Edit**: Before patching the library, consider weighting in [this
issue][issue-11] and using [this fork][kschaffer-fork].

**Update**: A [pull request][pull-15] addressing this issue has been
accepted. As of version 1.2.0, the class has now a default “do nothing”
constructor.

[issue-11]: https://github.com/dxinteractive/ResponsiveAnalogRead/issues/11
[kschaffer-fork]: https://github.com/kschaffer/ResponsiveAnalogRead
[pull-15]: https://github.com/dxinteractive/ResponsiveAnalogRead/pull/15


body:
I am trying to use atmega88 timer2 with a 32.768KHz crystal. I'm using a slightly modified version of [Nick Gammon's code][1]. I am using [Minicore][2]. No bootloader, 1MHz clock from internal oscillator, BOD disabled. Sleep is interrupted every 8 seconds. I use a counter to count 12 minutes. Since it overshoots about 8 seconds every 6 hours, I am subtracting 8 sec every 6 hours. I hope to eventually make a weather logger with this.

The code is mostly working in it's bare stripped down version, after I add a delay(100) after the digitalWrite. However, I also need Serial. When I enable Serial, it does not sleep anymore. Also, the serial output has a lot of excess weird characters. This happens at all baud rates, even 1200 (serial monitor set to same baud rate as in program). I think some interrupts are being called during digitalWrite and when the usart is powered on and it is messing with the sleep. I am a beginner regarding uC programming, and am really struggling with the datasheet and the code. Any help will be appreciated.

Here is the test code:

    #include <avr/sleep.h>
    #include <avr/power.h>

    const byte tickPin = 4;// (do not use 3 and 11)

    //byte intCounter = 0;
    //byte leapCounter = 0;

    int intCounter = 0;
    int leapCounter = 0;

    unsigned long prevTime = 0;
    unsigned long currTime = 0;

    // interrupt on Timer 2 compare "A" completion - does nothing
    EMPTY_INTERRUPT (TIMER2_COMPA_vect);

    void setup(){
      pinMode (tickPin, OUTPUT);

      Serial.begin(9600);
      prevTime = millis();
      Serial.print(" P: ");
      Serial.println(prevTime);

      // clock input to timer 2 from XTAL1/XTAL2
      ASSR = bit (AS2);

      // set up timer 2 to count up to 256 * 1024  (8 seconds)
      TCCR2A = bit (WGM21);                             // CTC
      TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
      OCR2A =  255;                                     // (zero-relative)

      // enable timer interrupts
      TIMSK2 |= bit (OCIE2A);

      // disable ADC
      ADCSRA = 0;

      // turn off everything we can
      power_twi_disable();
    //  power_timer0_disable();
    //  power_timer1_disable();
      power_spi_disable();
      power_usart0_disable();
      power_adc_disable ();

      // full power-down doesn't respond to Timer 2
      set_sleep_mode (SLEEP_MODE_PWR_SAVE);

      // get ready ...
      sleep_enable();

    }  // end of setup

    void loop(){
      sleep_cpu ();
      ++intCounter;

      power_usart0_enable();
      Serial.print("I: ");
      Serial.print(intCounter);
      Serial.print(" L: ");
      Serial.print(leapCounter);
      currTime = millis();
      Serial.print(" C: ");
      Serial.print(currTime);
      Serial.print(" E: ");
      Serial.print(currTime - prevTime);
      Serial.println();
      prevTime = currTime;
      power_usart0_disable();
      delay(1000);

      if ((leapCounter > 30) && (intCounter == 1)){
        leapCounter = 0;
        intCounter = 0;
      }
      if (intCounter > 89){
        ++leapCounter;
        intCounter = 0;
        digitalWrite (tickPin, ! digitalRead (tickPin));
        delay(100);
      }
    //  digitalWrite (tickPin, ! digitalRead (tickPin));
    //  delay(100);
    }  // end of loop

The chip is an Atmega88 (not P). It is drawing the same 6.5uA during sleep, with or without timer0 and timer1. So, I probably don't care if I have to leave them enabled.

I am planning to use a DHT11 and a ds18B20 and write the data to a w25Q64 flash, every 12 minutes. I'd prefer reading it all out via serial port every few weeks, without having to stop the uC.

**update**

Calling timer2 ISR, instead of handling wake up directly in main loop. Possibly more stable (not affected by Serial and digitalWrite)... but I am not sure.

    #include <avr/sleep.h>
    #include <avr/power.h>
    #include <avr/wdt.h>

    //const byte tickPin = 4;// (do not use 3 and 11)

    volatile bool t2flag = LOW;
    volatile byte t2counter = 0;

    byte leapCounter = 0;

    //preventing digitalWrite from causing interrupt (did not help much)
    EMPTY_INTERRUPT(PCINT2_vect);

    void setup(){
      pinMode (4, OUTPUT);
      pinMode (1, INPUT_PULLUP); //set TX pin default HIGH

      // clock input to timer 2 from XTAL1/XTAL2
      ASSR = bit (AS2);
      // set up timer 2 to count up to 256 * 1024  (8 seconds)
      TCCR2A = bit (WGM21);                             // CTC
      TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
      OCR2A =  255;                                     // (zero-relative)
      // enable timer interrupts
      TIMSK2 |= bit (OCIE2A);
      // disable ADC
      ADCSRA = 0;

      // turn off everything we can
      power_twi_disable();
    //  power_timer0_disable();
    //  power_timer1_disable();
      power_spi_disable();
      power_usart0_disable();
      power_adc_disable();
      wdt_disable();// reduces 6.5uA to 2.2uA @ 3.3V

      // full power-down doesn't respond to Timer 2
      set_sleep_mode (SLEEP_MODE_PWR_SAVE);
      sleep_enable();
    }

    //ISR to handle timer2
    ISR (TIMER2_COMPA_vect){
      ++t2counter;
      if (t2counter > 89){t2flag = HIGH;}
    }

    void loop(){
      if (t2flag == LOW){

        power_usart0_enable();
        Serial.begin(9600);
        Serial.print("I: ");
        Serial.print(t2counter);
        Serial.println();
        Serial.flush();
        delay(10);
        Serial.end();
        power_usart0_disable();

        //blip the tickPin every 8 sec
        PORTD |= (1<<PD4);
        delay(10);
        PORTD &= ~(1<<PD4);

        delay(100);//helps a lot
        sleep_cpu();
        return;
      }

      ++leapCounter;
      if (leapCounter == 30){
        t2flag = LOW;
        return; //delay another 8 sec every 6 hours
      }
      if (leapCounter > 30){leapCounter = 0;}

      t2flag = LOW;
      t2counter = 0;

      power_usart0_enable();
      Serial.begin(9600);
      Serial.print("L: ");
      Serial.print(leapCounter);
      Serial.println();
      Serial.flush();
      delay(10);
      Serial.end();
      power_usart0_disable();

      //long blip every 12 minutes
      PORTD |= (1<<PD4);
      delay(100);
      PORTD &= ~(1<<PD4);
    }

The problem is not always present. But when it appears, it happens the same way. After pressing reset button, first led blink is always after 8 seconds. After that, one of three things seem to happen. 1. Second flash is after 8 seconds and everything works as expected. 2. Second flash is after 3 seconds and all flashes after that are also after every 3 seconds. 3. Second flash happens immediately after first flash (and any delay() in the code) and this keeps on happening. In all cases, the serial output also shows the same pattern.

Sometimes it seems that wires connected to the serial or miso, mosi, sck may be causing this, but that is not always the case. The problem may occur even if these wires are not connected. Also, the problem may or may not occur with the same code (e.g. pressing reset after 30 sec may not show any problem, but pressing reset within 5 or 10 seconds leads to problem cases 2 and 3 above. So there is some kind of race condition, or buffer or interrupt noise or something.

I have to program with Arduino as ISP, as the bootloader is unable to sync with the ftdi chip for some reason while uploading sketch. But data transfer from the sketch with serial.print is working fine. So pulling out the miso mosi sck pins everytime is a hassle. Everything is on breadboard. I transferred full circuit to new breadboard (from old loose breadboard) but there is no change. So maybe not a breadboard issue.

  [1]: http://www.gammon.com.au/forum/?id=11504&reply=10#reply10
  [2]: https://github.com/MCUdude/MiniCore

title: atmega88 timer2 32.768KHz and Serial problem

Answers: 1

body:
I see two issues in this code.

The first is that you are trying to send data through an UART that has
been powered off. `Serial.print()` doesn't wait for the data to get out,
it merely stores it into a memory buffer. You should wait until
everything gets out before switching the UART off. This can be done by
calling either `Serial.flush()` or `Serial.end()`. I would use the
latter, as it feels safer to stop the UART before switching if off. But
then you have to `Serial.begin()` again on wakeup.

To avoid the garbled characters in the serial stream, you could try to
either `pinMode(1, INPUT_PULLUP);` or `digitalWrite(1, HIGH);`. This way
you ensure that the TX line stays `HIGH` (which is its normal idle
state) when the UART goes off.

The second issue is your use of the Arduino timekeeping functions
`millis()` and `delay()`. These functions rely on an interrupt triggered
by Timer 0. If you power off that timer, `millis()` and `delay()`
won't work. If you don't, `SLEEP_MODE_PWR_SAVE` does it for you while
sleeping. Then those function will work while awake, but `millis()` will
not count the time you spent sleeping.

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

**Edit:** There are two interrupts related to the UART that are enabled
by `Serial.begin()`:

* `USART_UDRE`, “Data Register Empty”, is used for transmission. It
  fires when the hardware transmit buffer is ready to receive new data.
  The corresponding ISR's job is to copy one byte from the transmit
  memory buffer (the one `Serial.print()` writes into) into the hardware
  transmit buffer.

* `USART_RX`, “Receive Complete”, is used for reception. It fires when a
  byte is received. The corresponding ISR copies this byte into receive
  memory buffer (the one `Serial.read()` reads from).

The first one fires when transmitting. Once you wait for the end of the
transmission (say with `Serial.flush()`), you shouldn't see this
interrupt firing anymore.

The second one fires only when receiving. If you are not receiving
anything, this interrupt shouldn't fire. If the RX pin is floating, the
interrupt could be triggered by external noise. This can be prevented by
enabling the internal pullup on the RX pin. Alternatively, you can
disable the receiver part of the UART:

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

    UCSR0B &= ~_BV(RXEN0);  // disable the UART receiver

Note that if you stop the UART with `Serial.end()`, both the transmitter
and the receiver are disabled, and you don't get UART-related interrupts
anymore.


body:
I noticed that OneButton library does not work with pins A6 and A7 (with A1 and A2 it works good) on my Arduino Nano. Is it because A6 and A7 are Analog only? There is possibility to make them work properly?

sketch example is here https://github.com/mathertel/OneButton/blob/master/examples/TwoButtons/TwoButtons.ino

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

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

title: OneButton with pins A6 and A7

Answers: 1

body:
Pins A6 and A7 are *analog only* pins. They have no digital functionality at all.

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

You can see that pins 19 and 22 only have ADCn on them - no Pxn for digital operation (ignore the colour scheme of those pins - that's an error in the datasheet).

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


body:
If I set timer2 to Compare Match mode, my LCD display stops working. If I use Overflow Interrupt it works fine.

Here's my test code. I have a loop() function which does its thing, and a timer interrupt which increments another variable, just to show it's working.

<!-- language: lang_cpp -->

    #include <LiquidCrystal.h>
    #include <avr/interrupt.h>
    #include <avr/io.h>

    LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2 LCD shield. LCD:

    int i;
    volatile int j;
    void setup()
    {
      i=0;
      j=0;
      //button adc input
      pinMode( A0, INPUT ); //ensure A0 is an input
      digitalWrite( A0, LOW ); //ensure pullup is off on A0
      //lcd backlight control
      pinMode( 10, OUTPUT ); //D10 is an output
      digitalWrite( 10, HIGH ); //backlight control pin D10 is high (on)
      //set up the LCD number of columns and rows:
      lcd.begin( 16, 2 );

      // setup timer interrupt
      cli(); //disable global interrupts
      TCCR1A = 0;   //set tccr1a and tccr1b to 0
      TCCR1B = 0;
      //set cs10 and cs12 bit so timer runs at clock iSpeed/ 1024
      TCCR1B |= (1 << CS10);
      TCCR1B |= (1 << CS12);

      // Compare Match Mode **Doesn't work**:
      //set compare match register
      OCR1A = 15624;
      // turn on CTC mode
      TCCR1B |= (1 << WGM12);
      // enable Timer1 compare interrupt
      TIMSK1 = (1 << OCIE1A);

      // Overflow mode **Works**
      // enable overflow interrupt
      // TIMSK1 = (1 << TOIE1);

      //enable global interrupt
      sei();
    }
    void loop()
    {
      lcd.setCursor( 0, 0 ); //top left
      lcd.print(i);
      lcd.setCursor(0,1); //bottom left
      lcd.print(j);
      delay(500);
      lcd.clear();
      i++;
    }

    ISR(TIMER1_OVF_vect)
    {
      j++;
    }

If I use overflow interrupts it works fine, the loop() counter is displayed on the top line and the interrupt counter on the second, but by using overflow interrupts I'm limited to the whatever timing the various prescalers give me.

If I use compare match the LCD display just shows faint flickering squares on its first line, like it's doing something but too quickly for the LCD to display.

I looked at the source for liquidcrystal.cpp, and it doesn't seem to use any timer or interrupts, so I'm completely mystified.

title: LiquidCrystal library and timers don't seem to be compatible

Answers: 1

body:
Dang, it was a bit of a noobish error. I had the interrupt handler setup for the overflow interrupt, but when I swapped the code in for the Compare Match interrupt I didn't make a handler for it. So since there's an interrupt without a handler [it seems it just resets][1], hence the flashy-flashy garbage I was seeing on the LCD.

Adding this fixed the problem:

    ISR(TIMER1_COMPA_vect)
    {
      j++;
    }

  [1]: https://arduino.stackexchange.com/questions/22398/why-does-enabling-timsk1-mess-up-serial


body:
Hello I am trying to send temperature data via bluetooth using the HC-06 module. Since TXD and RXD only allow 3.3V I have divided the circuit into two like the below image.
Is this method correct? or is there a better way to connect both two?

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

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

Any help is appreciated.

  [1]: https://i.stack.imgur.com/9BZl6.jpg
  [2]: https://i.stack.imgur.com/unQcu.jpg

title: Connecting HC-06 and LM35

Answers: 1

body:
As mentioned by chrisl, you cannot use HC-06 as a `master` device. Its firmware restricts it to behave only as a slave. So even if you are able to process the analog data from `LM 35`, you won't be able to send it using `HC-06`. It would be better if you go for `HC-05` module and try the command `AT+ROLE: x` (x = 1 for master/0 for slave) to get the job done.

Coming to the 3v3 voltage constraint, I would suggest you to go for any Zener diode (in reverse biased mode) with `3.3V Reverse breakdown voltage`. You can check the circuit for this [here][1] and order it from [this link][2]. If this is not possible anyhow, then you can also go for `LM1117 3V3`, but I would personally suggest you to go for zener diode. Comment back if you need any help in future.

  [1]: http://www.chegg.com/homework-help/questions-and-answers/33v-1n4728a-zener-used-33-v-voltage-regulator-5-v-source-shown--zener-diode-reverse-breakd-q19274856
  [2]: https://www.ebay.com/p/20-X-1N4728A-1n4728-Vishay-ZENER-Diode-3-3v-1w/1018498160


body:
I'm very new about this thing. I have made an arduino robot car for my assignment. There is a maze that I have to complete it. I'm using L298N Dual H-Bridge Motor Driver, Servo Motor, HC-SR04 Ultrasonic Sensor, DC Motor, Arduino Sensor Shield.

The problem when in the maze is, the sensor will check if there is wall front of the car. Then it will scan from left, then right. BUT, the maze was straight line and at the middle, has one way out.

I have a problem on how to make the sensor detect the 180 degree of wall every second. What I mean is, when the car move ahead inch, the sensor will scan left, front, right. Then, if there is a wall at left, the car move ahead inch, then scan again. I really need help for this assignment.

[![Figure 1][1]][1]
[![Figure 2][2]][2]

Here is my code:

    #include <Servo.h>
    // Pins for the Echo Sensor
    #define TRIG_PIN A0
    #define ECHO_PIN A1
    //Define all the connections maps to the L298N
    #define enA 13
    #define in1 12
    #define in2 11
    #define in3 7
    #define in4 6
    #define enB 5
    #define servoPin 2

    class Motor{

    int enablePin;
    int directionPin1;
    int directionPin2;

    public:

    //Methods to define motor pins
    Motor(int ENPin,int dPin1,int dPin2){
    enablePin = ENPin;
    directionPin1 = dPin1;
    directionPin2 = dPin2;
    };

    //Method to allow robot to turn and move forward and backwards
    void Drive(int speed){
    if(speed>=0){
    digitalWrite(directionPin1, LOW);
    digitalWrite(directionPin2, HIGH);
    }
    else{
    digitalWrite(directionPin1, HIGH);
    digitalWrite(directionPin2, LOW);
    speed = - speed;
    }
    analogWrite(enablePin, speed);
    }
    };

    Motor leftMotor = Motor(enA, in1, in2);
    Motor rightMotor = Motor(enB, in3, in4);
    Servo myservo; // create servo object to control a servo

    void motorInitiation(){
    pinMode(enA, OUTPUT);
    pinMode(in1, OUTPUT);
    pinMode(in2, OUTPUT);
    pinMode(enB, OUTPUT);
    pinMode(in3, OUTPUT);
    pinMode(in4, OUTPUT);
    // Set initial direction and speed
    digitalWrite(enA, LOW);
    digitalWrite(enB, LOW);
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
    digitalWrite(in3, LOW);
    digitalWrite(in4, HIGH);
    }

    //Variables--------------------------------------------------------------------------
    // Anything over 400 cm (23200 us pulse) is "out of range"
    const unsigned int MAX_DIST = 23200;
    bool ObsticalAhead = false;
    int servoPos = 90;

    enum Directions { Forward, TurnLeft, TurnRight, TurnAround,Brake};

    Directions nextStep = Forward;

    unsigned long t1;
    unsigned long t2;
    unsigned long pulse_width;
    float cm;
    float inches;

    //SETUP--------------------------------------------------------------------------
    void setup() {

    // The Trigger pin will tell the sensor to range find
    pinMode(TRIG_PIN, OUTPUT);
    digitalWrite(TRIG_PIN, LOW);

    // Serial monitor to view the sensor output
    Serial.begin(9600);
    myservo.attach(servoPin);
    motorInitiation();
    Directions nextStep = Forward;
    }

    void loop() {

    checkDistance();
    checkDirection();
    drive();
    }

    void checkDistance(){

    // Hold the trigger pin high for at least 10 us
    digitalWrite(TRIG_PIN, HIGH);
    delayMicroseconds(10);
    digitalWrite(TRIG_PIN, LOW);

    // Wait for pulse on echo pin
    while ( digitalRead(ECHO_PIN) == 0 );

    // Measures how long the echo pin was held high (pulse width)
    t1 = micros();
    while ( digitalRead(ECHO_PIN) == 1);
    t2 = micros();
    pulse_width = t2 - t1;

    // Calculate distance in centimeters and inches from sound to bounce back
    cm = pulse_width / 58.0;
    inches = pulse_width / 148.0;

    // Print out results
    if ( pulse_width > MAX_DIST ) {
    //Serial.println("Out of range");
    } else {
    //Serial.print(cm);
    //Serial.print(" cm \t");
    //Serial.print(inches);
    //Serial.println(" in");
    }

    // Wait at least 60ms before next measurement
    delay(60);

    if(cm<= 20){
    ObsticalAhead = true;
    Serial.println("Problem Ahead");

    }
    else{ ObsticalAhead = false;}

    }
    void checkDirection(){
    Serial.println("checking direction");
    if(ObsticalAhead ==true){
    nextStep = Brake;
    drive();
    myservo.write(180); // tell servo to go to position in variable 'pos'
    delay(400); // waits 15ms for the servo to reach the position
    checkDistance();
    if(ObsticalAhead ==false){//if left side is open
    nextStep = TurnLeft;
    Serial.println("Next step is TurnLeft");
    myservo.write(90);//reset servo position
    delay(400);
    }
    else{// left is blocked, now need to look at right
    myservo.write(0); // tell servo to go to position in variable 'pos'
    delay(800); // waits 15ms for the servo to reach the position
    checkDistance();
    if(ObsticalAhead ==false){//if right side is open
    nextStep = TurnRight;
    Serial.println("Next step is TurnRight");
    myservo.write(90);//reset servo position
    delay(400);
    }
    else{//right is blocked as well, need to turn around
    nextStep = TurnAround;
    myservo.write(90);//reset servo position
    delay(300);
    Serial.println("Next step is TurnAround");
    }
    }

    }
    else{nextStep = Forward;}//No obstical ahead
    }

    void drive(){
    switch (nextStep){
    case Forward:
    leftMotor.Drive(255);
    rightMotor.Drive(255);
    Serial.println("Forward");

    break;
    case TurnLeft:
    leftMotor.Drive(-255);
    rightMotor.Drive(255);
    Serial.println(" TurnLeft");
    delay(400);

    break;
    case TurnRight:
    leftMotor.Drive(255);
    rightMotor.Drive(-255);
    Serial.println(" TurnRight");
    delay(400);
    break;
    case TurnAround:
    leftMotor.Drive(255);
    rightMotor.Drive(-255);
    Serial.println(" TurnAround");
    delay(600);
    break;

    case Brake:
    leftMotor.Drive(0);
    rightMotor.Drive(0);
    Serial.println(" stopped");
    }
    }

  [1]: https://i.stack.imgur.com/Sn2Qk.jpg
  [2]: https://i.stack.imgur.com/bs6K3.jpg

title: Sensor Robot Car Arduino Cannot Detect Every Inch

Answers: 0


body:
My ESP8266 has stopped working.
The red power light comes on and the blue TX light is on solid.

Here's what I did.

Connecting

ESP8266  -> Arduino nano

`VCC`, `CH_PD`, `RST`  -> `5V` (external supply)

`TX` -> `TX`

`RX` -> `RX`

I could send AT commands via the serial monitor.

Then I connected

`RX` -> `11`

`TX` -> `10`

and set up software serial intending to repeat the experiment.
I was getting garbage characters in the response, and found that I had to `esp8266.println("AT+IPR=9600");` to reduce the baud rate.

Then the blue TX light cam on permanently and it's stopped working at all.

title: Connecting and using ESP8266 wifi

Answers: 1

body:
Serial devices should be connected RX to TX and TX to RX.

When you connected the RX to RX you connected the esp8266 to USB chip on Nano. Because the USB chip is connected to Atmega on Nano RX to TX, so if you connect the esp8266 to the same line, the it is connected RX to TX to USB.

On this picture esp8266 is connected to Atmega and not accessible from USB:

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

Communication from Serial Monitor over USB to esp8266 on pins 10 and 11 of the Atmega could work only with [SerialPassthrough sketch][2] resending data between Serial and SoftwareSerial on pins 10 and 11.

  [1]: https://i.stack.imgur.com/Ga5Ux.png
  [2]: https://www.arduino.cc/en/Tutorial/SoftwareSerialExample


body:
I try to control a Stepper motor with an arduino and a L298. I use the library stepper.h and it works well but i have a problem : the L298 become very hot. So i want to disable the break (the thing that we can't turn the motor by hand), but i don't know how to do this.
Do you have an idea ?
My code is simple :

    #include <Stepper.h>

    const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
    // for your motor

    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    void setup() {
      // set the speed at 60 rpm:
      myStepper.setSpeed(60);
      // initialize the serial port:
      Serial.begin(9600);
    }

    void loop() {
      // step one revolution  in one direction:
      Serial.println("clockwise");
      myStepper.step(stepsPerRevolution);
      delay(500);

      // step one revolution in the other direction:
      Serial.println("counterclockwise");
      myStepper.step(-stepsPerRevolution);
      delay(500);
    }

I took it from here : https://coeleveld.com/arduino-stepper-l298n/

Thanks !

title: L298 with stepper.h disable break

Answers: 1

body:
There is no facility in the stepper library to do what you want - however the stepper library just sequences IO pins in the right order.

There's nothing to stop you just placing those same IO pins in a different state - the library won't care.

    void sleepStepper() {
        digitalWrite(8, LOW);
        digitalWrite(9, LOW);
        digitalWrite(10, LOW);
        digitalWrite(11, LOW);
    }

That will effectively set every port of the L298 LOW, which is equivalent to "brake" mode on a normal DC motor, or "not actively driving" on a stepper (not perfect freewheel, there is still some flyback braking).

Another option is to connect the EN pin(s) of your L298 chip to a GPIO and use that to turn the whole system on and off. That will disconnect the drivers from the motor and give you even less movement resistance than the "all low" method above.