message:
Arduino Serial Response is Slow when in While Loop

Good evening all,

I'm having an issue with a quick "test" project that I am tinkering with (learning the "do's" and "don'ts") the NeoPixel LED strip.  I've been piecing together excerpts from other folks and so far everything is great.

I'm doing it over serial sending switch/case with numbers from the keyboard for different options.  The issue I am currently having is "case 1:", when I hit the "1" key and it fires off, I want to be able to interrupt it immediately by using key "0".  So basically, I'd like it to loop forever after hitting key "1" but terminate after hitting "0".

However, when hitting key "1", then key "0" immediately, the while loop repeats twice, then breaks.  I haven't done any C/C++ since I was 12 and now I'm 38 so now it is all trial and error based so please pardon my syntax.  Any help would be appreciated.

    #include <Adafruit_NeoPixel.h>
    #include <SoftwareSerial.h>

    #define PIN 6
    #define LEDs 16

    int LED_Fade_Interval = 5;

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDs, PIN, NEO_GRB + NEO_KHZ800);

    void setup() {

      Serial.begin(9600);

      strip.begin();
      strip.show();

    }

    void loop() {

      while (Serial.available() == 0);

      int numKey = Serial.read() - '0';

      uint32_t low = strip.Color(0, 0, 0);

      switch(numKey)
      {

        case 1:
          Serial.println("LED Strip is ON - BLUE FADE");
          while (numKey != 0)
          {
            int numKey = Serial.read() - '0';
            delay(50);

            ws2812_FadeInOut(0, 0, 255, LED_Fade_Interval);

            if (numKey == 0)
            {

              for( int i = 0; i<LEDs; i++){
                strip.setPixelColor(i, low);
                strip.show();
              }

              break;

            }

          }

        case 0:
          Serial.println("LED Strip is OFF");
          for( int i = 0; i<LEDs; i++){
              strip.setPixelColor(i, low);
              strip.show();
          }
          break;
       }
    }

    // *******************************************
    // FADER Function
    // *******************************************
    void ws2812_FadeInOut(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
      for(uint8_t b = 0; b <255; b++) {
         for(uint8_t i=0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
         }

         strip.show();
         delay(wait);
      };

      for(uint8_t b=255; b > 0; b--) {
         for(uint8_t i = 0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
         }
         strip.show();
         delay(wait);
      };
    };

body:
[`Serial.read()`](https://www.arduino.cc/en/Serial/Read) reads one character from the Serial stream, or returns -1 if there are no characters to read.

When you send a `1` from the Serial Monitor, the Arduino board first receives an Ascii 1, and then receives a line-end character (eg, an LF from Linux) or characters (eg, a CR and LF from MSWindows).

Since none of 1, CR, or LF are equal to an Ascii 0, the numkey value computed at the fourth line of case 1 is not 0, so the exit condition isn't met.  Thus the fade loop continues running, until it sees a `0` character.

Instead of continuing to read characters within while loops within the switch/case statement, test if more serial input is available.  Note, avoid exiting early from case 1, after you read a digit at the beginning of `loop()`, read and discard the line-ending characters that follow.


sender: user

sender: assistant

body:
NeoPixels' timing requirements are pretty tight - not necessarily high frequency but high accuracy, for at least certain parts of the serial pulse train. To achieve that, I believe the (Adafruit) NeoPixel library takes over one of the timers during the transmission and turns off interrupts for at least some of the time. That will have a negative impact on any background processes. Read through the NeoPixel library code; it should be clear.

However, while researching my answer (so as to not embarrass myself too badly!), I found [this article at josh.com][1] that describes driving NeoPixels with a much lower impact and goes on to demonstrate his technique with a video of a 1000 NeoPixel string(!) driven at 30 FPS by an old, apparently Atmega 168-based, Duemilanove.

  [1]: https://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/


message:
Getting the DS18B20 detected and temperature read

I'm quite new with the electronics part of Arduino, but I thought that this was the basic way to get the DS18B20 temperature device hooked up. However, I can't detect it in my program using OneWire and DallasTemperature.

This is an image of my connections:

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

Basically my approach was like this:

Connect ground on ground on the DS18B20.
Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables).
Between the 5V and the two yellow cables, I connected a 4.7K resistor.
Vdd on the DS18B20 is not connected to anything.

Anyone have any idea why this is not working as expected for me?

Thanks in advance!

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

body:
> Vdd on the DS18B20 is not connected to anything.

According to the datasheet:

>  When the DS18B20 is used in parasite power mode, the VDD pin must be connected to ground

---

> Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables).

That means port 2 would always be high, right?

---

According to [Temperature Sensor DS18B20](https://arduino-info.wikispaces.com/Brick-Temperature-DS18B20?responseToken=b846613ae07121485e0bd622a9bcd111) this is the wiring for non-parasitic power:

[![Non parasitic power][1]][1]

If you want the two-wire version (parasitic power) it would be:

[![Parasitic power][2]][2]

  [1]: https://i.stack.imgur.com/9JahP.jpg
  [2]: https://i.stack.imgur.com/irbaD.jpg


message:
How do you figure out an efficient battery setup for a project?

I have a project where I need an Arduino Uno and 4 DC motors to run on batteries. My first thought was that I'll just hook up 3 or 4 AAs to the Arduino and a 9V to the motor drivers.

I googled to be safe and the internet consensus seemed like that method would be very inefficient. Voltage wasn't the problem, but apparently 9V have very low current and I'd be wasting money, and the Arduino wastes current like a madman. Most solutions involved buying additional hardware.

**Is there a way I can efficiently power my project without buying more chips?**

body:
Our beloved admin Nick Gammon has made a [very neat articile][1] on this subject, I suggest you read it and apply as many of the methods he described.

Also, it can be worth to check the requirements of your project, how long should it work on battery to be acceptable? Set some realistic boundarys to avoid getting lost in (trying to) optimizing beyond all practical purposes.

There are two places where you can save power:

**In software**

The Atmega328P has a few tricks to save power.
Most notably is powering down peripheral devices and/or using sleep modes.
I believe the P version of the Atmega328 also has more power saving modes/ is more efficient overall.

Also take a look at [this][2].

**In hardware**

An Arduino board has a lot of chips that may not even be neccesary on your battery project.
Most notably the USB interface chip, if you're going to run off battery, you most likely won't need this chip.
But also, the voltage regulator on the Arduino is, I believe, a linear regulator and is likely to be inefficient.
Also power/status LED's will some current.

You can choose to put a ATMega328P on a breadboard, and power it directly with a source that will be between the min/max voltage of the ATMega328P. This way you don't get the losses that a regulator will have.
If you want to use a regulator (for a higher voltage source) you should use a switching regulator, they're typically more efficient.

Mind that on low voltages, the ATMega328P can't do a 16Mhz, but it's actually a pretty interesting point, since it will consume less power on 8Mhz, or even less on 1Mhz.

  [1]: http://www.gammon.com.au/power
  [2]: http://playground.arduino.cc/Learning/ArduinoSleepCode


body:
Agreed, the DC motors would drain the 9V in no time.

Consider the other way around. The 9V powers the Arduino and the 4 AA batteries power the motor.

Then again, you probably don't need the 9V at all, just power everything off of the 4 AA batteries.

I suggest using a large capacitor (something in the 470-1000uF region) to hold up the supply to the Arduino. Adding a diode before the capacitor will prevent the capacitor discharging to the motors when the motors are drawing a lot of current.

Using 4x 1.5V batteries will result in a voltage of just over 6V. The diode will have a voltage drop of around 0.6V, so the resulting voltage would be 5.4V.

This voltage is to low for the onboard voltage regulator on the Adruino. It is within limits for the raw 5V input (ie. 5.5V).

Optionally you can add a 5V zener diode across the Arduino's power input to protect ti from overvoltage. A 6.8 ohm resistor is added to limit the current flowing through the zener diode. As the voltage drops below 5V, the zener diode will turn off, allowing the micro to operate down to 4.5V. If you change to a lower frequency crystal/resonator you can operate the microcontroller down to 2.7V (1.8V is possible is the clock frequency is 4MHz or less but I doubt the motors will run).

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/98DqI.png)

<!-- End schematic -->


message:
Analog Reference (AREF) pin on Arduino MKR1000 not working?

Has anyone successfully used the AREF pin on [MKR1000](https://www.arduino.cc/en/Guide/MKR1000)?

I'm trying to use an EXTERNAL voltage reference (I need 1.5V instead of the default 5V) with:

    analogReference(EXTERNAL)

But when I compile I receive the following error message:

> MKR_001:161: error: invalid conversion from 'int' to 'eAnalogReference {aka _eAnalogReference}' [-fpermissive]

In the documentation (for analogReference) I found the following:

> DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)
INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)
INTERNAL1V1: a built-in 1.1V reference (Arduino Mega only)
INTERNAL2V56: a built-in 2.56V reference (Arduino Mega only)
EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference.

Thanks,
Corrado

body:
The compiler error

    MKR_001:161: error: invalid conversion from 'int' to 'eAnalogReference {aka _eAnalogReference}' [-fpermissive]
Is actually really simple once you understand what it means.

    analogReference(EXTERNAL);
The function `analogReference` takes an integer as a parameter, but you are passing it `EXTERNAL` which is an enumeration.  Its probably an enumeration that uses integers for its values, but to the compiler there is a difference.

If you want to disable the warning then you can use the `-fpermissive` flag on the compile command line, this is not a good idea because it invalidates the "type-safeness" of the language for the whole program.  Instead it is better to address them on a case by case basis and just cast EXTERNAL to an int.

    analogReference((int)EXTERNAL);


body:
In fact, the [documentation][1] suggests that for SAMD boards (MKR1000 is based on Zero) a different enumeration should be used where each value is prefixed with `AR_` so for example you should use `analogReference(AR_EXTERNAL);`.

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/


message:
How to turn on Solenoid based on Soil Moisture value?

I am powering solenoid with 24 volt as required however I am using TIP122

transistor that has base connected to Arduino Digital Pin 6 via a 1K Resistor.
And the collector is connected to negative side of 1N4001 diode, this also serves as the Negative out for solenoid. and emitter is connected to the 24 volt power input.
The positive input from power source is connected to positive terminal of diode is directly connected to solenoid.

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

As per the logic I am trying to turn on Solenoid based on Signal from Arduino PIN 6, but for some reason Solenoid doesnt power up.

