Can't use millis() instead of delay I am making a home coming/leaving light for car. First I want that whenever I press the car key lock, a timer will start for 10 seconds. And if I press a button twice within 10 seconds, pin 13 will remain high for 10 seconds. If I don't press the button it returns to the void loop or condition may get false. I am working on it but I'm not getting the correct approach. I'm not able to use millis twice in this program.

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;
unsigned long previousMillis = 0;
const long interval = 5000;

void setup() {
  Serial.begin(9600);
  pinMode(8, INPUT_PULLUP);
  pinMode(13, OUTPUT);
}

void loop() {
  unsigned long currentMillis = millis();
  buttonState = digitalRead(8);
  if (buttonState != lastButtonState) {
    if (buttonPushCounter <= 2) {
      if (buttonState == LOW) {
        buttonPushCounter++;
        Serial.println("on");
        Serial.print("number of button pushes: ");
        Serial.println(buttonPushCounter);
        if (buttonPushCounter % 3 == 0) {
          if (currentMillis - previousMillis > 10000) {
            digitalWrite(13, HIGH);
            previousMillis = currentMillis;
          } else {
            digitalWrite(13, LOW);
          }
        } else {
          digitalWrite(13, LOW);
        }
      } else {
        digitalWrite(13, LOW);
      }
    } else {
      buttonPushCounter = 0;
    }
    lastButtonState = buttonState;
  }
}

Here is what you have asked for:

  I am making home coming/leaving light for car. First i want that
  whenver i press car key lock a timer will start for 10 second.And if i
  press button twice within 10 second pin 13 will high remain for 10
  second and if i cant press the button it return to the void loop aor
  condition may get false. I am working on it but dont getting the
  correct approach . But i am not able to use millis twicely in this
  program.

So, I have refactored, and done my best to interpret your words, and the code that you wrote.

You will see that I broke down quite a bit the deep nesting of your code into separate methods.  I hope that you see that it makes it more readable and understandable.

I have replaced the "magic numbers" like 10000 with more readable code like tenSeconds.  And I hope the code does what you want now, but I'm not sure.  Hopefully the readability has improved enough that you can massage and reshape the code into what you want it to do, as well as shown you what direction to head when you don't understand your own code because it has grown (deeper, longer, more complicated, etc.) as most code does.

In the professional coding world, allowing code to remain like that is called "not paying down your design debt" and you (or your organization) will pay the consequences, with interest, just like a credit card.

Finally, note that my comments don't restate the code, but tries to add something (mine often tries to finish sentences involving readable code).  My comments also tend to be on the ends of lines to try to stay out of the way.

This code compiles, but has not been tested on an actual Arduino.  Please let me know if this meets your need, and please choose this as the answer if it does answer your question, and at least please vote up the answer if it doesn't quite answer you...   ...and give me a second chance, if possible.  Thanks.

// pins defined and named
int pin_button = 8;         // button Pin
int pin_LED = 13;           // LED Pin

int currentButtonState = 0;         // current state of the button
int lastButtonState = 0;

int buttonPushCounter = 0;   // counter for the number of button presses
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
const unsigned int tenSeconds = 10000; // 10,000 milliseconds

void setup()
{
    pinMode(pin_button, INPUT_PULLUP);
    pinMode(pin_LED, OUTPUT);
}

void loop()
{
    currentMillis = GetCurrentMillis();
    if (ButtonIsToggled() == 1)
    {
        CountButtonPushes();
    }
}

int ButtonIsToggled()
{
    int isToggled = 0;
    currentButtonState = digitalRead(pin_button);
    if (currentButtonState != lastButtonState)
    {
        lastButtonState = currentButtonState;
        isToggled = 1;
    }
    return isToggled;
}

void CountButtonPushes()
{
    int valueToWrite = LOW; // LED-OFF is default value unless overridden

    if (currentButtonState == LOW) // we just toggled from HIGH to LOW...
    {
        buttonPushCounter++; // We've successfully completed another button-press
        if (buttonPushCounter % 3 == 0) // if (buttonPushCounter==3) should be faster
        {                               // because compare is faster than division
            buttonPushCounter = 0;  // Reset
            valueToWrite = HIGH; // LED-ON
        }
    }

    if (valueToWrite == HIGH) // LED is ON
    {
        digitalWrite(pin_LED, HIGH); // valueToWrite
        while (currentMillis - previousMillis < tenSeconds)
        {
            // do nothing -- wait while LED is on
            // busy wait. Consider sleeping instead.
            currentMillis = GetCurrentMillis();
        }
        previousMillis = currentMillis;
        digitalWrite(pin_LED, LOW);
    }
}

unsigned long GetCurrentMillis()
{
    return millis();
}


Multiple definition class in arduino Help me out here. I don't know what I'm missing.
I have this code in my arduino IDE
#include "Foo2.h"
void setup() {
  // put your setup code here, to run once:

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

And I have five files: Foo.h, Foo.cpp, Foo2.h, Foo3.cpp and Foo.h
Foo.h
#ifndef Foo_H
#define Foo_H

class Foo
{
    public:
    Foo();

    public:
    bool Fooa();
    bool Foob();
};
#endif

Foo.cpp
#include "Foo.h"

Foo::Foo()
{

}

bool Foo::Foob()
{
    return true;
}

Foo2.h
#ifndef Foo2_H
#define Foo2_H
#define LIBRARY_VERSION 1.0.0
#include "Foo.h"

bool Foo::Fooa()
{
    return true;
}
#endif

Foo3.h
#ifndef Foo3_H
#define Foo3_H
#include "Foo2.h"

class Foo3
{
    public:
        Foo3();
        Foo _foo;
};
#endif

Foo3.cpp
#include "Foo3.h"

Foo3::Foo3()
{
}

And it is give me an error:
libraries\Foo\Foo3.cpp.o (symbol from plugin): In function `Foo::Fooa()':
(.text+0x0): multiple definition of `Foo::Fooa()'
sketch\kk2.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1

what i'm doing wrong
regards,

If you want Fooa() to be defined in a header that can be included in more than one .cpp file, you would need to declare it as an inline function like so:
#ifndef Foo_H
#define Foo_H

class Foo
{
    public:
    Foo();

    public:
    inline bool Fooa();
    bool Foob();
};
#endif

Alternately, you can provide the function definition directly inside class definition; this also makes the function inline despite not requiring the inline keyword.
Or if you want to keep Fooa as a non-inline function, you'd need to move the definition out of the header and into a .cpp file as you did with Foob().
Making a function inline has a second effect beyond implying that you want a function's code to be generated at the call site; it informs the compiler (or more accurately the linker) to expect to see multiple definitions (that are required to be identical) of the code for the function.  Without that advanced noticed, you will get the multiple definition of error when a function definition is inserted into multiple .cpp file by way of an #include.
As a side note: #include is an automated form of copy-and-paste.  It logically plants the contents of another file (and all of its reachable #include uses transitively) into place where the #include directive appeared.  It does not behave the same way that many similar looking directives in other languages do.  E.g. #include does not behave like the import keyword does in say Java or python for example.


Implementing sending from N and recieving from N with FreeRtos and RF24 radio module I'm trying to make my first chip send data through a nrf24 radio pipe and the other listen to it. After the first data is received it should switch to transmit mode and itself transmit new data. The main goal of all of this is to implement the raft protocol with at least 3 chips participating. So the requirements would be to have each chip listening all the time and to have it stop listening at random intervals to send a broadcast message to all other chips. Basically the communication is never between just two chips but always one to many. I've come across tutorials such as http://forum.arduino.cc/index.php?topic=421081 but it always comes down to a stable Master vs Slaves state while my situation is more dynamic.
This is my current task. The listener works perfectly until the first received message when it opens a writing pipe. It then does not write and does not go back to listening.

void test_Task(void *pvParameters){

    printf("some init\n");
    bool hastoSend = false;

    radio.openReadingPipe(1, address);
    while(1){

        radio.startListening();
        if (radio.available()) {
            radio.read(&rx_data, sizeof(rx_data));

                if (rx_data[1] == 101){
                    printf("Received message: %d\n", rx_data[1]);
                    hastoSend = true;
                    printf("%d\n",rx_data[0]);
                    //int someint = *((int*)pvParameters);

                    // turn on led1
                    write_byte_pcf(led1);
                    vTaskDelay(pdMS_TO_TICKS(200));
                    write_byte_pcf(0xff);
                }

        }else{
                if (hastoSend){

                    printf("I need to send a message!\n");
                    printf("sending a message\n");
                    radio.openWritingPipe(address2);
                    radio.stopListening();
                    transmit_nrf24();
                    radio.printDetails();
                    hastoSend = false;
                    radio.openReadingPipe(1, address);

                }
        }

    }

}

This is my radio setup:

static inline void setup_nrf() {

    uart_set_baud(0, 115200);
    gpio_enable(SCL, GPIO_OUTPUT);
    gpio_enable(CS_NRF, GPIO_OUTPUT);

    // radio configuration
    radio.begin();
    radio.setChannel(channel);
    radio.setAutoAck(false);

}

For testing purposes the messages being transmitted come from my other device which is just a manual transmitter. What would solve my problem is a way to completely reset the radio when the first message is received so that the pipes do not bother each other and the device could then be re-initialised as a transmitter.

Cheers!

Solved it by simply repeating

gpio_enable(SCL, GPIO_OUTPUT);
gpio_enable(CS_NRF, GPIO_OUTPUT);

// radio configuration
radio.begin();
radio.setChannel(channel);
radio.setAutoAck(false);

before opening a new writing pipe.


Alternative ways for read Serial Output its possible to read serial ouput from ICSP or Tx Rx pin instead from USB port? If it's possible how? thanks for reply

The TX and RX pins are connected directly to the USB to UART adaptor embedded in the board (an ATMega16U2 on the Uno R3, or a CH340G on a cheap Chinese clone). Anything that goes through the USB also goes through those pins.

You can also, if you must, use SoftwareSerial to get serial on any other pair of pins of your choice.


Self made microphone burns Arduino I'm very new to electrical engineering and I'm trying to read microphone input with Arduino Nano. I've made a separate microphone module (based on this example) and plugged it into Arduino like this:

Unfortunately it was the last time my Arduino was working. It's no longer displayed as a connection, and acts "randomly", so I think my microphone toasts controller for some reason. Here are some more pictures and a scheme of my mic module, could someone explain what am I doing wrong?

simulate this circuit – Schematic created using CircuitLab

R1 - CR1/4W 10 (brown,black,black,gold)

R2 - CR1/4W 2KO (red,black,red,gold)

I have no education in electrical engineering, so I'm not sure about the correctness of this schema of units, just pasted what's written on the pack

Your schematic shows R1 as 10k ohms.
Your color codes and description lists it as 10 ohms. 10K would be Brown, Black, Orange.

http://www.allaboutcircuits.com/textbook/reference/chpt-2/resistor-color-codes/

So R1 is the wrong value by a factor of 1000, you may want to fix that ;-)

