What is the default setting for a digital output pin With digitalWrite(pin_number,value), we can set an output pin as HIGH or LOW. But if only coding pinMode (pin_number, OUTPUT), what is the default state for the pin pin_number, LOW or HIGH? It is noted that: Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. Does that mean the pin will be in the state LOW?

On the AVR-based Arduinos at least, pins start in the INPUT, i.e. high
impedance state. If you then pinMode(pin, OUTPUT);, the pin turns to
OUTPUT LOW. Note, however, that if you first set the pin to
INPUT_PULLUP, and then to OUTPUT, the pin ends up in the
OPUTPUT HIGH state.

Sometimes you want to control the state the pin will have right when
it's turned to OUTPUT. You may for example simulate an open collector
output by switching between INPUT (or INPUT_PULLUP) and OUTPUT
LOW, while avoiding the OUTPUT HIGH state. In this case, a safe
idiom is to set the output level before switching the pin to OUTPUT,
e.g.

// Set pin to OUTPUT LOW without going throught the OUTPUT HIGH state.
digitalWrite(pin, LOW); // do this first
pinMode(pin, OUTPUT);

A side effect of performing a digitalWrite() on a pin that is not set
to OUTPUT is that the pin gets switched to either INPUT (if writing
LOW) or INPUT_PULLUP (if writing HIGH). This is an idiosyncrasy of
the AVR IO ports you should probably not rely on if you want your code
to be readable or portable.

Reference: the source code of pinMode() in the Arduino
core, and the datasheet of the relevant MCU. See for example the section
Ports as General Digital I/O in the ATmega328P’s datasheet.


Has pt.h library been removed from arduino? I'm trying to get a program to use protothreading and I've got an error at the include statement for the pt.h library stating that there is no such file or directory. This is how it's written in the program:

#include <pt.h>

pt.h has never, and will never, be part of the Arduino core distribution.  It is a completely separate third party library that you have to install yourself.

I think the library you want is this one.


How can I run two Arduinos in sync for video generation? I was thinking about building a video circuit that uses two Arduinos (maybe more) to generate video using NTSC and the AD725.  Although, VGA might be nice if possible.

Anyway, the idea is to use one Arduino as the background layer and the other one as the sprite layer (overlay).

Then, instead of masking the sprite data and having more cpu time, I was thinking of running the signals through a mux.  So that when drawing background data and no sprites (per scanline) then pipe the signal to the AD725.  But when there is a sprite mid-line, then the >0v signal of the sprite Arduino would cause the mux to pipe its contents through to the AD725.

Or, something similar.

I believe many arcade boards from the 80's did this.  Many of them had entire "sprite boards" attached and the signals would mix.  Each layer would have it's own RAM and not be aware of the other layer.

But to do this, I would have to keep the Arduinos sync'd perfectly.

So that's my question.  How I can do this?

Oh, my Arduino of choice in the beginning would be the UNO but I have others (DUE, Teensy3.1, etc.) if that would be a better fit.

Thanks.

I would take a look at MREtv which seems to promise all that you want to do, with just one arduino. This might not be the answer you're looking for, but getting threads to sync is a pain in the rear end, see this for explanation of why threads are a pain.

Now back on topic, it seems like MRETV might off what you want to do, and it can do some pretty impressive things from what I read in the arduino. You might need to modify the library a bit, but it offers already implemented encoding, so that is a plus.

http://www.instructables.com/id/MRETV-Video-Stereo-Sound-and-much-more-from-a-s/


"avr/io.h: No such file or directory" while compiling for board Generic STM32F103C series I'm trying to compile FastLED library for my STM32F103C using Arduino 1.8.5 IDE, but getting this error:

In file included from C:\Program Files
(x86)\Arduino\libraries\FastLED/led_sysdefs.h:32:0,

                 from C:\Program Files
(x86)\Arduino\libraries\FastLED/FastLED.h:44,

                 from
C:\Projects\ioSmartHome\arduino\ColorPalette_stm32\ColorPalette_stm32.ino:1:

C:\Program Files
(x86)\Arduino\libraries\FastLED/platforms/avr/led_sysdefs_avr.h:12:20: fatal
error: avr/io.h: No such file or directory

 #include <avr/io.h>

                    ^

compilation terminated.

exit status 1
Error compiling for board Generic STM32F103C series.

I just have no idea why it's trying to include this file which isn't existed for this platform. Any idea?

More specifically, for a variety of historical reasons, if FastLED can't determine the hardware platform/board being built for, it falls back to avr - and this particular STM chipset isn't directly supported in FastLED at the moment - there's a fork running around that has added support for it, but I haven't had a chance to pull it back into the main library.


Connect 5V DC Fan to Ardumoto I wish to connect 2 simple 5V DC Brushless Fan (80x80x15mm, https://www.sparkfun.com/products/9649) to Ardumoto (https://www.sparkfun.com/products/9815).

Therefore, how to I turn on/off the fan as I do not know how to address it? Do I need to connect a power supply to the Ardumoto, to the Arduino board or 2 separate power supplies to each one of them?

Thanks.

If you look at the schematic on the product page it shows that the Vin from the arduino is connected to the same Vin on the shield and the Vin to the motor driver. So it is either or where you want to connect power.

With regards to controlling the fan, brushless fans are polarized because of the internal control circuitry, this means that it cannot be made to reverse, therefore you should always give the direction pin a high signal. The Sparkfun hookup guide has a example code which shows how to control the motor shield, and some explination.


Is there any problem about calling if (Serial) many times? I am trying to debug a problem that I think may be related to the debug code itself and I tried to use theese macros:

#define DEBUG_PRINT(x) { if (Serial) { Serial.print(x);} }
#define DEBUG_PRINTLN(x) { if (Serial) { Serial.println(x);} }

That works a bit but everything starts running really slow and my sketch get to hung up quite fast. Maybe it is timing related but does not seems like that.

if I change that by this the problem is gone:

#define DEBUG_PRINT(x) { if (true) { Serial.print(x);} }
#define DEBUG_PRINTLN(x) { if (true) { Serial.println(x);} }

I'm using Arduino Pro Micro (Leonardo).

Is there any problem about calling if (Serial) so many times?

Full sketch here

There is no problem, no, but yes it will slow you down.

This is the source code to the boolean operator for the Serial constructor for CDC:

Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

As you can see from that all it does is check the value of a variable.  However it also imposes a 10ms delay¹.  Personally I'd have written it as:

Serial_::operator bool() {
    return (_usbLineInfo.lineState > 0);
}

And on top of that I'd have made it inline.

You might want to experiment by editing CDC.cpp to replace the bool operator with that smaller, leaner, code and see if it improves things (or breaks them completely)².

Edit: I have submitted a pull request to the Arduino GIT repository with a better method of monitoring the line state and imposing the delay(10) when it is actually needed rather than at every call to the bool operator regardless of need.

https://github.com/arduino/Arduino/pull/3624

¹ This is done to allow the port to complete opening at the PC end before data is allowed to be sent.  A better system would only perform the delay() at the moment of port opening rather than every call to the operator.

² Note that this would remove the delay which may be a bad thing as you may lose the first few bytes of the first debug message.  A better system is in the pull request mentioned in the edit to this answer.


Difference between these two NodeMCU boards? I recently received a NodeMCU (identical to the one shown in the first picture below) and originally, I was unable to connect it to my computer which eventually turned out to be driver issues; however, during my initial panic, I found that there seems to be two variations of the NodeMCU board.

As you can see from the pictures below, at first glance there seems to be no difference to the boards, however, some of the more noticeable differences are that the first one has only one "orange" chip whereas the second one has two. Moreover, the first one has a large square chip towards the USB port wheareas the second seems to have a rectangular one.

First one:

Second one:

I would really appreciate if someone could enlighten me to what these small differences are between the two boards are and also what are the implications of these differences (if there are any).

Thank you in advance for any help,

Kind regards,
John

The top one is a real NodeMCU version 1 board (ESP-12E module).

The bottom one is a knock-off copy - looks like the same module on it.

The biggest difference is the USB interface. The real one uses a CP2102 USB to UART bridge. The copy uses a CH340G chip.  The CH340G is notoriously unstable and liable to die at a moments notice.  The CP2102 is far more reliable.  I recently accidentally nuked a Wemos D1 Mini pro which has the same CP2102 on it with 12V.  It took out the voltage regulator. It took out the ESP8266 chip.  I replaced both those, and the CP2102 was proved to still be working fine. More than could be said for a CH340G - glance at one of those wrong and they die.


Getting negative results from calculations I'm trying to proportion potentiometer value to analog pin value. Like 1024 to 255.

int readVolumePot() {
    int val = analogRead(potVolumePIN);

    Serial.print("VOL");
      Serial.println((val * 255/1024));

      return (val * 255/1024);
  }

As potentiometer turns I got irrelevant values.

VOL3
VOL3
VOL3
VOL17
VOL-16
VOL-16
VOL-21
VOL-1
VOL-10
VOL-3
VOL-4
VOL11
VOL8
VOL13
VOL17
VOL15

In Arduino's website they say

  some constant calculations may overflow (e.g. 60 * 1000 will yield a
  negative result).

Notwithstanding, I cannot find an appropriate way to convert the potentiometer value to analog pin value.

analogRead() returns a number from 0 to 1023, and you want to convert that to a range from 0 to 255? One easy way would be to simply divide the reading by 4.

On a more general note, given that the numbers will (should!) never be negative, there's a flavour of int called unsigned int. By using that:

unsigned int val = analogRead(...);

you can cover a range from 0 to 65535 instead of int's -32768 to 32767. That will give you a little more head room - but not enough to multiply the maximum value 1023 by 255 first.

There's also another type long. That covers the range from -2 to 2 billion (and a bit), while unsigned long goes from 0 to 4 billion (and a bit) - but that uses a LOT of processing for the poor Arduino to work with.


rev id and read_rev_id() function What is a rev id? I have looked everywhere for a proper definition but I haven't found anything. I am trying to understand the code below. I don't understand why this read_rev_id function is necessary and yes, I tried to look in the user manual for the IMU I am using but it is practically none-existent. I am using the myAHRS IMU and the only manual I could find, on GitHub, didn't even show a register by this name.

void setup()
{
  //Initialization
  Wire.begin();
  Serial.begin(115200);
  who_am_i();
  read_rev_id();
  delay(1000); //Wait for 1second.
}

You haven't provided enough information for anyone to easily help you. Assuming that you took your code from GitHub myAHRS_plus_i2c.ino you can look further down the file to find the definition of read_rev_id(). It simply reads the revision number from the AHRS chip and displays it on the console. Since this is all that it does you could leave out the call to read_rev_id(). But if you are going to use it then be aware that it contains an obvious bug. The second read() should be to I2C_SLAVE_REG_REV_ID_MINOR.

//READ REVISION ID
int read_rev_id()
{
    uint8_t id_1 = 0;
    uint8_t id_2 = 0;
    read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_1, 1);
    read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_2, 1);
    Serial.print("READ REVISION ID= "); Serial.print(id_1); Serial.println(id_2);
}