In my code below I want to turn on solenoid if soil moisture goes above 60. the signal is coming from Pin 6 but solenoid doesnt power up.

    #include <SPI.h>

    int solenoidPin = 6;    //This is the output pin on the Arduino we are using

    int GLED = 5; // Wet Soil Indicator at Digital PIN D5
    int RLED = 9; // Dry Soil Indicator at Digital PIN D9
    int SENSE = 1; // Soil Sensor input at Analog PIN A1
    int val = 0;

    int greenLedPin = 2; // LED on pin 2
    int yellowLedPin = 3;
    int redLedPin = 4;

    int lightSensorPin = A0;
    int analogValue = 0;

    void setup() {
      pinMode(solenoidPin, OUTPUT);           //Sets the pin as an output

      // Open serial communications and wait for port to open:
      Serial.begin(9600);

      pinMode(greenLedPin, OUTPUT); // LED on pin 2
      pinMode(yellowLedPin, OUTPUT);
      pinMode(redLedPin, OUTPUT);

      pinMode(GLED, OUTPUT);
      pinMode(RLED, OUTPUT);

    }

    void loop() {
      val = analogRead(SENSE);
      val = val / 10;
      analogValue = analogRead(lightSensorPin);
      Serial.print("LDR value: ");
      Serial.print(analogValue);
      digitalWrite (redLedPin, analogValue < 55) ;
      digitalWrite (yellowLedPin, analogValue >= 55 && analogValue <= 100) ;
      digitalWrite (greenLedPin, analogValue > 100) ;

      Serial.print(" Soil Moisture: ");
      Serial.println(val);
      digitalWrite(GLED, (val < 50));
      digitalWrite(RLED, (val > 50));
      // Turn on Solenoid Valve if soil moisture value greater than 60
      digitalWrite(solenoidPin, (val > 60));

    }

I am doubting on the diode to use , because I am  powering solenoid of 24 volt and not sure if the diode is correct , as per my knowledge, diode can get direct if higher voltage is passed.

Any help will be greatly appreciated.

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

body:
When looking your schematic and assuming that **J1** connector is not powered by your MacBook as your Arduino board, the main problem is located to the **GND** signal.

In order to have a commutation current to the **Base** of the TIP122 through the 1K resistor, you need to link the **GND** signal its **Emitter** with the **GND** signal of your Arduino board.