As for damage to the main board, depending on the microphone used that may have put an excessive strain on the 5V supply pin. Does the power LED still come on at the same brightness as before? If not then the power supply regulator is probably toast. If it does then I'm not sure what the problem is, you shouldn't have broken anything else.


Is there an ICRn CTC mode interrupt vector? I can use the CTC waveform generation mode to loop to OCRnA and trigger the corresponding TIMER1_COMPA_vect interrupt.

// CTC mode
TCCR1A &= ~(1 << WGM10);
TCCR1A &= ~(1 << WGM11);
TCCR1B |= (1 << WGM12);
TCCR1B &= ~(1 << WGM13);
TIMSK1 |= (1 << OCIE1A);
OCR1A = 250;

ISR(TIMER1_COMPA_vect) {}

But if I use CTC mode with ICRn as "TOP" is there a corresponding interrupt vector?

TCCR1A &= ~(1 << WGM10);
TCCR1A &= ~(1 << WGM11);
TCCR1B |= (1 << WGM12);
TCCR1B |= (1 << WGM13);
TIMSK1 |= (1 << ???);    // which interrupt to enable?
ICR1 = 250;

ISR(???) {}              // which interrupt vector?

No, there isn't. But you do have a simple alternative: use WGM 14
(fast PWM with TOP = ICR1). Then the TOV1 flag will be set after
the timer reaches TOP:

TIMSK1 |= (1 << TOIE1);  // enable Timer 1 overflow interrupt

ISR(TIMER1_OVF_vect) {}  // Timer 1 overflow vector

Note that this waveform generation mode behaves very much like the CTC
mode. If you do not set any of the COM1 bits in TCCR1A, then there will
be no PWM output.

Edit: My bad. As noted by Gerben and confirmed by you, the
TIMER1_CAPT_vect can be used, and it is specified in the datasheet,
although maybe not very prominently:

In section 17.9.2 “Clear Timer on Compare Match (CTC) Mode”:

  An interrupt can be generated at each time the counter value reaches
  the TOP value by either using the OCFnA or ICFn Flag according to the
  register used to define the TOP value.

In section 17.11.40 “TIFR5 – Timer/Counter5 Interrupt Flag Register”, in
the description of bit 5 (Input Capture Flag):

  When the Input Capture Register (ICRn) is set by the WGMn3:0 to be
  used as the TOP value, the ICFn Flag is set when the counter reaches
  the TOP value.


Logging data to SD card from software serial I have an Arduino Uno and an Adafruit data logging shield and I have connected a digital pressure sensor that uses serial communication. The sensor requires a character to start transmitting data. I have managed to read the data using this code:

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

int depth;

void setup() {

    Serial.begin(9600);
    mySerial.begin(9600);
    mySerial.print("C");

}

void loop()
{

 if (mySerial.available()) {

   depth = mySerial.read();

 }

}

This returns the following:

  C1000
  C1000
  C1000

where 1000 is the value.

I have written another code that logs data to the shield and tested with other sensors but I cannot log data from this sensor by modifying the above code and cannot find any relevant examples.
If I add something like this it does not return the same value.

logfile.println(depth);

Complete newbie in so any suggestions are welcome.

UPDATE

use the C as the line start indicator. if received char is 'C' then do a file.println(); example with output to Serial

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

void setup() {
    Serial.begin(9600);
    mySerial.begin(9600);
    mySerial.print("C");
}

void loop() {
 if (mySerial.available()) {
   char c = mySerial.read();
   if (c == 'C') {
     Serial.println();
   }
   Serial.write(c);
 }
}


My Arduino Nano clone doesn't show in the serial this simple code. Why? Here is the code:

void setup() {
  Serial.print("hi");
}
void loop() {
}

The product is in here.

I also installed the drivers.

You haven't "started" the serial interface.  Before you use the serial you need to tell it to initialize the hardware and how fast you want to communicate.

You need to add, for instance,

Serial.begin(9600);

to your setup() function before you do your Serial.print().


How to detect lipo battery % charge left? I am currently working with a few robotic projects where i use lipo batteries. Currently I am working with a 1500 mah 3s lipo.

With my current setup I am using a arduino uno and a power distribution board. I put my lipo charger in my power distribution board which has two connections where I put two cables that goes to the VLN and GND.

(If needed I can make a quick schematic to explain it better!)

How can I now see the current battery percentage of the lipo?

I came across a project that uses this codesnippet:

long previousMillis = 0;

long interval = 1000;

int sensorValue = analogRead(A0);
float voltage = sensorValue * (5.0 / 1023.0);

unsigned long currentMillis = millis();

if (currentMillis - previousMillis > interval) {
  previousMillis = currentMillis;
 if (voltage <= 3.5)
      Serial.println("Low Battery");
     else
      Serial.println(voltage, DEC);
}

This snippet works with the A0 and I do not have anything connected there so I assume not.

Appreciate every help! :)

LiPo batteries do not work well for percentage of charge remaining when using voltage as a reference. Lithium chemistry batteries hold a voltage quite close to level up to the point of near-exhaustion. That is to say, you can deplete such a battery by 80%, leaving only 20% capacity and have a few tenths of a volt reduction, depending on the configuration of your battery pack.

Unfortunately, should you continue to deplete the battery, damage may result. Some will say that damage WILL result.

The only certain way to determine a battery capacity is to use a smart charger and/or a smart discharger (often combined into one) to profile a battery.

For example, I have a 2000 mAh battery. After a few conditioning runs, either in use or on the smart dis/charger, the battery shows as having 1600 mAh capacity to 80% discharge.

Using a device to monitor the discharge rate, one can determine that if one uses 1550 mAh of the capacity, one is quite close to the risky cut-off point.
To continue discharging, there is risk involved in the lifespan of the battery.

LiPo batteries will have greater than 4 volts reading immediately off the charger and will "flatten" to optimum voltage in a short time and hold very close to that level, depending on the current load, until it virtually vanishes at the cut-off point.

One can approximate a safe voltage for the cut-off point, but one risks the chance of an inaccurate volt meter. Collecting ampere-hours as a reference for cut-off is the most accurate method and also allows more capacity with less chance of damage.


arduino webserver serves single web page to WAN/Internet very very slowly I have an arduino web server running from a mega 2560 and a wiznet ethernet shield.

It serves the single page just fine (and very fast) to the LAN (192.168.1.50), but serves the same page very, very, slowly when accessed from the  WAN/Internet.

I have port forwarding set-up on the modem router so that the Arduino web page  can be accessed from the outside world, and it does work, I can see the page from anywhere, but it's page serve rate is impractically slow. The page takes 30 - 45 seconds to load up.

(I have the RaspPi with Apache set-up, also in the house, using the exact same port forwarding settings - with a different port - and it serves pages to the WAN/Internet very fast).

Has anyone any ideas what might be wrong ?

Thank you

I haven't used the ethernet library for a while, but I remember that it served up tiny packets - basically each write call went in its own TCP packet. It sounds like you may have latency issues across the WAN.

You could try using your Apache instance to proxy the Arduino pages. Details are at http://httpd.apache.org/docs/current/mod/mod_proxy.html I have this running but all my pages are small so I'm not sure how it would behave on larger pages.


arduino creates strange files in SD card I'm new to Arduino and electronics. I want to make a project including SD data-logger, but I had a problem. I would appreciate if someone show me where I made a mistake.

Firstly, circuit  was set up as in picture:

I am using 8 Gb micro SDHC card with SD adapter. I formatted in FAT32. I can play audio files which are in appropriate format and read and the print contents of text files.

But when I want to create a new file, strange file is obtained in SD card as in pic:

So I reformat SD card. the code that is used while creating file is as this;

// open a new file and immediately close it:
Serial.println("Creating example.txt...");
myFile = SD.open("example.txt", FILE_WRITE);
myFile.close();

Somewhere I read SDHC card with more than 2 Gb capacity  is not supported in Arduino and I bought 2 Gb SD micro with SD adaptor.

But in this case aurduino does not detect SD card. please someone help me.

I've had similar issues with large (> 1Gb) SD cards, I've had various different problems with different cards, some things that helped me debugging the problem:

make sure your wires are the same length and try to use short wires
make sure your power supply is sufficient, sd card readers can draw up to 150mA
format the card in either FAT16 or FAT32 and never use "quick erase", try to use official tools (like https://www.sdcard.org/downloads/formatter_4/index.html)
make sure if you're the correct BAUD rate (9600) to talk to your card
filename support is pretty old so keep them short and don't use spaces or special characters
make sure the SD card is not in "write lock" mode, there's a small switch on the side of some SD cards that can prohibit writing (but will allow reading)


Can the Arduino Due be used as a serial to USB converter? The Arduino due exclusively runs on 3.3V, so I am wondering if this can be used as a USB to serial converter just like the Arduino Uno could, or do you need to do level shifting?? Will I ruin the board if I just hook up RX and TX to a 5v device?

Yes it will work as a USB to serial device, however the serial will be at 3.3V not 5V. It'll still be serial though.

For it to send data to a 5V device, depending on the device, it might work.  3.3V is often around the "high" threshold for an input pin on a 5V device, but check the datasheet for the 5V device to be sure.

For receiving data the 5V will be above the 3.3V supply voltage of the main SAM3X chip, so should be avoided. As with most Atmel datasheets, actually finding the information you want is almost impossible, and I haven't found if there is a maximum "over voltage input current" or not, so to be on the safe side a full level shifting voltage divider should be used on the RX pin.


avrdude: stk500_recv(): programmer is not responding, arduino pro I'm trying to upload a sketch to upload the blink sketch to an arduino pro using a SparkFun Serial Basic Breakout (on Ubuntu 18.04).
setup
Within the arduino IDE I have the following set-up:

Tools -> Board: Arduino Pro or Pro mini
Tools -> Port: /dev/ttyUSB0
Tools -> Programmer: USBasp

I have connected:

DTR sparkfun to DTR on arduino
RX1 sparkfun to RX1 on arduino
TX0 sparkfun to TX0 on arduino
VCC sparkfun to VCC on arduino
GND sparkfun to GND on arduino

the error
The error that I get is as follows
Arduino: 1.8.13 (Linux), Board: "Arduino Pro or Pro Mini, ATmega328P (5V, 16 MHz)"

Sketch uses 924 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
/home/cmhughes/Desktop/arduino-1.8.13/hardware/tools/avr/bin/avrdude -C/home/cmhughes/Desktop/arduino-1.8.13/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyUSB0 -b57600 -D -Uflash:w:/tmp/arduino_build_457079/cmh-Blink.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/cmhughes/Desktop/arduino-1.8.13/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/cmhughes/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
...

The error message continues, and tries 10 attempts.
the question
I've tried many different things, including: changing the RX1 to TX0 connections, using a different FTDI serial adapter, trying a different USB cable, trying on Windows operating system.
What else can I try to see if I can progress this?
arduino pro

SparkFun Serial Basic Breakout - CH340C and USB-C

The upload procedure needs to reset the ATmega328 by use of DTR. This invokes the bootloader code in the ATmega328. If there is a problem with your DTR connection, you have to instead manually press the RESET button at the appropriate time.
So probably your connection to DTR was faulty or. less likely, there could be a fault in the onboard capacitor between the Pro-Mini's "DTR" header and the ATmega328 RESET pin
https://store.arduino.cc/arduino-pro-mini -> Documentation

Automatic (Software) Reset
Rather then requiring a physical press of the reset button before an upload, the Arduino Pro Mini is designed in a way that allows it to be reset by software running on a connected computer. One of the pins on the six-pin header is connected to the reset line of the ATmega328P via a 100 nF capacitor. This pin connects to one of the hardware flow control lines of the USB-to-serial convertor connected to the header: RTS when using an FTDI cable, DTR when using the Sparkfun breakout board. When this line is asserted (taken low), the reset line drops long enough to reset the chip. The Arduino software uses this capability to allow you to upload code by simply pressing the upload button in the Arduino environment. This means that the bootloader can have a shorter timeout, as the lowering of the reset line can be well-coordinated with the start of the upload.


Reading a part of bitmap image on Arduino I'm pretty much a beginner when it comes to programming and have only recently started learning C++. Right now I'm stuck trying to covert a bitmap into a binary array. This is for a Robotics competition I've entered. The bitmap is a 54*96 pixel monochromatic 1 bpp image. I'm confused with the offset positions while trying to read the header. This is the code I've written so far and would greatly appreciate any help. I think the error lies in increment of the lineNo variable which needs to be in hex, but how to increment such values?

What I want to ultimately achieve is to read only some parts of the bitmap particularly the boxes with cross on them (see image below). How do I find out the pixel locations?

#include <SD.h>
#include <SPI.h>
File bMap;
File Text;
void setup()
{
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.print("Initializing SD card...");
  pinMode(10, OUTPUT);
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
  int height = 0;
  int width = 0;
  int  bitmapOffset = 0xa;
  bMap = SD.open("map.bmp", FILE_READ);
  Text = SD.open("test.txt", FILE_WRITE);
  \\bMap.seek(0xa);
  \\bitmapOffset = bMap.read();
  \\Serial.println(bitmapOffset, BIN);
  \\Serial.println(bMap, HEX);
  bMap.seek(0x16);
  for (int i = 0; i < 4; i++) {
    height += (bMap.read() << (8 * i));
    Serial.println(height);
    int lineNo;
    int fileposition = 0;
    for (lineNo = 0; lineNo < height; lineNo++)
      fileposition = bitmapOffset + (lineNo);
    bMap.seek(fileposition);
    //Serial.print(lineNo);
    Serial.print(fileposition);
    //Serial.print(bitmapOffset);

  }

  bMap.seek(0x12);
  for (int i = 0; i < 4; i++) {
    width += (bMap.read() << (8 * i));
    Serial.println(width);
    if (Text) {
      Text.println(height, width);
      Text.close();
    }
  }
}

void loop() {}

Any coordinate in a bitmap (note: the term bitmap here [all lower case] refers to the concept of a grid of pixels, not the Windows BMP file format which I will always refer to as BMP all in capitals) can easily be calculated as long as you know the width.  The height is only needed to stop you going too far.

Any pixel offset in a buffer of pixels is calculated as y * width + x assuming a left-right / top-down pixel arrangement in the buffer.

The information you are really interested in with your bitmap is actually considerably less than is in the BMP that you show.  Your BMP is 56x96 pixels, but the information you actually care about is actually only in a resolution of 7x12 blocks.

It would be far simpler if you could pre-process the provided BMP on a PC to create an array of 84 entries each with a different tag or value to represent what it is.  Your image there could then be represented as the array:

{ 3, 3, 3, 3, 3, 3, 3,
  3, 1, 0, 0, 0, 1, 3,
  3, 0, 0, 0, 0, 1, 3,
  0, 0, 1, 1, 0, 0, 3,
  3, 2, 1, 0, 0, 0, 3,
  3, 1, 0, 0, 1, 0, 3,
  3, 0, 1, 0, 0, 0, 3,
  3, 0, 0, 0, 2, 0, 3,
  3, 0, 0, 1, 0, 0, 3,
  3, 1, 1, 0, 1, 0, 3,
  3, 0, 0, 0, 0, 0, 3,
  3, 3, 3, 0, 3, 3, 3 };

Where 0 is an open white space, 1 is a closed black space, 2 is a black space with a cross and 3 is a border space.

The two crosses would then be calculated as (1,4) = 4 * 7 + 1 = 29 and (4,7) = 7 * 7 + 4 = 53.

Working with BMP files is somewhat more tricky.  They come in multiple depths and multiple bit arrangements, as well as different versions with different header sizes.  They also have different padding requirements for different line lengths and bit depths, and are generally a rather nasty file format all round.

And on top of that they are upside down.  BMP is the only file format I know of where 0,0 is at the bottom left instead of the top left.  Consequently you have to invert all your Y coordinates to make sense of it, and parsing a BMP file from the top down is really slow because you have to keep jumping backwards in the file.

So it would be much better if you could write a program on a PC using software which already understands the BMP format and can render it into a buffer for your program to then parse each block to work out what it is and build up a small 84 byte file of the actual information you need for your robot.

If you must read the BMP file directly on the Arduino then I have code you use to help you.  It's not designed for the Arduino but for the chipKIT boards (though it's very similar) and is designed as part of my DisplayCore framework for chipKIT (and other more powerful) boards, but you are welcome to take whatever bits you like, or just use bits to give you more insight into how BMP files work.  You can get the code from Github here: https://github.com/MajenkoLibraries/DisplayCore/tree/master/ImageReaders/BMPFile

To parse your bitmap into an array you would have to take each 8x8 block of pixels and work out what shape is in it - whether it's all black, all white, a cross, or a border piece.


how fast does loop() run in Arduino Hi I am using Arduino Nano to gamify my experience on Unity3D. I know that Update() in Unity3D runs every frame per second but I because I'm not an electronics guy I don't know how loop() function runs on Arduino.

Does it depends on number of CPU cycles(or micro processor chip in case of Arduino) or what? Please explain. I facing some lags in my game. I can fix them only if know how is loop() function running on Arduino

There ain't a lot of information about loop() in arduino documentation

Loop runs as long as loop needs to run.

Instructions in a CPU run sequentially. The more instructions there are the longer it takes to run.

The more code you put in loop the longer loop will run.

There are two ways to know how long each iteration of loop will take:

Profiling: Actively time each iteration of loop, though be warned, the act of timing will affect the amount of time taken.
Cycle counting. Compile the source into assembly and total up the number of clock cycles needed for all the instructions (including calls to functions). Arduous for small loops, a gargantuan task for anything else.

Also note that many external factors can affect how long loop() takes to run - such as serial communication speed, etc.


Arduino as voltage monitor shorts to ground I need to monitor voltages of several DC circuits in a generator's contact box.  Whenever the generator has an alarm, a LED is lit in the box and voltage on the line drops to zero.  I successfully get readings using analogRead(), but whenever I connect a line it shorts to ground (which is shared between the contact box and the Arduino) and triggers the contact box's alarm.  I need to devise a way to monitor voltages without triggering the alarm.

Each 5V line and ground from the generator has a bus bar termination point that connects to a point in the proprietary alarm box that houses the LEDs and buzzer. I connected Arduino ground to generator ground, then used A0-A7 on a Nano to connect to individual lines on the bus bar. Arduino VCC is connected to 5V regulated DC power.

A voltmeter does not have a ground reference. An Arduino plugged into the USB port would have one. Conceivably a battery-powered Arduino might work, however a safer solution would be to use an opto-isolator to isolate the voltage being tested from the Arduino. Something like this:

In this case you connect the "data pin" to the thing you are sensing. If it is at 5V then the LED will conduct (taking around 7 mA) and the transistor in the isolator will drive the Arduino pin LOW. If the data pin goes to zero volts, the transistor will not conduct, and the 1k resistor will pull the Arduino pin HIGH. Thus you can detect if the pin has changed voltage.

The 560 ohm resistor is a current-limiting resistor for the LED in the isolator. A 1k resistor would probably also work, reducing the current draw on the data pin to around 3.8 mA.


Why use an int variable for a pin when const int, enum or #define makes much more sense Why do people use a variable to specify a pin number when the pin is unlikely to change throughout the execution of the code?

Many times I see an int being used for a pin definition,

int led = 13;

when the use of a const int

const int led = 13;

or enum, or #define

#define LED 13

makes much more sense.

It is even in tutorials on the Arduino site, for example, the first tutorial that most people run, Blink.

I read somewhere that const int is preferred over #define. Why isn't this encouraged right from the beginning, rather than allowing people to develop bad habits, from the outset? I noticed it a while back, but recently it has started to irritate me, hence the question.