Arduino audio output circuit I am looking to build my own arduino-based board that, when triggered, will play a file (line out, not amped to a speaker). Most of the audio shields I see are more complicated than I need, so what I'm wondering is what is the barebones circuit I would need for audio output? I've got the atmega and SDcard side fine, I'm just not sure what IC's are involved in audio output. WAV's are fine so I don't have to deal with mp3 decoding.

PS feel free to move this to electronics instead of arduino, I'm not sure where it belonged since it's built into an arduino board but is more the electronic circuitry.

If you don't care much about quality then all you need is two capacitors and a resistor. Use PWM to create the audio (there is a timerpcm pr something library that will do it). The resistor and pne capacitor form a low pass filter for the PWM, and the other capacitor removes the dc offset.

----/\/\/\----+----||------
              |
             ---
             ---
              |
              _
              -


About maximum length of matrix can be use for matrix invertsion on atmega32 what is the maximum length for matrix can be used for matrix inversion on atmega32,for example,can we implement matrix inversion for 15x15 matrix on atmega32? And if  it can be done on atmega32..does this will make the atmega32 to be slower?
I want to implement kalamn filter 15 states for euler angles estimation...the data of the matrix will be floating point..

Floats in the Arduino IDE are normally 4 bytes. So you can work out with a calculator that your matrix will take at least 15 x 15 x 4 bytes (900 bytes). That is out of a total of 2048 bytes of RAM on the Atmega32.
That may seem to be enough RAM, but other things, like the libraries, will also take RAM. I did an answer to a question about RAM a while back. Even a very simple sketch (in this case) took 346 bytes.
Also, your library, or whatever-it-is you are using for matrix inversion, may require RAM for variables, etc.
My suggestion would be to make your code invert a very small matrix (eg. 1 x 1) and see how much RAM that uses. Then you can extrapolate out fairly simply to how much would be needed for a larger matrix.


Why is this looping? I am trying to do something very simple.  I want the LED to fade from full brightness to off.  This works... However, the LED turns back on to full brightness and fades again, in a loop.  I am not sure why.  I think I am missing something obvious.  Once the legThreeBrightness decrements to 0, nothing should happen...
int legThreeBrightness = 255;

void setup() {

    pinMode(3, OUTPUT);

}

void loop() {

    if (legThreeBrightness = 255){
        do {
              analogWrite(3, legThreeBrightness);
              delay(30);
              legThreeBrightness = legThreeBrightness -5;
           } while (legThreeBrightness >= 0);
    }
}

