Find number of RX and TX-pin on ArduiMu I've got an Arduino V3+ and need to find the correct PIN number for its RX and TX-pin on the FTDI-connector.

How can I find out the correct number of them to use them with the SoftwareSerial-library?

Why I need these numbers:

I'm connecting a Sparkfun Bluetooth Mate/BlueSMIRF to the ArduiMUs FTDI headers and need to set a few settings in its command mode before it operates without flaws.
This is the code I'm using:

#include <SoftwareSerial.h>

int bluetoothTx = ???;  // TX-O pin of bluetooth mate, Arduino D2
int bluetoothRx = ???;  // RX-I pin of bluetooth mate, Arduino D3
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  Serial.begin(9600);  // Begin the serial monitor at 9600bps

  bluetooth.begin(115200);  // The Bluetooth Mate defaults to 115200bps
  bluetooth.print("$$$");  // Enter command mode
  delay(5000);  // Short delay, wait for the Mate to send back CMD
  bluetooth.println("U,9600,N");  // Temporarily Change the baudrate to 9600, no parity
  // 115200 can be too fast at times for NewSoftSerial to relay the data reliably
  bluetooth.begin(9600);  // Start bluetooth serial at 9600
}

You can use FTDI cable with your board on the last row of pads as you have highlighted.

Unfortunately your board designers do not publish a pdf version of the schematic so I opened the provided schematics in EAGLE and exported the FTDI connector diagram.

Here is the FTDI connector connections from the schematic:

Here is the pinout of the FTDI cable

So you can solder a 6 pin header on the bottom row and use the standard FTDI cable.

The FTDI row on your board indicates "BLK" on the left so orient your FTDI connector's black wire with the "BLK" pad on your board.

EDIT:

As per your edits you are using hardware serial on your arduino board to monitor and you are using one instance of "SoftwareSerial" to interface with bluetooth.

As SoftwareSerial library says, you can define any digital pins for Tx and Rx. In the example they have used Arduino pins 10 (pin 14 of the ATMEGA) and 11 (pin 15 of ATMEGA) for Rx and Tx respectively. In your non-standard arduino board, the micro-controller pin 14 is labeled as PWM1 and pin 15 is labeled as MOSI and they are brought out on connector JP7.

So in a nutshell you can use pin 4 of JP7 as SoftRx and pin 5 of JP7 as SoftTx.

If those pins are in use, you can always use other digital pins that are unused in your design. Just refer to the schematic of your board, ATMEGA328 datasheet and arduino libraries.


Galileo Positioning System signal receiving I want to determine my arduino's position. However, I want to use the European Galileo system instead of the US-American GPS.

Therefore, I searched for any possibilities receiving the Galileo signals. I figured out, that u-blox has some receivers: NEO 8 or the LEA 6 (firmware update required). However I did not find any arduino breakout board (, etc.) that uses these u-blox sensors or other Galileo-compatible hardware.

Does anyone know, how I could use the Galileo Position System?

You need the hardware and a library. Most GPS modules use a serial communication, and I think that also the Galileo compatible boards use serial communication. That makes them compatible with most microcontrollers and also with Arduino boards.

I could find a few shields that can be attached to an Arduino board.
This one is in development at the moment: Kickstarter shield with Galileo
This one is compatible via the serial pins: GA-001 Multi GNSS Ublox
There is a "NEO-M8N" shield and maybe one or two others.

All those boards are very new, and I don't know if they come with a library for an Arduino. Perhaps you have to wait a few months and then it should be a lot easier to buy a complete functioning module with a library.

Before buying a module, confirm that there is a library for Arduino or good documentation to write your own library.


How to merge two GPS coordinates without losing decimals I want to take the GPS coordinates like 42.1234 per 22.1234 and merge them as a string, with a separator character:

42.1234 x 22.1234

But using this code:

gps_string = (String)gps.location.lat()+' x '+(String)gps.location.lng();

I lose the last decimals and I get:

42.12 x 22.12

The only way I could see full coordinates is by specifying an extra parameter to println, like this:

Serial.println(gps.location.lat(), 6);

How can I create a string containing both two coordinates without losing decimals ? e.g 42.1234 x 22.1234

If you want 4 decimal places, you may try something like this:

gps_string = String(gps.location.lat(), 4)
           + " x "
           + String(gps.location.lng(), 4);


Multiple buttons on single interrupt, how to debounce? Buttons on separate interrupt pins work fine (triggered on FALLING), bouncing is handling by forcing a 80ms lockout period during which further presses are ignored. I like that solution for being lightweight.

My goal is to have 1 interrupt handle all events (buttons and other digital inputs). I don't want to depend on loop(), I wish to be free to use delay often rather than timer interrupts.
Most buttons execute an action when pressed, some, while pressed.

What I have now (just 2 buttons for now):

simulate this circuit – Schematic created using CircuitLab

void setup() {
  pinMode(17, INPUT_PULLUP);
  pinMode(16, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(3), wotHappnd, CHANGE);
}

boolean isDebouncing(){
  unsigned int now = millis();
  if(now - time_lastPressed > time_debounceLockout){
    time_lastPressed = now;
    return false;
  }
  return true;
}

void wotHappnd(){
  boolean interruptFalling = digitalRead(3) == LOW;
  if(interruptFalling && isDebouncing()) return;
  // digitalRead the pins; do stuff
}

Internal pullups on all used pins.

My problem is that often (~4%), on interrupt, the interrupt pin is LOW all button pins are HIGH ("not pressed" - likely bouncing just as I read it). How to fix that?

Can't use delay during an interrupt; delayMicroseconds to wait for stable readout still feels inappropriate; a cap-based delay on the interrupt pin induces a period of floating.
Prefer solutions in software or with no more than 1 extra component per input.

[edit] here's a claim that pin interrupts do some filtering already, which, if true, may make some solutions unreliable.

In the Isr, read the two pins and maintain their current status (UN debounced), and reset a counter.

In the main loop, increment that counter. If it is more than a certain number, it means that the current state of the key has been stable for a while - bounce no more.

Or Google Kuhn debounced. I wrote a blog page about that. If you want, I can post it later. The basic idea is the same.


Multiple Arduino Uno Slaves I am working on an Arduino project where I need more digital and analofgpins than the Uno offers. I was wondering how to hook up multiple Arduinos (4) together so I can use their digital and analog pins. Thanks in advance.

I suggest using a single Arduino Mega.  It offers 54 digital I/O and 16 analogue inputs.

I suppose you could also use I2C or SPI to communicate between multiple Uno's.


Connecting two arduinos with wifi over the Internet I have worked with Arduino before, but not with WiFi modules. I always used RF or other methods.

Now I am working on a project where i need to connect two UNOs, over long distance, but they will have a continuous internet connection.

One board with only send data, and one will only receive.

Will the esp8266 soc suffice for this? They will have fast network connection; at least 4g speeds. So can I send and receive real time data over the internet, and receive it fast? It should feel like there is no delay on the receiving side. Can I do this with the ESP, and if so, can any one point me towards the right material to get started.

thx in advance :)