See a proposed schematic from **["High-Power Control: Arduino + TIP120 Transistor"](http://bildr.org/2011/03/high-power-control-with-arduino-and-tip120/)**

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

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


message:
Multiple (3) RF transmitters to a single receiver?

How can I have three remote transmitters send distinct signals to a single receiver?

My project requires 3 remote controls, each with 2 inputs.

I need to distinctly identify these 6 signals from the 3 remotes onto one arduino board.

Is this possible to do with one receiver?

Would I be able to pair one remote to one receiver (so 3 receivers), or will there be noise / interference?

What is the simplest and/or cheapest solution to this?

FYI I am going to be using a 315 Mhz remote / receiver (remote control has 4 inputs). I am waiting for them to come in the mail but I want to start thinking about how I will build this.

body:
These transmitter all transmit on the same frequency so if you have multiple receivers they will all get the same signal.

The only way I can see you can do this is make some type of protocol where you send data with a station ID and only the receiver with the station ID matching the message will act on it.

EDIT:

Sorry have to get used to the double-enter making a send.

@JamesWierzba your 'remotes' will need to be more than just a push button to send a HIGH or LOW signal via the transmitter.

Your 'remotes' will need to each have a unique ID, we usually use DIP switches for this. A small microcontroller will need to read these DIP switch and compose the message to be send to the receiver.

A simple message like "ID_BUTTON_PRESS" where ID is the decimal or hex equivalent of the DIP switches.

On reception of the message the microcontroller receiving the message will know which remote it comes from by looking at the ID part of the message.


message:
Arduino DUE deadlock problem, watchdog not working

I am using Arduino DUE in my project. The project is massive (about 7000 lines of code in total, with massive schematic), so I decided not to post the whole code and schematic, except explain the hardware and configuration I am working with:

 - **Arduino DUE;**
 - **12V switching power supply**;
 - **LTC1660 DAC** (used withstandard SPI library);
 - **Nextion HMI** (Used with standard library `#include Nextion.h        //INCLUDE NEXTION LIBRARY)`;
 - **DS3231 RTC module** on I2C bus (Library used: [Wire](http://arduino.cc/en/Reference/Wire)  `#include <DS3231.h>`)
 - **24LC256 EEPROM** on same I2C bus (Library used: [Ext EEPROM](http://github.com/JChristensen/extEEPROM/tree/dev) `#include <extEEPROM.h>`)

The base line, is that on power-on the controller just freezes besides, it can't be the problem with power as I get this problem using both 12 V from switching PSU and 5 V USB cable. I can not really analyse the problem, as the deadlock occurs even before the program start to execute content of `void setup()`. My best guess is that the deadlock occurs due to infinite loops in the Arduino's `twi.cpp` where infinite loop can occur if the controller receives no acknowledge
bit. But then again I can not be sure here. However when I push restart button on the Arduino or enable Serial monitor in Arduino IDE when the circuit is powered on , it starts to work, and it works just as expected.

After reading the datasheet for the DUE's μC, I've found that it have the watchdog option embedded:

> After a Processor Reset, the value of WDV is `0xFFF`, corresponding to
> the maximum value of the counter with the external reset generation
> enabled (field `WDRSTEN` at 1 after a Backup Reset). This means that a
> default Watchdog is running at reset, i.e., at power-up. The user must
> either disable it (by setting the `WDDIS` bit in `WDT_MR`) if he does
> not expect to use it or must reprogram it to meet the maximum Watchdog
> period the application requires. The Watchdog Mode Register (`WDT_MR`)
> can be written only once. Only a processor reset resets it. Writing
> the `WDT_MR` register reloads the timer with the newly programmed mode
> parameters.

I've started to explore it, and as I got it, the watchdog is ON by default, and its timer period is 16 seconds by default, so as it is not normally used in DUE, I assumed, that somewhere it is just disabled, and in `main.cpp` I found the following:

    int main( void )
    {
       // Initialize watchdog
       watchdogSetup();
       init();
       initVariant();

where `watchdogSetup()` led to:

    void watchdogDisable(void)
    {
       WDT_Disable (WDT);
    }
    void watchdogReset(void)
    {
       WDT_Restart (WDT);
    }
    extern "C"
    void _watchdogDefaultSetup (void)
    {
       WDT_Disable (WDT);
    }
    void watchdogSetup (void) __attribute__ ((weak, alias("_watchdogDefaultSetup")));

As I got it, due to this, the watchdog was disabled for DUE by default, and commenting out `watchdogSetup();` in `int main()` would allow the watchdog to work (as watchdog is on at power on by default, according to datasheet).

I've also added the `WDT_Restart (WDT);` to `void loop()` of the program in order to kick watchdog every program cycle.

Well, for some reason, that did not help me, and I'm still receiving the deadlock when I power on the controller, even through the watchdog is technically not disabled, after 16 seconds it still do not restart the system. And, pressing the reset button or the Serial monitor in Arduino IDE makes the system run as expected. Am I missing something out? Your help and suggestions are appreciated, shall any additional info be needed, just let me know, I need to get this project running so badly.

By the way, my `void setup()` function is quite long, and if I set the watchdog to 1 second, using
`void watchdogEnable (uint32_t timeout)` instead of commenting out `watchdogSetup()` in `main.cpp`, and use reset button after power on, I can see the watchdog working as it can't get to `void loop()` in time in order to reset watchdog (as `void setup()` takes about 3 seconds due to delays).

body:
   Found people suffering with the same problem on Arduino's official forum. It turned out that the problem arises from the schematic of Arduino Due, that fails to hold 'reset' pin high for long enough period of time on power-on.

  There are multiple solutions involving adding some capacitance between reset pin and ground pin, but this might damage circuit in long run (at power-off), so I managed to find other way around it: **there is an ATmega16U2 used as USE-to-TLL serial chip that have access to reset pin of AT91SAM3X8E.**

  The ATmega16u2 can be reprogrammed so that on power-on it provide short "HIGH" period to AT91SAM3X8E reset pin. The program for ATmega16U2 can be found here:
https://forum.arduino.cc/index.php?action=dlattach;topic=167492.0;attach=52901

The updating precision is given here:
https://www.arduino.cc/en/Hacking/Upgrading16U2Due

**I've performed the given precision using Arduino UNO as programmer and can confirm that it worked properly.The problem's gone now.**


message:
Can't connect to serial port

I'm trying to make my Arduino's LED blink for the first time, but when I try to upload the code I get the following error in the Serial Monitor:

> Error opening serial port '/dev/ttyACM0'.
Try consulting the documentation at http://playground.arduino.cc/Linux/All#Permission

BTW, I have `serial.debug_rate=9600`, so I don't think that's the problem. Can anyone help me with this please?

body:
It seems your serial does not have the right permissions to be opened in _user mode_. Try adjusting that by typing

    sudo chmod a+rw /dev/ttyACM0

on the console (open it by CTRLALTT).


body:
That issue is due to your username not being in the dialout group.
Try: `sudo usermod -a -G dialout yourusername` and rebooting to load the changes, then check again if the problem still persists...

I wrote an article about that here: [Solving Arduino IDE upload problem, and serial monitor error on Ubuntu](http://osrc.rip/Articles/SolvingArduinoUploadProblemOnLinux.html).


message:
Receiving a packet via XBee radio

I am sending a packet of sensor information over an Arduino XBee setup. The first byte of the packet is the packet header for synchronization. The second byte is the number of bytes in the packet (excluding header and packet size byte). The first byte of the packet payload is an identifying number for the sensor. The second payload byte is the data from the sensor. The third payload byte is an XOR for simple error checking. The first payload byte for the sensor ID will never need to be escaped, but the other two payload bytes may need to be escaped. The following is code I wrote for sending a single packet:

    Serial.write(PACKET_HEADER); // Packet header for synchronization
    Serial.write(calculatePacketSize(data, XOR)); // Size of packet
    Serial.write(unitInfo);
    // Check if the data byte needs to be escaped
    if(data == ESCAPE || data == PACKET_HEADER) {
        Serial.write(ESCAPE);
    }
    Serial.write(data);
    // Check if the XOR byte needs to be escaped
    if(XOR == ESCAPE || XOR == PACKET_HEADER) {
        Serial.write(ESCAPE);
    }
    Serial.write(XOR);

What I am unsure about is how to process a packet on the receiving end. One issue I see is that because there are a variable number of payload bytes, I cannot check via `Serial.available()` whether or not there are enough bytes to process the payload during this run through of `loop()`. How do I go about processing a packet, and making sure the packet was received error free? I need to just discard incomplete packets or anything without a header.

body:
A state machine is what you want. That and to increase your preamble to two bytes, not one.  The reason being is that due to the escaping of the preamble character in the data it is impossible to have that character twice in a row. By then having it twice in a row as the preamble it is unambiguous that it is the preamble.

You should also (if needed) escape the packet size:

    Serial.write(PACKET_HEADER); // Packet header for synchronization
    Serial.write(PACKET_HEADER); // Packet header for synchronization
    uint8_t ps = calculatePacketSize(data, XOR); // Size of packet
    if(ps == ESCAPE || ps == PACKET_HEADER) {
        Serial.write(ESCAPE);
    }
    Serial.write(ps);
    Serial.write(unitInfo);
    ... etc ...

You might like to abstract the escaping into a function:

    void sendEscape(uint8_t c) {
        if (c == ESCAPE || c == PACKET_HEADER) Serial.write(ESCAPE);
        Serial.write(c);
    }

Then you can just call:

    sendEscape(calculatePacketSize(data, XOR));

etc.

Now for receiving. Implement a Finite State Machine. In that machine you have a number of states, such as *look for first preamble*, *look for second preample*, *look for size*, *look for id*, and *look for data*. As bytes arrive they trigger the next state.

So you start by looking for the first preamble byte. When that arrives it triggers looking for the second preamble byte - any other byte besides the second preamble byte causes the FSM to reset. If it arrives, then it triggers the reading of the packet length. And so on.

In pseudocode it may be something like:

    State is idle.
    If character available:
        Read character into variable C

        Select on state:
            State IDLE:
                If C is PACKET_HEADER:
                    Set state to PREAMBLE
            State PREAMBLE:
                If C is PACKET_HEADER:
                    Set state to GETSIZE
                Else
                    Set state to IDLE
            State GETSIZE:
                If C is ESCAPE and you haven't just seen ESCAPE
                    Remeber you had an escape
                Else
                    Store C in variable SIZE
                    Clear array DATA and prepare for reception
                    Reset Seen ESCAPE flag if needed
                    Set state to GETID
            State GETID:
                If C is ESCAPE and you haven't just seen ESCAPE
                    Remeber you had an escape
                Else
                    Store C in variable ID
                    Reset Seen ESCAPE flag if needed
                    Set state to GETDATA
            State GETDATA:
                If C is ESCAPE and you haven't just seen ESCAPE
                    Remeber you had an escape
                Else
                    Append C to array DATA
                    Decrement variable SIZE
                    Reset Seen ESCAPE flag if needed
                    If SIZE is 0
                        If checksum matches
                            Process packet
                        Set state to IDLE

The main thing to watch is the remembering (and subsequently forgetting) that you have just seen an ESCAPE. That way you can know if you have two ESCAPE characters in a row and you only discard the first one - the second gets handled as a real character.

The beauty of an FSM is that at any point in the sequence, if you decide that the packet is invalid (maybe the size is too big, or the sensor ID is invalid) you can just reset the FSM to the IDLE state and reset any flags/counters and you instantly start looking for a new packet.


message:
Arduino bug when "myFile = SD.open" is inside loop()

My Arduino resets / bugs each time I put `myFile = SD.open` in `loop()`.

In `setup()` it works fine.

I have a 20*4 LCD and an RTC connected to I2C, an SD card reader connected to SPI, and a fingerprint sensor.

Here is my code:

    #include <Adafruit_Fingerprint.h>
    #include <SoftwareSerial.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <SPI.h>
    #include <SD.h>
    #include <DS3231.h>;

    LiquidCrystal_I2C lcd(0x3f,20,4);
    DS3231  rtc(SDA, SCL);
    SoftwareSerial mySerial(2, 3);

    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
    Sd2Card card;
    SdVolume volume;
    SdFile root;

    int etat = 0;
    int getFingerprintIDez();
    const int chipSelect = 10;
    SDFile myFile;

    void setup() {
      lcd.init();
      lcd.backlight();
      rtc.begin();
      finger.begin(57600);
      SD.begin();

      // Reglage Heure
      //rtc.setDOW(TUESDAY); // Set Day-of-Week to SUNDAY
      //rtc.setTime(10, 57, 0); // Set the time to 12:00:00 (24hr format)
      //rtc.setDate(24, 11, 2016);   // Set the date to January 1st, 2014
      if (finger.verifyPassword()) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Capteur Initialise");
      } else {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Capteur Deconnecte");
      }
      delay(2000);
      if (SD.exists("data.csv")) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("data.csv OK.");
        delay (1000);
      } else {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Creating data.csv...");
        myFile = SD.open("data.csv", FILE_WRITE);
        myFile.close();
        delay (1000);
      }
    }

    void loop() {
      if (etat == 0) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Put Finger");
        getFingerprintIDez();
      }
      if  (etat == 1) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("ID #");
        lcd.setCursor(4,0);
        lcd.print(finger.fingerID);
    //  myFile = SD.open("data.csv", FILE_WRITE);
    //  myFile.print(rtc.getDateStr(1));
    //  myFile.print("\t");
    //  myFile.print(rtc.getTimeStr(1));
    //  myFile.print("\t");
    //  myFile.println(finger.fingerID);
    //  myFile.close();
        lcd.setCursor(0,2);
        lcd.print("Loged");
        etat = 0;
      }
      delay(1000);
    }

    int getFingerprintIDez() {
      uint8_t p = finger.getImage();
      if (p != FINGERPRINT_OK)  return -1;
      p = finger.image2Tz();
      if (p != FINGERPRINT_OK)  return -1;
      p = finger.fingerFastSearch();
      if (p != FINGERPRINT_OK)  return -1;
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Found ID #");
      lcd.setCursor(14,0);
      lcd.print(finger.fingerID);
      etat = 1;
      return finger.fingerID;
      delay(1000);
    }

Each time I uncomment lines using SD, the Arduino resets at the end of the loop.

What is the problem?

body:
The solution to your problem is to extend your 2 states machine in a multiple states machine.

Declare the `enum eState` before `setup()`:

    typedef enum e_State {
     STATE_START = 0, // starting the loop (add some initialisation)
     STATE_READ_FINGER, // Step1: read the finger print
     STATE_DISP_FINGER, // Step2: display the finger print
     STATE_OPEN_LOGGER, // Step3: open the log file
     STATE_WRITE_LINE, // Step4: append a timestamp finger print
     STATE_CLOSE_LOGGER // Step5: close the log file
    } eState;

And update the `loop()` function with the state-machine:

    void loop()
    {
     static eState LoopState = STATE_START; // to store the current state

     eState NextState;  // for the next loop

     switch (LoopState) {
     case STATE_START:
      // add additional settings
      NextState = STATE_READ_FINGER;
      break;
     case STATE_READ_FINGER:
      etat = 0; // keep use your 'etat'
      // or return a boolean from your 'getFingerprintIDez()'
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Put Finger");
      getFingerprintIDez();
      if (etat == 1) {
       NextState = STATE_DISP_FINGER;
      }
      break;
     case STATE_DISP_FINGER:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("ID #");
      lcd.setCursor(4,0);
      lcd.print(finger.fingerID);
      NextState = STATE_OPEN_LOGGER;
      break;
     case STATE_OPEN_LOGGER:
      myFile = SD.open("data.csv", FILE_WRITE);
      if (myFile) {
       // record only if file is opened
       NextState = STATE_WRITE_LINE;
      }
      else {
       lcd.setCursor(0,0);
       lcd.print("Can't open file");
      }
      break;
     case STATE_WRITE_LINE:
      myFile.print(rtc.getDateStr(1));
      myFile.print("\t");
      myFile.print(rtc.getTimeStr(1));
      myFile.print("\t");
      myFile.println(finger.fingerID);
      myFile.flush();
      NextState = STATE_CLOSE_LOGGER;
      break;
     case STATE_CLOSE_LOGGER:
      myFile.close();
      lcd.setCursor(0,2);
      lcd.print("Loged");
      NextState = STATE_READ_FINGER;
      etat = 0;
      break;
     default:
      NextState = STATE_START;
     }
     // next loop()
     LoopState = NextState;
     delay(200);
    }


message:
Run 'Serial.begin(9600)' before loop()

My sketch looks somehow like this:

    ClassA classA;

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

        classA = ClassA();
        Serial.println("Bar")

        ...
    }

    void loop() {
        classA.functionFoo();
    }

The constructor of `ClassA` however calls some internal methods that perform a `Serial.println()`.

My problem is, that the first (implicit) call of the constructor of `ClassA` comes in the first line of the sketch with

    ClassA classA;

This is before the Serial interface has been initialized (with `Serial.begin(9600)`). Therefore the Serial.monitor cannot interpret the first messages coming from the serial interface.

How can I either suppress any Serial.writes before the setup function or otherwise make sure that the Serial interface is initialized before the setup function?

body:
In order to be sure that your `classA` object doesn't use the `Serial.println()` function before the baudrate is defined, it is necessary to add functions in your `class ClassA` and to inform from `setup()` your `classA` object.

The simplest way is to add:

 1. a boolean `bool bSerialReady`to keep the status of the Serial object,
 2. in all `ClassA` constructors, initialize that `bSerialReady = false;`,
 3. add a function `void SetSerialReady()` to switch the status `bSerialReady = true;`. The function should be called in the `setup()`function just after `Serial.begin(9600);`,
 4. and in all functions of `ClassA`, add a if-condition `if (bSerialReady)` before calling the `Serial.println()`.

Your `class ClassA` will become:

    class ClassA
    {
    private:
     bool bSerialReady;
    public:
     ClassA() {
      // ...
      // Initialize bSerialReady
      bSerialReady = false;
     };
     void SetSerialReady() {
      bSerialReady = true;
     };
    };

Your `setup()` function becomes:

    void setup() {
     Serial.begin(9600);
     classA.SetSerialReady();
     ...
    }

And in functions of `ClassA`, it looks like:

    if (bSerialReady) {
     Serial.println("Bar");
    }


body:
You can make your current object a pointer so it isn't instantiated:

    ClassA *classA;

Then create an object with new:

    classA = new ClassA();

The constructor is then only called when the object is made.

Note that you will have to change your accessors to `->`:

    classA->myFunction();


message:
Scan multiple ESP8266

I am working on wifi based LED project which involves various ESP to be connected to router. Basically grouping of ESP has to be done. The android app sends HTTP command to IP address which is given by router to the ESPs, the IP are not static and expires after some time. Now my question is how can mobile app can get the IP of all the ESP connected to router?

Does using HTTP protocol complicates the process? Shall I switch to multicast UDP? or use UnPn Protocol for scanning (Sounds complicated though).

Please help!

body:
The best protocol for these kind of applications is MQTT.

Read more [here][1]

  [1]: http://mqtt.org/


body: You can go with UDP Multicast.


body: Yes, Multicast is the only option.


message:
Does an I²C IO Expander needs additional resistors for outputs?

I have following setup (see also schematic in the end)

Arduino Nano is connected via I²C to the PCF8575C ([link][1]) IO Expander.
Both, SCL and SDA have 10kOhm pull-ups to 5V.
The Expander pins are connected to a MOSFET-driver that turns on/off 12V LED stripes.
The Expanders Bus address is set via Expanders A0-A2 pins to 0 (0x20).
The MOSFET driver pins have to be pulled to logic 1 (above 2.2V) in order to turn on the stripe.

Currently Arduino runs an blink example, that turns all Expander IO pins on/off every second (using Arduino Wire Library), but the **MOSFET-driver does not turn on/off any Stripe.**

I can manually turn on Stripes by connecting MOSFET-driver pins to Arduinos 5V (or 3.3V)

The power supply to the IO Expander is O.K.

By measuring the resistance between GND and IO pins of the Expander, I can see that it alternates every second (so I²C communication to the Expander works also)

**Curious thing:** While measuring this resistance (holding the multimeter test leads) to GND and to the IO pin of Expander, the MOSFET-driver turns the Stripes on and off! When I take the test leads away it stops working! **Magic?!**

**What am I missing?** Do the output pins of the PCF8575C need some extra pullup/pulldown resistors or something else?

Thank you in advance!

Schematics:
[![Schematics][2]][2]

  [1]: https://www.sparkfun.com/products/retired/8130
  [2]: https://i.stack.imgur.com/xrVRi.jpg

body: Yes, according to the datasheet (which should always be your first port of call for any chip) the outputs are Open Drain. That means you require a pullup resistor, exactly as if the outputs were simple buttons.


body:
Think of the oped drain output (or open collector) as a pin that connects to ground when the device is on. If you connect the anode of an LED to plus and connect the kathode to the open drain pin, then you do not need a pull-up resistor (you may need a current limiting resistor though)

The test leads of the Ohmmeter produce a current to masure resistance, it also provides a current path to ground if the that's where you placed one of the leads. This would explain the **Magic**

More [here][1] about open collector outputs.

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


message:
Can't run two separated DC Motors

I'm trying to build Bluetooth RC car, but I can't run only one DC motor.. only both of them. Everything works fine, the bluetooth, the app but when i try to go forward/backward/left/right nothing happens, only when i run both of them. I'm running the Arduino Nano with usb cable. The bluetooth connection is stable, The DC motors are working. I don't know what I'm doing wrong. Thanks!

[![Schematic][1]][1]

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

    const int AIA = 2;
    const int AIB = 3;
    const int BIA = 4;
    const int BIB = 5;
    byte vSpeed = 255;
    int state;

    void setup() {
    pinMode(AIA, OUTPUT);
    pinMode(AIB, OUTPUT);
    pinMode(BIA, OUTPUT);
    pinMode(BIB, OUTPUT);

    // Initialize serial communication at 9600 bits per second:
        Serial.begin(9600);
    }

    void loop() {
      //Save income data to variable 'state'
        if(Serial.available() > 0){
          state = Serial.read();
        }

      /***********************Forward****************************/
      //If state is equal with letter 'F', car will go forward!
        if (state == 'F') {
          analogWrite(AIA, vSpeed);
          analogWrite(AIB, 0);
          analogWrite(BIA, 0);
          analogWrite(BIB, 0);
        }
      /**********************Forward Left************************/
      //If state is equal with letter 'G', car will go forward left
        else if (state == 'G') {
          analogWrite(AIA, vSpeed);
          analogWrite(AIB, 0);
          analogWrite(BIA, vSpeed);
          analogWrite(BIB, 0);
        }
      /**********************Forward Right************************/
      //If state is equal with letter 'I', car will go forward right
        else if (state == 'I') {
          analogWrite(AIA, vSpeed);
          analogWrite(AIB, 0);
          analogWrite(BIA, 0);
          analogWrite(BIB, vSpeed);
        }
      /***********************Backward****************************/
      //If state is equal with letter 'B', car will go backward
        else if (state == 'B') {
          analogWrite(AIA, 0);
          analogWrite(AIB, vSpeed);
        }
      /**********************Backward Left************************/
      //If state is equal with letter 'H', car will go backward left
        else if (state == 'H') {
          analogWrite(AIA, 0);
          analogWrite(AIB, vSpeed);
          analogWrite(BIA, vSpeed);
          analogWrite(BIB, 0);
        }
      /**********************Backward Right************************/
      //If state is equal with letter 'J', car will go backward right
        else if (state == 'J') {
          analogWrite(AIA, 0);
          analogWrite(AIB, vSpeed);
          analogWrite(BIA, 0);
          analogWrite(BIB, vSpeed);
        }
      /***************************Left*****************************/
      //If state is equal with letter 'L', wheels will turn left
        else if (state == 'L') {
          analogWrite(BIA, vSpeed);
          analogWrite(BIB, 0);
        }
      /***************************Right*****************************/
      //If state is equal with letter 'R', wheels will turn right
        else if (state == 'R') {
          analogWrite(BIA, 0);
          analogWrite(BIB, vSpeed);
        }
      /************************Stop*****************************/
      //If state is equal with letter 'S', stop the car
        else if (state == 'S'){
          analogWrite(AIA, 0);
          analogWrite(AIB, 0);
          analogWrite(BIA, 0);
          analogWrite(BIB, 0);
        }
    }

body:
Connect the Nano ground to the driver board ground.  Since they do not share a common ground, they can have odd behavior as their ground planes float.

You need only connect the grounds, the USB can still provide +5 to the Nano, and the +9 can still provide power to the driver.  The only energy that will flow through the black wire connecting the grounds is the energy that flows between pins 2,3,4,5 and the driver's AIA, AIB, BIA, BIB, for the logic signals, which I'd bet is in the sub-uA range.


message:
Serial question : Going from Mega to Uno

I have a code sample that uses serial3 (RX3 on a Mega) which I want to try and get working on a Uno.  It reads on RX3 and streams to USB.  What I had read, you use Serial for RX0, however Serial seems to be used for USB

     /*
    Arduino Neato XV-11 Laser Distance Scanner
    Motor control board v0.2 by Cheng-Lung Lee

    XV-11 LDS adapter reads LDS data from RX3 then relay to TX. Also extract the speed
    data from the data stream to do speed control on LDS motor. Everythin can power
    from USB no extra power required.

    Change log:
    V0.2 Add simple speed control code update PWM 3 times per rev.
    V0.1 Opend loop control version.

    This code is tested on Arduino Mega 1280
    I/O:
    Motor drive by low side driver IPS041L connect to PWM Pin4, Motor power from 5V
    Neato XV-11 LDS Vcc(red) : 5V
    Neato XV-11 LDS TX(Orange) : RX3

     */

    const int DesiredRPM=300;  // Setting Desired RPM Here.
    const int MotorPWMPin=4;
    int inByte = 0;         // incoming serial byte
    unsigned char Data_status=0;
    unsigned char Data_4deg_index=0;
    unsigned char Data_loop_index=0;
    unsigned char SpeedRPHhighbyte=0; //
    unsigned char SpeedRPHLowbyte=0;

    int SpeedRPH=0;
    const unsigned char PWM4dutyMax=255;
    const unsigned char PWM4dutyMin=100;
    unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

     void setup() {
        pinMode(MotorPWMPin, OUTPUT);
        Serial.begin(115200);  // USB serial
        Serial3.begin(115200);  // XV-11 LDS data

      // prints title with ending line break
      Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

      // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
        analogWrite(MotorPWMPin, PWM4duty );
    }

    void loop() {
        // if we get a valid byte from LDS, read it and send it to USB-serial
      if (Serial3.available() > 0) {
        // get incoming byte:
        inByte = Serial3.read();
        //Serial.print(inByte, BYTE);
        //Serial.write(inByte);
        Serial.print((char)inByte);
        decodeData(inByte);
      }

    }

    void decodeData(unsigned char inByte){
      switch (Data_status){
      case 0: // no header
      if (inByte==0xFA)
      {
        Data_status=1;
        Data_loop_index=1;
      }
        break;
      case 1: // Find 2nd FA
        if (Data_loop_index==22){
          if (inByte==0xFA)
          {
            Data_status=2;
            Data_loop_index=1;
          }
          else // if not FA search again
          Data_status=0;
        }
        else{
          Data_loop_index++;
        }
        break;
      case 2: // Read data out

         if (Data_loop_index==22){
          if (inByte==0xFA)
          {
            Data_loop_index=1;
          }
          else // if not FA search again
          Data_status=0;
        }
        else{
          readData(inByte);
          Data_loop_index++;
        }
        break;
      }

    }
    void readData(unsigned char inByte){
      switch (Data_loop_index){
        case 1: // 4 degree index
        Data_4deg_index=inByte-0xA0;
    //      Serial.print(Data_4deg_index, HEX);
    //      Serial.print(": ");
        break;
        case 2: // Speed in RPH low byte
        SpeedRPHLowbyte=inByte;
        break;
        case 3: // Speed in RPH high byte
        SpeedRPHhighbyte=inByte;
        SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

        SpeedControl ( DesiredRPM ) ; //
    //      Serial.print(SpeedRPHhighbyte, HEX);
    //      Serial.println(SpeedRPHLowbyte, HEX);
        break;
        default: // others do checksum
            break;
      }
    }

    // Very simple speed control
    void SpeedControl ( int RPMinput)
    {
     if (Data_4deg_index0==0) {  // I only do 3 updat I feel it is good enough for now
      if (SpeedRPH<RPMinput*60)
         if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
      if (SpeedRPH>RPMinput*60)
         if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
      }
      analogWrite(MotorPWMPin, PWM4duty ); // update value
    }

body:
Arduino UNO only has one **hardware** UART, hence only one `Serial` available, which is linked to USB, but you could still use it for something else by connecting directly to D0 & D1.

However, if you need 2 separate, independent, UART then go for `SoftwareSerial` for the second one.

Now, if you need to connect 2 devices, one to exclusively get data from, the other exclusively to send data to, then you can use just one UART, i.e. `Serial` for both devices, as long as both links work at the **same speed** and **settings** (parity...)

Also you must ensure that USB won't receive anything otherwise you would get it and confuse it with input from the first device.

The non USB device providing input to the Uno should be connected to D0 (RX).


message:
Arduino Nano + ESP8266 and saving to EEPROM

I am going to create a project with a friend, but I have some technical questions.

The Arduino Nano has an EEPROM capable of storing the known WiFi connections. Basically what I want is say "Arduino, connect to this WiFi and remember it". When I then disconnect the Arduino completely, it should still save that information. Can the EEPROM store that without power?

I need an easy, but rather small, WiFi module to work with the Arduino Nano. I've looked at the ESP8266. I don't mind soldering the ESP8266 to the Arduino Nano *once*, but doing it more times (perhaps because I need more GPIO or something) is not a variable solution. If I get the ESP8266 ESP-12, I would only have to solder it to the Nano once. However:

 1. Is the ESP8266 ESP-12 compatible with the Arduino Nano?
 2. I like the ESP-05 because it's small and simple. Would that work?

Are there perhaps better ways of doing this whole thing? Should I go for something else than the Arduino Nano? I need to hook up:

 - WiFi
 - Microphone (smallest and easiest way)
 - LEDs

body:
It sounds like you are quite new to all this stuff.  In summary I think you are taking the wrong approach and need to re-think things.

EEPROM is capable of storing data without any power.
Both the devices have EEPOROM, also you could look at external devices, which would be easier to replace if you wear them out (limited number of write cycles - see their data sheets for details but they are usually in the tens of thousands).

The difference between the ESP8266 range are the number of GPIO lines they offer up, to the 12E has more than the 5, etc.

You shouldn't be soldering this stuff more than once.  You should design it right in the first place (easier said than done!)  What you could do is mount the Nano on a board that took all the lines off to a single 30 odd pin connector the design a series of daughter boards for the ESP8266 which were compatible with the base board, so you could switch between the different ESPs.

Also, don't forget you will need logic level conversion between the 5V Arduino and the 3.3V ESP8266 unless you are planning on smoking electronics.

What do you think you are doing with the MIC connector?  Are you planning on processing sound on the Arduino?  You might want to research that before you design it.

Are you aware that the ESP8266 can be programmed via the Arduino and has a 80MHz processor and 256KB of RAM (compared to the Nano's 32Mhz & 32KB) so using the ESP as a slave to the Arduino is not necessarily the best idea.

If you are interested this is the approach I would take:
 1. Solder some male pins to the Nano so you can put it into a bread board.
 2. If you have a 12E, Buy a ESP8266 mounting board (£1 for 10 from you favourite Chinese web market) and solder pins to that.
 3. If you have a 5 then solder pins to that.
 4. Make all you other parts breadboard-able and try it all out.
 5. Once it works download Fritzing and draw it up.
 6. Make a Vero board version and play with it for real.


body:
The ESP8266 is a SoC (System On Chip) that includes a microcontroller. For most applications, you’ll need only the ESP without the Nano. ESP-12E boards are very handy for tinkering. You can program the ESP in different languages, even in Arduino C (https://github.com/esp8266/Arduino/).

Note that the ESP is only 3.3V tolerant, so it is not that easy to use it with a Nano that works at 5V. It is of course possible to use logic level shifters, but frankly, I would rather use the ESP alone.

You don’t have to worry about storing WiFi connection settings, they are usually hard-coded in the main program.

Connecting LED is described everywhere on the internet, so I don’t think that is a major problem. If you need a lot of LEDs, you can buy LED strips.

For the microphone I suggest that you search for I²C modules.


message:
How to restart void loop if condition is met

This should be a quick question.

I'm trying to figure out how I can restart `void loop()` if a certain condition is met. In this instance, if (s>10), I want the loop to restart. Any help will be appreciated.

     void loop() {

      if (getDistance(0) == true)                   //if the car passed the first sensor
      {
        while (getDistance(0) == true && getDistance(1) == false);
        unsigned long currentMillis = millis(); //time when the passed the first sensor

        while (getDistance(1) == true && getDistance(0) == true); //wating car to pass the second sensor

        unsigned long endMillis = millis(); //time at which the car passed the second sensor

        unsigned long timeMillis = endMillis - currentMillis; //get duration in ms
        float timeSeconds = timeMillis / 1000.0; //because 1000ms = 1s

        float s = sensorDistance / timeSeconds; //speed = distance / time

        if(s>=7 && s<=10) // for red to turn on
        {
        Serial.print(s); // printing the speed magnitude
        Serial.print(" m/s");// printing the units of speed
        Serial.println(); // new line in printing

        char msg[2] = {'h','#'}; // sending some random message to indicate that speed is greater than 10
        digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
        vw_send((uint8_t *)msg, 2); // sending a message
        vw_wait_tx(); // Wait until the whole message is gone
        digitalWrite(led_pin, LOW); // again bringing the flash light to low

        }
        else if (s<7)
        {
        Serial.print(s); // printing the speed magnitude
        Serial.print(" m/s");// printing the units of speed
        Serial.println(); // new line in printing

        char msg[4] = {'h','e','l','#'}; // sending some random message to indicate that speed is greater than 10
        digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
        vw_send((uint8_t *)msg, 4); // sending a message
        vw_wait_tx(); // Wait until the whole message is gone
        digitalWrite(led_pin, LOW); // again bringing the flash light to low
        }

        delay(2000);
      }
    }

body:
To expand on what jfpoilpret said setup() and loop() are called by the code you can't see in every program.  `setup()` is called once and `loop()` is called in a `while(true)` loop until the program crashes or the universe ends.

To call you code while a condition is met you could either wrap it in a loop or an if, within the `loop()` function, so something like this:

    void loop ()
    {
        if (s > 10)
        {
            // Your stuff....
        }
    }

This will only call your code IF `s > 10`.  Something you need to watch for is ensuring that there is some code that can cause `s` to be greater than `10`.

You can also move `"// Your stuff..."` into a function of its own

    void MyCode ()
    {
        // Your stuff ...
    }

and then call this function from inside the if statement.  This makes you code easier to read and easier to fix.

If this answer wasn't what you meant then feel free to comment and I'll see if I can come up with a better answer.


body:
When programming with arduino IDE, you declare 2 functions, setup() and loop().

Before compilation, arduino IDE basically expands to :

    int main(void)
    {
        /* run the Arduino setup */
        setup();
        /* and the event loop */
        while (1) {
            loop();
        }
        /* never reached */
        return 0;
    }

So, from here you can see that setup() is called once at startup and then, loop() is called in an infinite loop.
Il you return from within your loop function, it will be called again.


body: I hate to bring this up, but I've now been programming for 58 years. One curious and often overlooked feature of the C & C++ languages is the GOTO keyword. It can be very useful. My second language was FORTRAN I. I know, now I'm relegated to the 9th circle of he|| where the miscreants are frozen into glaciers head down with their legs protruding?


message:
Waking up async the Arduino while it is sleeping periodically

I´m using `LowPower.h` and `PinChangeInt.h` libraries to put my Arduino into the sleep mode every 8 seconds and then it wakes up, modifies a counter and it goes to sleep again, but also I need to wake it up when a button is pressed asynchronously.

I´ve reached to wake up the Arduino every 8 seconds using `LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF)` and, in other code, I´ve also reached to wake it up while it sleeps indefinitely with `LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF)` but I can´t combine that periodical awakening with the asynchronous awakening.

Here is my code:

    void setup(){

        Serial.begin(9600);

        //Pines declaration

        loopsToSend = setTimeToSend();  //

        //The three async buttons
        PCintPort::attachInterrupt(4, readOpinion,RISING);
        PCintPort::attachInterrupt(5, readOpinion,RISING);
        PCintPort::attachInterrupt(6, readOpinion,RISING);
    }

    void loop(){

        if(loops < loopsToSend ){

            byte opinionValue = readOpinion(); //This method must awake the Arduino ASYNC to give a value to the opinionValue var, write the result in the file and go to sleep

            if(opinionValue != 0){
                Serial.println("Button pressed!");

                //Writing result in a file
                opiniones++;
                delay(500);
            }
            //Go to sleep 8 seconds
            LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
            opinionValue = 0;
        }
        else {
            wdt_disable();

            if(opiniones > 0){
                //Send file using GSM module
            }
            else{
                loops = 0;
            }
        }
        loops++;
    }

Can anyone help me? Thanks

body:
My aim was to attach multiple interrupts to my Arduino but my problem was that I didn´t know if when the board changed to sleep mode using `LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF)` then it could be awake using another interrupt instead of the timer.

The `void loop()` method must sleep the board every 8 seconds if no button is pressed. Aside there is a method that is called when a button is pressed, that´s because in the `void setup ()` I´ve attached an interrupt using `PCintPort::attachInterrupt(PIN_NUMBER, METHOD_TO_CALL,MODE);`

----

OP (PinaGamer) posted this answer inside the question, hence the community wiki answer.


message:
What is the maximum current for each I/O pin?

### Question ###

As far as I know each I/O pin has to keep around 20mA, what are the consequences of going higher or lower? But if I am using all I/O pins is there a maximum current value I should keep in mind? For example, the sum of all currents in all pins should not be greater than 100mA.

body:
The power limits per pin and per chip are listed for each model (based on the Atmel chip).  You can look up the Atmel chip number and see the power ratings.  For example, the chip may have a maximum of 40mA per pin, but a total of 200mA for everything on the chip. These numbers are just examples. The actual numbers depend on which Arduino and which chip you are talkng about.

Remember that microcontroller chips are NOT designed to SWITCH any significant amount of power. That is NOT the job of the microcontroller. Its job is to CONTROL external devices (transistors, thyristors,SSR, relays, etc.) which do the actual "heavy lifting" of switching larger amounts of power.

Your last question really does not make any sense. Can you clarify it?

VCC is the name of the main power bus and input to the microcontroller chip. It may or may not be 5V depending on which Arduino you are talking about. The older ones were 5V, but newer chips (including those used in Arduino) are tending more to 3.3V.


body:
This comes up as first result when Googling your question:

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

And can be confirmed by page 313 and 314 of the [datasheet][2]:

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

To know where each pin is connected to (on the Arduino Uno) you can look the official (messy) [schematic][4].

I provide an excerpt below that shows the **Vin** and **5V** pins at the headers, and the power barrel connection.

[![enter image description here][5]][5]

If you want to control a 12V motor or a 12V LED strip or other DC loads you can use the following (which is also easy to find using Google):

*Note that your 12V Gnd and Arduino Gnd have to be connected.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/urNHq.png)

<!-- End schematic -->

  [1]: https://i.stack.imgur.com/XL0p4.jpg
  [2]: http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
  [3]: https://i.stack.imgur.com/zJZgj.png
  [4]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
  [5]: https://i.stack.imgur.com/kDojF.png


message:
How to output a true analog voltage at output pin

Regarding my program, it is a program that does some calculations and then outputs a voltage based on the result using analogWrite function. However my problem is that I had done my programming based on a misconception that analogWrite function via PWM does output an analog voltage, where in fact it only "simulates" the analog voltage instead.

Here are the relevant parts of my code :

    int pwmOutput = 11;
    int pwm = 0;

    void compareNewOldVoltageYes(void)
    {
      if(pv_Vnew > pv_Vold && pwm != 255)
      {
        ++pwm;           //increasing value
      }
      else if(pwm != 0)
      {
        --pwm;           //decreasing
      }
    }

    void compareNewOldVoltageNo(void)
    {
      if(pv_Vnew > pv_Vold && pwm != 0)
      {
        --pwm;
      }
      else if(pwm != 255)
      {
        ++pwm;
      }
    }

    void loop()
    {
       reading();
       PowerCalculation();

       if(pv_NewP > pv_OldP)
       {
          compareNewOldVoltageYes();
       }
       else
       {
          compareNewOldVoltageNo();
       }

       analogWrite(pwmOutput, pwm);           //analogWrite

       float displayPWMvolt = pwm * 0.0196;

       Serial.print("Output Voltage: ");
       Serial.print(displayPWMvolt);
       Serial.println(" V");

       pv_OldP = pv_NewP;

       Serial.print("Previous Power: ");
       Serial.print(pv_OldP);
       Serial.println(" W");

    }

As for the circuitry, output pin 11 is being connected to a 1 ohm resistor and then to GND. (Where I measured the voltage) I am using Arduino Uno board.

**UPDATE**:

As said in the comments by @DatHa, pwm does not output voltage. **Is there a way to output voltage as said, without changing the board?**

body: As far as I know Arduinos have ADC (Analog to Digital Converters) but do not have any DAC (Digital to Analog Converters). So you can not output a set voltage from any pins based on a digital value.


body:
At 5V, a 1 ohm resistor will try to sink 1A and far exceed the 40mA specs.  Please use at least a 5/0.040=125 ohm resistor to protect your pin.  And if you put the a capacitor between your resistor and ground, the RC circuit of the capacitor will smooth out the PWM into an analog voltage.

Please try the suggested [@russell answer][1] with a 47K resistor and 1uF capacitor, you will get an analog voltage at the junction to use with your electronic load.

  [1]: https://arduino.stackexchange.com/a/10047/6628


body:
NO.. There is no way to get an analog voltage from the Arduino. The best that you can do is to use Arduino as a Buck Voltage converter in linear or boost mode using a voltage regulator, inductor and the mosfet transistor.  You will also might need to use a Mega or Dulorme which provide a PWM frequency other that the standard 50o Hz.

Best luck


body:
You basically have three options:

1. Switch to an Arduino Due which has a built-in DAC which outputs a real voltage.
2. Add an external DAC chip (such as the MCP4821/2) to create the voltage for you
3. Use a low-pass filter (R-C network) on a PWM pin.

Of the three options I usually use an MCP4822 since it gives the best results and doesn't cost as much as using a Due.


body:
There is no direct way.

In addition to @Majenko

Alternative way: you can use H bridge like L293d to provide continuous level. Many diy inverter circuits are useing this technique.

http://www.instructables.com/id/How-to-Make-an-Inverter-Using-ARDUINO/?ALLSTEPS


body:
I wondered if this would give a more stable output.

[![PWN presented to RC.  Cap charges, sample is made by another analog input.  When PWN pin goes low, slow discharge of cap.  Maybe a large resistor is needed in parallel with the cap for slow discharge?][1]][1]

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


message:
Emulate non-standard keyboard from Arduino

I want to emulate keyboard presses in an old C64 microcomputer using an Arduino.

The keyboard connection is a non-standard 20-pin port (i.e. the Arduino keyboard libraries won't be useful) which, as I understand, works as a simple matrix of switches.

Since my Arduino Mega has more than 20 general purpose I/O ports, I understand I can approach the problem by simply mapping these 20 keyboard pins to individual "digital" Arduino ports, and then programming around it, right?

Or is this too naive and I'm missing something here?

I'm new to Arduino, so any comments highly appreciated. Thank you!

body:
Emulating a keyboard matrix is actually harder than you would at first think. It's not just a case of setting certain combinations of pins as HIGH or LOW - you need to actively monitor one side of the matrix as it sweeps across each row and control the other side depending on the buttons that are pressed or not pressed on the current row. And all that has to be done fast enough that the C64 doesn't see buttons constantly bouncing up and down.

Further, you really need all your outputs to be *open drain* so as not to interfere with each other or the rest of the system (depending on just how the C64 system works), and Arduinos can't do *open drain* natively - instead you have to emulate it by switching between INPUT and OUTPUT + LOW which adds extra latency.

If you only want access to a few of the buttons a better arrangement would be to add a small N-channel (logic level) MOSFET or an NPN BJT between the two sides of the matrix for whichever button(s) you want to control (check the schematics for which pins and which way round to connect it). Activating the transistor would then be the same as pushing the button down. It can even be in parallel to the existing button so as to not break the keyboard.


message:
How to use while(1) loop in arduino?

I have been trying to exit from the `while(1)` loop by getting a value from the sensor and then run the code outside `while(1)`.But the problem is that it does not exit. How may I fix this problem?

See Code Below.......

    void setup() {
     pinMode(2,INPUT);
     Serial.begin(9600);
    }

    void loop() {
     int sensor;
     while(1)
     {
      sensor = digitalRead(2);
      if(sensor == 0)
      {
       Serial.println("inside while loop");
      }
      break;
     }
     Serial.println("Break......");
    }

body: In the Arduino paradigm, unlike ordinary C programming where there is only 1 entry point called "main()", there are 2 entry points called "setup()" and "loop()".  "setup()" is called only once after booting up.  But "loop()" is called over and over again right after "setup()" is called.  There is no need to create your own infinite loop (for example a "while(1)" statement) as in ordinary C programming.


body:
instead of while(1), one can use the variable name in while and change the value of the variable when you want to exit the loop. part of the code can be modified based on the following concept.
`bool condition= true;
while(condition){
if (sensor==0)
condition=false;`
This is my suggestion for the above problem.


body:
Used like this

    void setup() {
        pinMode(2,INPUT);
        Serial.begin(9600);
    }

    void loop() {
         bool cond = true;

    int sensor;
    while(cond)
    {
        sensor = digitalRead(2);
        if(sensor == 0)
        {
            Serial.println("inside while loop");
        }
        cond = false;
    }

      // like this you can used while inside the void loop()

    }


message:
Using 2D servo array in my class

I need to use a servo library in my class.
I read this question - https://arduino.stackexchange.com/questions/9296/use-object-of-other-class-within-class and it works fine for my LCD application, but now I need to use a 2D servo array in my class. I made one approach, it worked, but I think it is bad programming approach, what is right way to solve my problem?

1. My main file

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

        #include <SoftwareServo.h>
        SoftwareServo servo[5][5];
        Servolib Servoarray;

        void setup(){
          blah blah blah

2. My cpp file

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

        #include "Vending.h"
        #include "Arduino.h"
        #include <SoftwareServo.h>

        Servolib::TurnSevo(){
          for(int row=0;row<5;row++){
            for(int collum=0;collum<5;collum++){
              servo[row][collum].attach(Object[row][collum]);
              servo[row][collum].write(0);
            }
          }
        }

3. my .h file

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

        #ifndef Vending_h
        #define Vending_h
        #include "Arduino.h"
        #include <SoftwareServo.h>

        class Servolib:SoftwareServo{
        public:
          void TurnServo();

        private:
          SoftwareServo servo[5][5];
          int Object[5][5]={
            {42,21,20,19,18},
            {37,41,36,38,35},
            {31,33,30,34,39},
            {67,28,66,29,65},
            {56,63,55,64,54}
          };
        };
        #endif

So this code worked, but please give me better solution.

body:
You can indeed use pointers, but passing multi-dimensional arrays is a bit of a pain in C(++).

There's a pretty good explanation [here][1].

  [1]: https://stackoverflow.com/questions/8767166/passing-a-2d-array-to-a-c-function


message:
arduino web client uploading data to mysql database

I have got this quick sketch that post data to mysql db using php add.php module.

    #include <SFE_BMP180.h>
    #include <SPI.h>
    #include <Ethernet.h>
    #include<dht.h>
    dht DHT;

    // You will need to create an SFE_BMP180 object, here called "pressure":
    SFE_BMP180 bmp;

    #define DHT11_PIN 2

    double tempInC;
    int humidity;

    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    IPAddress ip(192, 168, 1, 177);
    char server[] = "192.168.1.3";

    EthernetClient client;
    byte php_server[] = {192 , 168 , 1 , 3};

    long previousMillis = 0;
    unsigned long currentMillis = 0;
    long interval = 250000; // READING INTERVAL

    String data;

    void setup() {
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      if (bmp.begin()) {
        Serial.println("BMP init Success");
      }

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, ip);
      }

      // give the Ethernet shield a second to initialize:
      delay(1000);
      Serial.println("connecting...");
      data = "";
    }

    void loop() {
      int chk = DHT.read11(DHT11_PIN);
      char status;
      status = bmp.startTemperature();
      if (status != 0) {
        delay(status);
        status = bmp.getTemperature(tempInC);
      }
      else Serial.println("error retrieving temperature measurement\n");

      humidity = DHT.humidity;
      data = "?temp1=" + String(tempInC) + "&hum1=" + String(humidity);

      if (client.connect(server, 80)) {
        Serial.print("connected. My IP is ");
        Serial.println(Ethernet.localIP());
        client.println("POST /arduino/add.php HTTP/1.1");
        client.println("Host: 192.168.1.3");
        client.println("Content-Type: application/x-www-form-urlencoded");
        client.print("Content-Length: ");
        client.println(data.length());
        client.println();
        client.print(data);
      }
      else {
        Serial.println("connection failed");
      }
      Serial.println(data);
      // if there are incoming bytes available
      // from the server, read them and print them:
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
      }
      if (client.connected()) {
        client.stop(); // DISCONNECT FROM THE SERVER
      }
      delay(300000); // WAIT FOR A WHILE BEFORE SENDING AGAIN
    }

but its not updating the database, using the below **add.php** file from arduino **web-client.ino**

    <?php
            include("connect.php");

            $link=Connection();

            $temp1=$_POST["temp1"];
            $hum1=$_POST["hum1"];

            $query = "INSERT INTO `tempLog` (`temperature`, `humidity`)
                    VALUES ('".$temp1."','".$hum1."')";

            mysql_query($query,$link);
            mysql_close($link);

            header("Location: index.php");
    ?>

i checked in mysql prompt which is also the result displayed if I open the server url : 192.168.1.3/arduino/index.php

    mysql> select * from tempLog;
    +---------------------+-------------+----------+
    | timeStamp           | temperature | humidity |
    +---------------------+-------------+----------+
    | 2016-11-28 11:50:37 |           0 |        0 |
    | 2016-11-28 12:30:25 |           0 |        0 |
    +---------------------+-------------+----------+
    2 rows in set (0.00 sec)

I don't know how the first entry got created but second one I created by manually executing the url 192.168.1.3/arduino/add.php?temp1=26.64&hum1=18

the index page is showing he data from db as shown above in sql, that means connection is established and mysql and table is fetched from correct db. i.e. *arduinoSensorData*  in my case.

my serial monitor window got updated:

    BMP init Success
    connecting...
    connected. My IP is 192.168.1.131
    ?temp1=26.64&hum1=18
    connected. My IP is 192.168.1.131
    ?temp1=26.64&hum1=18
    connected. My IP is 192.168.1.131
    ?temp1=26.57&hum1=18

which means arduino is not able to put data to db using add.php

body:
I came to learn in my php code posted above, I am using `$_POST` variable when I should rather be using `$_GET`

In the PHP script, there are $_GET and $_POST variables that contain the data passed to the script, depending on the method used to to activate the script.

so using `$temp1=$_GET["temp1"];` and `$hum1=$_GET["hum1"];` fixes the problem.


message:
Running multiple motors simultaneously

I have this code for a DC motor (using [this][1] library)
<!-- language-all: lang-cpp -->

    #include <Arduino.h>
    #include <Vnh2sp30.h>

    //              ENA A   B   PWM   CS    inv
    Vnh2sp30  mtrL( A0, 7,  8,  5,    A2,   0);

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

    void loop() {
      if (Serial.available() > 0)   {
        String first  = Serial.readStringUntil(',');
        Serial.read();
        String second = Serial.readStringUntil(',');
        Serial.read();
        String third = Serial.readStringUntil(',');
        Serial.read();
        String echo = Serial.readString();
        Serial.println(echo);
           if(first == "start"){
                    Serial.println("Starting DC motor");
                    int duration = atoi(second.c_str());
                    int power = atoi(third.c_str());
                    int starttime = millis();
                    int endtime = starttime;
                    while ((endtime - starttime) <= duration) // mS
                    {
                      endtime = millis();
                      mtrL.run(1023);
                    }
                    mtrL.stop();
                    Serial.println("DONE");
           }
       }
    }

Then I have this code to drive multiple stepper motors (using [this][2] library):

    #include "BasicStepperDriver.h"

    int incomingByte = 0;   // for incoming serial data
    String readString = "";

    void setup() {
        Serial.begin(9600);
        motors.begin();
    }

    void loop() {
        if (Serial.available() > 0) {
        String first  = Serial.readStringUntil(','); // start
        Serial.read();
        String second = Serial.readStringUntil(','); // motor number
        Serial.read();
        String third = Serial.readStringUntil(','); // motor steps
        Serial.read();
        String fourth = Serial.readStringUntil(','); // duration (millisec)
        Serial.read();
        String fifth = Serial.readStringUntil(','); // deg
                    if(first == "start") {
                      if(second == "ALL") {
                        Serial.println("Starting stepper motor ALL");
                        int steps = atoi(third.c_str());
                        int duration = atoi(fourth.c_str());
                        int deg = atoi(fifth.c_str());

                        BasicStepperDriver stepper1(steps, DIR, STEP, ENBL);
                        stepper1.enable();
                        stepper1.setMicrostep(MICROSTEPS);
                        stepper1.setRPM(MAX_RPM);

                        BasicStepperDriver stepper2(steps, DIR_2, STEP_2, ENBL_2);
                        stepper2.enable();
                        stepper2.setMicrostep(MICROSTEPS);
                        stepper2.setRPM(MAX_RPM);

                        BasicStepperDriver stepper3(steps, DIR_3, STEP_3, ENBL_3);
                        stepper3.enable();
                        stepper3.setMicrostep(MICROSTEPS);
                        stepper3.setRPM(MAX_RPM);

                        BasicStepperDriver stepper4(steps, DIR_4, STEP_4, ENBL_4);
                        stepper4.enable();
                        stepper4.setMicrostep(MICROSTEPS);
                        stepper4.setRPM(MAX_RPM);

                        int starttime = millis();
                        int endtime = starttime;
                        while ((endtime - starttime) <= duration) // mS
                        {
                          stepper1.rotate(deg);
                          stepper2.rotate(deg);
                          stepper3.rotate(deg);
                          stepper4.rotate(deg);
                          endtime = millis();
                        }
                        stepper1.disable();
                        stepper2.disable();
                        stepper3.disable();
                        stepper4.disable();
                        Serial.println("DONE");
                      }
                    }
            }
    }

My goal is to merge this two codes together and still be able to run both the DC motor and one (or all) the stepper motors all together simultaneously. The first code is running on Arduino UNO and the other code runs on Arduino MEGA board and has been tested to work. The goal is to migrate the code from Arduino UNO to the MEGA board. Driving the motor for a specific time will block Arduino from executing the Stepper motors and vice versa with the DC motor. What can be done with these codes to make sure it can run the DC motor and Stepper motors at the same time?

  [1]: https://github.com/OliviliK/Arduino-Robot/blob/master/libraries/Vnh2sp30/Vnh2sp30.h
  [2]: https://github.com/laurb9/StepperDriver/blob/master/src/BasicStepperDriver.h

body:
Use the AccelStepper library along with the Adafruit MotorShield library

https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/install-software


message:
Arduino Uno Digital to Analog Converter

I'm trying to read in an analog signal (a heartbeat) to pin A0 on the Arduino Uno and then convert it to digital. I'm hoping to use the digital signal to make an LED light up every time the voltage of the heartbeat signal goes over 1 volt. This is the code I have right now, but something is wrong because it isn't lighting up the LED.

    unsigned int analog0;             // Raw data from A0 ranging from 0 to 1023
    unsigned long data_range = 2000;  // Length of time to record data for
    double volts;                     // The analog data from A0 converted to volts
    int ledPin = 13;
    unsigned long start_time;
    unsigned long data_time;

    void setup() {
      Serial.begin(9600);             // Initialize and set serial port baud rate
      pinMode(ledPin , OUTPUT);
    }

    void loop() {
      start_time = millis();
      while ((millis() - start_time) < data_range)
      {
        // Record current time of analog acquisition
        data_time = millis();

        // Record analog data on A0
        analog0 = analogRead(0);

        // Convert raw data into voltage
        volts = (analog0 / 1023.0) * 5;

        Serial.print(volts);
        Serial.println();

        // Slow the rate of data acquisition
        //delay(1);

        if (volts > 1.5){
          digitalWrite(ledPin, HIGH);
          //delay(50);
        }
        else{
          digitalWrite(ledPin, LOW);
        }
      }
    }

body:
Try commenting out the serial in your sketch. In my experience serial communication takes time, and I assume you have a short window where the voltage peaks at more than a volt. Or initialize the serial with a stupidly high baud rate.<br>
Edit: even better, you could try this for a faster response time:

    void setup(){
      digitalWrite(13,0);
      pinMode(13, OUTPUT);
    }

    void loop(){
      if(analogRead(A0)>204){ //at ~1V the ADC will read between 204 and 205
        digitalWrite(13,1);
        delay(100);
        digitalWrite(13,0);
      }
    }


message:
Digispark / DigiKeyboard change keyboard layout

I'm trying to use the [Digispark][1] as a [Rubber Ducky][2] but the Digispark is only usable with the US laylout. German keyboard layout is QWERTZ. Some keys can be changed, like y and z, but if there are `[` or `]` this isn't possible. Trying to define a `[`-key in DigiKeyboard.h displays a `ü`.

Does someone know a solution?

  [1]: http://digistump.com/products/1
  [2]: https://hakshop.com/products/usb-rubber-ducky-deluxe

body:
You can edit the file scancode-ascii-table.h in your DigiKeyboard library.
It basically states which ASCII code corresponds to which keyboard scancode.

So if you try to print the ':' character but get a '>' instead, you know that in the above mentioned file at the ASCII position for ':' is the scancode for a '>'.

Using this, you can swap the scancodes around and basically create your own 'mapping'. For example, if you swap the values at ASCII 89, 90 and 121, 122 you for example solve the Y/Z switch.

However, I have not figured out how to correctly print a backslash. You might have to map that do a different ASCII character you don't need.

To add to this answer, there exists a workaround using mame82's duck2spark:
https://github.com/mame82/duck2spark


body:
Solution is here:
Python script to convert RubberDucky payloads to DigiSpark sketch with respect to choosen keyboard layout:

[duck2spark][1]

Btw: The keys '<' '|' and '>' are on NON-US-KEY-100 on German keyboard layout. The key has value 0x64 for USB HID and the right modifiers have to be set (f.e. ALT_GR for '|' ). You could send them using

    DigiKeyboard.sendKeyStroke(key,modifier);

For details see [USB HID usage tables][2]

  [1]: https://github.com/mame82/duck2spark
  [2]: http://www.freebsddiary.org/APC/usb_hid_usages.php


body:
here is a library version of Digistump with german keyboard support https://github.com/adnanonline/DigistumpArduinoDe
I adapted the keyboard library: digistump-avr/libraries/DigisparkKeyboard/DigiKeyboard.h to the german layout


message:
Serial 3 vs Software Serial

So I have a program that works great on the Mega, it uses serial 3 to read and streams out to the USB (I posted a previous question which someone answered)  I tried to use Serial (D0) to read and then write to serial, which did not work.  So now I am looking in to Software Serials

Is there a difference between a real serial and software serial as it does not seem to be working, It all runs a bit slower

    #include <SoftwareSerial.h>

    const int DesiredRPM=300;  // Setting Desired RPM Here.
    const int MotorPWMPin=4;
    int inByte = 0;         // incoming serial byte
    unsigned char Data_status=0;
    unsigned char Data_4deg_index=0;
    unsigned char Data_loop_index=0;
    unsigned char SpeedRPHhighbyte=0; //
    unsigned char SpeedRPHLowbyte=0;

    int SpeedRPH=0;
    const unsigned char PWM4dutyMax=255;
    const unsigned char PWM4dutyMin=100;
    unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

    SoftwareSerial mySerial(10, 11); // RX, TX

    void setup() {
        pinMode(MotorPWMPin, OUTPUT);
        Serial.begin(115200);  // USB serial
        Serial3.begin(115200);  // XV-11 LDS data

        // prints title with ending line break
        Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

        // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
        analogWrite(MotorPWMPin, PWM4duty );

        mySerial.begin(115200);
    }

    void loop() {
        // if we get a valid byte from LDS, read it and send it to USB-serial
      if (Serial3.available() > 0) {
        // get incoming byte:
        inByte = Serial3.read();
        //Serial.print(inByte, BYTE);
        //Serial.write(inByte);
        Serial.print((char)inByte);
        decodeData(inByte);
      }

      if (mySerial.available() > 0) {
        // get incoming byte:
        inByte = mySerial.read();
        //Serial.print(inByte, BYTE);
        //Serial.write(inByte);
        Serial.print((char)inByte);
        decodeData(inByte);
      }

    }

    void decodeData(unsigned char inByte){
      switch (Data_status){
      case 0: // no header
      if (inByte==0xFA)
      {
        Data_status=1;
        Data_loop_index=1;
      }
        break;
      case 1: // Find 2nd FA
        if (Data_loop_index==22){
          if (inByte==0xFA)
          {
            Data_status=2;
            Data_loop_index=1;
          }
          else // if not FA search again
          Data_status=0;
        }
        else{
          Data_loop_index++;
        }
        break;
      case 2: // Read data out

         if (Data_loop_index==22){
          if (inByte==0xFA)
          {
            Data_loop_index=1;
          }
          else // if not FA search again
          Data_status=0;
        }
        else{
          readData(inByte);
          Data_loop_index++;
        }
        break;
      }

    }
    void readData(unsigned char inByte){
      switch (Data_loop_index){
        case 1: // 4 degree index
        Data_4deg_index=inByte-0xA0;
    //      Serial.print(Data_4deg_index, HEX);
    //      Serial.print(": ");
        break;
        case 2: // Speed in RPH low byte
        SpeedRPHLowbyte=inByte;
        break;
        case 3: // Speed in RPH high byte
        SpeedRPHhighbyte=inByte;
        SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

        SpeedControl ( DesiredRPM ) ; //
    //      Serial.print(SpeedRPHhighbyte, HEX);
    //      Serial.println(SpeedRPHLowbyte, HEX);
        break;
        default: // others do checksum
            break;
      }
    }

    // Very simple speed control
    void SpeedControl ( int RPMinput)
    {
     if (Data_4deg_index0==0) {  // I only do 3 updat I feel it is good enough for now
      if (SpeedRPH<RPMinput*60)
         if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
      if (SpeedRPH>RPMinput*60)
         if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
      }
      analogWrite(MotorPWMPin, PWM4duty ); // update value
    }

body:
There are huge differences. The most important ones are:

* SoftwareSerial is half duplex (it can send or it can receive, it cannot do both at once)
* SoftwareSerial is blocking - while it is sending or receiving nothing else can happen

SoftwareSerial is very much a poor-man's serial port. It should only really be used for very low volume data (things like NEMA messages once a second or so) and only if you have absolutely no choice (and, let's face it, you always have a choice).


message:
Cannot move TM1637 from Uno to Pro Mini

I have a very simple setup which works fine with an *Uno*.

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

    #include <SevenSegmentTM1637.h>
    #include <SevenSegmentExtended.h>

    const byte PIN_CLK = 2;
    const byte PIN_DIO = 3;
    SevenSegmentExtended display(PIN_CLK, PIN_DIO);

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

      display.begin();
      display.print(F("TEST"));
    }

    void loop() {}

When I use the very same setup with a *Pro Mini* (XCSOURCE ATMEGA 328P, 5V 16Mhz), the display doesn't light up. I get monitor outputs and can blink the onboard LED, but no reaction from the *TM1637* display.

I get this output in the console:

    �E%MA1e� 10001111
    Acknowledged: 0
    ADDR :  11000000
    DATA0:  0
    write byte: 84
    ADDR :  11000000
    DATA0:  1111000
    write byte: 69
    ADDR :  11000000
    DATA0:  1111000
    write byte: 83
    ADDR :  11000000
    DATA0:  1111000
    write byte: 84
    ADDR :  11000000
    DATA0:  1111000

Does anyone have an idea how to debug or fix this?

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

body:
Since you're using a Grove Display, I believe it will be using I2C.

For better debugging, try using the actual I2C pins on your Pro mini, which are A4 and A5.

> I2C: A4 (SDA) and A5 (SCL). Support I2C (TWI) communication using the
> Wire library.
> https://www.arduino.cc/en/Main/ArduinoBoardProMini

I2C may need pull-up resistors on your data lines.

(https://en.wikipedia.org/wiki/I²C)

It can also be nice to use "verified to be working" code, like example code from the manufacturer.

    /*
     * TM1637.cpp
     * A library for the 4 digit display
     */
    #include "TM1637.h"
    #define CLK 39 //pins definitions for TM1637 and can be changed to other ports
    #define DIO 38
    TM1637 tm1637(CLK,DIO);
    void setup()
    {
        tm1637.init();
        tm1637.set(BRIGHT_TYPICAL);//BRIGHT_TYPICAL = 2,BRIGHT_DARKEST = 0,BRIGHTEST = 7;
    }
    void loop()
    {
        int8_t NumTab[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};//0~9,A,b,C,d,E,F
        int8_t ListDisp[4];
        unsigned char i = 0;
        unsigned char count = 0;
        delay(150);
        while(1)
        {
            i = count;
            count ++;
            if(count == sizeof(NumTab)) count = 0;
            for(unsigned char BitSelect = 0;BitSelect < 4;BitSelect ++)
            {
                ListDisp[BitSelect] = NumTab[i];
                i ++;
                if(i == sizeof(NumTab)) i = 0;
            }
            tm1637.display(0,ListDisp[0]);
            tm1637.display(1,ListDisp[1]);
            tm1637.display(2,ListDisp[2]);
            tm1637.display(3,ListDisp[3]);
            delay(300);
        }
    }

You will need to adapt the pin numbers.

But after these steps it should work just fine.

Source: http://wiki.seeed.cc/Grove-4-Digit_Display/


body:
4.7k resistors on 2 and 3 pins does not help.

Works great if the tm1637 directly connected to 12 and 13 pins.


message:
How do I change PGA gain in this Arduino program?

Below is the link to three files I am using with a 32 bit ADC from TI, ADS1262, plus a link to it's datasheet. It works fine but I'm not getting any better voltage resolution than with a 16 bit ADC. I am using it for small voltage, from 0 to 0.070 volts. For example, for a known stable voltage of 0.01000 volts from a Fluke thermocouple calibrator I get 0.010000 to 0.010006. I get this same 0.000006 volt jitter if I short the ADS1262 input pins together. I suspect it may be a programmable gain amplifier issue. I can put 2.5 volts into it and not damage it. There is a line in the .ino file, #define PGA 1. On a guess, I changed this to #define PGA 32 but it had no effect on the results, it's like my attempted program change didn't take. I read in the ads1262 datasheet that the PGA Gain is in the MODE2 Register, address 05h. A gain of one is set with 000 and a gain of 32 is set with 101. But I do not know how to proceed. Perhaps somebody can help me out.

https://github.com/Protocentral/ProtoCentral_ads1262/tree/master/Libraries
http://www.ti.com/lit/ds/symlink/ads1262.pdf

body:
The symbol `PGA` appears in `exapmle.ino` (sic) twice, once each in lines 28 and 30:

     #define PGA 1                     // Programmable Gain = 1
     ...
     #define VFSR VREF/PGA

It is not used elsewhere in the example or the library code.  The only effect of changing its value from 1 to 32 is to change the value of `VFSR`, and as`VFSR` appears only in line 30, that effect is nil.

Looking at the `ads1262.cpp` file from github, it appears that `ads1262::ads1262_Init()` initializes register `MODE2` to 0x6, via:

    ads1262_Reg_Write(MODE2, 0x06);

which per the ADS1262 spec sheet, page 93, table 44, enables the PGA and sets its gain to 1 and sets the sample rate to 60 SPS.

Apparently, if you wish to use some other gain setting, you should define `PGA` appropriately and put a corresponding setting into `MODE2`.  For example, if you want to set up a gain of 16 and sample rate of 400 SPS, in `setup()` you could say

    PC_ADS1262.ads1262_Reg_Write(MODE2, 4<<4 | 8); // 4=gain 16, 8=400 SPS

More generally, you could set up some constants for gain codes and SPS rates, and reference those constants when writing to `MODE2`.  For example, after

    enum { GainCode1, GainCode2, GainCode4, GainCode8, GainCode16, GainCode32 };
    enum { SPSCode2p5, SPSCode5, SPSCode10, SPSCode16p6, SPSCode20, SPSCode50,
           SPSCode60, SPSCode100, SPSCode400, SPSCode1200, SPSCode2400,
           SPSCode4800, SPSCode7200, SPSCode14400, SPSCode19200, SPSCode38400};

you would say

    PC_ADS1262.ads1262_Reg_Write(MODE2, GainCode32<<4 | SPSCode2400);

to set the gain at 32 and the sample rate at 2400 SPS.

(Note, `enum` is a C language element used to define integer constants.  In an `enum`, each symbol mentioned without an explicit value has a value one more than the previous symbol, or zero if there's no preceding symbol.  So `GainCode1` is 0, `GainCode2` is 1, `GainCode4` is 2, etc.)

Note, to get better ultimate resolution, you may need to combine multiple readings, or may need to set the ADS1262's filtering parameters.


message:
Arduino based Fan controller for PC

My fellow programmers,

I'm planning on creating a fan controller for my PC using an Arduino Duemilanove and a generic motor sheild. (Fan controllers are not exactly cheap here and i'd rather spend my money on an SSD than on a fan controller =)

On a normal scenario, I want my fans to spin slowly, just to keep some air flowing but not enough to make too much noise. Obviously, they should turn on at full speed (or so) during a demanding scenario, like playing a game.

My idea is to use a usb port to communicate with Windows, so that my arduino knows when a demanding application was started. Is there an easy way to do this or should I buy myself some cheap temperature sensors, place them on the more important parts and control my fans with these temperature readings?

I'd also like to have an option to turn of the communication between the arduino and whatever informs it about the computer usage, so that I can program it in order to test a different algorithm.

Thanks for any help!

body:
Any Arduino with a USB interface can communicate with a PC via pseudo-serial ports (that is, serial-over-USB links).  If you have a PC program that somehow monitors what processes are running, your plan of telling the Arduino to speed up the fan when certain programs are running is practical to do.

On Linux systems, fan speed can be controlled by user programs like [fancontrol-gui](https://github.com/Maldela/fancontrol-gui) and [tpfanco](https://github.com/tpfanco/tpfancod/blob/master/src/tpfancod/control.py).  Probably similar programs are available on Windows and Mac systems.  Your Arduino could measure temperatures and send them to the host OS for fan speed control.  Or vice versa, your PC could use DBus or ACPI calls to measure its chip temperature and send it to the Arduino to control a fan.

Note, there's a thermometer built in to several ATmega devices.  Its resolution isn't great and due to chip thermal mass it might not respond quickly, but you might find it worthwhile to experiment with.  For example, see §24.8, Temperature Measurement, on page 247 of the document Atmel-8271J-AVR-ATmega-Datasheet_11/2015, which says to select the internal 1.1 V ADC voltage reference, read ADC channel 8, and scale the result per Table 24-2 to get °C.


body:
Yes you can. One of the options is using Visual Studio if you are Windows user (using built in [library][1] is enough to meet your 'option to turn off' needs). There so many examples of serial communication using either C# or C++ with Arduino, so you can do communication between Laptop - Arduino via serial cable or even built in bluetooth in laptop (with extra bluetooth module for Arduino).

The most simple setup is your laptop act as master and arduino as slave. Arduino does not need any information about what program is running, instead just waiting command from Laptop wether to turn off or turn down the fan

You can read  information from your PC (for Windows), such as [temperature][2] or [battery level][3]

  [1]: https://msdn.microsoft.com/en-us/library/system.io.ports.serialport(v=vs.110).aspx
  [2]: https://stackoverflow.com/questions/1195112/how-to-get-cpu-temperature
  [3]: https://stackoverflow.com/questions/18865979/battery-level-c-sharp