This line:
if (legThreeBrightness = 255){

assigns the value 255 to legThreeBrightness.  That is non-zero so it enters the block and runs the fade now that the variable has been set to 255.
If you just want to compare the value to 255 then use:
if (legThreeBrightness == 255){

and that way when the loop function repeats it isn't there setting the value back to 255.  This way it will stay at 0.


Where could I find the "Serial.find()" source code? As written in the title, could you tell me where to find the source code of the function "Serial.find()"?

I haven' t installed the Arduino IDE, so I'm glad if you could me link a web resource, or if you directly copy the source code here .

Thanks for your time.

It is part of the Stream class which the Serial class inherits from.

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L93

It just calls findUntil() which is a little further down in the same file:

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L114

That itself calls findMulti() which is where all the magic happens:

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L256

int Stream::findMulti( struct Stream::MultiTarget *targets, int tCount) {
  // any zero length target string automatically matches and would make
  // a mess of the rest of the algorithm.
  for (struct MultiTarget *t = targets; t < targets+tCount; ++t) {
    if (t->len <= 0)
      return t - targets;
  }

  while (1) {
    int c = timedRead();
    if (c < 0)
      return -1;

    for (struct MultiTarget *t = targets; t < targets+tCount; ++t) {
      // the simple case is if we match, deal with that first.
      if (c == t->str[t->index]) {
        if (++t->index == t->len)
          return t - targets;
        else
          continue;
      }

      // if not we need to walk back and see if we could have matched further
      // down the stream (ie '1112' doesn't match the first position in '11112'
      // but it will match the second position so we can't just reset the current
      // index to 0 when we find a mismatch.
      if (t->index == 0)
        continue;

      int origIndex = t->index;
      do {
        --t->index;
        // first check if current char works against the new current index
        if (c != t->str[t->index])
          continue;

        // if it's the only char then we're good, nothing more to check
        if (t->index == 0) {
          t->index++;
          break;
        }

        // otherwise we need to check the rest of the found string
        int diff = origIndex - t->index;
        size_t i;
        for (i = 0; i < t->index; ++i) {
          if (t->str[i] != t->str[i + diff])
            break;
        }

        // if we successfully got through the previous loop then our current
        // index is good.
        if (i == t->index) {
          t->index++;
          break;
        }

        // otherwise we just try the next index
      } while (t->index);
    }
  }
  // unreachable
  return -1;
}


How to test custom cables? I'm trying to make a cable checker to help me make custom cables for my computer. I'm thinking I plug the cable ends into sockets on the device, then the Arduino checks between different pins to make sure that no wires are in the wrong spot or unplugged.
So I'm thinking it runs through like this:
I plug the cable into connectors on the device. The Arduino has the PSU pinouts saved. Pin 1 represents one end of the cable, pin 2 represents the opposite end. Same with 3-4/5-6 etc. If the cable is assembled correctly, it should act as a connection between pins 1-2, pins 3-4, 5-6 etc.
tests pin 1 - 2 to see if they're connected, if yes, light up a green LED, if not, light up a red LED
tests pin 3 - 4, does the same thing
Repeats this  for every wire in the cable
Am I on the right track? How would I do this? I've seen people talking about pullup resistors but I'm also seeing people say that shorting can damage the board

The scope of your question is too wide for a simple answer so let us constrain it to slow signals (audio frequencies or less) over short cables (not more than several meters) in a electrically clean environment (such as found in most homes).
That said, it is likely most looking for similar solutions reading your question will have different specific requirements.  So to make this question and answer useful to others let us consider the most generic, economical and Arduino based solution.

Most cables worth automatically testing will have far more individual connections than common Arduino boards, such as the Arduino Uno, have GPIO pins.  Consider using a GPIO expander or multiple Arduinos which communicate with each other to coordinate efforts.
When testing a cable that will be used for low frequencies, short distance and low immunity to noise it is likely the only faults that are of concern are OPENS and SHORTS.
As this design uses GPIO pins we have the following options at any given GPIO pin: Drive High, Drive Low and Input With Pull Ups.
Build a cable test rig where one end (the near end) of the cable under test is connected to GPIO pins designated as the driver side and the other end of the cable under test (the far end) is connected to GPIO pins designated as the sensing side.
For a SHORTS and OPENS test set all the sensing  and driving GPIO pins to Input With Pull Ups.  Verify that all sensing GPIO pins report a 1.  Next change one and only one of the driver GPIO pins to an output and send a 0.  Record that state of all sensing GPIO pins.  Return the driver GPIO pin to Input with NO PULL UPS and repeat these steps for the next GPIO driver pin.
If this is a STRAIGHT THROUGH cable only 1 sensing GPIO pin should report a 0 in each testing pattern recorded.  If more than 1 sensing GPIO pin reports a 0 then there is a short between the 0 reporting pins.  If none of the GPIO pins reports a 0 then there is an open for that GPIO pin.
Use the same test for cables containing intentional SHORTS (perhaps multiple ground pins are shorted together) expecting to see the associated GPIO pins to all change to 0 at the same time.
For even more complex cables containing loop backs at both ends consider only the "GPIO pin set to an output sending 0" as the driver and record the state of ALL OTHER GPIO pins as they are now all possible outputs.


External Interrupt Pins on Nano Clones Long time lurker, first time poster here.
Do the cheap Arduino Nano clones such as this one have external interrupt pins?
For example, the original Nano has pins 2 and 3 usable for interrupts. Do clones tend to incorporate this feature? If so, can anyone recommend one which does?
I'm planning on using an encoder for my next project and want to make sure I can use interrupts so my code doesn't skip over encoder counts.
Thank you!

I understand your doubt. In a world where Uno WiFi i not Uno it is better to ask. And the Wawgat boards which are named Uno but use a different 8-bit MCU are a trap too.

The Nano in your link has Atmega 328p and interrupts are a feature of the MCU. There is no reason for the clone manufacturer to not use the standard Nano pinout as specified in Open Hardware Nano schematics. Then the board is compatible with Arduino Nano as defined in Arduino AVR boards package.

The clones usually use a cheaper chip for USB. You will maybe need to install a driver for the CH340.

In a few days Nano Every will be available and I expect clones of it in a short time because it is a very simple board. It will use the ATmega 4809 and Arduino advertises exact pin compatibility with old Nano. But I expect in details problems similar to Uno WiFi R2 versus classic Uno problems. One of the problems could be the mapping of interrupt pins.

And later this year Nano 33 will be released. It is a Nano format board with SAMD or nRF52 MCU so 3.3 V (the 33 in name).


How to avoid the code interrupting itself? I have this code, which I am using with a potentiometer to control the speed of a automotive fuel injector. In it, I have specified how long the injector shall stay open by using the delay functions. However, whenever the code runs into a delay call, it pauses the whole code for that amount of time. Although it's not significantly long, it would still be better if it could keeping running analogInput and at the same time run through the if statements, without any interference from either. So basically run two different process simultaneously.

I remember reading somewhere that this is possible with threading? But do you need a library for that? I know Python has a threading library built in, and you can actually use it pretty easily, but what about Arduino? How could I run these two process at the same time?

Here's my code:

#define in1 12

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

void loop(){
 float rotationValue = analogRead(A1);            //read raw input from potentiometer
 float percentValue = rotationValue / 10.23;      //convert to percent 0-100
 Serial.println(percentValue);                    //print it to screen
 if(percentValue >= 0.0 && percentValue <= 1.0){
  digitalWrite(in1, LOW);                         //injector 1 off
 }
 else if(percentValue > 1.0 && percentValue <= 25.00){    //cycle at 100 millisec.
  digitalWrite(in1, HIGH);
  delay(100);
  digitalWrite(in1, LOW);
  delay(100);
 }
 else if(percentValue > 25.00 && percentValue <= 50.00){    //cycle at 50 millis.
  digitalWrite(in1, HIGH);
  delay(50);
  digitalWrite(in1, LOW);
  delay(50);
 }
 else if(percentValue > 50.00 && percentValue <= 75.00){      //cycle at 25 millis.
  digitalWrite(in1, HIGH);
  delay(25);
  digitalWrite(in1, LOW);
  delay(25);
 }
 else{              //cycle at 10 millis.
  digitalWrite(in1, HIGH);
  delay(10);
  digitalWrite(in1, LOW);
  delay(10);
 }
}

You can't use threads on an arduino, they don't exist. you can get some pseudo multitasking going with interrupts, but that is not necessary in your case.

You should be able to refactor your code to avoid using delays without much work. The arduino library provides millis() to keep tract of the time since the arduino was powered on in milliseconds.

something like this could replace all the delays in your code

static boolean state;
static uint32_t time;
if(time < millis()){
    time += delayFromPercent(percentValue);

    state = !state;
    if(percentage < 1.0) state = false;
    digitalWrite(in1, state);
}

Then, somewhere else place

uint32_t delayFromPercent(float percent){
    if(percent < 25) return 100;
    if(percent < 50) return 50;
    if(percent < 75) return 25;
    return 10;
}

alternately, if you don't really want the discrete steps, you could use this instead

uint32_t delayFromPercent(float percent){
    return max(10, 100-percent); // don't return less than 10ms
}

you could change it to react a bit quicker by comparing the time plus calculated delay now rather than when it last set the pin, but that strays farther from what your initial implementation would have done.

In any case, this code will should be able to switch pin in1 without making the rest of your code slow down, as long as the other code does not use delays either.


Ribbon sensor resistance slowly drops when released I recently bought a ribbon sensor (the one displayed here), with the intention to use it as a touch-enabled music instrument.

I used it correctly (so it seems), but I have two issues :

When not pressed, the sensor seems to give random data, as if nothing was plugged to the pin.
When unpressed, the resistance slowly decreases (and so is my sound pitch). Is that a normal behaviour ?

I don't know how to solve both issues. Has anyone an idea ?

A tinker of my test (Currently corrected thanks to @VE7JRO) can be seen here with my code here (The ribbon is replaced by a potentiometer but the principle remains the same). The code is also Available on GitHub.

The Adafruit website says this:

There is a nominal 10K resistance across the two outer leads. The middle pin resistance with respect to either of the outer pins changes depending on where on the strip one presses. When no pressure is applied, the middle pin floats, so be sure to use some sort of weak pullup, such as 100K ohm.

To use Connect one side pin to ground via a 10K resistor in series. Connect the other side pin to your Vcc power line (3V, 5V etc) via a different 10K resistor in series. Then read the analog voltage on the center pin. It will range from 1/3 Vcc to 2/3 Vcc . Do not connect to Ground and Power directly!

Here is a diagram of how I would connect it to a 5V Arduino Uno.


Reasons why it is not OK to connect a relay directly from an Arduino digital pin After looking into various schematics on controlling a relay via an Arduino, I have noticed that, most of the time, transistors are used to switch the separate supply into the relay coil rather than directly supplying the relay with the 5-Volt output from the I/O pin of the Arduino. For example, I have a 5-volt DPDT relay and also a small dc motor. I want to drive both directly from my Arduino UNO (SMD clone) with an Atmel328 processor? Would it be advisable to proceed?

If not (most likely):

Can someone give a detailed explanation and might as well important cautions on current limits and stuff?
How can one control such components without risking the Arduino? What are some common means to accomplish this?
What other devices can generally harm an Arduino board (or any microcontroller unit) in a similar manner?

I'm just a beginner who wants to be extremely cautious. Thanks.

Processor pins have strictly limited current drive capability.

The rated values may vary depending on whether you want a high or low drive.
Some processors will supply only a few mA and the most you will usually officially get is in the 20 to 30 mA range.
There is usually a total current limit for the processor and only a few pins can provide peak current simultaneously.
Processor pins have significant effective resistance and a high voltage will "drop" as increasing current is drawn and a low voltage will rise as load increases. Pins MAY be specific with a maximum short circuit current but at that point a high pin will be pulled low and a low pin will be pulled high so short circuit current has limited applicability.

Even if you have a say 25 mA per pin rated processor the power available is small. 25 mA · 4V say (1V drop on 5V Vcc) = 100 mW. Most motors will take more than that and only very small motors will run well when powered only by a pin.

Electric motors and inductors will generate significantly high voltages when current is interrupted - voltages of tens of volts can easily result and 100+ volts can happen. Connecting a motor of inductor to a processor pin directly is an invitation to destruction. Murphy will often oblige.

A transistor (bipolar or MOSFET) that will drive typical hobby motors costs 10's of cents (or free from scrapped equipment) and allows the port pin current drive to be buffered and "amplified". Use of a transistor or other buffer is an extremely good idea if you have one or a few processors and do not wish them to die semi-randomly.

MOSFET motor driver - from here - section 8.

Voltages and part numbers are for their example - select to suit.
A NPN biploar could be used with the addition of an input resistor to the transistor base.

Bidirectional driver - if you want the driver to be able to drive a load high and low this circuit will work. from here
The input gate is in this case the internal processor driver. The two MOSFET gates connect directly to the processor pin. Vdd should usually be no higher than processor Vmax_drive_out. Slightly higher can be made to work with suitable design. Much higher voltage loads can be driven with this circuit (or similar) plus one extra transistor.

A buffer such as a ULN2803 (and other family members) will drive 8 channels x 500 mA/channel and several can be paralleled.

A ULN2803 is essentially 8 x "Darlington" transistors with emitters connected to a common ground, 8 x "open collector" (unconnected) collectors, and 8 flyback diodes to deal with over voltage spikes (use optional). (There is a ULN280x family with slightly different input characteristics).

This device provides a reasonably priced means of providing 8 x 500 mA pull down drivers. A load connected from an output to V+ is turned on when the input pin is driven high. Once you've used one a few times you'll find them trivially easy to use and very useful. (There is also a ULN200x family with 7 channels per package).

YouTube "how to" video

Driving a stepper motor

Also here

Driving small DC motors - and quite a lot else.

A zillion examples

Digikey - available in 1's if desired $0.72/1, $0.29 in 1000's.

ULN2803 datasheet

For sale at Sparkfun  - can be had rather cheaper but these are available


Can I get a Datetime object from a unix timestamp? Is there a way to get a DateTime object from a unix timestamp and hour offset? I want to be able to print a formatted string, for example Wed Apr 02 17:15:06 2014.

I have:

A unix timestamp: 1396451852.
An offset from my hour zone, +1 hour.

Note: I get the timestamp from an internet service and want to make the conversion in the Arduino.

The seconds since (UNIX) epoch relies on a database.

  New editions of the database and code are published as changes warrant, usually several times per year.

Your options can:

Reduce the timezone database to the timezone you are actually interested in;
Don't forget about daylight savings time for you specific timezone;
The leap years are well known too and reasonably easy to program;
The leap seconds are decided upon usually only couple months before they are introduced and therefore cannot be accounted for in an algorithm.

Conclusion

So can you convert epoch to a time/date format? Yes.
Will it be accurate? It'll drift away over time (months or years)

Advise

If you retrieve epoch from an Internet service, why not use (another?) webserver that has the full timezone database available to convert it to accurate date/time, or 'synchronize' against every once in a while?


Flickering LCD backlight with fingerprint scanner I have the following problem: for some *** reason, my LCD is flashing when my fingerprint scanner turns on. Here is a video of the behavior: https://www.dropbox.com/s/mqk4u0vu8yvhiwz/IMG_3171.m4v?dl=0.

More details: I have a membrane keypad. When I start typing on it, the LCD turns on, and when I type the correct code, the fingerprint scanner turns on, and the LCD prompts the user to press a finger upon the scanner. However, then the LCD backlight starts flashing badly. Interestingly, if I just plug the wall adapter into the arduino and try the scenario, the LCD does not flash. However, if let's say 10-15 have passed since the adapter is plugged in, the LCD flickering becomes visible and irritating (again, when the fingerprint scanner is turned on). So, what could be the reason and how to fix it? Why if I just plug the adapter and execute the scenario, the LCD does not flash, and if I wait some time with the adapter plugged in, and then execute the scenario, the LCD flickers?

Just to add: My fingerprint scanner is GT511C1R (https://www.sparkfun.com/products/13007) and I am using the standard scheme for wiring it (560/1000 ohm for the RX). I am not using lcd.clear() command as I know it's heavy, and even if I don't write any text, the still LCD flickers.

Best regards,
Nike

The backlights on these LCDs are just an LED array with a series resistor so the intensity will be directly proportional to the input voltage; flickering voltage = flickering backlight.

Check these things:

Measure the output of the 5V regulator with an AC volt meter to see if the regulator is oscillating when the backlight flickers, i.e. AC voltage >> 0V.  If it is, then you probably need to increase the size of the output and possibly the input capacitors.
Measure the Input-to-Output voltage differential of the regulator and multiply it by the output current.  If you dissipate more power than the thermal design allows this will heat the regulator making (1) more likely as well as driving the regulator into thermal shutdown.

If the regulator is linear, i.e. 7805 etc, you can solve both (1) and (2) by changing the regulator to a drop in switching type.  These will dissipate heat as a percentage of the output power instead of as a function of the input voltage and can be made self contained with regard to input/output capacitors which would be on-board instead of off-board.  A switcher can also do something a linear can't do:  Supply more current than the source.  A 12V 0.5A power supply into a 5V regulator can supply 5V at 0.5A with 3.5 watts of waste heat.  That same 12V supply into a decent switcher can deliver 1.14A at 5V with only 300mW of waste heat!

This PDF is an example circuit that runs about 95% efficient and fits on a 7805 footprint.

This PDF is the circuit of the 1516 switcher linked above configured to replace the NCP1117 linear regulator use on the Uno Rev3.

This PDF is a full thermal analysis of the Arduino Uno NCP1117 regulator running under the conditions stated in your question.  As you can see, you were right on the edge of what the NCP1117 could handle at 200mA (LCD plus scanner).  I have included a thermograph showing the same unit supplying 1.85A at 5V using a drop in switching regulator with no issues.


How to use Ultrasonic Sensor's trig pin, and why it is needed? I have HC-SR04 Ultrasonic Sensor with me. I couldn't understand the "Trig" pin's working structure and the working technic. Do we really need it while we use?

(With Arduino examples, I generally use Echo pin more than trig pin.)

Yes, you do need it.

The purpose of the TRIG pin is to cause the module to send out a "Ping".  It's what makes the whole thing work.  As soon as the TRIG pin goes HIGH then LOW (for a period of not less than 10µs) the internal clocks start ticking.  8 cycles of 40KHz audio are sent out of the transmitter and it starts counting how long it takes for the echo to arrive.

If you don't use the TRIG pin the module won't be able to do anything at all.


Help Understanding FFT Analysis and analogRead()? Here's the deal, I'm attempting to learn how to use an FFT (Fast Fourier Transformation) Library for sound analysis (link is here). My issue is that this comes with included C++ code to show users how to use the FFT library. There are three examples, but I'll show this one because it's closest to the application I have planned for it:

/*
fft_adc_serial.pde
guest openmusiclabs.com 7.7.14
example sketch for testing the fft library.
it takes in data on ADC0 (Analog0) and processes them
with the fft. the data is sent out over the serial
port at 115.2kb.
*/

#define LOG_OUT 1 // use the log output function
#define FFT_N 256 // set to 256 point fft

#include <FFT.h> // include the library

void setup() {
  Serial.begin(115200); // use the serial port
  TIMSK0 = 0; // turn off timer0 for lower jitter
  ADCSRA = 0xe5; // set the adc to free running mode
  ADMUX = 0x40; // use adc0
  DIDR0 = 0x01; // turn off the digital input for adc0
}

void loop() {
  while(1) { // reduces jitter
    cli();  // UDRE interrupt slows this way down on arduino1.0
    for (int i = 0 ; i < 512 ; i += 2) { // save 256 samples
      while(!(ADCSRA & 0x10)); // wait for adc to be ready
      ADCSRA = 0xf5; // restart adc
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int k = (j << 8) | m; // form into an int
      k -= 0x0200; // form into a signed int
      k <<= 6; // form into a 16b signed int
      fft_input[i] = k; // put real data into even bins
      fft_input[i+1] = 0; // set odd bins to 0
     }
    fft_window(); // window the data for better frequency response
    fft_reorder(); // reorder the data before doing the fft
    fft_run(); // process the data in the fft
    fft_mag_log(); // take the output of the fft
    sei();
    Serial.println("start");
    for (byte i = 0 ; i < FFT_N/2 ; i++) {
      Serial.println(fft_log_out[i]); // send out the data
    }
  }
}

Now, with that said, I have a very general grasp of the idea that those lines referencing some variable called ADMUX and ADCSRA have to do with the analogRead() method and that the ADCH and ADCL refer to another two components that are combined to provide the returned integer that analogRead() spits out. What I don't understand whatsoever are those seemingly random strings of characters that these are being set equal to. For example, what does 0x40 or 0x01 or 0xe5 even refer to in the setup() method (if nothing else maybe somebody could point me in the right direction for this, because that part I really am entirely clueless about). And furthermore, why manipulate these directly in the first place, because if you reference the source code for analogRead() they look awfully similar. Thanks for any help in advance!

Nick Gammon already gave a very fine answer about the meaning of the
mysterious numbers you were wondering about. Here I am trying to answer
only your last question:

  why manipulate these directly in the first place, because if you
  reference the source code for analogRead() they look awfully similar.

One of the reasons is, as Dave X said in a comment, to get a higher
sample rate. Assuming this is an Arduino Uno or similar (ATmega328P @
16 MHz), the Arduino core normally configures the ADC prescaler to 128.
This gives a conversion time of 104 µs (equal to 13 × prescaler ÷
F_CPU), and a maximum sample rate of about 9.6 kHz. This is fine for
telephone quality audio, but insufficient for hi-fi applications. This
example code sets the prescaler to 32 for a conversion time of 26 µs and
a maximum sample rate around 38 kHz. According to Atmel, the ADC should
work fine with this kind of sample rate, except that you should not
expect to get the full resolution.

The main reason, however, is not to get a fast sample rate, but rather
to get a consistent sample rate. The problem with analogRead() is
that it is a blocking function. If you look at its source code you
will see a busy wait like this:

// ADSC is cleared when the conversion finishes
while (bit_is_set(ADCSRA, ADSC));

This means that the CPU is not doing anything useful while waiting for
the ADC to finish the conversion. If you do analogRead() in a loop,
the CPU will wait for the ADC, then the ADC will be idle while the CPU
completes the loop and so on. The conversion period is then the time
required by the ADC plus the time taken by the CPU to loop. And the
CPU time is hard to predict because it can be influenced by interrupts
and by conditional branches inside the loop.

This code, in contrast, configures the ADC to work in free running
mode. In this mode, the ADC starts a new conversion as soon as the
previous one is done. This way you get a steady sample rate while the
ADC and the CPU work in parallel. In the loop you see these lines:

while(!(ADCSRA & 0x10)); // wait for adc to be ready
ADCSRA = 0xf5; // restart adc

The comments are a bit misleading. The first line (which I would rather
write loop_until_bit_is_set(ADCSRA, ADIF);) waits for a flags that is
set when the current conversion is done and the data register updated.
The next line does not restart the ADC (it restarted itself, as it is in
free running mode): it only clears the flag so that it can be
meaningfully tested on the next iteration.

Now, I have a few comments on this code that are not directly related to
your question, but may be useful if you are going to build your program
on this basis.

First, it should be noticed that the whole ADC-reading loop is done with
interrupts disabled. This is not normally needed, as the free running
mode gives you a steady sampling even if the CPU timing is somewhat
jittery. The only valid reason I see for disabling interrupts is if
one of your ISRs takes so long to execute that you may miss one sample.
This could very well be the case with such a high sampling frequency.
But still, there is no point in keeping the interrupts disabled during
the FFT processing. And there is no point in turning off Timer 0 if you
are disabling interrupts anyway.

My second point is about the three lines starting with byte m = ADCL;.
Those are meant to read the ADC data register in the proper order: low
byte first. However, the C compiler is well aware of the proper way to
do read a 16-bit I/O register (see “Accessing 16-bit Registers” in the
datasheet chapter about Timer 1). Thus, these three lines can be
simplified to just int k = ADC;.

My last point is that having the CPU left adjust the result (k <<= 6)
takes some time, as it is implemented as a loop. There is no point in
doing this when the ADC can do it for free: you just have to set the
ADLAR bit when configuring ADMUX in setup(). Then the 5 lines starting
with byte m = ADCL; would be reduced to

int k = ADC - 0x8000;  // ADC reading as a 16 bit signed int


What is the work of pulseIn? I have code for an ultrasonic sensor which I found from a site. Here is the code:

#define trigPin 12
#define echoPin 13

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}

However, I don't understand the work of pulseIn() function. I mean, I want to know when the time count starts and when it ends. For example, in this code, does the time start at digitalWrite(trigPin, HIGH); or does the time start at the pulseIn() function?

If it's the second one, when it stops, then how does the time give us the distance of an obstacle when I am already delaying 1000 microseconds after I send a ping in air?

From the docs:

  Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
  HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then
  waits for the pin to go LOW and stops timing. Returns the length of
  the pulse in microseconds. pulsein

So, in this case, pulseIn(echoPin, HIGH) starts counting the number of microseconds until echoPin goes HIGH and stores that in duration.

It starts and ends on that line, it's what is known as a blocking function. It will really sit there until echoPin goes high and tells you how long it took (unless you specify a timeout).

That also means that any delays you have before or after the pulseIn call don't affect it in any way.

The way you get distance from this time is by the following equation:

distance = (duration/2) / 29.1;

You divide by two because it goes out and back so the time would be double that of a one-way travel. The 29.1 is the speed of sound (which is 343.5 m/s => 1 / 0.03435 = 29.1). So note the result is in CM's, not inches. You could probably figure it out by looking at the data sheet of the sensor or just get a lot of samples relating duration to distance (you would measure the distance manually) and get an equation that is very similar.


Current consumption of a buzzer I want to use the buzzer KPEG2000 in my Arduino application. I would like to know if a GPIO can directly drive this buzzer, without destroy the uC (a GPIO can deliver 40 mA max). In the datasheet, we can find the current consumption under 12 volts (40 mA), but if I decrease the driving voltage to 5V, will this buzzer use more or less then 40 mA ?

https://docs-emea.rs-online.com/webdocs/07a8/0900766b807a8e16.pdf

I already tried to make this buzzer work on an Arduino, and it works. But I would like to know if plugging this buzzer directly to the Arduino will not destroy it.

In the datasheet I read 14 mA @ 12V, which is below the recommended current of a GPIO pin of 20 mA.

Note that 40 mA for a GPIO pin is the max current, recommended is 20 mA. But 14 mA is way less.

To see if it changes for 5V, try connect it without an MCU (directly to a 5 V adapter/USB/breadboard power) and measure the current using a multimeter.

In case it uses more than 20 mA @ 5V, than use a transistor/mosfet to drive the buzzer.

In case you want to have the buzzer at full power, connect a VCC 5V power rail pin to a boost converter, which is controlled by a transistor/mosfet controlled by a GPIO pin.

Thus

Arduino VCC 5V -> Boos converter to 12 V -> Transistor/Mosfet -> Buzzer -> GND
                                                 ^
                                           Arduino GPIO pin


Use interrupts with analog pins in arduino or another possible solution? I have a very simple circuit, but my program is some what complicated.

Here is the circuit diagram:

Here is the code:

/*
  01 - GND -------- GND
  02 - +5V -------- 5V
  03 - V0  -------- Potentiometer Middle
  04 - Reset ------ 9
  05 - Read/Write - GND
  06 - Enable ----- 8
  07 - Data0 ------ NC
  08 - Data1 ------ NC
  09 - Data2 ------ NC
  10 - Data3 ------ NC
  11 - Data4 ------ 10
  12 - Data5 ------ 11
  13 - Data6 ------ 12
  14 - Data7 ------ 13
  15 - +LCD ------- 5V
  16 - -LCD ------- GND
*/

//include LCD library
#include <LiquidCrystal.h>

//Initialize an LCD object
/*Pins should be mentioned in this order:
  Reset
  Enable
  Data4
  Data5
  Data6
  Data7
*/
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
int onTimePin = A0;
int onTime = 0;
int offTimePin = A1;
int offTime = 0;
int ledPin = 13;

void setup()
{

  pinMode(onTimePin, INPUT);
  pinMode(offTimePin, INPUT);

  pinMode(ledPin, OUTPUT);

  //Begin the LCD interface
  lcd.begin(16, 2);

  lcd.print("ON  TIME : ");
  lcd.setCursor(0, 2);
  lcd.print("OFF TIME : ");

}

void loop()
{
  onTime = map(analogRead(onTimePin), 0, 1023, 1, 3);
  lcd.setCursor(11, 0);
  lcd.print(onTime);

  offTime = map(analogRead(offTimePin), 0, 1023, 1, 9);
  lcd.setCursor(11, 1);
  lcd.print(offTime);

  digitalWrite(ledPin, HIGH);
  delay(onTime * 1000);

  digitalWrite(ledPin, LOW);
  delay(offTime * 1000);
}

The above code works. But there is a small problem:

When I turn the potentiometer wiper, there is a delay.

It's obvious because when the loop completes, the changed value of potentiometer is displayed. So, I decided to do the same thing using interrupts. But only digital pins have interrupts.

I would like to know the solution for using interrupts on analog input.

You are looking for the bad solution for a simple problem. As Ignacio
Vazquez-Abrams puts it, the problem is you using delay(). The simplest
solution is to manage the timings with millis(). See the Blink
Without Delay Arduino
tutorial.


Adafruit CC3000 jumper pads if I solder the jumper pads on the adafruit cc3000 for use with the Arduino Mega will it still work fine with the Uno?

This module is designed to be "plug in and go" without access to anything except the connector pads at the board edge. While there are a number of pads on the face of the board these are for "experts only" access and are unneeded for normal operation.

The only soldering required should be the addition of a 9 pin row of pins to allow the CC3000 module to be plugged into a solderless breadboard or a socket. If this is all you do then the module will work directly and interchangeably with  Arduino Uno, Leonardo/Micro & Mega. These are the only Arduino versions that a full library is available for so far. ADAFruit promise more versions will be supported "sometime".

Additional information is available from
 WIRELESS / WIFI / ADAFRUIT HUZZAH CC3000 WIFI BREAKOUT WITH ONBOARD ANTENNA

Solder on connector and go ...

Larger version of photo here makes pin use clear - + see link above

Example use weather station

Low power use tutorial

Example use wireless lamp

Library


How reliable is Arduino Uno Serial, via USB (ATmega16U2), CRC needed? I have a question about the reliability of Serial communication, i.e. in particular if I need to implement CRC/checksum/ECC because of bit transmission errors?
I

I however think there is no general answer as there are different ways in which serial communication with the Arduino Uno's Atmega328P chip might work.

(a) The serial communication is between two Atmega328P Chips, and using rather long wires
(b) The serial communication is between two Atmega328P Chips, and using rather short wires
(c) The serial communication is between one Atmega328P and the ATmega16U2, who picks up and forwards the signals via USB protocol (e.g. to a PC)

My question is with regard to the ATmega16U2. The distance (wire/line length) on the Arduino R3 board is about 2cm/1" tops, which I expect to reduce the likeliness that a signal will become corrupted.
Assuming that the USB protocol which is further employed to transport the signal by itself provides by itself an ECC/CRC/checksums, I wonder if it is not rather superflous to implement a CRC when receving and sending messages via the serial communication in the case (c), while I however expect it to be more necessary for (b) and almost certainly necessary for (c).

Also, if this matters to respond to the question, I was wondering if the power supply (i.e. if Arduino Uno is powered by the USB provided voltage of ~4.5V or rather via an external 12V power adapter) would have an impact on the "corruptability" of the signals on the TX/RX serial lines?

If you use the appropriate buffering of the 0/5V signal over the long wires, case A, no error detection and correction is needed. RS232, RS485, your data will be just fine (can be up to thousands of feet).

Shorter wires, from Atmega device to Atmega device, I've neved had to use anything, even at 115200 speeds, case B, case C.

16U2 to PC, that will depend on the quality of the USB cable. The +/-3V differential signal (similar to RS485 levels) is quite high speed, like 4 Mbits/second, so you want a good cable with good shielding.


RF missing characters I've got two arduino nano devices connected via RF 433 MHz. The modules are MX-05V and MX-FS-03V. I'm using VirtualWire for sending and receiving. The speed is set to 1000 bps.

One has got a pir sensor and sends "1:ON" when it detects movement and "1:OFF" when movement stops.

The other is just receiving these messages, but after a while (20 messages) the text is chopped off. I only receive "1". If I restart everything the same thing happens.

They are currently on my table (cca 20cm distance) and powered by my PC via USB.

What can I do? Is it because the modules are from ebay and probably not the best quality?

Receive part:

// recieve

int ledPin = 13;
int rcvPin = 13;

#include <VirtualWire.h>
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message

void setup() {
  Serial.begin(9600);
  Serial.println("Device is ready");

  // Initialize the IO and ISR
  vw_set_rx_pin(rcvPin); // set pin for rx
  vw_setup(1000); // Bits per sec
  vw_rx_start(); // Start the receiver

  digitalWrite(ledPin,HIGH);
}

void loop() {
  // non-blocking receive
  if (vw_get_message(message, &messageLength)) {
    Serial.print("Received: ");
    for (int i = 0; i < messageLength; i++)  {
      Serial.write(message[i]);
    }
    Serial.println();
    digitalWrite(ledPin, LOW);
    delay(500);
    digitalWrite(ledPin,HIGH);

  }
}

Transmit part:

/*
SimpleSend
This sketch transmits a short text message using the VirtualWire library
connect the Transmitter data pin to Arduino pin 12
pin 11 to high for power
gnd connected to gnd
*/

// RF
int ledPin = 13;
int trxPin = 12;
int pwrPin = 11;

// PIR
int inpPin = 2;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                    // variable for reading the pin status

#include <VirtualWire.h>

void setup()
{
  Serial.begin(9600);
  Serial.println("Starting...");

  // PIR
  pinMode(inpPin, INPUT);     // declare sensor as input
  // RF
  pinMode(pwrPin, OUTPUT);   // Set digital pin 11 as OUTPUT pins
  digitalWrite(pwrPin,HIGH);

  // Initialize the IO and ISR
  vw_set_tx_pin(trxPin);
  vw_setup(1000); // Bits per sec

  Serial.println("Device is ready to send.");
}

void loop() {

  val = digitalRead(inpPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion on seonsor 1!");
      send("1:ON");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
    digitalWrite(ledPin, LOW); // turn LED OFF
    if (pirState == HIGH){
      // we have just turned of
      Serial.println("Motion ended on seonsor 1");
      send("1:OFF");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }

}

void send (char *message)
{
  vw_send((uint8_t *)message, strlen(message));
  vw_wait_tx(); // Wait until the whole message is gone
}

In your first sketch, you have

int ledPin = 13;
int rcvPin = 13;

Did you mean both those to be assigned to the hardware LED on the Nano? (Pin 13 is the on-board LED). If so, why? With all the pins available to you.

The other thing I don't understand is your use of:

byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message

It will always just be one byte, won't it?

Why not use available()?

http://arduino.cc/en/Serial/available

I see this was posted six months ago - no doubt you have already solved it.


Is it possible to execute a code in runtime when gets updated over the air (OTA)? I would like to build a lib like ArduinoOTA but with no downtime at runtime. To achieve that I am wondering if it is possible to create a simple setup and loop code to

Check for new releases
If we have a new one start download it
As download routine is not finished keep running the current release
When download has finished, swap current release to the new one.
Now the normal routine is running the new release.

I am pretty interested if it is possible to do by myself something like that.

I didn't find any paper or articles similar to this and I don't known if this is a challenge for Arduino scope or C/C++.

Maybe I am saying something bizarre but I have been thinking of save new release into flash memory, point to it and discard the old release from flash memory.

On many Arduinos the processor is only a few dollar part.  You are asking for a feature that only starts appearing on platforms where the processor is over an order of magnitude higher in price.  Further, such inexpensive processors normally run a single program.  Running a sketch while managing a download & update would best be done by two programs existing in an operating system.  Again, likely requiring a processor an order of magnitude higher in price.

Instead, consider implementing your design using two different Arduinos.  Swapping one out for the other after updating.   Hot swapping may not be trivial.  This really depends on how your application interfaces with the world. But likely will be much easier than solving the problem of designing the supporting software to make sketch updates transparent to the Arduino user.


Can't find OV2640 module! pid: 254 I'm trying to follow this tutorial.
But I'm stuck in this error:

Can't find OV2640 module! pid: 254

I tried to contact the author of the program, but I have not had an answer yet.
I'm using the ArduCAM Mini module OV2640.

Has anyone ever been in this situation?

If you look at line 762 of 'ArduCam_ESP8266_FileCapture.ino' you should see it is looking to read two bytes from the camera to check that the model number is either a '2641' or '2642'.

You are seeing the error because you are not getting those values back.  So between 761 and 762 insert some debug and print what you are getting back:

Serial.print ("vid = ");
Serial.println (vid);
Serial.print ("pid = ");
Serial.println (pid);

I guess you will either get 00 00 or a different valid (maybe) model number.  If you think its a valid model number add another condition to the if statement and see if it works.

Oh and don't forget to post the results, because I'm going to give it a chance too when I get time :)


Ethernet shield connected to local network, not to internet Using the WebServer example file I have been able to confirm that my arduino is connected to my local network and I can open the page in my browser. However any attempt at contacting addresses outside my own network fails. For example this simple script:

    #include <SPI.h>
    #include <Ethernet.h>

    EthernetClient client;

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 1, 25);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress dns(8, 8, 8, 8);
    byte server[] = { 64, 233, 187, 99 }; // Google

    void setup() {
      Ethernet.begin(mac, ip, dns, gateway);
      Serial.begin(9600);
      delay(1000);
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      if (client.connect(server, 80)) {
        Serial.println("connected");
        client.println("GET /search?q=arduino HTTP/1.0");
        client.println();
      } else {
        Serial.println("connection failed");
      }
    }

This consistently returns connection failed. The ethernet cable in the arduino has an active internet connection, albeit via a switch. My board is an arduino uno.

Find a server that doesn't automatically switch modes to https as google does.  If you put 64.233.187.99/search?q=arduino%20HTTP/1.0   in your browser you'll see that it switches to https.

If make the same request via the wget terminal app it fails.

--2020-01-17 11:42:26--  http://64.233.187.99/search?q=arduino%20HTTP/1.0
Connecting to 64.233.187.99:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: http://www.google.com/search?q=arduino%20HTTP/1.0 [following]
--2020-01-17 11:42:26--  http://www.google.com/search?q=arduino%20HTTP/1.0
Resolving www.google.com... 172.217.4.132, 2607:f8b0:4007:80c::2004
Connecting to www.google.com|172.217.4.132|:80... connected.
HTTP request sent, awaiting response... 403 Forbidden
2020-01-17 11:42:28 ERROR 403: Forbidden.

There should also be an error returned to the client object which you can print out for debugging the conection.

Change your code to print out the return value of the client.connect call like so

void loop() {
      int result = client.connect(server, 80);
      if (x) {
        Serial.println("connected");
        client.println("GET /search?q=arduino HTTP/1.0");
        client.println();
      } else {
        Serial.println("connection failed");
        Serial.println(x);  // print out the error
      }
    }

One last thing, you set your dns server to 8.8.8.8 which should generally be set to your gateway / router of 192.168.1.1.


Get UUID from Arduino Nano, ATmega328 I need to know how to obtain the UUID from an Arduino Nano ATmega328 for a project.

You don't have a UUID.

You only get a UUID in the USB-enabled chips, like the ATMega32U4.

You would have to create your own UUID and store it in EEPROM, or embed it within your sketch.


Pattern library for addressable LED strips Is there any central place that we can get drawing pattern functions for the addressable LED strips like the once based on the WS2812B component?  These are sold on the Adafruit site under the NeoPixel name.  For example I know of a few pattern examples like the Larson Scanner (Cylon), a candle light flicker or a rainbow pattern.  However I could not find a single pattern repository.

I am working on a project for kids learning to program the Arduino and it would be nice to have all the patterns in a single place and to be able to switch between the program examples with a mode switch.

If people send me links I am happy to post a blog of them.

I have never found a single pattern repository, however FunkBoxing has a fantastic sketch with 30 or so patterns well documented. http://funkboxing.com/wordpress/?p=2154

He uses the Fast_SPI (now FastLED) library, which is truly exceptional!

https://plus.google.com/u/0/communities/109127054924227823508


Multiple buttons to control relays Dears,

I have a problem that I could not solve for a while, I tried the code below but it did not work.
There will be 4 buttons controlling 4 relays but in a way that button one will turn relays 1&3 on, if button 2 is pressed only relay 2 turns on, if button 3 is pressed relays 1,2 and 3 will turn on, if button 4 is pressed it is supposed to toggle relays 1&4. one more thing: I need to be able to pass from any button to any of the others and the corresponding relays will be activated while the others will go off.

    #include <Bounce2.h>

    const int     BUTTON_COUNT = 4;
    const int16_t DEBOUNCE_DELAY = 50;
    const uint8_t buttonPins[BUTTON_COUNT] = {28, 29, 30, 31};
    const uint8_t ledPins[BUTTON_COUNT] = {34, 35, 36, 37};

    Bounce buttons[BUTTON_COUNT];
    uint8_t ledStates[BUTTON_COUNT];

    void setup() {
    for (int i = 0; i < BUTTON_COUNT; i++) {
    buttons[i].attach(buttonPins[i], INPUT);
    buttons[i].interval(DEBOUNCE_DELAY);
    pinMode(ledPins[i], OUTPUT);
    ledStates[i] = HIGH;
    digitalWrite(ledPins[i], ledStates[i]);
     }
    }

    void loop() {

// Update the debouncers.
for (int i = 0; i < BUTTON_COUNT; i++)
    buttons[i].update();

// When the first "laban" button is pressed:
if (buttons[0].rose()) {

    // Light up the first LED.
    digitalWrite(ledPins[1], LOW);
    digitalWrite(ledPins[3], LOW);

    // and turn off all the others.
    for (int i = 0; i < BUTTON_COUNT; i++) {
        ledStates[0] = HIGH;
        ledStates[2] = HIGH;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

// When the first button is released:
if (buttons[0].fell()) {

    // turn off relays.
    digitalWrite(ledPins[1], HIGH);
    digitalWrite(ledPins[3], HIGH);

}

// When the first "Soda" button is pressed:
if (buttons[1].rose()) {

    // Light up the first LED.
    digitalWrite(ledPins[2], LOW);

    // and turn off all the others.
    for (int i = 0; i < BUTTON_COUNT; i++) {
        ledStates[0] = HIGH;
        ledStates[1] = HIGH;
        ledStates[3] = HIGH;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

// When the first button is released:
if (buttons[1].fell()) {

    // turn off the first LED.
   digitalWrite(ledPins[2], HIGH);

}

// When the first "labanUP" button is pressed:
if (buttons[2].rose()) {

    // Light up the first LED.
    digitalWrite(ledPins[1], LOW);
    digitalWrite(ledPins[2], LOW);
    digitalWrite(ledPins[3], LOW);

    // and turn off all the others.
    for (int i = 0; i < BUTTON_COUNT; i++) {
        ledStates[0] = HIGH;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

// When the first button is released:
if (buttons[0].fell()) {

    // turn off the first LED.
     digitalWrite(ledPins[1], HIGH);
     digitalWrite(ledPins[2], HIGH);
     digitalWrite(ledPins[3], HIGH);
}

// When circulation button is pressed:
 if (buttons[3].rose()) {

    // Toggle its state.
    ledStates[3] = !ledStates[3];
    digitalWrite(ledPins[3], ledStates[3]);
    digitalWrite(ledPins[0], ledStates[0]);
     }
    }

Below code is an simple example of what you described, each button will turn on the relays defined for them and turn off other relays. except for button 4 which will toggle relay 1 and 4.

int relay1 = 2;
int relay2 = 3;
int relay3 = 4;
int relay4 = 5;
int sw1 = 6;
int sw2 = 7;
int sw3 = 8;
int sw4 = 9;
int sw1Status, sw2Status, sw3Status, sw4Status;
int order = 1; // default is to set all relays off.

void setup() {
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  // input pull-up, so default state of buttons is HIGH.
  pinMode(sw1, INPUT_PULLUP);
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  pinMode(sw4, INPUT_PULLUP);
}

void loop() {
  // read the buttons status
  sw1Status = digitalRead(sw1);
  sw2Status = digitalRead(sw2);
  sw3Status = digitalRead(sw3);
  sw4Status = digitalRead(sw4);

  if (sw1Status == LOW) { // if button 1 pressed
    order = 2; // go to case 2
  }
  if (sw2Status == LOW) {
    order = 3;
  }
  if (sw3Status == LOW) {
    order = 4;
  }
  if (sw4Status == LOW) { // button 4 toggle
    if (order != 5) { // if order is not equal 5 turn on relay 1 & 4
      order = 5;
    }
    else { // else go to case 1, which will turns off all relays
      order = 1;
    }
  }

  switch (order) {
    case 1: // if order equals 1
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, LOW);
      break;

    case 2: // if order equals 2
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      break;

    case 3: // if order equals 3
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, LOW);
      break;

    case 4: // if order equals 4
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      break;

    case 5: // if order equals 5
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, HIGH);
      break;

    default: // if none of above cases is valid go to case 1
      order = 1;
      break;
  }
}

Having a tidy code format and using simple coding style (if possible) will help to debug/edit/improve the code more easily.

Don't forget to de-bounce the buttons.


Error 'exec: "python": executable file not found in $PATH Error compiling for board AI Thinker ESP32-CAM.' in Arduino IDE 1.8.12 I am trying to upload a sketch to the ESP32-CAM board using Arduino IDE 1.8.12 and I get an error message:

exec: "python": executable file not found in $PATH
Error compiling for board AI Thinker ESP32-CAM.

My OS is Ubuntu 18.04.4.LTS.

When I type python in the console, it does open python:

$ python
Python 2.7.17 (default, Nov  7 2019, 10:07:09)
[GCC 7.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
KeyboardInterrupt
>>>

Also python is in one of the directories referenced by PATH:

$ which python
/usr/bin/python
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

I added an additional URL referring to the ESP32 boards on the Espressif website:

Arduino IDE > File > Preferences > Settings > Additional Boards Manager URLs: > https://dl.espressif.com/dl/package_esp32_index.json

Then I added the libraries for all ESP32 boards:

Arduino IDE > Tools > Board > Boards Manager > esp32 version 1.0.4

(I tried with version 1.0.3 and it didn't change anything...)

I selected my board in the interface:

Arduino IDE > Tools > Board > AI Tinker ESP32-CAM

I granted all permissions to the USB port:

sudo chmod a+rwx /dev/ttyUSB0
ls -la /dev/ttyUSB0
crwxrwxrwx 1 root dialout 188, 0 Mar  4 21:25 /dev/ttyUSB0

My sketch is really simple:

void setup() {
}

void loop() {
}

I get the same error for any example sketch and for any ESP32 board.

Any idea how this could be fixed ?

All right so I was able to fix the problem. The Arduino IDE I was using had been installed from the Ubuntu Software Center. I uninstalled it.

Then I reinstalled the Arduino IDE by downloading it from the www.arduino.cc website and doing a manual install in /opt. Now it works awesome.


Generating 200 kHz pulse on Arduino Uno in normal mode I need to obtain 200 kHz from Arduino Uno. I am using Timer0. I have configured it to run in normal mode and the Prescaler is set to clk/8 (the clock frequency of Arduino is 16 MHz). TCNT0 is set to 0xFB and the code toggles 2 pins of PORTB as timer overflow flag is set.

Here is my code (I am using Atmel Studio 7):

#include <avr/io.h>

int main(void)
{
   DDRB = 0x03;
   PORTB |= 0x02;
   while (1)
   {
       TCNT0 = 0xFB;
       TCCR0A = 0X00;
       TCCR0B = 0x02;
       while ( (TIFR0 & 0x01) == 0 );
       PORTB ^= 0x03;
       TCCR1A = 0x00;
       TCCR1B = 0x00;
       TIFR0 = 0X01;
  }
}

When I check on the oscilloscope, it shows that the pulse is 166 kHz instead of 200 kHz. Although I can use Fast PWM Mode and use interrupts, I am just curious to know why it doesn't work? Did I make any mistake?

That's simple enough - you forgot that everything takes time.

Your timeline is:

Configure timer
Set count
Wait for count to overflow (33 ticks)
Toggle pin
Do something with T1 (why...?)
Clear overflow bit
Go back to 1.

Here's how that looks as assembly:

90: 3b ef           ldi r19, 0xFB
92: 42 e0           ldi r20, 0x02
94: 23 e0           ldi r18, 0x03
96: 91 e0           ldi r25, 0x01

while (1) {
98: 36 bd           out 0x26, r19   ; TCNT0 = 0xFB;
9a: 14 bc           out 0x24, r1    ; TCCR0A = 0X00;
9c: 45 bd           out 0x25, r20   ; TCCR0B = 0x02;

while ( (TIFR0 & 0x01) == 0 );
9e: a8 9b           sbis    0x15, 0
a0: fe cf           rjmp    .-4         ; 0x9e <setup+0xe>

PORTB ^= 0x03;
a2: 85 b1           in  r24, 0x05
a4: 82 27           eor r24, r18
a6: 85 b9           out 0x05, r24

a8: 10 92 80 00     sts 0x0080, r1
ac: 10 92 81 00     sts 0x0081, r1
b0: 95 bb           out 0x15, r25

}
b2: f2 cf           rjmp    .-28

So assuming that the waiting for the timer overflow takes 8*4+
1=33 clock cycles, and referencing the datasheet for how long each instruction takes, we can add up everything in the main while loop:

while (1) {
98: 36 bd           out 0x26, r19   ; 1
9a: 14 bc           out 0x24, r1    ; 1
9c: 45 bd           out 0x25, r20   ; 1

while ( (TIFR0 & 0x01) == 0 );
9e: a8 9b           sbis    0x15, 0 ; 2 (at end)
a0: fe cf           rjmp    .-4     ; 33 (while running)

PORTB ^= 0x03;
a2: 85 b1           in  r24, 0x05   ; 1
a4: 82 27           eor r24, r18    ; 1
a6: 85 b9           out 0x05, r24   ; 1

a8: 10 92 80 00     sts 0x0080, r1  ; 2
ac: 10 92 81 00     sts 0x0081, r1  ; 2
b0: 95 bb           out 0x15, r25   ; 1

}
b2: f2 cf           rjmp    .-28    ; 2

You can see that takes 48 clock cycles (We don't care about what is in the inner while except when it comes to finishing, and that's just the SBIS instruction). For 200kHz you want 40 clock cycles. You have 48. 16000000/48 = 333333. Divide by two for your pin toggling, and you get 166666Hz.

If you want to use this kind of method you need to ensure that the timer is completely free running and the overflow flag gets set at a regular interval, not just at 32 ticks after you start it.

You should be operating in CTC mode so it counts up from 0 to your target value and then resets back to 0 whilst setting the overflow flag. Your loop then looks like:

while (1) {
    if ((TIFR0 & 0x01) == 0x01) {
        PORTB ^= 0x03;
    }
}

All the timer configuration is done before the loop and it just runs and runs until you say otherwise.


Arduino Nano- Programer not responding after upload WDT I followed an example link for WDT. Code was copied as is, and uploaded to Nano successfully.

Now- when I wish to upload another code, I get an error message saying avrdude: stk500_recv(): programmer is not responding.

Is it possible to undo it ?

code:

#include <avr/wdt.h>

#define led 13 // pin 13 is connected to a led on Arduino Uno

void setup()
{
  pinMode(led, OUTPUT);      // set pin mode
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);                // wait for a tenth of a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(100);                // wait for a tenth of a second
}

void loop(){
  wdt_enable(WDTO_15MS);     // enable the watchdog
                             // will fire after 15 ms without reset

  while(1)
  {
//     wdt_reset();          // uncomment to avoid reboot
  }
}

If the WDT program is running when you try to upload a new one, it may be blocking the bootloader. Try holding the reset button while you click the the IDE's upload button, releasing the reset once you see avrdude launch. It may take a few tries to get the button-dance just right.

Update:

  what is avrdude ?

It is the program on your PC that uploads the compiled image to the Arduino. You'll see it running in the lower pane of the Arduino IDE.


Can't get Ubuntu to see FTDI cable for breadboarding Arduino project I am in the process of breadboarding an Arduino for a project and am using my FTDI Serial cable Adafruit FTDI Cable (tested working on Windows 7). I have also tested the breadboarded Arduino successfully on Win7.

When I plug the FTDI Serial cable into my Linux (Ubuntu 14.04 with Mint Desktop) laptop and the other end to my project (exactly as I did for Windows and it works for Win7), the Tools, Port is grayed out when in Linux.

I have tried running Arduino as root, with no success.

The output of : dmesg | tail is

sudo dmesg | tail
[  729.069015] usb 4-1.2: New USB device strings: Mfr=1, Product=2,     SerialNumber=3
[  729.069019] usb 4-1.2: Product: TTL232R-3V3
[  729.069022] usb 4-1.2: Manufacturer: FTDI
[  729.069024] usb 4-1.2: SerialNumber: FTF50VXW
[  729.487689] usb 4-1.2: USB disconnect, device number 4
[  729.615330] usbcore: registered new interface driver usbserial
[  729.615384] usbcore: registered new interface driver usbserial_generic
[  729.615432] usbserial: USB Serial support registered for generic
[  729.621997] usbcore: registered new interface driver ftdi_sio
[  729.622057] usbserial: USB Serial support registered for FTDI USB Serial Device

When I type "lsusb" into the terminal, there is no difference between when the FTDI is plugged in and not plugged in.
I have tried switching ports with no success.

Any suggestions?

Check if the driver is loaded, in Terminal type:

lsmod | grep  ftdi_sio

If you get no answer then it's not loaded, load it using:

sudo modprobe ftdi_sio

I hope this helps.


How do I make a Servo Stop if it Hits Resistance? I am trying to make a device which will turn a turn key with a servo.

However, I want it to stop turning the turn key if the resistance is too great (meaning it is locked and will not ever turn).

How do I do this? Would I just tell it to turn and then have it turn back after a time (because if it is locked or not it should be done within that time)?

I do not want to damage my servo by having it try to turn something that it can't turn.

I am using an Arduino Uno and the library "Servo.h". The servo being used is a Batan S1123.

You could either:

Use a limit-switch to sense that the servo has completed it move. If it doesn't complete it a reasonable time, return it to its original position. Or,
Measure the motor current by putting a low value resistor inline with the ground side of the motor's power supply. With one of the A/D pins, measure the voltage on the motor side of the resistor, which increases with motor current. You'll need to have figured out how much current the motor draws when operating normally. If the motor stalls, your controller could sense that by seeing that current increase. Pick a value (try 150%, for example) of over-current as an indicator that the motor is stalled, and return it to its original position.

The first way is easier to implement but possibly lets the motor stall while you wait for the expected move time to expire. The second way lets you detect stalling and take action immediately.


RF Remote Clone using NRF905 I have come across the various blogs which talks about cloning RF remote using cheap 434 MHz Tx/Rx and RCSwitch library.

I tried using RF 434 MHz ASK (https://www.sparkfun.com/products/10532) module with arduino, but the range I get it very less , just around 5-6 centimeters. Seems these RF 434 MHz modules are not stable. So I am planning to use now another RF Module which uses NRF905.
Link -
http://www.ebay.com/itm/2pcs-NRF905-wireless-module-PTR8000-wireless-transmission-433-486-915MHz-/270963407796

My query is can I use NFR905 based RF modules which is also 434 Mhz to clone any existing remote working on 434 MHz. Please help

You can connect an external antenna to pin 8 on that module. Just use a piece of wire that is 17.3cm long. But since the range is that bad to start with, probably means it isn't tuned very well. I'd return it, or try fiddling with the pot at the back. Not sure why Sparkfun has these crap transceivers for sale. Transceivers without a crystal are very inaccurate in their frequency.

If you only need to transmit, I'd suggest this products: https://www.sparkfun.com/products/10534
 . Those worked great for me, and are currently switching on the power sockets for my lights when it gets dark enough.


Clear GET params from URL I have a simple GET webform that takes in text. Once that text is submitted the URL permanently displays the text as the parameter. This causes echoing issues when I check the input from the web form; the string I am looking for is always found because the URL is never cleared. I cannot use an HTTP redirect and am looking for a way to do this based upon code.

this is exaclty waht get are supposed to do. Use a POST or use a redirect; a POST is way better as the "back" button of the browser will take care of it


Help with Serial.print() How does the Serial.print() transmit the data? Can you please explain this with respect to TX buffers?

Also, What would happen if i try to output the data that is greater than 64 bytes? How is this transmitted?

And please explain the difference with Serial.write()

Thanks!

Serial.print() feeds the data into the TX buffer one character at a time (through the Print class's inherited .write() function which HardwareSerial implements). If there isn't enough room in the TX buffer for the next character it waits for there to be room available.

Characters are removed one at a time from the TX buffer and sent through the physical UART by the UART's TX interrupt.

To put it in more detail:

When you call Serial.print() it's actually calling Print.print(), because Print is a parent class of the HardwareSerial class.
Print.print() repeatedly calls Print.write() for each character to print.
Print.write() is a pure virtual function (which means it's only got the definition in the Print class and child classes must implement it).
HardwareSerial.write() implements the Print.write() function which takes the character and (with possible blocking while waiting for space) adds it to the TX buffer.
Serial is an instance of the HardwareSerial class.


Getting issues while using SoftwareSerial I am trying to read string send from esp8266 esp01 to Arduino mega. When I use normal Rx and Tx ports, it works properly but when i am initializing new serial port using SoftwareSerial then nothing is being shown on the serial monitor.

Please help me as i have been stuck and trying to solve this for weeks now.
Below are the code for esp8266 and Arduino mega

    Code for ARDUINO MEGA

#include<SoftwareSerial.h>

SoftwareSerial myS(4,5);

String data="true";

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
myS.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(myS.available()){
  data=myS.readString();
  }
  Serial.println(data);
  //Serial.write(data);
  delay(2000);
}

    Code for ESP8266

void setup() {
  Serial.begin(9600);     // Initialize the Serial interface with baud rate of 9600
}

// the loop function runs over and over again forever
void loop() {
  if(Serial.available()>0)    //Checks is there any data in buffer
  {
    Serial.print("We got:");
    Serial.print(char(Serial.read()));  //Read serial data byte and send back to serial monitor
  }
  else
  {
    Serial.println("Hello World..."); //Print Hello word every one second
    delay(1000);                      // Wait for a second
  }
}

Moreover, i have tried read() as well instead of readString(), but it does not work either. I have also tried switching Rx and TX pins meaning connecting Rx->Tx, Tx->Rx and vice versa i.e. Rx->Rx and Tx->Tx, but it does not work in any of the case.
Any help or suggestion will be appreciated.
Thanks

SoftwareSerial only works on a few select GPIO pins on the Mega. Specifically those pins that have PCINT on them.

But that is irrelevant. There is no reason to use SoftwareSerial on a Mega except in exceptional circumstances.  You have four hardware UARTs on the Mega, so there is no call to use SoftwareSerial.  Use the real UART pins and objects:

Serial -> RX(0) / TX(1)
Serial1 -> RX1(19) / TX1(18)
Serial2 -> RX2(17) / TX2(16)
Serial3 -> RX3(15) / TX3(14)

Just replace all references in your code to the SoftwareSerial instance with Serial1 (delete the #include and the object instance constructor) and use TX1 and RX1 to connect your module:

String data="true";

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    Serial1.begin(9600);
}

void loop() {
    // put your main code here, to run repeatedly:
    if(Serial1.available()){
        data=Serial1.readString();
    }
    Serial.println(data);
    //Serial.write(data);
    delay(2000);
}


Everything is ready for project . I have one doubt! I am using transmitter + Arduino *Uno*..and receiver + arduino *nano* will it work? Everything is ready for project except hardware!

I have one doubt!

I am planning to use transmitter of Arduino Uno and receiver of Arduino Nano.  Will it work? Both Uno and Nano obey for same program? (The transceivers used are  Nrf24lO1 pa+lna!)

Yes, it will work, in much the same way that you can send an email from a Mac to a Windows PC. The type of PC doesn't matter as long as they use the same protocol. As you haven't shared any details in that direction, I would say that if you have coded correctly, then it will work.


Arduino not detected On El Capitan Public Beta 6 Since I updated to El Capitan Public Beta, my Arduino Uno doesn't show up in the serial devices list.

The System Information utility shows an Arduino connected on the USB port (as 'Communication Device'), but a serial port does not get created at /dev.

The board works on Windows and the previous versions of El Capitan.

The problem persists on beta 6.

As noted elsewhere, there have been plenty of problems with the CH340 driver and the OSX El Capitan betas, culminating into the driver flat out not working in the latest beta. This is either a bug with OSX or a bug in the driver. I would lean towards this being a bug in the driver, which hasn't been updated since late 2013.

There are other 3rd party drivers that might work on El Capitan. mac-usb-serial.com is the most reliable looking one that I could find, and it does appear to be actively developed. It does cost money, but it is signed (which the mfg. driver isn't) and it has a test utility you can use before purchasing.

The only other options after that are:

Hope that WCH update their driver (don't hold your breath).
Program using an external programmer
Buy an Arduino not using the CH340


Streaming sensor data over UDP using an Arduino Yún - how to do it and how fast could it be? The company where I work wants to do a proof of concept for our new product, a force-sensing platform.

The platform contains four three-axial load cells, so we have 12 channels, which are to be digitized at 2kHz and 16bits. This gives us 2.000 dataframes per second, with 24 bytes of payload each.

Our proposed architecture is as following:

The analog signals from the cells is acquired by a dedicated data-acquisition board;
The digital stream is sent to the ATmega on Yún over SPI;
The data is then relayed to the Atheros over Serial;
Finally, the data is transmitted over UDP (or TCP).

I wonder if it is a sensible way of doing it, with the following questions:

How would one normally use the Ethernet functionality? Can I call a function on the sketch, or do I need to put some program or script in the Linux, calling it from the sketch?
What would be the maximum transmission speed (in bytes per second) from the ATmega side to the Linux side?
What would be the maximum throughput of the Ethernet?

I have calculated 24 bytes * 2000 = 480 bytes per second, or a baud rate of 480 * 8 = 3840bps. Is that right?

I would appreciate any help, it could be just a link to the proper information resources.

The Yun is really two different computers (one AVR and on Linux) connected by a serial link. Basically the AVR is connected to a serial console on the Linux machine, so you can "type" commands into Linux by sending strings out the serial port from the AVR.

The serial link normally comes up at 250,000 buad, so that should not be a bottleneck for your application.

Typically, the AVR will "type" a command to run a Python program on the Linux side (called the Bridge) that will then communicate with AVR code using a high level protocol. Unfortunately, this "bridge" connections tends to be slow and flaky.

But you could do what you want very easily by just pumping netcat commands into the Linux machine from the AVR machine every time you wanted to send a UDP packet out. The overhead would only be a few serial bytes per packet (you'd send "nc -u   \r" where everything but data is likely the same for every packet).

Here is an example of a program that runs on thew AVR and periodically reads some data from temperature sensors connected via 1-Wire, and then runs a "curl" command on the linux console to record  the readings to a server...

https://github.com/bigjosh/SimpleTempLoggerYun/blob/master/Arduino/SimpleTempLoggerYun/SimpleTempLoggerYun.ino

In your case, your replace the 1-Wire reading code with SPI reading code, and replace the "curl" that sends HTTP data command with an "nc" command that would send a UDP packet (using the "-u" parameter).

With this technique, I think you could get something working very very quickly and likely easily meet your data rate requirements.

Note that while this is a great technique for getting a proof-of-concept working quickly, I would not use a setup like this in production. Instead consider something like a BeagleBone Black where you could read the SPI data and send the UDP pack in a single C program that ran as a normal Linux process.


Arduino Nano, Uno and Mega - XBee connection difference I have a simple sketch working on arduino Uno and Nano sending data using an XBee.
However, if I run the project on an Arduino Mega it does not work.

What differences between Uno/Nano and the Mega could be causing issues?

Connection:  I just connect 3.3V->3.3V, Gnd->Gnd, and have tried various ports for DIN and DOUT (normally pins 2/4, but have tried A0/A1, 22/23 etc..).

Sketch: pastebin

Have brought a second Mega in case of hardware faults, but the problem persists.  Have stripped anything which might be tying up a timer.  Am choosing the right board type in the arduino IDE.

Not all arduino Mega pins support 'change interrupts', which is needed for Software Serial.  Only the following can be used for RX:

10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).


ESP8266 shows garbage in serial monitor I have my ESP8266 connected via serial to USB like the image shows:

It worked just fine, however, when I tried flashing Blynk code

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

char auth[] = "YourAuthToken";

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, "ssid", "pass");
}

void loop()
{
  Blynk.run();
}

It started outputting loads of garbage in the serial monitor, while Blynk app said ESP is not connected to network. I've tried since then flashing empty sketches or some other stuff, whatever I do, serial monitor shows loads of junk. I've tried changing modes, I've tried changing baud rates (57600 was default, and AT worked just fine).

Junk example:

  …ÕZªP‚,JHVYº—¡VÕ]J*ÉW¥¡Õ¥Õ-”ªUŠQd®”¡âJ%H
!HiZÊIIRPÖuUPÒ‚BñZT¥ *EUeZB\)*EVjU!\©Š_¥¢”ÅVªqYiUµP”¬ÕPQT°*uH)HZKB*ÕXªuH!HBHBH…µEIâHBH!H©ªqY+hZVB\BH!HÊ*Òµe�qHBHBHŠ*i±…Z¦-hUµPÔ¬ÔPQT°*uH)H-KB*ÕXªuH!HBHBH…µEB\!H!HBVªqY+iZVB\BH!HeVÒZ¢qHBHBHŠ*iQ…Z¦-hUµPÔ¬ÔPQTaYRB\    jHiBHªaYRB\BH!HBVªaYRB\BH!HBVªqY+iZVB\BH!HÊVÒZ¢qHBHBHŠ*i±Õ\V
iUµPÔ¬ÕPQT°*uH)H-JBVªaYRB\BH!H!VªaYR!\BHBH!Vªq©+hZW!\BHBHJ*iµE�âHBH!HŠ*i±…Z¦-hUµPÕ¬ÔPQTaYR!\    %Hi!HÕXªuH!HBHBH…µEIqHBHBH

I think the default baud rate of ESP8266 is 115200.


Arduino Mega - I2C pins (20/21) unreliable Has anybody else noticed that the Arduino Mega pins 20/21 are exceedingly unreliable over long periods of time? It has been the case four times now where I have hooked up no more than 3 I2C devices to these pins and had them fail after approx. 10 days of light use on average.

For example, my team and I had 3 sensors hooked up and were successfully running tests for about two weeks, then right before our launch, I2C stopped working entirely, returning completely incorrect (all zero) data every time.

Again, I have had this issue four separate times in the past, some where pull-up resistors are present, others not.

I seem to be unable to find related information on the web.

Has anyone else noticed this?

The I2C pins on the Arduino Mega 2560 board are 100% reliable, but you have to use them correctly.

The Wire library could halt when something is wrong with the hardware I2C bus. In that case the sketch stops. The Wire library should have timeouts programmed in case something is wrong with the hardware, but sadly it doesn't have timeouts.

Hardware
The hardware I2C bus on the Arduino Mega 2560 board is a 5V I2C bus, because the Arduino Mega 2560 has 10k pullup resistors to 5V for SDA and SCL.
The wires for I2C can only be short. Long wires will not work.
The worst thing is when SDA and SCL are in a flat ribbon cable next to each other. The crosstalk between SDA and SCL will make the I2C very unreliable.
Because it is a 5V I2C bus, you may not connect 3.3V sensors to that 5V I2C bus. In that case you need a level converter.
The total value of all pullup resistors in parallel should not be too high (more sensitive for electrical noise, longer wires are not possible) and not be too low. The I2C specificiation is maximum 3 mA pulling of down current to get the signal low.
Everything that is connected to the I2C bus must have proper power supply. If one sensor has a power supply that fails, then that sensor will probably pull down the SCL and SDA signals.
A test with a breadboard might fail, due to bad contacts of the breadboard.

Software
The Arduino Wire library is often used in a wrong way.
If one of the sensors is an Arduino board as a I2C slave, then the code for the slave must be done right, because there are many ways to do it wrong.
You could check the return value of every Wire.endTransmissions for an error, and check every return value of Wire.requestFrom for the amount of data that is received.

If you tell us everything about the sensors, the wires (with photos), the logic level converters, the sketch, and so on, then we can tell you what the problem is.


ESP8266 stops working when I use 2x static const char(PROGMEM) *Sdk version: 2.2.2-dev(5ab15d1)
*Core Version: 2_6_1

This is the error returned:

Exception 3: LoadStoreError: Processor internal physical address or data error during load or store PC: 0x4000bf64 EXCVADDR: 0x4024e963
Decoding stack results
0x4020175d: HTML1(String) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266/WString.h line 128
0x40238c26: umm_info(void*, int) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\umm_malloc/umm_info.c line 164
0x40100278: millis() at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\core_esp8266_wiring.cpp line 188
0x40238c26: umm_info(void*, int) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\umm_malloc/umm_info.c line 164
0x4020af74: String::copy(char const*, unsigned int) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\WString.cpp line 214
0x40201a3c:

Code:

static const char HTML1[] PROGMEM = R"=====(
<!DOCTYPE HTML><html><head>
<meta charset='utf-8' name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0'>
)=====";

static const char HTML2[] PROGMEM = R"=====(
<button type='button' onclick='sendData(2)'>Test2</button>
)=====";