The ESPs are easy to work with and more than capable, BUT (there's always a "but"): with a public network in the middle, latency, routing, and traffic issues will be beyond your control. Look, for instance, at the variability in page load times when loading over the internet.

If you use an IoT server in the middle, there will be server delays outside your control as well, though connecting to a common server from both ends can make it much easier to get everything talking for the first time. (There may, however, be data-rate limits imposed on you if the server in the middle is a free service.)

  So can I send and receive real time data over the internet, and
  receive it fast?

Define "real fast". Do you mean "really quickly" (short delay from start of transmission to start of reception at the other end)? Or "really high throughput" (moving lots of data in a short time, or continuously without falling behind? Or something else?

Since you're working with an Uno, if you need to use a SoftwareSerial port to talk to the ESP, the SS will be limited to 9600 baud (equivalent to 960 Bytes/sec) and your ability to push data through it to somewhat under that. If you can use the built-in hardware UART your data-rate to/from an ESP can be much higher, at least 115200 baud or 11,520 B/sec (again, gross rate; rate of pushing data will be somewhat lower).

tl;dr: The network will be a much greater limitation than the ESP devices.

Update:

  the problem i see is the delay with communication over the internet
  between the two uno if i use a server.can i communicate between the
  two with out the use of a server

Of course. Using an intermediate server might be a useful step on the way to getting your devices to talk directly. It would allow you to focus on the clients themselves at first and leave (most of) the networking issues to work out later. But you'll still have the issues of any network and especially a public network. If you have no other choice, you build it and you get whatever you get for performance. How serious are the consequence of a delay or a lost packet? Inconvenience? Delayed system functions? Will it cost someone money? Could someone get hurt? Could someone die? How dire the consequences could be will determine how stringent (and expensive) your solution has to be and what backups might have to be in place.


Adafruit motorshield v2.3 not working I want to connect my adafruit motor shield v2.3 to a touch board from bare conductive so that the motor turns when one of the electrodes is touched.

I've tested the touch part and that isn't a problem so i tested the motor shield on my arduino uno. I am using the DCMotorTest example and when uploading it doesn't give any errors. The shield is getting powered, but the motor isn't turning.

The motor does turn when connected to a 9v battery.
The motor doesn't turn when connected to motor shield without external power and VIN jumper connected.enter image description here
The motor doesn't turn when connected to motor shield with external power with and without VIN jumper connected.

/*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438
*/

#include <Wire.h>
#include <Adafruit_MotorShield.h>

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  myMotor->run(FORWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tock");

  myMotor->run(BACKWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tech");
  myMotor->run(RELEASE);
  delay(1000);
}

https://imgur.com/a/tEGndDQ

I just used a different motor-shield and it works now, thank you all for your replies and research in this!


ESP8266 with RTC DS1307 shield - WS2818B shield won't blink - I2C issue? Dear Ladies and Gentlemen,
I'd like to let a LED blink base on the time of the day. So I took Wemos D1 mini and a WS2818B shield and a RTC DS107 Shield for the before mentioned ESP8266 model.
Based on my observation, I can let the LED blink on its own without starting the initialization of the RTC. As soon as I initialize the communication with the DS1307 shield, the LED shield won't translate any commands toward the desired behavior (e.g. the LED won't blink anymore).
What am I doing wrong?
I'm using the Ardunio IDE to program the D1 mini.
I stacked the shields and kept an eye on the pins to be sure I did wire everything the right way.
Libraries in use:
RTC: https://github.com/Makuna/Rtc
LED: Adafruit NeoPixel
Code:
// WIFI
#include <ESP8266WiFi.h>

// RTC
#include <RtcDateTime.h>
#include <RtcUtility.h>
#include <Wire.h> // must be included here so that Arduino library object file references work
#include <RtcDS1307.h>
RtcDS1307<TwoWire> Rtc(Wire);

// LED
#include <Adafruit_NeoPixel.h>
#define PIN        D2
#define NUMPIXELS 1
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ400);

int DELAYVAL = 1000; // Time (in milliseconds) to pause between pixels

void setup() {

  Serial.begin(57600);
  Serial.println();
  Serial.flush();

  setupLed();

  setupWifiConnection();

  setupRtc();

}

void loop() {

  pixels.clear(); // Set all pixel colors to 'off'
  pixels.show();   // Send the updated pixel colors to the hardware.
  delay(DELAYVAL); // Pause before next pass through loop

  pixels.setPixelColor(0, pixels.Color(0, 150, 0));
  pixels.show();   // Send the updated pixel colors to the hardware.
  delay(DELAYVAL); // Pause before next pass

}

void setupRtc () {

  Rtc.Begin();

  RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
  Serial.println();

  if (!Rtc.IsDateTimeValid())
  {
      if (Rtc.LastError() != 0)
      {
          // we have a communications error
          // see https://www.arduino.cc/en/Reference/WireEndTransmission for
          // what the number means
          Serial.print("RTC communications error = ");
          Serial.println(Rtc.LastError());
      }
      else
      {
          // Common Causes:
          //    1) first time you ran and the device wasn't running yet
          //    2) the battery on the device is low or even missing

          Serial.println("RTC lost confidence in the DateTime!");
          // following line sets the RTC to the date & time this sketch was compiled
          // it will also reset the valid flag internally unless the Rtc device is
          // having an issue

          Rtc.SetDateTime(compiled);
      }
  }

  if (!Rtc.GetIsRunning())
  {
      Serial.println("RTC was not actively running, starting now");
      Rtc.SetIsRunning(true);
  }

  RtcDateTime now = Rtc.GetDateTime();
  if (now < compiled)
  {
      Serial.println("RTC is older than compile time!  (Updating DateTime)");
      Rtc.SetDateTime(compiled);
  }
  else if (now > compiled)
  {
      Serial.println("RTC is newer than compile time. (this is expected)");
  }
  else if (now == compiled)
  {
      Serial.println("RTC is the same as compile time! (not expected but all is fine)");
  }

  // never assume the Rtc was last configured by you, so
  // just clear them to your needed state
  Rtc.SetSquareWavePin(DS1307SquareWaveOut_Low);
}

void setupLed () {

  pixels.begin();

  pixels.clear();
  pixels.show();
}

void setupWifiConnection () {

  WiFi.begin("some ap", "some password");

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
}

According to your code, you’ve connected the Neopixel to D2. The RTC is an I2C device, so it’s also connected to D2. How is that supposed to work? The Neopixel isn’t an I2C device.
Move the Neopixel to a different pin that’s not used by anything else - so not D1. Try D3. Update your code to use D3. There may be other issues but at least you won’t be trying to use the same pin to talk to two very different devices.


Logging to multiple destinations (serial & SD card) I am building a rover using an Arduino Mega and an Arduino Uno. The Mega has a sensor shield that has an SD card slot. The intent is for the rover to be autonomous, and I currently send logging info to the serial port (to log actions like boot, diagnostics, etc.)

Is there a simple way to redirect this output to BOTH the serial and the SD card? I would be happy with just a single file with lines added for each entry.

My complication here is to prevent using Serial.println as well as SD.println as two separate commands. Is there any other way around this?

The simplest thing you can do is to create a simple function that performs both tasks for you.  However, there are certain caveats that you should look out for.  The most basic function would be:

void log(const char *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

However that is not the best way of doing it since that requires all your messages to be in RAM.  So you should really use the __FlashStringHelper type as well as an overload function so you can use the F() macro to save RAM:

void log(const char *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

void log(const __FlashStringHelper *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

And that will pick the right version of log depending on what you pass.  But what if you want to pass some variables, like numbers?  Overloading can help again here.  Another pair of functions now that take two parameters instead of one:

void log(const char *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

void log(const __FlashStringHelper *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

void log(const char *msg, int v) {
    Serial.print(msg);
    Serial.print(" ");
    Serial.println(v);
    myFile.print(msg);
    myFile.print(" ");
    myFile.println(v);
}

void log(const __FlashStringHelper *msg, int v) {
    Serial.print(msg);
    Serial.print(" ");
    Serial.println(v);
    myFile.print(msg);
    myFile.print(" ");
    myFile.println(v);
}

So now you have 4 functions called log, and they can be used in these different ways:

log("This is a message"); // Could be a char * variable
log(F("This is a message"));
log("The temperature is:", temp);
log(F("The temperature is:", temp);

And of course you can keep expanding and expanding the parameters in different ways for different combinations of parameters.  Just be warned that for some combinations of parameters the compiler won't be able to work out which is the right function to call (for instance if you have one that takes a long and one that takes a byte in the same place and you just pass a numeric literal), so you have to think carefully about how you arrange your parameters.


Check if the board is in sleep mode I'm using seep sleep mode with UNO with a simple sketch that turning on an LED and then goes to sleep. as far as the ATmega328p datasheet in sleep mode part showing the wake up sources and deactivated clock sources in deep sleep mode and the I/O clock becomes deactivate so we expect when the board goes to sleep the LED should become off because of no clock. but it doesn't happen and LED keeps ON in sleep mode. what is the problem?7 and how can we even find out that the board is on sleep mode or not?

The IO doesn't require the clock to keep its current state. It only requires it to change state.

There is no real external signal provided by the chip to indicate if its in sleep mode or not. However you could monitor the current consumption of the chip and when it drops below a certain threshold you can assume that it is in sleep mode.


How do I provide a negative current? I'm trying to use an ATMega328 board to control a board of a broken UPS device. I replaced all the internals of the UPS by custom components, so the only things which remain are the chassis and the front board.

On this board, there are five buttons, and three LEDs.

All those components are connected to the ground, each one through its own resistor. By connecting the different pins to the ground and to analog pins of the ATMega328 board, I can successfully detect when the buttons are pressed.

Things, however, get tricky when I want to turn the LEDs on. They have their anode connected to the ground (through a 47Ω resistor), and their cathode connected to a dedicated pin. This means that if I apply voltage to this pin, the LED remains off.

The LED, however, turns on if I connect the ground to a 5V pin on ATMega328 board and the cathode pin to the ground of the ATMega328 board. However, connecting the ground to 5V makes it impossible to read the state of the buttons (or should I wire them somehow specifically?)

Therefore, how do I feed negative current from the ATMega328 board?

There is a similar question on this subject, but while the author wants to “understand the underlying electronics of the arduino and microcontrollers in general,” I, instead, just want to know how to make it work. Reading the answers from the linked question, I have an impression that this is possible, but they don't explain how to do it.

If the LEDs turn on when you apply 5V to ground then what you have identified as GND on the board is actually VCC.
There is no such thing as negative current: current is either sourced or sinked, depending if it’s exiting or entering into a node.

The diodes (LED) are one way valves, so you have a clear current direction: once that is established, identifying a button press can work either triggering when it gets LOW or when it gets HIGH, in other words that can be easily reversed.

If previously you where detecting a button press with digitalRead(BTN_PIN) == HIGH then just switch to digitalRead(BTN_PIN) == LOW and you have your solution.


Error: "invalid use of incomplete type" and "forward declaration" I have the following errors trying to use a TFT library function inside my library. My library uses the pointer to an instance of the TFT library in the constructor, as well described there:

Basic C++ programming, how to pass constructor argument into class?

The errors are:

error: invalid use of incomplete type 'class TFT'
_TFTscreen->background(0, 0, 0);

error: forward declaration of 'class TFT'
class TFT;

MESmenu.h:

#ifndef _MESMENU_H_
#define _MESMENU_H_

#include <SPI.h>
#include <SD.h>

class TFT;

class MESmenu{
public:
  MESmenu(TFT* pTFT) : _TFTscreen(pTFT) {};
  void start();
  void execute();
private:
  TFT* _TFTscreen;
};

#endif

MESmenu.cpp:

#include "Arduino.h"
#include "MESmenu.h"

void MESmenu::start(){
  _TFTscreen->background(0, 0, 0);
  _TFTscreen->text("starting menu...", 0, 0);
  //...
}

void MESmenu::execute(){
   //some code...
}

The Arduino sketch is:

#include <SPI.h>
#include <SD.h>
#include <TFT.h>  // Arduino LCD library
#include <MESmenu.h>  // my library

// --------- TFT LCD ---------
// pin definition for the due
#define sd_cs  7
#define lcd_cs 10
#define dc     9
#define rst    8
TFT TFTscreen = TFT(lcd_cs, dc, rst);

// MES menu class
MESmenu *mainMenu = new MESmenu(&TFTscreen);

void setup() {
  // initialize TFT
  TFTscreen.begin();
  TFTscreen.background(0, 0, 0);
  // set the stroke color to white
  TFTscreen.stroke(255,255,255);
  TFTscreen.fill(255,255,255);
  TFTscreen.setTextSize(2);
  TFTscreen.text("TEST", 0, 0);

  // Start menu
  mainMenu->start();
}

void loop () {
  mainMenu->execute();
}

The problem is related to the function:

_TFTscreen->background(0, 0, 0);

inside the MESmenu::start() in the .cpp file.

UPDATE:

As suggested by frarugi87 I've updated the question with the details of .h and .cpp files.
Those file are in the Arduino\libraries\MESmenu folder.

I try to change

class TFT;

with

#include <TFT.h>

and removed the #include  from the main arduino sketch.

This leads to the following errors:

libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)'
sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: first defined here

libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `PImage::read16(SDLib::File)'
sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/PImage.h:17: first defined here

libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `PImage::read32(SDLib::File)'
sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/PImage.h:17: first defined here

libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `PImage::loadImage(char const*)'
sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/PImage.h:17: first defined here

Try to change

class TFT;

to

#include <TFT.h>

Then you can remove the #include <TFT.h> from the main arduino sketch.

Moreover you should at least write a piece of code to make the compiler include your library just once; this is the usual way to do it:

#ifndef _MESMENU_H_
#define _MESMENU_H_

#include <SPI.h>

...
the rest of your library
...

  TFT* _TFTscreen;
}

#endif

_MESMENU_H_ is any unique string (usually the filename is used, remembering that you can't put spaces or other punctuation marks except the underscore). And you should put it only in the header file (*.h or .hpp), not in the source (.c or *.cpp or *.ino)

EDIT:

The additional info lead me to analyze the library and.. there are problems with the library. Particularly the file TFT/src/utility/Adafruit_GFX.h has a big problem: it has the code for the functions.

To fix it, you have to modify the library.

Go into the folder TFT/src/utility/ and make a copy of Adafruit_GFX.h, calling it PImage.cpp.

Open Adafruit_GFX.h and delete everything between line 227 and line 370. This means that from

bool useFill;
};

#if defined(__SD_H__)  // Arduino SD library

#define BUFFPIXEL 20

void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) {

...

  return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip);
}

#endif

#endif // _ADAFRUIT_GFX_H

it should become

bool useFill;
};

#endif // _ADAFRUIT_GFX_H

Having done this, open PImage.cpp and delete everything above line 227, then delete the function Adafruit_GFX::image and the last endif and add, at the beginning, #include Adafruit_GFX.h. This means that the file should look like

#include "Adafruit_GFX.h"

#if defined(__SD_H__)  // Arduino SD library

#define BUFFPIXEL 20

// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.

uint16_t PImage::read16(File f) {

...

  return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip);
}

#endif

Then try to compile again the program

BTW: the source I looked at is at this page.


Will M2.5 screws fit the holes in the Arduino Uno? I'm developing a sump pump monitor/alarm setup that will include an Arduino Uno as well as a Raspberry Pi. Both boards will be mounted to a piece of wood. The Arduino is designed to take M3 screws, but the Pi is designed to take M2.5 screws. The difference in these two screw sizes is 0.5mm (2.4mm M2.5 vs 2.9mm M3). Is this going to be close enough to be able to use the smaller M2.5 screws for both? Due to cost reasons, I want to avoid having to purchase two different sizes of screws and standoffs.

With the screw holes for the Arduino being the larger screw holes, the 2.9mm screws would fit, but would probably need a nut and/or a washer to properly secure things. In the end if you intend to be doing more work with Arduinos and Pis in the future that require screwing things together then just go and get proper screw sizes, you won't regret it.


Connect an mp3 player to an Arduino? I have been looking for a good way to play sounds using an Arduino.  I started to consider just buying a cheap mp3 player and replacing the player's buttons with optical switches, which connect to an Arduino.  I wanted to know if anyone has done this before and if there was a good mp3 player for this (one that may have some sort of control port / ir sensor.)

Yes, people have done this before, and they have documented it on their own blogs and similar sites.  Maybe you should have asked Google first before you came here?  You'd most likely have ended up on instructables, where someone has documented exactly what you want to do and how to do it. and saved yourself this entire step.


How to automatically reset the NRF24L01 module For my home-automation project I'm using several arduino nano's with each a NRF24L01+ module. Each module is able to both receive and transmit with one another. Everything seemed to be flawless for a couple of hours, but after a couple of hours it either stops transmission (completely frozen) of receives the last data repeatedly. In my design I'm using the RF24 and RF24Network libraries, I was wondering whether someone managed to automatically reset the NRF24L01 module using code, when one of these errors occured, and could share his/her code?

I already found this form, but this is only using the standard RF24 library, whereas I'm also using the RF24Network library. Furthermore, in this form it is having a seperate TX and RX side, whereas I like to have each module to be able to both send and receive.

Some extra side information, I use a stable power supply with a capacitor connected to the module, also the wires are soldered to the module.

I hope somebody can help me with this,

Guido

This is a known problem with those chips (especially Chinese clones). It is caused when a chip gets stuck in TX mode waiting for an ACK that never arrives back.

The chips don't have a "reset", but switching them into low power mode and then back on again, which doesn't affect any register settings, aborts the current TX operation.

RF24Network is merely a protocol layer on top of the RF24 library. That RF24 library has powerDown() and powerUp() methods. Simply call powerDown followed by powerUp on your RF24 driver object.


Compute the size of an array that was passed as a parameter to a function When passing an array to a function, you usually pass the length of the array along with it. You can compute the size of the array with sizeof(myArray)/sizeof(myArray[0]), which works just fine.

However, if you try to do this within the function that you pass the array to, this doesn't return the length of the array - eg. if it is an int array, it returns 1, if it is a double array, it returns 0.

Why is that so and is there any way to compute the size of an array that was passed as a parameter?

You can't. You are passing a pointer to the array, and sizeof will give you the size of that pointer (2 on an 8-bit Arduino).

Instead the normal way is to pass the size of the array as a parameter to your function.

myFunction(myArray, sizeof(myArray) / sizeof(myArray[0]));


Read Audio Data in Real-time over 3.5mm Stereo Cable My Goal

Have Arduino read audio output from a TRS stereo audio cable (coming from a computer, smartphone, etc.). As motivation for this use-case, once some audio data (depending on the sample rate) have been stored in a buffer, the Arduino will perform an FFT on the buffered data. The power contained in the FFT is mapped to the red, green, and blue frequency-bands of visible light to determine the color of an LED strip.

My Set-up

The obvious first step was to connect a Right-Angle 3.5mm Stereo Plug to Pigtail Cable to the Arduino. As is commonplace, this cable has a Tip, Ring, and Sleeve connector; Adafruit labels the black wire as ground (sleeve). They further label the red wire as "left channel live" (tip) and the white wire as "right channel live" (ring), if I can trust Wikipedia:

  Stereo sockets commonly provide two such NC contacts, one for the tip (left channel live) and one for the ring or collar (right channel live).

My Question

So, I've plugged the red wire into the A0 pin and the white wire into the A1 pin. However, I'm unsure of how to sample the actual audio signal from these analog pins.

I don't believe the analogRead() function solves the whole problem - it only converts a voltage reading at the pin into a value between 0 and 1023. Presumably, if I knew the bit rate (i.e., sample rate) & of each packet in the transmitted audio signal, I'd be able to construct signal from that. Is it possible to extract the original audio's waveform from a simple voltage signal? If not, what approach would enable the Arduino to read audio data from an audio cable?

Note: For those wondering, I have indeed heeded the advice from this Electronics SE answer to attach a DC-blocking/DC-bias circuit to the signal source before driving it into an analog pin on the Arduino.

The middle path

Build the simple op-amp (or whatever) 70s-era color organ, but without all the LEDs. Then basically feed the organ's LED-driving lines into the Arduino's ADCs. Sampling that pre-processed/summarized data, you can define a wide variety of RGB interactions without complicated math or an EE background. The timing requirements will be well-within the Arduino's reach, unlike computing FFTs or other "difficult" processes. Besides, old/new hybrids are cool!


NodeMCU ESP12 Voltage I'd like to power an NodeMCU off of four 1.5v batteries.  That's 6v.

Depending on the source I've read that 5.1v will fry the board and, just a few clicks later, that the board will take up to a 20v input.

What is the real, practical input voltage range for an NodeMCU?  Even the spec sheets seem to disagree.

I edited your question and changed ESP-12 to NodeMCU, based on the title and tag.

5.1 V will 'fry' a plain ESP12, but the NodeMCU is development board with esp8266 and the board has a power regulator for USB power or Vin pin. The parameters of the regulator depend on the regulator used by the manufacturer of your board.


Why Smart Plugs don't require setting port forwarding on router and how to accomplish this with NodeMCU (ESP8266) I have a NodeMCU (ESP8266) board that I use to control some devices over the internet. To be able to access it I have to enable port forwarding on my router and set the port manually like in the image below:

But with Smart Plugs (that use a cloud based app) I don't have to set up anything on my router. I am only required to type my Wi-Fi password. So my question is how Smart Plugs are accessed over the router (why they don't need manual port forwarding setting), and how to apply this to my NodeMCU so I don't have to set port forwarding manually.

Port forwarding is required to allow a device outside your router to access a device inside a router that performs NAT (Network Address Translation).

When a NodeMCU is acting as a simple server to respond to requests, it is inside your network, and so the port-forwarding is required so that your phone or computer on the Outside can access it.

However, for the cloud-based "smart" devices, it is different. The smart device opens a connection from itself to a server (the cloud) outside your network. In this case, the router understands that a new two-way connection is created between the cloud server and your smart device.

The only communication to your smart device is from the cloud server to the smart device. If you have an app on your mobile device or computer, that app or website only accesses the cloud server, when then passes the instruction on to your smart device. Reverse direction for status info from the smart device to your app, etc.

These smart devices rely on the infrastructure of their creators to continue to work. There are no LAN-to-LAN connections from the client to the device. Everything goes through the Internet to the remote cloud server, and back.

Many home routers support a protocol called uPNP, that allows a device inside the network to request port forwarding to itself. Some routers require this to be explicitly enabled, because it's a security risk to allow any device to be able to open holes in your firewall/router.

To have your NodeMCU device do this, look for libraries for ESP8266 that implement uPNP. I did a quick search and found https://github.com/ofekp/TinyUPnP though I cannot vouch for it's effectiveness or safety.


Arduino uno PWM CTC mode - strange behaviour on interrupt i have this simple code that i use for generating a square wave signal of 125 KHz on pin 9 using Timer1 in the "Clear Timer on Compare Match (CTC) Mode".
I also use Timer1 Compare Match A interrupt for toggling pin 7 of PORTD.

void setup() {
pinMode(9, OUTPUT);
pinMode(7, OUTPUT);

TCNT1 = 0;
TCCR1A = 0;
TCCR1B = 0;

OCR1A = 7;
TIMSK1 = _BV(OCIE1A);
TCCR1A = _BV(COM1A0);
TCCR1B = _BV(CS11) | _BV(WGM12);
}

void loop() {
}

ISR(TIMER1_COMPA_vect)
{
  PORTD = PORTD ^ 128;
}

It happens that

The 125KHz waveform on pin 7 is delayed by 1us with respect to the waveform of pin 9. I think that is related to the time that the microcontroller takes to "entering" the interrupt function and toggling the PORTD pin (1us are 16 clock cycle of the 16MHz master clock).
Sometimes the waveform on pin 7 (the one generated inside the interrupt service routine) has some "gaps". For example, this is the waveform acquired with my scope:Why this strange behaviour happens?

Thank you

This isn't the only ISR in the Arduino, there is at least the one counting millis. Counter 0 overflow ISR is not as short as yours, so every 1024us it'll cause some jitter (or as in your case, skipping the edge and basically inverting the phase). It'd be also several clock cycles delayed (against HW generated signal). Pushing and poping the registers into the stack are the deterministic delays, but the latency between setting the ISR flag and calling the ISR routine depends on currently executed instruction (some of them takes 2cycles, and there are also longer ones).

There is not much time to do anything else either. Your ISR might take less than 20 cycles, but you only have 64 cycles (ISR is called at 250kHz rate so it generates 125kHz signal).
So if anything else prevents your ISR to be called (another ISR, disabled interrupts), you can miss them, as there is only one interrupt flag.

If you want the same waveform on pin 7, just use a wire and let the pin mode as INPUT.

BTW: You don't have to use PORTB = PORTB ^ _BV(PB7);, the PINB = _BV(PB7) toggles PB7 without read-modify-write access.


Is there some sample code for operating a servo with an Adafruit Motor Shield? I have an Adaruit Motor Shield v2, and a Tower Pro SG92R micro servo. I've got it setup so the shield works with my Arduino Uno, and I've successfully tested using other types of motors on the shield. I could not find any sample code for working with a servomotor though. The shield has two dedicated spots for a servo (labeled "Servo 1" and "Servo 2"). I'm planning to use wall wart transformer to power the motor separately from the Arduino. Any pointers/links to documentation/sample code would be appreciated.

On the Motor shield the servo headers are directly connected to pins 9 and 10 (I think 9 is servo 2 and 10 is servo 1).  So you can use the standard servo examples using pins 9 and 10.

If you need to power the servos with an external power supply you must cut a trace on the back of the board -- the silk screen tells you where to cut.  Then you need to connect power to the "Opt Servo" input.

The power to the servos is not changed by the power jumper used for the DC/stepper motors.


How to get current time and date in arduino without external source? I'm working on a project using Arduino Uno and SD card shield.
I'd like to store a variable at a specific time everyday in the SD card. How can I get the current time in Arduino ?
Any help would be appreciable.

NOTE : Arduino is NOT connected to PC.

An accurate enough way is to use the millis() function. It  will return the value in milliseconds since the start of the Arduino. If you start the Arduino at a specific time, you will be able to calculate the exact date and time.

Why not an external module?? An RTC such as the DS3231 in merely 5$ and it includes a temperature sensor for you!


Custom built Arduino is not working - double blinks I've made a home-made Arduino based on this video. The problem is that I can't upload anything, it doesn't react, only the LED double blinks in every second. What does that mean? How to fix it? Thanks.

Update:

It's a reasonably clear photo (another couple would help) however I do see at least one major problem. Pin 8 (and pin 22) are Ground, but I don't see any wires running to that. Also the 22 pF (or similar) capacitors connected to the crystal should have their other sides grounded.

I suggest you look at my page Breadboard Arduino which has clear photos and wiring guides. In particular:

Notice the ground wire, and how the capacitors are connected.

I suggest you double-check all wiring, and make sure it is very similar to this:


Pull-down resistor value for interrupts I wonder how to calculate pulldown resistor to make interrupt work?
I need to connect 5 buttons to A0 and get pressing event via interrupts.
Using different resistors, finally, I made work only 4 buttons. On 5th interrupt does not fire.
Currently I use the following resistors for the buttons:

R1      Vout
0       5,00
2,7K    4,45
5K      3,70
10K     2,77
22K     1,78

And Pulldown Resistor = 22K.

If pulldown Resistor = 10K I can get event for 1-3 button only.
Looks like the voltage 1,78V is quite low.
But I’d liked make it work with 1V at most.
I use RISING mode.

PS. Arduino Nano

An Arduino running at 5V needs at least 3.0V on the pin to read it as rising high.  You probably want to go a little more than that.  So that means your lowest voltage has to be like 3.3V or so.

Note that the analog pins don't have an external interrupt, you'll have to use pin change interrupts and then read with analogRead in the ISR.  So you can't use "RISING".  The pin change interrupts act on any edge.  So they'll trigger when falling as well.

That's a pretty poor way to handle these buttons.  Normally one would just poll buttons like this.  If your loop takes so long that you might miss a human pressing a button then perhaps you should look at that instead.


Beginner here, trying to start learning arduino, which starter kit should I buy? I'm really interested in arduino but I don't know much about it. I want to buy a starter kit to play with, but when I searched it on amazon, there are couple unofficial starter kit and a more expensive official one. So, can some one tell me the major difference between the unofficial starter kit and official starter kit? And which one would you recommend me to buy? Thank you!

Sorry, bonus question: why is the start kit($89) in arduino website is much cheaper than the official starter kit in amazon($120)?

You could do worse than a cheap 37-in-1 Sensor Kit from eBay and any Arduino board of your choice.

Also some Dupont Jumpers are essential.  Get a selection of M/M, M/F and F/F.


Timestamping AnalogBinLogger data I would like to timestamp the data collected from AnalogBinLogger.ino on an Arduino Uno. The sketch uses 512-byte buffers, and I have read that writing data in 512-byte chunks is 'better' in terms of write latencies.

The sketch uses this structure for the buffers:

// Data block for 10-bit ADC mode.
const size_t DATA_DIM16 = 254;
struct block16_t {
  unsigned short count;    // count of data values
  unsigned short overrun;  // count of overruns since last block
  unsigned short data[DATA_DIM16];
};

Since I want to add the timestamps which are of unsigned long type, I would have to modify the structure as follows:

// Data block for 10-bit ADC mode.
const size_t DATA_DIM16 = 254;
struct block16_t {
  unsigned short count;    // count of data values
  unsigned short overrun;  // count of overruns since last block
  unsigned short data[DATA_DIM16];
  unsigned long  milli[DATA_DIM16]; // time in milliseconds
};

Now, this structure exceeds 512 bytes and is 1528 bytes. Due to unavailability of enough free stack, my program doesn't run (sketch reports FreeStack to be 1135 bytes). How can I go about this?

PS: My root problem is to achieve time-synchronisation among multiple data-collecting Arduinos which sample at high rates like 8kHz. Due to clock drifts, even if I sync the start times, the timestamps collected afterwards would not be relative to each other. Hence I plan to have a master Arduino send its time to the others in regular intervals.

The straightforward solution:

const size_t DATA_DIM16 = 84;
struct block16_t {
  unsigned short count;    // count of data values
  unsigned short overrun;  // count of overruns since last block
  unsigned short data[DATA_DIM16];
  unsigned long  milli[DATA_DIM16]; // time in milliseconds
  unsigned long padding;   // pad to 512 bytes
};

Now, I suggest to think again about your requirements. Do you really
need a 32-bit timestamp for every data point? If they are closely spaced
in time, a 16-bit, or even 8-bit timestamp should be enough. You could
put a full 32-bit timestamp at the beginning of each block, then only
8-bit timestamps for every data point. This would allow you to store
168 samples per block. You could even pack a 6-bit timestamp with
the data sample into an uint16_t, and have 252 samples per block.


Issues while making ESP8266 as web server I have programmed ESP8266 with below program. I used USB to TTL convert to program ESP8266. This is how I wired my circuit:

USB TTL---------------- ESP8266 ESP-01

GND-----------------------GND

TX---------------------------RX

RX---------------------------TX

3.3V-----------------------VCC & CH_PD

GND------------GPIO0

#include <ESP8266WiFi.h>

const char* ssid = "shiv";//type your ssid
const char* password = "manmohan@12345";//type your password

WiFiServer server(80);

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

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request

  int value = LOW;
  if (request.indexOf("/LED=ON") != -1) {
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1){
    value = LOW;
  }

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("");

  client.print("Led pin is now: ");

  if(value == HIGH) {
    client.print("On");
  } else {
    client.print("Off");
  }
  client.println("

");
  client.println("Click here turn the LED on pin 2 ON
");
  client.println("Click here turn the LED on pin 2 OFF
");
  client.println("");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

It was successful, here are the logs:

Archiving built core (caching) in: C:\Users\williams~1\AppData\Local\Temp\arduino_cache_375631\core\core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____feb0d75f3cf4e05271af4f91549cd009.a
Sketch uses 230073 bytes (52%) of program storage space. Maximum is 434160 bytes.
Global variables use 32376 bytes (39%) of dynamic memory, leaving 49544 bytes for local variables. Maximum is 81920 bytes.
Uploading 234224 bytes from C:\Users\williams~1\AppData\Local\Temp\arduino_build_189179/sketch_may14d.ino.bin to flash at 0x00000000
................................................................................ [ 34% ]
................................................................................ [ 69% ]
.....................................................................            [ 100% ]

Once this was completed, I opened serial monitor and it was empty there, baud rate was 115200. It is weird, Isn't ?

I followed this tutorial https://create.arduino.cc/projecthub/ROBINTHOMAS/esp8266-esp-01-webserver-7248ca and on serial monitor it should be like below snapshot. What wrong I am doing ? Can anyone help me.

Tying GPIO0 to ground puts the ESP into programming mode, allowing you to flash it.  To actually run the code, pull it high - that is, disconnect it from ground and connect a resistor (about 10k) between GPIO0 and +3.3v.

Do the same with RST.


3-speed DC fan control with Uno I have built this MOSFET circuit, which is supposed to run 2 DC fans using an Arduino Uno.

I am trying to get the two DC fans running with four settings: OFF, LOW, MED and HIGH. I have been having issues with the MED option, because when its option is selected by the rotary switch (5 V pulse detected by the analog pin A2) the speed of the fan is not the constant 75% duty cycle (191) as defined on line 75 in the code below:

int motorPin1 = 3;
int motorPin2 = 9;
int DCfanSpeed = 0;
int voltageZero = 0;
int voltageOne = 1;
int voltageTwo = 2;
int voltageThree = 3;

void setup() {
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  digitalWrite(voltageZero, INPUT_PULLUP);
  digitalWrite(voltageOne, INPUT_PULLUP);
  digitalWrite(voltageTwo, INPUT_PULLUP);
  digitalWrite(voltageThree, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  int voltageReadingZero = analogRead(voltageZero); // OFF SWITCH
  int voltsZero = voltageReadingZero / 204.6;
  if (voltsZero == 5) {
    delay(300);
    if (voltsZero == 5) DCfanSpeed = 0;
    // else DCfanSpeed = DCfanSpeed;
    while (voltsZero == 5) {
      analogWrite(motorPin1, DCfanSpeed);
      analogWrite(motorPin2, DCfanSpeed);
      voltageReadingZero = analogRead(voltageZero);
      voltsZero = voltageReadingZero / 204.6;
    }
  }
  int voltageReadingOne = analogRead(voltageOne); // LOW SWITCH
  int voltsOne = voltageReadingOne / 204.6;
  if (voltsOne == 5) {
    delay(300);
    if (voltsOne == 5) DCfanSpeed = 128;
    //else DCfanSpeed = DCfanSpeed;
    while (voltsOne == 5) {
      analogWrite(motorPin1, DCfanSpeed);
      analogWrite(motorPin2, DCfanSpeed);
      voltageReadingOne = analogRead(voltageOne);
      voltsOne = voltageReadingOne / 204.6;
    }
  }
  int voltageReadingTwo = analogRead(voltageTwo); //  MED SWITCH
  int voltsTwo = voltageReadingTwo / 204.6;
  if (voltsTwo == 5) {
    delay(300);
    if (voltsTwo == 5) DCfanSpeed = 191;
    //else DCfanSpeed = DCfanSpeed;
    while (voltsTwo == 5) {
      analogWrite(motorPin1, DCfanSpeed);
      analogWrite(motorPin2, DCfanSpeed);
      voltageReadingTwo = analogRead(voltageTwo);
      voltsTwo = voltageReadingTwo / 204.6;
    }
  }
  int voltageReadingThree = analogRead(voltageThree);  //  HIGH SWITCH
  int voltsThree = voltageReadingThree / 204.6;
  if (voltsThree == 5) {
    delay(300);
    if (voltsThree == 5) DCfanSpeed = 255;
    //else DCfanSpeed = DCfanSpeed;
    while (voltsThree == 5) {
      analogWrite(motorPin1, DCfanSpeed);
      analogWrite(motorPin2, DCfanSpeed);
      voltageReadingThree = analogRead(voltageThree);
      voltsThree = voltageReadingThree / 204.6;
    }
  }
}

Excuse the poor formatting but the basic rundown of the medium option is such that the voltage across the analog pin 2 is measured and converted into volts and if it is 5 Volts (rotary turned to the medium position) then it enters a while loop where the voltage is monitored such that if there is any change then there must be a speed setting change. This is the only option for which I get this pulsating speed on the fans instead of smooth and continuos operation.

Any ideas about how I could improve this? I have taken away one fan to see if one was faulty but this didn't work.

Solved simply by condensing code and getting rid of unnecessary variable declarations.

Corrected program:

    int motorPin1 = 3;
    int motorPin2 = 9;
    int DCfanSpeed = 0;

    void setup()
    {
      pinMode(motorPin1, OUTPUT);
      pinMode(motorPin2, OUTPUT);
      digitalWrite(A0, INPUT_PULLUP);
      digitalWrite(A1, INPUT_PULLUP);
      digitalWrite(A2, INPUT_PULLUP);
      digitalWrite(A3, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop()
     {

       int voltsZero = analogRead(A0)/204.6; // OFF SWITCH
       if(voltsZero == 5)
        {
          delay(300);
          if(voltsZero == 5) DCfanSpeed = 0;

           while(voltsZero == 5)
            {
              analogWrite(motorPin1, DCfanSpeed);
              analogWrite(motorPin2, DCfanSpeed);
              voltsZero = analogRead(A0)/204.6;

            }
         }

      int voltsOne = analogRead(A1)/204.6;    // LOW SWITCH
      if(voltsOne == 5)
        {
          delay(300);
          if(voltsOne == 5) DCfanSpeed = 128;
          while(voltsOne == 5)
           {
             analogWrite(motorPin1, DCfanSpeed);
             analogWrite(motorPin2, DCfanSpeed);
             voltsOne = analogRead(A1)/204.6;
           }
        }

       int voltsTwo = analogRead(A2)/204.6;  //  MED SWITCH
       if(voltsTwo == 5)
        {
          delay(300);
          if(voltsTwo == 5) DCfanSpeed = 191;
          while(voltsTwo == 5)
           {
             analogWrite(motorPin1, DCfanSpeed);
             analogWrite(motorPin2, DCfanSpeed);
             voltsTwo = analogRead(A2)/204.6;

           }
        }

      int voltsThree = analogRead(A3)/204.6;  //  HIGH SWITCH
      if(voltsThree == 5)
        {
          delay(300);
          if(voltsThree == 5) DCfanSpeed = 255;
          while(voltsThree == 5)
           {
             analogWrite(motorPin1, DCfanSpeed);
             analogWrite(motorPin2, DCfanSpeed);
             voltsThree = analogRead(A3)/204.6;
           }
         }

    }


Combining arduino leonardo code with water alarm code I need to create something for a school assignment, but I'm stuck at the moment.
I have one code, which makes the Arduino Leonardo press space button on my laptop, which works.

I have another code, that turns on the LED when 2 wires are put in water.

Now I want to combine them, but I have no success.

Hope someone will help me with this.

These are the codes:

The keyboard code leonardo:

bool eenkeergeweest = false;

#include <Keyboard.h>

void setup()
{
    // make pin 2 an input and turn on the
    // pullup resistor so it goes high unless
    // connected to ground:
    pinMode(2, INPUT_PULLUP);
    // initialize control over the keyboard:
    Keyboard.begin();
}

void loop()
{
    // while (digitalRead(2) == HIGH) {
    //   // do nothing until pin 2 goes low
    //   delay(500);
    //  }
    delay(1000);
    // new document:
    if (!eenkeergeweest) {
        eenkeergeweest = true;
        Keyboard.print(' ');
        delay(100);
        //Keyboard.releaseAll();
    }

    // wait for new window to open:
    delay(1000);
}

The code for the water LED:

int out = 12;
int in = 4;

int rd;

void setup()
{
    pinMode(out, OUTPUT);
    pinMode(in, INPUT);
}

void loop()
{
    rd = digitalRead(in);
    if (rd == HIGH)
    {
        digitalWrite(out, HIGH);
        delay(100);
    }
    else
    {
        digitalWrite(out, LOW);
        delay(100);
    }
}

How do you want them to work ? Do you want the spacebar pressed when there is a high signal read (when the light goes on)?

If you want the space bar press when it goes high this might work:

#include <Keyboard.h>

bool eenkeergeweest = false;
int out = 12;
int in = 4;

void toggleKeyPress (const char& keypress)
{
    if (!eenkeergeweest)
    {
        eenkeergeweest = true;
        Keyboard.print(' ');
        delay(100);
    }
}

void setup()
{
    pinMode(out, OUTPUT);
    pinMode(in, INPUT);

    // initialize control over the keyboard:
    Keyboard.begin();

}

void loop()
{
    const int rd = digitalRead(in);
    if (rd == HIGH)
    {
        toggleKeyPress(' ');
        digitalWrite(out, HIGH);
        // wait for new window to open:
        delay(1000);
    }
    else
    {
        digitalWrite(out, LOW);
    }
}


can i use L298N H bridge with 12v 7AH battery? guys i am working on a rare project so i just need to ask some questions
I have a L298N H bridge motor driver, a Aduino uno board, 12v dc 4000rpm 2ampere motor and a 12v 7ah battery
I just want to ask can i use 12v 7ah battery with my L298N H bridge motor driver
please answer this project is very important to me
please help

Yes, though at 2A you're at the top end of the L298N current limit. Expect excessive heating. You will have to manage your thermal environment appropriately.
You should consider a more capable driver with more current headroom and less heat problems. (Note: the L298N is a very old chip and uses old technology. It's not a good choice for modern drive systems and a more appropriate device should be investigated, for example the MC33931 as the first hit on google).


Non line of sight radio and arduino uno I've been using a pair of arduino uno and nrf24l01 and found it wasn't really suitable due to low range when it comes to obstacles.

Essentially I'd like to use it in country areas where it would ideally transmit through dense trees and over hills at around 500 meters.

I've spotted the SI4432 and the sx1272 (which seems ideal but it doesn't seem popular despite it's high NLOS range capabilities?)

I was just wondering if anyone had any recommendations on which would be the best radio module to try? Any help would be really appreciated. Many thanks in advance.

General rule is, the lower the frequency, the longer the range (but lower bandwidth). So both should have a better range at 433Mhz and 137MHz instead of the 2.4Ghz of the NRF. Antennas also affect the range.

The "over the hills" part I think will be problematic. The RF won't be able to penetrate through the hill. So the signal has to bounce of the ionosphere to get over the hill, which is to long a distance. So you probably have to have some kind of repeater on top of the hill to accomplish this.


How to refine ultrasonic readings I am trying to filter ultrasonic readings using averaging technique. I've also used millis() to measure time from start so that I can calculate readings up to 1 second and average them. I've re-initialized the elapsedTime variable each time to zero in the loop but again when the program execution hits this code the time starts from the time it was before. Is there any way to solve this problem?

This is the code:

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

int dist, ctr, filteredDist;
long rawValue = 0;
unsigned long StartTime = millis();

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}
//********************************************************************************************************************
void loop() {
  delay(500);
  unsigned long elapsedTime = StartTime;

  while (elapsedTime < 1000) {
    ctr++;
    dist = sonar.ping_cm();
    rawValue += dist;
    elapsedTime = millis();
  }
  filteredDist = rawValue / ctr;
  Serial.println(filteredDist);
}

elapsedTime=millis(); sets elapsedTime equal to the current value of millis(), which in the sketch above is the total time since the Uno powered up.  Thus  elapsedTime will exceed 1000 any time after the first second of execution, in which case the while won't do anything.

Instead say elapsedTime=millis() - StartTime; within the loop.  Whenever you want to start the averaging cycle again, say StartTime = millis();.

If your only use of elapsedTime is to control the while loop, get rid of that variable; instead of  while(elapsedTime < 1000), say while(millis()-StartTime < 1000).


Multiplication operator with or without braces I have written a simple calculator program for an LCD keypad shield. It works fine except for the multiplication case. It gives me zero. However, I have noticed that when I enclose the expression num1 * num2 in parenthesis it does work. Why is that so?

#include <LiquidCrystal.h>

LiquidCrystal lcd (8, 9, 4, 5, 6, 7);

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();
}

void loop() {

  float ans = 0;

  lcd.print("Starting Calc");
  delay(500);

  lcd.clear();
  lcd.print("Enter 1st Num");
  while (Serial.available() == 0) {}
  float num1 = Serial.parseFloat();

  lcd.clear();
  lcd.print("Enter 2nd Num");
  while (Serial.available () == 0) {}
  float num2 = Serial.parseFloat();

  lcd.clear();
  lcd.print("Enter Operator");
  lcd.setCursor(0, 1);
  lcd.print(" R+, U*, D/, L- ");
  int val = analogRead(A0);

  while (val > 1000) {
    val = analogRead(A0);
  }

  if (val == 0) { // addition
    ans = num1 + num2;
  }

  if (val >= 97 && val <= 98) { // multiplication
    ans = num1 * num2;
  }

  if (val >= 253 && val <= 254) { // division
    ans = num1 / num2;
  }

  if (val >= 407 && val <= 408) { // subtraction
    ans = num1 - num2;
  }

    lcd.clear();
    lcd.print("Answer is = ");
    lcd.print(ans);
    delay(2000);
}

Modified Code

#include <LiquidCrystal.h>

LiquidCrystal lcd (8, 9, 4, 5, 6, 7);

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();
}

void loop() {

  float ans = 0.0;

  lcd.print("Starting Calc");
  delay(500);

  lcd.clear();
  lcd.print("Enter 1st Num");
  while (Serial.available() == 0) {}
  float num1 = Serial.parseFloat();

  lcd.clear();
  lcd.print("Enter 2nd Num");
  while (Serial.available () == 0) {}
  float num2 = Serial.parseFloat();

  lcd.clear();
  lcd.print("Enter Operator");
  lcd.setCursor(0, 1);
  lcd.print(" R+, U*, D/, L- ");

  // here we split our logic.. first repeatedly read input value until valid operator read
  // secondly we perform the arithmetic operation accordingly

  char input = ' '; // space = no operator read so far
  int val;

  do {
    val = analogRead(A0);
    // see how if statements are written concisely for readability
    // if only one statement after condition you can skip curly brackets
    if (val == 0) input = '+';
    if (val >= 97 && val <= 98) input = '*';
    if (val >= 253 && val <= 254) input = '/';
    if (val >= 407 && val <= 408) input = '-';
  } while (input == ' ');

  Serial.println(input);
  Serial.println(num1);
  Serial.println(num2);
  delay(1000);

  // perform arithmetic operation
    switch (val) { // not written in a standard way but very readable
      case '+': ans = num1 + num2; break;
      case '-': ans = num1 - num2; break;
      case '*': ans = num1 * num2; break;
      case '/': ans = num1 / num2; break;
    }

  lcd.clear();
  lcd.print("Answer = ");
  lcd.print(ans);
  delay(2000);
}

The parentheses should definitely make no difference. My guess is that
what you saw was just a coincidence. The analog ranges you have defined
are extremely narrow. Any instability in the circuit can throw your
readings out of the expected ranges. If you get a reading that does not
fit in any of those ranges, none of the if conditions will evaluate to
true, and you end up with the result being zero, as this is how you
initialized the variable ans.

I suggest two changes to your program:

Make the ranges wider
Repeatedly read the analog input until you get a valid reading.

To illustrate the second item, here is a code snippet that splits the
logic of you if chain in two parts: first read the operator
(repeatedly until we get a valid reading), then perform the operation:

// Read the operator.
char op = ' ';  // space = no operator read so far
do {
    int val = analogRead(A0);
    if (val == 0) op = '+';
    if (val >= 97 && val <= 98) op = '*';
    if (val >= 253 && val <= 254) op = '/';
    if (val >= 407 && val <= 408) op = '-';
} while (op == ' ');

// Perform the operation.
switch (op) {
    case '+': ans = num1 + num2; break;
    case '*': ans = num1 * num2; break;
    case '/': ans = num1 / num2; break;
    case '-': ans = num1 - num2; break;
}


What is the phase of tone? Is it garanteed (with some precision) that the phase of a PWM-signal generated by tone is the same on each pin? Can it be altered (by internal means of Arduino) so that it's different on different pins?

I'm looking for a way to adjust phases of signals from several pueso-buzzers by either adjusting distances (least preferrable) or programmaticaly (most preferrable) or by external components (if they're not very complicated).

If you want fine control over the phases, I assume you may also care
about having low phase noise. In this case your best bet is to avoid
toggling the pins in software and go for a hardware signal generation.

With an Arduino Uno or similar board, this can probably achieved by
programming a timer. I would try the following:

Configure Timer 1 in waveform generation mode 12, i.e. CTC
mode with TOP = ICR1. Set the compare output mode of both channels
to toggle on compare match. Set ICR1 so that the timer has half the
period of the signal you want. Now you can independently adjust the
phases of both outputs by writing to OCR1A and OCR1B.

Note that those registers are not double buffered in this mode, so you
have to be careful about when you write them.

The Arduino core library has no support for such timer configuration:
you will have to learn how to program it yourself. If you are not
familiar with the subject matter, I recommend you start by reading
Nick Gammon's tutorial on timers.


How to prevent flickering relay upon waking from deep sleep using ESP01 board? I have a cheap ESP01 relay module and am using it with ESPEasy. I soldered the GPIO pin 16 to RST to allow deep sleep and that all works great.
However when the unit wakes up the relay flickers quite a bit. The application I had in mind was for a 12v fridge which draws quite a bit of current on start up. I think this flickering would damage the fridge compressor or controller pretty quickly, not to mention wearing out the relay itself.
I need the unit to wake up from deep sleep, and keep the relay in the off position, unless triggered by some external criteria.
Perhaps a capacitor would absorb the pin high voltage for a short period until it's booted? Trouble is that I don't really want to hack the module, I'll probably break something.

The only two pins that don't glitch or change state during reset and boot are GPIO4 and GPIO5, and neither of them are brought out to the 2x4 header on an ESP-01.
https://rabbithole.wwwdotorg.org/2017/03/28/esp8266-gpio.html
All of the other pins will make your relay click or chatter.  Pick a different module, or try soldering a wire onto GPIO4 or 5. The boot time is ~ 150ms long, so it'd take a long time constant R-C circuit to filter it out, on the order of 1/2 second or more.


Arduino SD Card open file modes append / overwrite Running Arduine IDE SD DataLogger Example, my data gets appended to a txt file.

File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
  dataFile.println(dataString);
  dataFile.close();
}

Is there an explicit option to open the file in overwrite / append modes?

You only need to open the file with FILE_WRITE and use file.seek(EOF) to go to de end of the file. After that you can write whatever you want that will be appended to the end of the file.

File outputFile = SD.open(LOG_FILE, FILE_WRITE);
outputFile.seek(EOF);
outputFile.println("Appended to the EOF");


Sending serial commands to yourself Is it possible to "send" a serial command to the device itself to see the response?
I have written a little routine based on a couple of serial sends and receives and want to see if that works out like I want.

EDIT:

I have a device (an AVR with arduino boot loader) and as part of my program, the device exchanges phrases with peripheral devices over a serial connection. Since I have right now just the arduino itself and can't really test, if at least the logic behind the serial part of works out, I would like to get serial commands from somewhere and trigger 'continuous talking', so I want to monitor the response behavior of my module, if it gets a certain command (stability reasons). Instead of waiting for a second device, is it possible to "link the TX/RX line to itself" internally or externally to test my program with itself?

Yes, you can do that by cross-connecting the transmit and receive pins on the Arduino. But then your devices sits there silently murmuring to itself (or not...) and you can't really tell what it's saying, or if it's doing anything unless you can observe some other hardware - LEDs, a 'scope, f/ex.

But why not hand-type or script some messages to it on your PC? If the Arduino sketch would make some brief, coherent replies you could confirm what it's doing and debug it if necessary.

I've done just this in your situation: Two of us defined a serial protocol - the ASCII (for human readability!) commands and replies that either end could make or expect. Then each of us wrote the communication code for one of the two devices and proved that it met the protocol. Once both of us had finished and were confident in our respected communication code, we plugged the two devices together, and - they played! Nicely! :)  And if they hadn't we could have eavesdropped on the serial line and printed their attempted conversation to discover where it went wrong.


Read signal from co-ax cable with ADC I have an Arduino Uno and I'd like to read a signal from a co-ax cable with it. The cable carries 12VDC (power for other components) along with a signal (of about 1 Ghz frequency). How do I go about recording this signal with my Uno? I'm new to this field so I don't know the full capabilities of the ADC. Also, the Uno can't handle >5 VDC, so what should I do to make the signal readable?

It's not possible. To sample a 1GHz signal you need to sample at least 2 billion times per second (a sample rate of 2Gsps). You can maybe get a couple of hundred KILO samples (thousand) per second on an Arduino.

Also the 1GHz signal itself is of no interest to you. What is of interest is what is modulated on the 1GHz signal.

What is normally done is:

Down-mix (filter) the carrier signal to an IF (Intermediate Frequency) usually in the order of a few kilohertz
Demodulate the signal using whatever modulation scheme was used to encode it.
Extract the encoded information from the demodulated signal.

To do that you'd need

the precise carrier frequency (1GHz is not the same as 1.029GHz)
the modulation scheme used (there's loads to choose from)
knowledge about any data formats and encodings used in the signal

As well as the hardware to do all that.

So no, you're never going to come even anywhere close with an Uno. You need specialised RF hardware just to prepare the signal for working with.


Is there an Arduino library that uses ARP to get list of connected devices on network? I have been looking for a library that can execute an ARP (Address Resolution Protocol) command to return a list of connected devices on the network. The idea is that it would send the request to the gateway and get a list of MAC addresses of currently connected devices as a sort of "who's home" request.

I have searched around Arduino's libraries and have not found any that specifically perform this type of functionality so I was hoping that maybe it was available in a function within a broader networking library.

The particular networking interface (wifi via ESP8266/ESP32 or Ethernet) does not matter as I have not chosen a specific board for the job yet. I'm interested in any library solution that would allow me to poll the gateway to see which devices are currently online without having to buy a special device like FingBox.

Any recommendations for a library that includes this functionality or an approach that would allow me to send ARP commands over the network?

ARP isn't generally used the way you described. Per the spec, to resolve an IP address into a MAC address, you broadcast an ARP request for the IP address, and receive  a unicast response from the host whose address it is - not a router. It also only resolves a single IP address in one request; it doesn't return the contents of the entire ARP cache.

While you could potentially unicast ARP requests to a router, it's anybody's guess as to whether the router would respond - it's not required to. By spec only the computer who's IP address is being queried should respond - so a router should not unless you've sent it an ARP request for its IP address. You'd also have to send one request for each IP address in the range specified by the LAN's network mask.

You're better off using SNMP, if the router supports it. SNMP can read the router's entire ARP cache with very little overhead (and very few packet exchanges).

The are SNMP implementations for the ESP32 and ESP8266, but they're likely to be difficult to use. Googling will find them for you.


How to drive 16 stepper motors with Arduino? I'm trying to drive 16 of these little steppers on an Arduino Uno.

Each test driver uses 4 digital pins for control (2 for each coil) so that would be 64 pins I will need.

I'm thinking either getting something like this or 4 of these.

Would something like that work ?
What's the most straight forward way to drive these on an Arduino Uno ?

If you need to drive all 16 simultaneously and independently, the Uno may not have enough capability to do it. Consider the worst-case number of motors and highest rate(s) you expect to drive at once, plus anything else you need the Uno doing at the same time. You might try a simple sketch to do all of these things (substituting LEDs for the motor drivers) at once, and use a scope to examine those LED output signals for the right frequency, wave-form, and lack of jitter. Without I/O expanders, you won't get to 16 motors' worth of outputs (unless you already have an I/O expander) but you might try doubling up on the existing output (use non-overlapping motor phases if you can).

If the Uno can manage that with clean outputs, you'll have a better idea whether it can manage the full load. If it doesn't, you may need to reconsider your choice of processor with respect to its clock-speed, both kinds of memory (depending on what you learned), number of outputs, possibly number of available timers and of interrupts.


Is there a semi-permanent way to attach wires to the Nano? At least for prototyping, is there a semi-permanent way to attach wires to the Nano posts?

And yes, usually the Nano is hanging in free space by its wires (yes I know, quick and dirty, should be using something cleaner, even for prototypes).  So I'm hoping for the best of both worlds, sturdy "enough" to stay attached, yet possible to remove and switch around.  Having no luck finding such advice on the internet, perhaps searching for the wrong terms.

EDIT:  I neglected one important point, each wire is attached individually just like the SparkFun wires with the female header as mentioned in @TheDoctor's answer below.

There are jumper wires that have a female header on one end and a male header on the other. Example: https://www.sparkfun.com/products/9140

You could also attatch several wired to a strip of breakaway female headers, such as https://www.sparkfun.com/products/115


I want to make two arduino to communicate over different wifi. Is that possible? I want to make any 2 Arduino module from different places to communicate over wifi. I really need to know if it possible? If yes, advice me more about it. I want send data from sensor module from one Arduino to another and vice versa. That's the basic idea. Do I need a third party services such as cloud services to make it happen? Or simply can send ovee wifi with the help of Ip adress. Sorry, I have less knowledge on this. Help me out. Thank you in advance.

If they are on the same (wifi) network; then yes.
If you are on a different network, it would be more difficult. You would have to setup port forwarding on your router. Then you would have to somehow know the public IP address of the other router. These addresses can change from time to time with certain ISPs. I wouldn't advice doing this.
Instead I'd go with an third party service. For example Adafruits offers an MQTT server. I'd probably use this even if they are on the same network.


Detect if multiple variables are the same? I'm setting a series of variables with: uint32_t currentLedColor[9]

What I'd like to check is if certain ones of those are the same.

Basically want to say if currentLedColor[0] and currentLedColor[1] and currentLedColor[2] are equal

How would I write that?

You run multiple checks. For example:

if (currentLedColor[0] == currentLedColor[1] && currentLedColor[0] == currentLedColor[2]) {
    // do something
}


Low Power library messing up serial text I noticed something unusual using the Low Power library today.
When printing text in the loop and using LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF); to sleep for one second, all the text in the loop gets messed up in the Serial Monitor as if you chose the wrong baud rate.

Example code:

#include "LowPower.h"

void setup() {
  Serial.begin(9600);
  Serial.println(F("HELLO"));
  Serial.println(F("HELLO"));
}

void loop() {
  Serial.println(F("HELLO"));
  LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);
}

This code just prints

����11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=

even when using different baud rates. (I used the same baud rate on both the arduino and the monitor).
Replacing the low power command with delay(1000); works fine

The problem is most likely that the system is going to sleep while it's still sending the serial data.

Forcing all the serial data to be sent before you go to sleep should fix the problem (serial data is sent in the background using an interrupt so as to keep sketch slowdown to a minimum):

Serial.flush();
LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);


How can I set a timer? I would like to set a stopwatch timer that will determine how long an input is in a certain state before changing. I want to set it so that, depending on the output my code executes one of 2 switch cases. But my trouble comes in on setting a timer. Is there a function I could use? Or a method that somebody knows? The time that the input will be for each case is not fixed so I cannot use a delay.

Your title is about “setting a timer”, but your actual question is about
measuring the length of a pulse. There are two functions provided by the
Arduino IDE for this purpose, pulseIn() and pulseInLong():

pulseIn() is based on a carefully timed delay loop. It
has a resolution of the order of one microsecond, but will not count
the time spent servicing interrupt requests. It works best for very
short pulses timed with interrupts turned off.
pulseInLong() is based on micros(). It has a
resolution of 4 µs and will not work properly if interrupts are
turned off. It works best for longer pulses where its limited
resolution and interrupt latency are tolerable.

Both of these are blocking functions: they completely block your
sketch while they perform the measurement. If you don't want your sketch
to be unresponsive during this time, you can write a non-blocking
version of pulseInLong() using a finite-state machine like
this:
// Measure the length of a pulse in a non-blocking manner.
// Returns 0 if no measurement is available at the time of the call.
void get_pulse_length() {
    static enum {
        INITIAL_WAIT,    // wait for the first (partial) pulse to end
        BETWEEN_PULSES,  // wait for the pulse to start
        WITHIN_PULSE     // wait for the pulse to end
    } pulse_state = INITIAL_WAIT;
    static uint32_t pulse_start;  // when the current pulse started

    uint8_t pin_state = digitalRead(pulse_pin);
    uint32_t now = micros();
    switch (pulse_state) {
        case INITIAL_WAIT:
            if (pin_state == LOW)
                pulse_state = BETWEEN_PULSES;
            break;
        case BETWEEN_PULSES:
            if (pin_state == HIGH) {
                pulse_start = now;
                pulse_state = WITHIN_PULSE;
            }
            break;
        case WITHIN_PULSE:
            if (pin_state == LOW) {
                pulse_state = BETWEEN_PULSES;
                return now - pulse_start;
            }
            break;
    }
    return 0;
}

Note that this measures high pulses. You will have to swap HIGH and
LOW if you want to measure low pulses. You would use it like this:
void loop() {
    uint32_t pulse_length = get_pulse_length();
    if (pulse_length) {
        // handle the pulse
    }
}

The resolution of the measurement is the execution time of loop(), so
you have to make sure there is nothing blocking there, and specially no
calls to delay(). If you need a better resolution from a non-blocking
method, you can use interrupts to trigger the measuring process:
volatile uint32_t pulse_start, pulse_length;
volatile bool pulse_valid;

void on_rise() {
    pulse_start = micros();
    attachInterrupt(digitalPinToInterrupt(pin), on_fall, FALLING);
}

void on_fall() {
    pulse_length = micros() - pulse_start;
    pulse_valid = true;
    attachInterrupt(digitalPinToInterrupt(pin), on_rise, RISING);
}

uint32_t get_pulse_length()
{
    if (!pulse_valid) return 0;
    noInterrupts();
    uint32_t pulse_length_copy = pulse_length;
    pulse_valid = false;
    interrupts();
    return pulse_length_copy;
}

void setup() {
    attachInterrupt(digitalPinToInterrupt(pin), on_rise, RISING);
}

This should give you the resolution of micros(), i.e. 4 µs, but
occasionally you may get results that are slightly off if interrupts
happen to be disabled when the input transitions. If this is
unacceptable, the only other options I see is to use a hardware timer
with input capture capability. You will have to look at the datasheet
of your microcontroller to see how it works, and maybe do a Web search
for “Arduino input capture”.


MPU6050 or GY521/HMC5883 chips are burnt for no reason I been trying to interface MPU6050 and HMC5883 with an Arduino Pro Mini/Nano. I²C scanner works just fine and identifies the device with no issues. I let the I²C scanner run like for 5 minutes and I see fumes coming out of the chips and sometimes the Arduino itself is burnt. I tried pull up resistors 2.2k, 7k without any luck. Has anyone got any inputs to this issue. Really frustrating to spend a weekend on this :(

To rule out the possibility of 5V supply causing the burn out I tried 3.3V from Nano and made promini 3.3V from 5V. Please see the pictures below.

Arduino Nano 3.3v was used to power up the I²C.

.

.

Pro Mini jumper was desoldered from 5V to 3.3V to see if the I²C chips are saved from being burnt. In both these setup voltage accross the I²C chip was measured and it was 3.3V.

Still no luck!

If you guys are to make the same circuit how would you do it and where would you get the components from? I must be doing something wrong and hope we together can figure it out.

Components are bought from eBay and the links are here.
GY521 = goo.gl/Y4aDph
HMC5883 = goo.gl/DfrC9l
Arduino Nano = goo.gl/CaAykI
PROMINI = goo.gl/79PVOM

This is some background of why this issue resolution is so important to me:
Just give you a backgroud of why I am doing this: I am building a quadcopter myself. Infact built one using GY80, but the module was expensive also it eventually got burnt out for the same reason mentioned above. Here is the first successful test flight of my first quadcopter goo.gl/rn6xWG (add https:// since I am rookie there is limitation on how many links I can post). If I can make the same thing work using GY521 and HMC5883 it would be awesome and cheaper.

Update on 08/11 @12:45 PM CST
I think it is because of the Pro Mini, I²C chips are getting fried. When using Nano, I think it is because of the voltage level difference between the SDA/SCL lines causing the problem. With Pro Mini tripped for 3.3V, I was not able to see any serial data from the chip too. To end all these I placed an order for 3.3V 8 MHz Pro Mini from amazon goo.gl/FjgTGj Let see how that goes.

Fixed the issue with a dedicated 3.3V power supply.  I2C scanner is running for 30 minutes with no issues so far.


The Arduino robot tutorials describe a cord comming with the official robot, now I'm confused I recently got the Arduino Robot and have been looking at the examples for the RobotLibrary. As I looked, I found something quite confusing (for me at least), a few of them describe connecting a sensor (like an IR sensor or Ultrasonic sensor) to a port with a cable that was provided with the robot. But I never received a cable. Which got me to question, what type of cable is this, because it is not the same cable you would use on an UNO, at least not according to the pictures. So does anyone know what type of cables these are and/or where I can get them? Thanks :smiley-mr-green:

Here are the pictures btw:

And the next one:

Usually, Arduino gives you the minimal board and sends you on your way. Reading over the instructions, I think they mean a cable that would have come with the IR sensor. That three-tone cord you see in the pictures are actually just three wires. You connect them as described if they came with the sensors. More likely, if they did not, you can use your own wires to connect these. Just be sure that you understand which is the ground (GND), power (+5V or some other +V), and signal. Usually, ground is denoted by the darkest color: black or brown; power is usually red, and signals can be any light color. USUALLY (READ about your device before you plug it in) ground and power are side-by-side for IR sensors, and signal is on the outside. Take a few minutes to Google up your device before plugging it in if you don't have documentation.

Good Luck!


status whether the switch is connected to arduino or not? I made a small circuit in which a push-button is connected to Arduino via a pulldown resistor. So, whenever it is pressed it connects to 5V otherwise pulled down to the ground. this is working fine but I wanted to know is there any way to detect whether the push-button is connected to the circuit or not? In case if push-button disconnects from the circuit, how to detect it?

The simplest way, as @jsotola has said, is to put a resistor across the terminals of the SPST push-button and read the voltage using an ADC input of the MCU.
However, the resistor needs to be bonded to the push-button (or inside the push-button housing) to ensure that when, for example, a vandal rips the push-button out of your switchboard, the resistor is certain to go with it so that the MCU can tell the difference between HIGH, LOW, and MISSING as @EdgarBonet pointed out. You also need to consider the continuous current draw of the extra resistor for low power/battery devices. You could increase the resistor values, but that tends towards weak pullup/pulldown. If you increase the value of only the extra resistor, it shifts the output voltage closer to the rail voltage reducing the margin for error.

Figure 1 – SPST Push-Button AWOL Detector.
Perhaps a better, but more expensive way, is to use a SPDT push-button. This push-button requires no modification, but is more expensive than a SPDT push-button and requires an extra wire and resistor. This circuit draws less continuous current and has stronger pullup/pulldown.

Figure 2 – SPDT Push-Button AWOL Detector.


How to Home a stepper and make it move 45 degree after that I am trying to let a stepper find home (via microswitch) after power up. After that make it move 45 degrees (or the equivalent in steps) and wait for 3 seconds. Below is the code i found/adapted.

The setup part kind of works, but does not run smoothly.

The stepper1() part does not work at all (only jerking movements).

I would also like the motor to be disable when it waits which in my understanding should be achieved by digitalWrite(M2en,HIGH);but when I place this at the beginning and end (LOW, HIGH) of stepper1() it never worked. Any ideas would be great.

#include "AccelStepper.h"

int M2dirpin = 4;  //Motor Y direction pin
int M2steppin = 5; //Motor Y step pin
int M2en=12;  //Motor Y enable pin
#define home_switch 9 // Pin 9 connected to Home Switch (MicroSwitch)

// AccelStepper Setup
AccelStepper stepperX(1, 5, 4);   // (1,2,3) = (Dedicated Board, STEP, DIR)
// Stepper Travel Variables
long initial_homing = -1; // Used to Home Stepper at startup

void setup() {

  pinMode(home_switch, INPUT_PULLUP);
  pinMode(M2dirpin,OUTPUT);
  pinMode(M2steppin,OUTPUT);
  pinMode(M2en,OUTPUT);
  digitalWrite(M2en,LOW);
  Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
  stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper

  // Start Homing procedure of Stepper Motor at startup
  Serial.print("Stepper is Homing . . . . . . . . . . . ");

  while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
    stepperX.moveTo(initial_homing);  // Set the position to move to
    initial_homing--;  // Decrease by 1 for next move if needed
    stepperX.run();  // Start moving the stepper
    delay(20);
  }

  stepperX.setCurrentPosition(0);  // Set the current position as zero for now
  stepperX.setMaxSpeed(50.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  stepperX.setAcceleration(50.0);  // Set Acceleration of Stepper
  initial_homing = 1;

  while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
    stepperX.moveTo(initial_homing);
    stepperX.run();
    initial_homing++;
    delay(20);
  }

  stepperX.setCurrentPosition(0);
  Serial.println("Homing Completed");
  Serial.println("");

 // Move 10 steps forward from the limit switch (to get out of the switch)
  while (stepperX.currentPosition() != 10)
  {
    stepperX.setSpeed(10);
    stepperX.run();

}
}
void loop()
{
//stepper1();
}

void stepper1()
{
  stepperX.move(22.5);
  stepperX.run();
  delay(3000);
}

You need to call run more often. From the documentation:

  You must call this as frequently as possible, but at least once per minimum step time interval, preferably in your main loop. Note that each call to run() will make at most one step, and then only when a step is due, based on the current speed and the time since the last step.

So a single run call and then a delay, will make the motor move only one step. So you need to rewrite for example:

stepperX.run();
delay(3000);

to

unsigned long startMillis = millis();
while( millis()-startMillis<3000 )
{
  stepperX.run();
}

Secondly, move only works on integers, stepperX.move(22.5); will actually become stepperX.move(22);

Lastly, why are you using a totally different method from the rest, to move the motor 10 steps? I'd use a moveTo(10), like you are using everywhere else.


Arduino Pro Micro TX and RX leds flash quikly while power drawn from VCC pin I just got a 5V Arduino Pro Micro, which I connected to an RC RX powered from the VCC and GND pins of the board.

However, whenever I do so and power on the board from a computer USB connection or a wall adapter USB connection, the board goes into an odd mode where the red RX and TX leds flash rapidly (~0.5s on and ~0.5s off) and USB serial ceases functionality. (presumably, because the MCU isn't on anymore)

If I remove the load and power the board again, everything works as normal.

This is an odd behavior, especially since I read online that the VCC pin is rated for ~150ma max and my device (FS-iA6b) isn't a very high power device, tested by me to draw 30-50ma max.

What is happening here? I haven't even connected the 5v signal pin yet!

Aah, I figured it out! @JeffWahaus was correct, the RC RX was placing too great a strain on the Arduino Pro Micro. My latest working theory is that when the RC RX is in communication with the RC TX, it has current spikes that allow the system current draw to exceed that required to drop the voltage coming out of the 5V regulator below that required to shut off the ATmega32U4 MCU.

The solution I found, upon recommendation, was to move the RC RX voltage source from the VCC pin to the RAW pin which taps power from ahead of the 5V regulator and add a 10uf capacitor in parallel with the RC RX to smooth out any current spikes.

simulate this circuit – Schematic created using CircuitLab


setting a dc motor to work for a fixed amount of time I am trying to set a DC motor to work for a fixed amount of time. For example if I will press left, I want it to work for a minute and after that to stop. If I will press right, to work for a minute and than to stop. What do I need to change on this code?

https://github.com/gabrielniculita/arduino-dc-motor.git

There are two possibilities:
Easy way (but with limitations)
I see a delay of 200 (ms)… So if you want to have it working for a minute, than use 60,000.
If 60,000 is not accepted (maybe the input argument is a signed integer, having a max value of 32,767), than use a for loop and do a delay of a second for 60 times.
This solution will make it not respond within those 60 seconds to another left or right command.
Update: See comment of JRobert, 60,000 can be used without a problem.
Prevent a delay
If you want to respond to a left/right command WHILE the motor moving in these 60 seconds, you have to store the time (with millis) in a variable, and check against the time to know when to switch off the motor.
See command of Duncan C. This is very similar to the 'Blink without Delay' sketch which can be found here.
(Actually, there is a third way using interrupts, but I assume the second solution is best in your case, and is responsive enough considering the tasks you want to do with the Arduino.)


Arduino loop over a function is always displaying 0 as final values I trying to loop over a function in arduino to get values for 2000 times, and then divide it by 2000 to get an average offset:

int16_t x_offset = 0;
int16_t y_offset = 0;
int16_t z_offset = 0;

And inside setup():

for(int i=0; i<2000;i++)
  {
    GetXYZ(x_offset, y_offset, z_offset);
    x_offset += x_offset;
    y_offset += y_offset;
    z_offset += z_offset;
    Serial.println(x_offset);
    delay(3);
  }
  x_offset /= 2000;
  y_offset /= 2000;
  z_offset /= 2000;
  Serial.println(x_offset);Serial.println("...");Serial.println(y_offset);Serial.println("...");
Serial.println(z_offset);Serial.println("...");

Here is the GetXYZ() function:

void GetXYZ( int16_t &x, int16_t &y, int16_t &z) {
  // Get the gyro values
  Wire.beginTransmission(MPU);
  Wire.write(0x43);     // first register of gyro values
  Wire.endTransmission(false);

  Wire.requestFrom(MPU,6);
  x = Wire.read() << 8 | Wire.read();
  y = Wire.read() << 8 | Wire.read();
  z = Wire.read() << 8 | Wire.read();
}

The values printed in the serial of x_offset, y_offset and z_offset are always 0.

There's a couple of things wrong here:

You are just getting the last read value doubled:

x_offset += x_offset;

However x_offset is always replaced with the lates reading.  You're not summing anything.

To get anything other than 0 out of dividing an integer by 2000 the value stored in the integer would have to be > 2000. But since you can only store a maximum of 32767 in your int16_t variables, even if you didn't have the problem in point 1, the variables would overflow and the results would be meaningless.

You need to:

Use a second variable per axis to store your total
Ensure that it is big enough to store the maximum reading × 2000.  I'd suggest a long or int32_t.

For instance:

int16_t x_offset = 0;
int16_t y_offset = 0;
int16_t z_offset = 0;
int32_t x_total = 0;
int32_t y_total = 0;
int32_t z_total = 0;

And inside setup():

for(int i=0; i<2000;i++)
  {
    GetXYZ(x_offset, y_offset, z_offset);
    x_total += x_offset;
    y_total += y_offset;
    z_total += z_offset;
    Serial.println(x_offset);
    delay(3);
  }
  x_total /= 2000;
  y_total /= 2000;
  z_total /= 2000;
  Serial.println(x_total);Serial.println("...");Serial.println(y_total);Serial.println("...");
Serial.println(z_total);Serial.println("...");