Memory/processing/computing wise is a const int, enum, or for that matter #define, better than a plain int, i.e. occupies less memory, stored in different memory (Flash, EEPROM, SRAM), faster execution, quicker to compile?

This may appear to be a duplicate of Is it better to use #define or const int for constants?, but I am addressing the question of why people use variables, and how does the performance improve when they don't, rather than which type of constant is better.

const int led = 13;

That is the correct method. Or even:

const byte led = 13;

How many pins do you have?

Some of the tutorials did not quite go through as much quality control as they might have.

Performance will be better using const byte, compare to int however the compiler may be smart enough to realize what you are doing.

What you can do is gently encourage people to use more efficient techniques by using them in your own code.

Responses to comments

A commenter has suggested that byte is not standard C. This is correct, however this is an Arduino StackExchange site, and I believe using standard types supplied by the Arduino IDE is acceptable.

In Arduino.h there is this line:

typedef uint8_t byte;

Note that this is not exactly the same as unsigned char. See uint8_t vs unsigned char and When is uint8_t ≠ unsigned char?.
Another commenter has suggested that using byte will not necessarily improve performance, because numbers smaller than int will be promoted to int (see Integer Promotion Rules if you want more on this).

However in the context of a const identifier, the compiler will generate efficient code in any case. For example, disassembling "blink" gives this in the original form:

00000086 <loop>:
  86:   8d e0           ldi r24, 0x0D   ; 13
  88:   61 e0           ldi r22, 0x01   ; 1
  8a:   1b d1           rcall   .+566       ; 0x2c2 <digitalWrite>

In fact it generates the same code whether the 13:

Is a literal
Is a #define
Is a const int
Is a const byte

The compiler know when it can fit a number into one register and when it can't. However it is good practice to use coding that indicates your intent. Making it const makes it clear that the number won't change, and making it byte (or uint8_t) makes it clear that you are expecting a small number.

Confusing error messages

Another major reason to avoid #define is the error messages you get if you make a mistake. Consider this "blink" sketch which has an error:

#define LED = 13;

void setup() {
  pinMode(LED, OUTPUT);      // <---- line with error
}

void loop() {
  digitalWrite(LED, HIGH);   // <---- line with error
  delay(1000);
  digitalWrite(LED, LOW);    // <---- line with error
  delay(1000);
}

On the surface it looks OK, but it generates these error messages:

Blink.ino: In function ‘void setup()’:
Blink:4: error: expected primary-expression before ‘=’ token
Blink:4: error: expected primary-expression before ‘,’ token
Blink:4: error: expected `;' before ‘)’ token
Blink.ino: In function ‘void loop()’:
Blink:8: error: expected primary-expression before ‘=’ token
Blink:8: error: expected primary-expression before ‘,’ token
Blink:8: error: expected `;' before ‘)’ token
Blink:10: error: expected primary-expression before ‘=’ token
Blink:10: error: expected primary-expression before ‘,’ token
Blink:10: error: expected `;' before ‘)’ token

You look at the first highlighted line (line 4) and don't even see a "=" symbol. Plus, the line looks fine. Now it's fairly obvious what the problem is here (= 13 is being substituted for LED), but when the line is 400 lines further down in the code, it isn't obvious the problem is with the way LED is defined.

I've seen people fall for this many times (including myself).


Using PROGMEM to save RAM I am successful putting and retrieving char array into Arduino flash memory using PROGMEM char arrays.

I am building my app using header files with class definition / implementation and would like to keep the strings  in same header file.

If I define another PROGMEM char array neither one can be executed. In other words - these PROGMEM are global arrays as far as Arduino compiler is concerned, they compile but won't show up.

Here is my test code

  lcd.clear();
  lcd.print(*strFlashDebug[0]);  // in CDebug
  lcd.setCursor(0,1);
  lcd.print(*strFlashTrack[0]);  // in CTrack

If I put both definitions in same header file it only works with only one lcd.print enabled, not commented out.

It appears that multiple PROGMEM arrays can be defined and compiled but only one is actually usable.
Any comments are appreciated.
Cheers Vaclav

The important thing to know for PROGMEM is that the AVR chip you’re using does not have a single flat address space. I.e., it does not use a von Neumann architecture; instead, it uses a specific version of what is known as a Harvard architecture: it has separate address spaces for RAM, program memory, and EEPROM. All of them start at 0. Which means that while dereferencing a nullptr is technically still undefined behavior in C++, it can be (and often is) perfectly valid in Arduino code.

The short version is: If you have a PROGMEM pointer, whatever function you pass it to must work on PROGMEM pointers. lcd.print does not, and afaict there is no way the function could possibly detect this is not a RAM pointer. You have to call a different function, assuming there is one in the first place.

See http://arduino.cc/en/Reference/PROGMEM for examples on how to use PROGMEM data.


I can't control my DC motors speed with analogWrite() I have Arduino Uno and I attached it to 2 DC motors with L298N bridge.
I want to control the speed of the motors so they don't move at maximum speed.
I use analogWrite() but it does nothing,and the motors move at maximum speed

Here is my code:

//motor A
int enA = 9;
int in1 = 8;
int in2 = 7;

//motor B
int enB = 3;
int in3 = 5;
int in4 = 4;

void setup() {
  Serial.begin(9600);
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}

void loop() {

  analogWrite(enA, 0);

  analogWrite(enB, 0);

  digitalWrite (in1, HIGH);
  digitalWrite (in3, HIGH);
  digitalWrite (in2, LOW);
  digitalWrite (in4, LOW);

  delay(50);
}

I did find solutions for the problem. It turned out that the bridge does not work as it should be and the pins of en(A,B) is replaced with the in pins ..now I can control the speed but can't reverse the direction of the motors


External RAM (23LC1024) and external Flash (W25Q64JVSSIQ) with Sparkfun SAMD21 i'm trying to extend the capabilities of the Sparkfun SAMD21. My question is, which pins do I have to share? I mean, I understand that MISO, MOSI and SCK are shared, but CS connects each to a different pin, am I correct?
My schematics:

I connect my CS_RAM to the D10(PA18 on SAMD21).
and i connect my CS_FLASH to the D6(PA20 on SAMD21)

You are correct, MISO, MOSI and SCK are common to all the SPI devices. Be sure they are all set up for clock polarity etc. The CS\ line is the select line. If the device is not selected it does not matter what goes on with MISO, MOSI and SCK. There are chips such as the 74HC138 that will give you chip selects with just a few additional pins. 1 pin gives you 2 selects 2=4 and 3 gives you 8 selects.


How to use attachInterrupt() in ATtiny85 with Arduino IDE? It's possible use external interrupts/attachInterrupt() with the ATtiny85 when I program with Arduino IDE?

If is possible, how many inputs (for external interrupts) the ATtiny85 have and which are they?
Someone have an example code?

Pin PB2 is the only pin that has a real external interrupt.  This is INT0.

Whether you can use attachInterrupt(0, ...) or not is entirely down to whether it is implemented in the core that you are using.


Arduino outputs garbage values on serial monitor with ESP8266 I have connected my Arduino with an ESP8266.

When I check the ESP8266, by manually entering commands at serial monitor, I get correct results.

However, when I run this program

#include<SoftwareSerial.h>

SoftwareSerial esp8266(2,3);

void setup() {
  Serial.setTimeout(5000);
  Serial.begin(115200);
  esp8266.begin(115200);
  delay(1000);
}

void loop() {
  delay(2000);
  String command="AT";

  esp8266.println(command);
  if(esp8266.available())
  {
    while(esp8266.available())
    {
      char c=esp8266.read();
      Serial.write(c);
    }
  }
}

I get garbage values where sometimes it has an OK in between the output:

  " Received: "ÁT OK " Received: "AÔ ÏË " Received: "AÔ OK " Received: "ÁT ÏË " Received: "ÁT OË " Received: "ÁÔ OK " Received: "Á¬ OK " Received: "ÁT OË "

Could someone help me?

As noted by Matt, the baud rate for the ESP8266 can vary depending on the firmware version/manufacturer.  9600 and 115200 are the most common.  If you can connect using a serial terminal program (like CoolTerm) you can then test the baudrate.

It sounds like the ESP8266 is set to 115200, but in my experience (and others') SoftwareSerial isn't capable of 115200 baud rate (despite "allowing" this as a setting). Some reports suggest as high as 57600 is workable, though in my experience 9600 is best for reliability.  But you can reset this and see what the max reliable value is for you in your configuration.

How to change the baud rate on the ESP8266 will depend on the firmware version. I've had success with AT+IPR=9600. You only need to run this command once (it's a persistent setting). I'd suggest, based on your description, that this is the most likely culprit that's causing the intermittent "garbage" output you describe.


Arduino Starter Kit - firmly wiring longer parts I am getting started with project 01 on the Arduino starter kit. I'm facing an issue when wiring parts with long ends e.g. led & resistor. To make the simple circuit with led, resistor & switch work, I have to hold down the resistor & led, and then press the button. The parts don't connect well to the wires underneath the breadboard.

I want ask if someone could suggest how to better deal with such parts. On searching, I found people cut their parts short, but are there other approaches ?
Thanks.

Cutting them short is proven solution, but there is sometimes still problem with legs too thin to fit good.

Other, even more reliable, is to solder them to pinheader https://commons.wikimedia.org/wiki/File:16_Pin_Header.jpg (just break away 2 or 3 pins depending on how many legs you need). Works even for SMD resistors and diodes https://divnoblog.files.wordpress.com/2015/10/005-odpor_1.jpg

Also you can use small piece of universal stripboard https://en.wikipedia.org/wiki/Stripboard / perfboard https://en.wikipedia.org/wiki/Perfboard, to solder anything on that and solder the pinheader under it. Works perfectly for switches etc.

(of course you can buy "modules" from any suplier, where is the part, maybe accompanied by one or two resistors or such, but the price is higher, than is you do it manually at home and there is not such wide range, as is in normal analog/digital parts, which you can solder to fit your needs)

The problem with https://en.wikipedia.org/wiki/Breadboard is, that usually the holes are good just for the pinheader-sized legs (a lot of IC have the right dimensions too), while nearly any pasive/simple parts are much thinner and do not fit reliably. But for some fast playing with and non-critical application it is usually usable enough.


Isolating IR receiver from disruption? I'm using a simple IR receiver connected to the Arduino through A0 analog pin. The problem is that I want to stabilize the output of IR receiver when it's not receiving an IR signal from a specific IR source, or at least minimizing the disruption to a specific range that I can handle, no matter where its position, But in my case moving the IR receiver a few inches in any direction will results in different voltage output. the difference between values on disruption is very random to handle.

What can I do to isolate IR receiver, may be a specific material or a specific color?

I would suggest two things. First You could put electrical tape around the receiver in such a way that it will only pick up signals from a certain direction. Also you could use low and high pass filters to accept input only in the 38khz range(range of most infra red remotes).  Keep in mind that you will need a couple of rounds for it to work effectively.


Arduino: Error: 'PubNub' was not declared in this scope I'm new to Arduino. When Arduino verifies this sketch https://github.com/MediaTek-Labs/Real-Time-Bicycle-Tracking-Map-using-PubNub throws the following:

Build options changed, rebuilding all
BikeTracker.ino: In function 'void setup()':
BikeTracker.ino:45:5: error: 'PubNub' was not declared in this scope
BikeTracker.ino: In function 'void loop()':
BikeTracker.ino:91:14: error: 'PubNub' was not declared in this scope

I've read most answers are pointing out to www.arduino.cc/en/Guide/Libraries some people say it's common Arduino linking issue (easy to fix) after tried out multiple approaches with no dice.

I've also followed PubNub customer support advice (with list of steps below) but no avail:

  OCT 12, 2015  |  10:23AM PDT  PubNub replied: Eduardo,

  I got this from our hardware/IoT/embedded engineer:

  You are probably not including all the libraries, or has the wrong
  path for them.

  When you download the source at
  MediaTek-Labs/Real-Time-Bicycle-Tracking-Map-using-PubNub on GitHub:

  Click .ino file and a pop up will ask if you need a new folder for the
  sketch – click Yes.
  Then copy the rest of the files from the source to
  this new folder.
  Compile it and see if you get any library path errors
  that you need to provide. Let me know if you require further
  assistance.

BTW this is my PubNub.h https://gist.github.com/egomez99/fb1d738ec39913629e9a

Hope someone can shed some lights.

It turns out my Arduino IDE could not find PubNub.* files until I manually added them as a Library.


ESP32 bluetooth discovery parse names I'm running a sample code from ESP32 examples and I'm scanning available BLE devices. I can see device MAC address etc. But for few devices I can't see their names.I am using ESP-WROOM-32 with hardware support checked out directly from their github (some bugs were fixed earlier on github than via lib manager)When I use LightBlue app for discovery of BLE Devices I can see names for more devices that ESP. What can I change to see the names correctly? OR Can how can I parse device name from the data I'm receiving?

This callback code

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
      Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
      Serial.print(" RSSI: ");
      Serial.println(advertisedDevice.getRSSI());
    }
};

produces this output:

Advertised Device: Name: , Address: 1d:0c:c7:3a:fb:c6, manufacturer data: 4c0009060378c0a81f12, payload: 1073609632
 RSSI: -75

Bluetooth has two ways of dealing with device names. A device can optionally choose to advertise its device name. It also has to respond to a "get device name" request. The former is passive, and is what you normally see when scanning. The latter is active and requires you to connect to the device and make a request. If the device doesn't advertise the device name then the only way you can get the name is to make a GATT "Name Characteristic" request to the device. The ESP32 doesn't (AFAIK) do that automatically because these things are designed to be "light weight". Your heavier-weight "reference" software can go off and do more things because it's a full-blown application.

You can sometimes see the difference in the devices because your reference application might populate the list of devices with a combination of MAC addresses and names, and then replace the MAC addresses with names in a later step. Also it probably caches names that it has queried in the past.


ESP8266 I2C datasheet pins not the same as several examples According to espressif datasheet of the ESP8266 it uses
MTMS (I2C_SCL) and GPIO2(I2C_SDA) for I2C.

However in several examples I've seen the typically use is GPIO(4&5) or GPIO(0&4) to connect to the I2C.
I guess all method works? but what is the real difference?

Many modules don't have the right pins for I2C available. Thus it was decided that the sensible option would be to use a bit-banged implementation of I2C using software only.

Also GPIO2 has a special meaning for booting, and using it is risky at best, and should be avoided.

Doing it 100% in software has the advantage that any pin combination can be used for I2C.


7-12V Power supply + USB Im connecting a servo to my Arduino Uno Rev.3. The general recommendation is to put a 7V -12V power supply for servos as far as I understand. However I’d like to combine it with an USB to a computer since I use it to flush data from a different probe on the Arduino to my PC.

Will it be safe to use both a AC/DC adapter and serial bus?
Will it use the USB for power draw even if adapter is connected?

You will see that the Servos have 3 wires [GND, Power, and Data/Signal]. You can connect your external power supply to GND and Power of the servos, and connect the GND and Signal wires from the Servos to the Arduino.

By connecting the Grounds of the Arduino and Servos together, they share the same 0V reference and you will not damage either by powering the Servos from a higher voltage and the Arduino from USB.

It is not necessary to connect the Arduino Vin or barrel jack to the external power supply. Look at the Servos+power supply as one independent unit, and the Arduino+USB/Computer as a separate independent unit, and the only things connected between them should be GND and the servo signal/data wire.


Arduino IDE missing libread.s0.6 I just recently installed the ESP8266 libraries on the arduino IDE using the boards manager, the code compiles fine with the ESP, but when the board is changed to UNO, i get this error,

opt/arduino-1.6.7/hardware/tools/avr/bin/avrdude: error while loading shared libraries: libreadline.so.6: cannot open shared object file: No such file or directory

Any solution to this?

So install it?

$ sudo apt-get install libreadline6

Or, if you need the i386 version on an x64 platform:

$ sudo apt-get install libreadline6:i386


Arduino and 127/220 Volts: Relay and Isolation I am new to Arduino, also, I am not fluent in english.

I wish to create a controller for several circuits. All of those circuits are "in parallel" with additional circuits.

My question is:

Do a Relay Shield protects the Arduino board from the current and voltage from the power supply?

Suppose the following:

The retangular boxes are "parallel switches" connected to the devices.

R = Power Supply Phase

S = Another Power Supply Phase

N = power Supply Neutral

Arduino, C2 and C3 are 127 Volts, (S+N)

C0 and C1 are 220 Volts (R+S)

Are the Shields safe from oscilations from the eletrical supply?
What / Where / How should I look on what to ground? Local regulations state that I cannot let R and/or S be grounded.

Do a Relay Shield protects the Arduino board from the current and voltage from the power supply?

A relay provides galvanic isolation in the circuit.  The mains power is electrically isolated from the rest of the circuit since the device that performs the actual switching (the contacts in the relay) have no physical connection to the rest of the circuit - they are merely acted upon by magnetism.

That doesn't mean that it's safe, however.  There are a number of things you still need to deal with:

The Arduino cannot directly drive a relay - it can't provide enough current. You must use a drive circuit.
Back-EMF from the relay coil as the magnetic field collapses can damage sensitive semiconductors - good snubber circuit design is important here.
Mains electricity is dangerous and must be treated with respect.  Proper circuit design is paramount to ensure that the mains is kept away from the rest of the circuit. Proper connectors must be used and exposed high voltage points must be rendered inaccessible, either by the project housing or by the addition of plastic insulating shielding.
Relays as they turn on and off cause sparks. Sparks cause EMI. EMI causes induced currents. Induced currents cause damage to electronics.  Minimizing the spark generation not only prolongs the life of your relay but the life of everything else around. Ensure your relays can switch fast enough for the currents you are dealing with, or consider using solid state relays (SSRs) that don't suffer from this issue.


Debouncing Switch Issue I’m trying to use a LDR to monitor the light levels and if the LDR is covered and the button is pressed, the LED should switch on. I’m in the process of adding debouching but every time I run the code, the it goes in the if (val > 421) part the led is on, but the button hasn’t been pressed and the code stops.

I’m suspecting it may be a logic issue with the states. I’m using the millis function for the debouncing so the code should ignore the first 200ms of when the button is pressed. I just help in regard to the debouncing so when the LDR is covered and the switch is pressed , the LED should turn on.

The code is shown below:

const int buttonPin = 8;
const int ldrPin = 0;
const int LEDPin = 13;

boolean buttonState = 0;
boolean NEWbuttonState = 0;
boolean LEDState = 0;
int bounce_time = 200;
unsigned long my_time;

boolean on;

int val = 0;

void showValue(float myval)
{
  Serial.print(myval);
  Serial.print(" lightstatus ");
  Serial.println(LEDState);
}

void setup()
{
  pinMode(buttonPin, INPUT);
  pinMode(LEDPin, INPUT_PULLUP);
  on = false;
  analogReference(DEFAULT);
  pinMode(ldrPin, INPUT);
  Serial.begin(9600);
  my_time = millis();
}

void loop()
{

  val = analogRead(ldrPin);

  NEWbuttonState = digitalRead(buttonPin);

  if ((millis() - my_time) > bounce_time)
  {
    digitalWrite(LEDPin, LOW);

    if (buttonState != NEWbuttonState)
    {
      buttonState = NEWbuttonState;

      //if button is pressed
      if (NEWbuttonState == 1 && LEDState == 0)
      {
        buttonState = NEWbuttonState;

        if (val > 421)
        {
          my_time = millis();

          digitalWrite(LEDPin, 1);
          LEDState = 1;
          showValue(val);
          Serial.print("button press");
        }

        if (val < 420)
        {
          my_time = millis();

          digitalWrite(LEDPin, 0);
          LEDState = 0;
          showValue(val);
        }
        buttonState = 1;
      }
      else
      {
        if (NEWbuttonState == 0)
        {
          buttonState = 0;

        }
      }
    }
  }
}

Bouncing of a mechanical switch happens in very few milliseconds, faster than you can see a led shine.

So, for your task, you don't need any debouncing.

The description or your task lacks what should happen "if not". I assume the led should shine while both button is pressed and ldr is covered. If either button is not pressed, or ldr is lit, the led should remain off.

This one is too simple:

void loop() {
  bool ldrDark = analogRead(A0) < MAX_LDRBRIGHT;
  digitalWrite(led, ldrDark && digitalRead(buttonPin));
}

To add a delay (led goes on only when button is pressed some time) is easy as well.

const byte LED = LED_BUILTIN; // 13 on UNO

const byte BUTTON = 8;  // Button connects to GND
const byte PRESSED = LOW; // due to INPUT_PULLUP
const int DELAY = 300; // ms
bool btnState; // true = HIGH when presse

const byte LDR = A0; // LDR to 5V, Resistor to GND : Low values when dark
const int MIN_LDRBRIGHT= 420; // depends on resistor and LDR

void setup() {
   pinMode (LED, OUTPUT);
   pinMode (BUTTON, INPUT_PULLUP);
}

void loop() {
  static unsigned long lastOpen;
  if (digitalRead(BUTTON) == PRESSED) {
    if (millis() - lastOpen > DELAY)
      btnState = HIGH;
    else btnState = LOW;
  } else {
      lastOpen = millis(); // to remember last moment button was released
      btnState = LOW;
  }

  bool ldrDark = analogRead(A0) < MIN_LDRBRIGHT;

  digitalWrite(LED, ldrDark && btnState);
}


Error uploading Arduino Micro Sketch using Kubuntu I have an arduino micro which I want to program from my Kubuntu 15.10 system. I installed the arduino software using apt-get, but when I try to upload the program (for test purpose I use the Basics\BareMinimum sketch) I get the following error:

Found programmer: Id = "0.00 V1"; type =
    Software Version = 0..; Hardware Version = 0.0
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?

The proper device "Arduino Micro" is selected and also the proper port "/tty/ACM0". I found people on the internet which have the same error and could solve it by using another USB port or cable. But I tried it with two different cables and different ports and didn't manage to get it working. I even tried it on my Laptop running an older version of Kubuntu which produced the same error.

Therefore I tried the newest version of the Arduino software from the arduino homepage. With this I get a different error:

avrdude: ser_open(): can't open device "/dev/ttyACM0": Device or resource busy
avrdude: ser_send(): write error: Bad file descriptor

My user is added to the dialout group, so I should have access to the port. It is also the right port as the port disappears from the arduino menu when I unplug the board.

The arduino itself shouldn't be the problem, as I can upload the sketch from another windows laptop without problems.

EDIT: when I plug in the arduino, the following is added to the dmesg output:

[ 8390.293960] usb 1-2: new full-speed USB device number 6 using xhci_hcd
[ 8390.424861] usb 1-2: New USB device found, idVendor=2341, idProduct=8037
[ 8390.424863] usb 1-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[ 8390.424864] usb 1-2: Product: Arduino Micro
[ 8390.424865] usb 1-2: Manufacturer: Arduino LLC
[ 8390.425283] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
[ 8390.426815] input: Arduino LLC Arduino Micro as /devices/pci0000:00/0000:00:14.0/usb1/1-2/1-2:1.2/0003:2341:8037.0007/input/input21
[ 8390.482163] hid-generic 0003:2341:8037.0007: input,hidraw4: USB HID v1.01 Mouse [Arduino LLC Arduino Micro] on usb-0000:00:14.0-2/input2

Therefore I tried the newest version of the Arduino software from the arduino homepage.

  The package version I am using is 1:1.0.5+dfsg2-2, the other I tried was 2:1.0.5+dfsg2-4.

That is not the newest version.

I think the more recent versions of the IDE are more robust - after all they have fixed reported bugs. Try 1.6.5 or 1.6.7. The version 1.0.5 is pretty old.

I too have had "upload completed" on my Leonardo (virtually the same as the Micro) when it did no such thing.

I am using Ubuntu 14.04 and don't have any problems programming my Micro with IDE 1.6.7.

When programming you should see the Tx/Rx and yellow LEDs flicker. If not, press Reset when it starts to upload and try again.

Have you followed the instructions here? Arduino Troubleshooting.

  I installed the arduino software using apt-get ...

Personally I download the IDE from this page: https://www.arduino.cc/en/Main/Software

Update

I just compiled and uploaded "Blink" with IDE 1.6.7 to my Micro on Ubuntu 14.04. This is what I saw:

Forcing reset using 1200bps open/close on port /dev/ttyACM1
PORTS {/dev/ttyACM0, /dev/ttyACM1, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, /dev/ttyACM1, } => {/dev/ttyACM1, }
Found upload port: /dev/ttyACM1
/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avrdude -C/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM1 -b57600 -D -Uflash:w:/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/nick/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM1
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: devcode selected: 0x44
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587
avrdude: reading input file "/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex"
avrdude: writing flash (4456 bytes):

Writing | ################################################## | 100% 0.33s

avrdude: 4456 bytes of flash written
avrdude: verifying flash memory against /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
avrdude: load data flash data from input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
avrdude: input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex contains 4456 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.03s

avrdude: verifying ...
avrdude: 4456 bytes of flash verified

avrdude done.  Thank you.

Can you please compare to what you get? Or post exactly what you see?

What do you see in your Port menu? This is what I see:

Installing Arduino on a fresh Ubuntu system

I did the following steps to get Arduino up on Ubuntu 14.04, on a PC where it was not previously installed.

Download and install

Downloaded Linux IDE 1.6.7 (64 bit) from https://www.arduino.cc/en/Main/Software
Un-archive downloaded file into ~/development folder
Executed from terminal:  ./arduino

Compile "blink"

Selected Uno device type
Loaded "Blink" from examples
Uploaded (checked Uno showed in menu as shown above)
Got error:

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device

Check permissions, join dialout and tty groups

See owner of /dev/ttyACM*

$ ls -l /dev/ttyACM*
crw-rw---- 1 root dialout 166, 0 Feb  1 07:32 /dev/ttyACM0

Am I in that group? (No)

getent group dialout
dialout:x:20:

Add to group dialout:

$ sudo usermod -a -G dialout nick

Am I in that group? (Yes)

$ getent group dialout
dialout:x:20:nick

Try again:

avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Add to group tty:

$ sudo usermod -a -G tty nick

Check groups I am in:

$ groups nick
nick : nick adm tty dialout cdrom sudo dip plugdev lpadmin sambashare

Try again (same error).

Log out and log back in

After logging out and back in, it uploaded OK! Changed to Micro board (very similar to Leonardo) - still uploaded OK (after changing board type in IDE).

Check USB for Micro

After reset:

$ lsusb | grep Arduino
Bus 002 Device 014: ID 2341:0036 Arduino SA

After about 3 seconds:

$ lsusb | grep Arduino
Bus 002 Device 015: ID 2341:8037 Arduino SA


delayMicroseconds not working on STM32F103C8T6 Due to the fake STM32F103C8T6 module in the market, the delayMicroseconds function is working qucker than expected, when I expect a delay of 1000 us , I get a delay of 500 us. Is there a better method, like to create separate module for counting in microseconds using micros timer? Or there are other proper bootloaders than this one . I use Arduino IDE for programming STM32F103C8T6

Have you considered using a RTC? Something like a DS1307 breakout with I2C communications will provide you with accurate timing.
https://www.bobmixon.com/2020/03/real-time-clock-and-arduino/


Two batteries sharing ground? I need to power my arduino and 2 DC motors requiring 6V each, I want to power the DC motors with a 6V battery through the vM pin on an h-bridge and use a 9V battery to power the Arduino itself.

On my breadboard I have a dedicated power line and ground line on each side, is it okay to share the ground between both batteries and consequently share grounds for any servo motors or sensors i connect?

Not only can you share the grounds - sharing the grounds is required for there to be any form of meaningful circuit for signals to get around the place.

To copy-and-paste a blog post I wrote some time back:

A lot of the time on the Arduino forums we get questions regarding wiring things together. One common format is:

  I want to connect my 12V powered LED strip to my Arduino but I can’t get it to communicate. I have checked all the connections and they seem fine. I have a 12V power supply for the LEDs and the Arduino is powered from the computer.

And 9 times out of 10 the first question we have to ask in return is:

  Have you connected the grounds together?

And guess what the reply to that usually is? Yep:

  No, do I need to? And isn’t that dangerous, connecting a 12V ground to the 5V Arduino ground?

That in itself shows a fundamental lack of knowledge about what “ground” actually is. So let’s start by clearing that up:

Ground, technically, is just a name given to a point in your circuit. That point is a point chosen by you against which all other voltages in the circuit are measured. Often it is the point of lowest potential, such as the – side of a battery, or the – connection of a power supply. Or it may have been chosen for you, such as the ground signal from the USB connection to your computer.

The 5V pin of the Arduino isn’t actually 5V – it is 5V with respect to the ground pin. Equally you could rename the 5V pin to Ground, and what was the ground pin then becomes -5V with respect to [the new] ground.

So ground has to be a single point in your circuit against which all voltages “make sense”.

Let’s take a look at the typical circuit from the original question. An Arduino connected to some 12V device (such as some 12V LEDs):

Here you can see the Arduino connected to, for example, a 5V USB charger. It could be a battery, or it could be the USB port on your computer. It matters not. Connected to that is a 12V device which then has its own 12V power supply. Now. Where is ground in that circuit?

The 5V pin of the Arduino is 5V with respect to the ground pin of the Arduino. So seen from the Arduino’s point of view ground is, in the image above, the bottom line of the Arduino’s power circuit (charger -). However, the 12V of the external circuit is 12V with respect to the – side of the 12V PSU. So seen from the point of view of the 12V device the ground is the lower side of the 12V circuit – the “PSU -” connection.

That doesn’t sound too bad, does it? Each device’s power is correct with respect to the power supply it is running off. As far as that goes, sure. However take a look at the data signal going from the Arduino to the 12V device. What voltage is that at?

Well, seen from the Arduino’s point of view, with respect to it’s ground, since it is generating the signal, it is a 5V signal. But, what about what the 12V device sees? What voltage is that signal with respect to the 12V circuit ground?

Given that voltages aren’t absolute – they are only relative to a reference point within the same circuit, it is impossible to know what the voltage is there.

There’s something more fundamental at play here though which can help you to understand it even better. In the image above there are two red arrows in loops. That is the flow of the current around the circuit (shown as conventional current flow). The key phrase there is around the circuit. Current has to flow out of a supply, through a circuit, and back to the supply from where it came.

In the circuit above the current can flow out of the 5V, through the Arduino, and back to the 5V again because there is a complete loop there. Likewise there is a loop from the 12V supply, through the 12V device, and back to the 12V supply again. But there is no such loop for the signal from the Arduino to the 12V device.  If we think of the Arduino’s output pin as a small power supply there really should be some way for the current to get out of the Arduino, through whatever it is connected to, and then back to the Arduino again. There is no way for that to happen in this circuit.

So you connect the grounds. As soon as you do that a lot of things start to happen. Let’s do that now and see how the circuit looks:

The grounds are now linked by the green wire at the bottom. Immediately we can now see a loop has appeared where the current from the IO pin can flow through the 12V device, out of the ground connection of the device, along the green wire, and back up through the ground connection of the Arduino.

In actuality the loop is a branch from the 5V power loop. Current goes from 5V into the Arduino where it splits, some to run the Arduino and some out of the IO pin. From there it goes through the 12V device, down to ground, then joins the current flowing out of the ground of the Arduino to go back to the 5V supply. It’s useful to think in terms of discrete loops though so you can get a better idea of how the ground fits into things.

Also, now, since the ground of the 5V section and the ground of the 12V section are one and the same (in a schematic all points along a line are the same point) any signals generated from the 5V side are recognisable by the 12V side as 5V since the reference point (ground) is the same for every point in the circuit.

But isn’t it dangerous?

Absolutely not. Not only is it not dangerous, it’s safer than not connecting grounds together. Since now the whole circuit has a single baseline voltage to reference everything from 12V is 12V and 5V is 5V. Without that link the voltage difference between ground on the 5V side and 12V on the 12V side could potentially be many hundreds of volts (especially when the distances between the two points is great). For fully isolated systems, such as battery powered devices, that is not a problem. For anything using power supplies though it can be quite dangerous. And that leads me on to my next point – a slight variation on the question:

I built a circuit with a 12V device powered from a power supply which is controlled by my Arduino. It all works well. But as soon as I run the Arduino from a battery instead of my computer it stops working.

This is a classic case where the grounds haven’t been connected together by the user, but there exists another path linking the grounds together. This is most often the earth connection of the computer and the earth connection of the power supply being linked together through the house wiring:

As you can see the current loop still exists, it just takes a longer route. As soon as you remove the Arduino from your computer and power it from batteries – or a power supply that has no connection to earth – the lower part of that loop disappears completely and you are back to the original circuit with only 2 loops. And it stops working.

Connect the grounds together manually, though, and you reinstate that portion of the loop, making it all work again.

So there you have it. If you have multiple power supplies in your project, whatever they may be (except in special circumstances) you must connect the grounds together for it to work. If it works without connecting the grounds together then you are inadvertently relying on some pre-existing ground connections to do the job for you, and that is likely to fail if your setup ever changes.


Can we use ESP32 to program ESP32-CAM through ESP-IDF Can we just use an ESP32 NodeMCU for example to program an ESP32-CAM? I saw a lot of people programming ESP32-CAM using an arduino Uno, can we do the same for ESP32 NodeMCU? Of course, in the "Arduino as ISP" programming mode.
If we can, is there anything more that I need? if not, why? and are there any other solutions to program it?

Moreover, I want to use ESP-IDF which is better than using the Arduino GUI app.

All you need to program any ESP32 (Cam or not) is a serial interface.  How you make that serial interface is up to you.

Most ESP32 development boards have a USB to UART converter on them which you can use just like on an Arduino - keep the ESP32 you're using for the programming in RESET so it doesn't try and respond on the UART.

You could also program the "programmer" ESP32 as a UART passthrough to connect the USB UART through to the other UART so you don't need to mess with holding in RESET.


Bluetooth radio control of a motor I need to purchase the correct bluetooth module for interfacing some simple functionality between an arduino and a motor. The tricky bit is getting the bluetooth radio to play nice with android and apple ios. There are things like MIT App Inventor, but I'd love to hear from someone with experience how to reliably control arduino from tablets/phones. Preferrably in a way that lets me define the control on the arduino. I can build android apps (slowly), not ios apps, but I would then have to either ask users to install untrusted apks or get it out through the google app store, which would take too long. Any help on this would be great.

You may want to have a look at the Adafruit BLE modules:
https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend/bleuart?view=all

They have provided great examples of how to connect from Android and iOS devices, as well as providing apps or code to integrate into your own apps and you get to implement the motor controller code yourself on the Arduino so should have full control over that side.

They even have an example where they are controlling a motor using an Arduino and Bluetooth, it may not be exactly what you need but hopefully gets you closer to an answer:
https://learn.adafruit.com/bluetooth-motorized-camera-slider/overview?view=all


Arduino with DS18b20 and ENC28J60 to thingspeak Can anyone help me to make this work? I have been trying for a couple of days to make this work, but no luck. I use a DS18b20 Temperature sensor and an ENC28J60 Ethernet module. The last code that I find like close to work is:

/*
| Post temp. values from a DS18B20 to ThingSpeak using the Ethercard interface based on the
| ENC28J60 chip.
| Based on the Ethercard example from www.jeelabs.org
| Phil Grant Jan 2014
*/
#include <EtherCard.h>
// change these settings to match your own setup
#define APIKEY  "xxxx"

//DHT Setup
//#include "DHT.h"
//#define DHTPIN 2     // what pin we're connected to
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
//DHT dht(DHTPIN, DHTTYPE);

// ethernet interface mac address, must be unique on the LAN
byte mymac[] = { 0x12,0x11,0x22,0x12,0x21,0x11 };
char website[] = "api.thingspeak.com";
byte Ethernet::buffer[700];
uint32_t timer;
Stash stash;

void setup () {
Serial.begin(57600);
//dht.begin(); //Initializate DHT
  Serial.println("\n[webClient]");
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
    Serial.println( "Failed to access Ethernet controller");
  if (!ether.dhcpSetup())
    Serial.println("DHCP failed");
  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);
  if (!ether.dnsLookup(website))
    Serial.println("DNS failed");
  ether.printIp("SRV: ", ether.hisip);
}

void loop () {
  ether.packetLoop(ether.packetReceive());
  if (millis() > timer) {
    timer = millis() + 60000; //Transmit every minute
    delay(2000);  // Wait a few seconds between measurements.
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  char h_buffer[10];
  String Hstring = dtostrf(h,0,5,h_buffer);
  //Convert Humidity value to String
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  //float f = dht.readTemperature(true);
  char t_buffer[10];
  String Tstring = dtostrf(t,0,5,t_buffer);
  //Convert Temperature value to String
  byte sd = stash.create();
  stash.print("field1=");
  stash.println(Hstring);
  stash.print("&field2=");
  stash.println(Tstring);
  stash.save();
  // generate the header with payload - note that the stash size is used,
  // and that a "stash descriptor" is passed in as argument using "$H"
  Stash::prepare(PSTR(
    "POST /update HTTP/1.1" "\r\n"
    "Host: $F" "\r\n"
    "Connection: close" "\r\n"
    "X-THINGSPEAKAPIKEY: $F" "\r\n"
    "Content-Type: application/x-www-form-urlencoded" "\r\n"
    "Content-Length: $D" "\r\n"
    "\r\n"
    "$H"),
    website, PSTR(APIKEY), stash.size(), sd);
    // send the packet - this also releases all stash buffers once done
    ether.tcpSend();
  }
}

But on the serial monitor I get this message:

[webClient]
IP:  192.168.88.252
GW:  192.168.88.1
DNS: 8.8.8.8
DNS failed
SRV: 0.0.0.0

I have try all of this network configurations and I am sure that arduino have access to internet from my home router. I can ping arduino IP address from other computers in my network and all computers have access to Internet from same router and same subnet with same DNS.
Any more ideas?

But on serial monitor I get msg: [webClient] IP: 192.168.88.252 GW: 192.168.88.1 DNS: 8.8.8.8 DNS failed SRV: 0.0.0.0

The line above shows that you have the Ethernet interface configured to use a private IP address (192.168.X.Y) and that you're trying to reach Google's DNS server at 8.8.8.8. That means that you've got to have a connection to the Internet accessible through your gateway (192.168.88.1). The gateway will have to be doing NAT since your router will not (should) not route traffic from private addresses to the Internet – and even if it did other routers would not be able to route traffic back to you.

The first thing to do is to confirm that you've got an Internet connection and that the address you're trying to reach exists. If you've got another computer on the same network that can reach the Internet try the address you're trying to reach (api.thingspeak.com) and confirm that the name resolves to an IP address. Then confirm that the gateway you're using on that machine matches what you've got configured on the Arduino.

Another good thing to check would be that the Arduino seems to be working on the wire. There are a number of ways that you could confirm this:

Check to see that you can ping it.
Check to see that it shows up in your ARP cache (use the command arp -a in the terminal if you're on Linux or OS X. You're looking to see that the IP address assigned to the Arduino is unique and that you get back the MAC address that you expect.
Try pointing your DNS at your router (assuming it is configured to act as a DNS server). That will let you see if you get a response from inside your network. Before doing this configure that api.thingspeak.com resolves using ping or by going there on another machine. If this works, you should try it pointing another machine at 8.8.8.8 as your DNS server – just to confirm that this works. If it works and the Arduino fails then it is getting more puzzling.

At this point you most likely will have identified the problem. If you haven't it would make sense to spend some time learning a bit about tcpdump or Wire Shark so that you can watch TCP traffic on the network. At the very least you'll want to be able to watch to see the basic DNS transaction. One possibility may be that the Arduino expects the DNS server to be on the local wire and that it is timing out too fast.


How to drive a 4bit GLCD? i've got a huge (about 6 x 23 cm) graphics LCD. I used my multimeter and the datasheet the LCD driver chips (6 x KS0104 and 2 x KS0103) to get the pinout. It has the following pins: GND, M, FCS (not 100% shure), CL1, CL2, D0-3, VDD and a ground for the metal part.

My problem is that i dont know how i can drive a 4bit GLCD with an Arduino because i didnt found a library which can do this (e.g. OpenGLCD supports only the KS0104 which is an 8 bit controller)

@MikaelPatel answered your question in the comments:

  That gives a total of 54K pixels. And with 4-bit per pixel, two pixels
  in a byte, 27K byte to store a packed off-screen bitmap. Even an
  Arduino Mega would have too little memory for that. This might explain
  why there are no supporting library for that device.


Iterate an Object Array I'm trying to create an array of objects and later iterate over it and do something with each object. My C++ skills just don't go far enough.

Here's what I have so far. I've tried to strip out all the meaningless code. Whats wrong is my tr object is not what I expect it to be. It's numOfCars property is 0 so I know I'm not accessing the train object that I expected.

#include <stdlib.h>

class Train {
    public:
        int numOfCars;
        void init();
        void move();
};

void Train::init() {
    //code intentionally removed
}

void Train::move() {
    //code intentionally removed
}

const int trainCount = 2;
Train train1;
Train train2;
Train trains[trainCount] {train1, train2};

void setup() {
    Serial.begin(9600);
    train1.numOfCars = 5;
    train1.init();

    train2.numOfCars = 5;
    train2.init();
}

void loop() {
    for(int n = 0; n < trainCount; n++) {
        Train tr = trains[n];
        Serial.println(tr.numOfCars); //always prints 0
        tr.move();
    }
}

You are not creating an array of references, you are creating the array from the objects; they are being copied. You can see that this by moving the line (and adding an equals)

Train trains[trainCount] = {train1, train2};

to the bottom of your setup method. However, that is beside the point, as you are not fully using the power of arrays. You needn't create separate objects everywhere, simply create an array of objects right off the bat with new[] and use them. Like this:

#include <stdlib.h>

class Train {
    public:
        int numOfCars;
        void init();
        void move();
};

void Train::init() {}
void Train::move() {}

const int trainCount = 2;
Train* trains = new Train[trainCount];

void setup() {
    // initialize trains
    for (int i = 0; i < trainCount; ++i) {
        trains[i].numOfCars = 5;
        trains[i].init();
    }
    Serial.begin(9600);
}

void loop() {
    for(int n = 0; n < trainCount; n++) {
        Serial.println(trains[n].numOfCars); //always prints 0
        trains[n].move();
    }
}


How to add two assembly arrays in arduino Hey guys what I'm trying to do is to sum two arrays and return a new array; for example if given
  uint8_t a[] = {2, 4, 6};
  uint8_t b[] = {1, 2, 3};

I should get { 3, 6, 9} What I'm trying to do is have a .ino file call on an assembly file that will do this in assembly and not in C and this is what I currently have in assembly:
// mimics void sumArrays(uint8_t *a, uint8_t *b, uint8_t *c, byte length){} method
    .global sumArrays
    sumArrays:
      //r18 is the byte length
      //r24 and r25 first  array 31,30
      //r23 and r22 second array 29,28
      //r21 and r20 third  array 27,26

      mov r30, r24
      mov r31, r25
      mov r28, r22
      mov r29, r23
      mov r26, r20
      mov r27, r21
      ldi r17, 0 //counter variable
      ldi r19, 1
      call printRegs
      //jmp sumLoop

      ret

    sumLoop:
      cp r17, r18
      brge endSumLoop
      ldi r16, 0
      add r16, Z+
      add r16, Y+
      st X+, r16
      add r17, r23
      jmp sumLoop:

    endSumLoop:
      ret

However, I get sketch/assignment13.S:65: Error: constant value required which is most likely from the
add r16, Z+
add r16, Y+

Lines but otherwise, how would I add it to a temporary variable while progressing the pointer?

add r16, Z+

You probably meant something like
add r16, memory[Z+]

However, the AVR is a RISC processor. It has instructions to address the
memory, and instructions to do arithmetics, but it has no “complex”
instructions that both address the memory and do arithmetics with the
addressed data. So you have to use separate instructions to:

Load (ld) the data from RAM

do the arithmetics

store (st) the result in RAM

Now, looking at your assemble code, I have a few comments:

If you are mixing assembly and C/C++, you should pay attention to the
ABI conventions. Specifically, some registers, like r28 and
r29, “belong” to the caller. If your function needs to use them, it
should save their contents (typically by pushing them to the
stack) before clobbering them, and restore them (pop) before
returning.

For adding two 8-bit numbers (a + b), a single addition is enough.
There is no point in starting the addition with zero (i.e. computing
0 + a + b).

For managing the counter, it can be more convenient to decrement the
initial count you where given (like in C: if (--length) return;)
rather than using an extra variable that is incremented.

There is no need to split such a simple function into smaller
functions.


TPIC6B595 Output Unable to Allow Supplied Power to 7-segment Display We have an Arduino Nano connected to 4 small (0.5") common-anode 7-segment displays and 2 large (3") common-anode 7-segment displays. We are trying to multiplex the displays. The larger one requires more power than the smaller one (9V) which the shift register cannot supply.
Therefore, we have supplied 9V to the open drain outputs of the shift register that are connected to the larger displays with a pull-up resistor (390ohm). However, more power (7.5V) goes to the resistor than the display (1.5V).
They are connected like in the ShiftDisplay library's schematic, with a pull-up resistor added according to this link on open drain.
How do we use the open drain outputs logic to supply power to the display?
The data sheet of the big 7-segment display can be found here. Each display requires 160mA of continuous current.

You are getting confused. The pullup resistor is only needed on open drain when you are using it to generate logic levels. It turns the OD output into an RTL output.
You don't want that.
Instead you want your open drain outputs to act like a low-side switch transistor - which is infact what they are.
You can do that by simply placing your LEDs in series with your "pullup" resistor, thus:

simulate this circuit – Schematic created using CircuitLab
I have only shown two elements there (everything inside the dashed box is inside the shift register), but you can see now how when an output is "on" the transistor conducts, and the current flows through the LED, through the resistor, through the transistor, and down to ground.
Your resistor value is then calculated as simply
    9 - Vfled
R = ---------
      Iled

For 20mA and a 2V forward voltage that comes out as 350Ω - so your 390Ω resistors are perfectly fine.


Gauss solver for IIR filter I write a piece of code in online GDB using c++, the code calculates some coefficients for a IIR filter which tries to approximate a fractional derivative and integral for a fractional PID control. The code works as expected in the online IDE, but when I try to execute it in a Arduino Due, the results and only overflows and nan, and really don't know what's the problem so,

Here is the code in GDB online https://onlinegdb.com/rycwt62XL which gives the expected results:

Array A, Array B

1.41421,1

-0.707107,0.5

-2.12132,-1.5

0.883883,-0.625

0.883883,0.625

-0.265165,0.1875

-0.0883883,-0.0625

0.0110485,-0.0078125

And here is the code for the Arduino Due, which only change the printing method using the serial commands, https://onlinegdb.com/ByAs5xyVU, and the results are:

Array A, Array B

ovf,1.00

ovf,ovf

ovf,0.00

inf,ovf

ovf,0.00

inf,ovf

ovf,3.89

inf,ovf

And really don't know where to start for fix this results, thanks. The Method is  exactly the same.

I can't find the root cause of the problem - it's probably because the Due is possibly the worst board that Arduino ever made, and the compiler / linker / support libraries barely work at the best of times.

However, some things you need to look at in your code:

    double* h = new double[L];
    for(int n = 0; n <= L; n++){
        for(int k = 0; k <= n; k++){
            h[n] += pow(operador,-alpha-n+k)*pow(1.0-operador,n-k)*Binomial_E(alpha,k)*Binomial(-alpha,n-k);
        }
    }

There you allocate L (15) doubles in an array. But then you go on to access array slices 0-15. That's 16 entries in an array of size 15, so you're overflowing it and corrupting other memory.

Also you have no delete to balance the new, so you have a memory leak.  You would be better using:

double h[L+1];

instead of new.


Determine Object Heading Is there a sensor I could use which would let me know which direction an object is heading/facing? i.e. I have a servo that can rotate 0 to 180 degrees, and I have another sensor on a block. When I turn the block 45 degrees, I want the servo to also turn 45 degrees - I thought I could do this with a compass, but the varying magnetic fields make it impossible. Gyro/acc maybe? Except I don't know how to use that to solve this problem.

So in other words we need to know the block was rotated 45 degrees using a sensor on the block, which tells the servo to rotate 45 degrees.

Use a gyro, it will give you the angle. Gyros are difficult to find spare, so you should buy an IMU like MPU6050 that contains also an accelerometer.


SoftwareSerial.h alternative with AVR (Two Serial/UART ports in atmega328p) Arduino pins can be used as UART using the SoftwareSerial.h library. Is there any alternative for AVR?

I need more than one serial port on a ATmega328P, but i don't use Arduino.

SoftwareSerial.h is tied to Arduino.h and Arduino pins. I do not use Arduino, i use avr-gcc with atmega328p and atmega8.

AVR274 describes a single-wire, half-duplex software UART.

AVR304 describes a half-duplex, interrupt-driven software UART, and AVR305 describes a polled alternative.

AVR307 describes implementing a half-duplex UART using a USI.

All code associated with each app note can be downloaded from Atmel's website.


MPU6050 accelerometer giving output as -1 -1. Can anyone tell the issue in the code? // MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

void setup() {
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0); // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
}

void loop() {
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333);
}

Serial Monitor output:

AcX = -1 | AcY = -1 | AcZ = -1 | Tmp = 36.53 | GyX = -1 | GyY = -1 | GyZ = -1
AcX = -1 | AcY = -1 | AcZ = -1 | Tmp = 36.53 | GyX = -1 | GyY = -1 | GyZ = -1
[…]

I found that there was a communication problem between MPU and Arduino which I found using code given in this link http://playground.arduino.cc/Main/I2cScanner .
Then I found thought problem Must be in MPU or arduino and problem was in Arduino MCU.
So after changing the Arduino MCU it worked


#include showing error message i was trying to send some data to a webpage via esp8266wifi module connected to arduino uno. My sketch contains a header file .After searching online I could get the library Arduino-master.zip from github. I extracted the files and put it in inside the directory arduino->hardware->arduino->avr->libraries.but even then it was showing me the error message like this:

 fatal error: ESP8266WiFi.h: No such file or directory

 #include

                         ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

How can I remove this error. please refrain from technical words as i am new to this language. Thank you.

EDIT: After adding esp8266WiFi.h in the library i got out from that error message .But it showed me a new one

C:\Program Files (x86)\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory

 #include

                   ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

I dont know how to come out of this error. some websites give a solution but it didn't worked for me.

That library is part of the ESP8266 core. It's not for the Arduino, but for programming the ESP8266 as a standalone unit without an Arduino connected to it.