String html_return = HTML1;
html_return += "<button type='button' onclick='sendData(1)'>Test</button>";
Serial.println("Before Second Const Char");
html_return += HTML2; //<< ESP stops working here

See Guide to PROGMEM on ESP8266 and Arduino IDE.

Since you put your char array into PROGMEM, special functions must be used to load it from flash into RAM; so to load it into a String object, the FlashHelper class must be used. You can simply use the macro FPSTR(progmem_ptr).

#include <Arduino.h>

void setup() {
    Serial.begin(115200);
    Serial.println("\nStart firmware");

    static const char HTML1[] PROGMEM = R"=====(
    <!DOCTYPE HTML><html><head>
    <meta charset='utf-8' name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0'>
    )=====";

    static const char HTML2[] PROGMEM = R"=====(
    <button type='button' onclick='sendData(2)'>Test2</button>
    )=====";

    String html_return = HTML1;
    html_return += "<button type='button' onclick='sendData(1)'>Test</button>";
    Serial.println("Before Second Const Char");
    //html_return += HTML2; //crashes
    html_return += FPSTR(HTML2); //works
    Serial.println("Result");
    Serial.println(html_return);
}

void loop() {

}

Outputs

Start firmware
Before Second Const Char
Result

        <!DOCTYPE HTML><html><head>
        <meta charset='utf-8' name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0'>
        <button type='button' onclick='sendData(1)'>Test</button>
        <button type='button' onclick='sendData(2)'>Test2</button>


What are the basics in writing a program in Arduino? I am an undergrad in ICE. I was searching for ideas to do mini projects on and found this Arduino boards and programs. So actually what are the basics to develop our own gadgets? Any guidelines...?

There are some excellent books available as well as videos and articles on the Internet which will walk you through basic projects.  The most common method of programming is to use the free Arduino IDE which will talk to the board from your Mac or PC.  You can run the board straight from the USB port's power, or from an external source if you need it to be portable.

The programming language is very similar to C.  The program structure is basically a setup portion and then a continuous main loop that runs until the board is powered off.

If you want to experiment without actually purchasing one, there are some emulators available which will let you build entire project on a virtual breadboard before buying any actual components.  Fritzing is a great board planner that you can install, or if you would rather, you can use 123D Circuits from your web browser which will let you edit and simulated the circuits.

Basic knowledge of electrical circuits will be helpful for getting started, and is a great asset when designing larger projects.