How to connect MPU6050 to arduino using only digital pins I am relatively new to Arduino and microchips, but I am good at electronics. I want to connect MPU6050 accelerometer+gyroscope module to Arduino. I searched on the internet and everywhere it is said to connect the SCL and SDA pins to two analog pins of the Arduino. As far as I know, the MPU6050 is a digital sensor, so why 2 analog pins are required for the sensor?

Also, is there any way to connect the sensor with only digital pins? because I need the analog pins for some other purpose.

The MPU6050 communicates over I2C. I2C uses clock line SCL and data line SDA. I2C pins on Uno are pins A4 and A5.
This is because the ATmega328p MCU used on Uno has the I2C peripheral on the same pins. It has nothing to do with the DAC function of the pins.

Alternatively MPU6050 can communicate over SPI. This are pins 11, 12, 13 on Uno and one more pin for CS. Pin 10 must be output while ATmega328p is SPI master so it is recommended to use it as CS for the SPI slave device.   EDIT Sorry, only MPU6000 has SPI.


Clear existing array when getting new serial command I'm starting to build my first Arduino project but I'm running into some problems with serial communication.

I get serial data from the console and store it in a char array called "data".

Then, when I send a new console message to the Arduino, I want it to clear the existing "data" array and store only the new data in that array.

I don't understand exactly what's wrong with my code: I believe those nested Serial.available() statements don't work but I have no ideas on how to fix the code.

Data is correctly stored by the Arduino but it concatenates the newer string to the old one.

int count = 0;
char data[30];
boolean dataComplete = false;

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

void loop() {

  if (Serial.available() > 0){
    if (dataComplete == true){
    Serial.println("There is data already, clearing...");
    char data[30];
    dataComplete = false;
  }
    if (dataComplete == false){
      Serial.println("New command, collecting...");
      while (Serial.available()>0){
        char character = Serial.read();
        data[count] = character;
        count++;
      }
     dataComplete = true;
    }
  }
  Serial.print("Command received: ");
  Serial.println(data);
  delay(1000);
}

Thanks in advance!

To clear an array you would do:

for( int i = 0; i < sizeof(data);  ++i )
   data[i] = (char)0;

or

memset(data, 0, sizeof(data));

, which does the same thing using a library function.

However, because strings of characters (not referring to 'String' objects here) are terminated by a zero byte, only the first byte needs to be zeroed:

data[0] = (char)0;

will do it.


100khz square wave with 50% duty cycle How to generate 100khz square wave with 50% duty cycle using arduino uno
The following code was tried but did not give appropriate output

void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delayMicroseconds(5); // wait for 5 micro seconds, 100khz frequency with  50%
                           // duty cycle
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delayMicroseconds(5);              // wait for 5 micro seconds
}

The problem with your program is that it does not loop fast enough. Each
call to delayMicroseconds() should take roughly the requested time to
execute, but the CPU also needs time to execute the rest of your code,
including the time needed to return from loop() and call it again.
The period of the signal ends up being considerably longer than the
desired 10 µs.

The simplest software-only approach would be to get rid of the delay
using the technique described in the Blink Without Delay Arduino
tutorial. With one twist: instead of

// save the last time you blinked the LED
previousMillis = currentMillis;

you would use

// save the last time you should have blinked the LED
previousMillis += interval;

This way the small timing errors do not add up: you get, on average
the correct period. Oh, and obviously, you track time in microseconds,
not milliseconds:

const uint16_t TOGGLE_TIME = 5;  // toggle pin every 5 us

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

void loop() {
    static uint16_t last_toggle;
    static uint8_t pin_state = LOW;

    if ((uint16_t) micros() - last_toggle >= TOGGLE_TIME) {
        pin_state = !pin_state;       // invert pin state
        digitalWrite(13, pin_state);
        last_toggle += TOGGLE_TIME;
    }
}

This may somehow work if you have a fast enough Arduino, maybe a Due or
a Zero. If you have an AVR-based board (like the Uno and actually most
Arduinos), you will not get anything faster than ≈ 50 kHz with
this. This is because digitalWrite() is sooo slooow, it cannot cope
with your 100 kHz. You can improve things by using direct port
access[] instead of digitalWrite():

void loop() {
    static uint16_t last_toggle;

    if ((uint16_t) micros() - last_toggle >= TOGGLE_TIME) {
        PINB = _BV(PB5);             // invert pin state
        last_toggle += TOGGLE_TIME;
    }
}

Now you have roughly the requested frequency, but with some terrible
jitter: testing on my Uno I could see each level being held for
slightly less than 5 µs. Then, from time to time, one level is
held for ≈ 9 µs. Things could still be made faster by wrapping
the if inside an infinite loop, instead of relying on the Arduino core
to repeatedly call loop():

void loop() {
    uint16_t last_toggle = 0;

    for (;;) {  // infinite loop
        if ((uint16_t) micros() - last_toggle >= TOGGLE_TIME) {
            PINB = _BV(PB5);             // invert pin state
            last_toggle += TOGGLE_TIME;
        }
    }
}

And now the signal looks still worse: with the program running faster,
levels are held most of the time for only 3.5 µs, and then one out
of every ≈ 4 levels is held for about 9 µs. The average
frequency is probably right, but the jitter is absolutely awful, which
is likely due to the 4 µs resolution of micros() noted by user
Talk2.

The conclusion from these tests is: your only hope to get a somewhat
clean signal at this frequency is to generate it in hardware, not in
software. Choose one of the timers and have it generate the signal you
want. I would avoid timer 0, as it is needed by the Arduino timing
functions (delay(), millis()...). Here is how it can be done with
timer 2:

void setup() {
    // The output will be on digital 3 = PD3 = OC2B.
    pinMode(3, OUTPUT);

    // Configure timer 2 for PWM @ 10 kHz on OC2B.
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // mode 7: fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(WGM22)   // ditto
           | _BV(CS21);   // clock @ F_CPU / 8
    OCR2A  = 19;          // period = (19 + 1) * 8 CPU cycles
    OCR2B  = 9;           // HIGH for (9 + 1) * 8 CPU cycles
}

void loop() {
    // Nothing to do here, the signal is generated in hardware.
}

And now you have a perfectly clean 10 kHz square wave, while your
program is free to do other stuff at the same time. Notice that the
output is now on pin 3: the pin choice is limited when using the
hardware-based approach. Notice also that you loose the PWM capability
on pin 11, since it depends on timer 2.


Use ISRs inside a library more elegantly At the moment I try to make a library which uses attachInterrupt(?,?,RISING) to read a sensor. The article of Nick Gammon on Calling an ISR from a class helped me a lot, but his "Glue routines" get pretty ugly with more than 30 potential Interrupt Pins on the ESP32, which all need their own static void. Has anyone got a more elegant idea how to do this "Gluing"?

As a matter of efficiency, I would favor chrisl’s advise to use the
platform's low-level interrupts if at all possible. This, however, comes
at the cost of portability: you would need an implementation specialized
for each platform you want to support. If you don't want to or cannot
maintain all this platform-specific code, attachInterrupt() may be a
reasonable option.

Then, you will absolutely need all those glue routines: since the
interrupt system calls your handlers with no parameters, you will not be
able to share handlers between interrupts, and you end up with as many
handlers as interrupts you are going to use.

There is, however, an elegant way of creating all these specialized
functions without writing them explicitly: you can ask the compiler to
write them for you on the basis of a template you provide.

Below is a version of Nick Gammon's example code modified to use a
template class. Note that you do not necessarily need a class to use
templates: you could use template functions as interrupt handlers if
that is appropriate for your use case.

template <uint8_t pin>
class myClass
{
    static volatile bool switchChanged;

public:
    static void begin()
    {
        pinMode(pin, INPUT_PULLUP);
        attachInterrupt(digitalPinToInterrupt(pin),
                        switchPressed, FALLING);
    }

    static void switchPressed()
    {
        switchChanged = true;
    }
};

template <uint8_t pin>
volatile bool myClass<pin>::switchChanged;

myClass<2> foo;
myClass<3> bar;

void setup()
{
    foo.begin();
    bar.begin();
}

void loop(){}

Note also that myClass<2> and myClass<3> are two different classes:
you actually have a different class for each pin. This means that
foo::switchChanged and bar::switchChanged are two different class
members even though both are static. Since you should (in principle)
have at most one instance of each pin-specific class, you can make
everything within the class static.

The main caveat of this method is that the pin numbers have now to be
compile-time constants. The great advantage is that you will have a
class created for each interrupt that is actually used: no need for an
array of 32 instances on an ESP32 if only a handful of interrupt pins
are going to be actually used.


How to add extra USB port to Arduino Nano? I'm trying to use V-USB library to emulate a keyboard using Arduino Nano but because of precaution, I don't want to use it's built-in USB port.

My idea is to add another USB port so I cant power my device with the new USB port and use free digital pins as input/output of the new USB serial port in V-USB project.

What circuit I should use and how to add extra USB port to Arduino Nano.

USB is deceptively simple.  The underlying protocol is very complex. So a complete answer to your question requires some USB background.

USB is divided into 2 types.  USB Hosts and USB Devices. We are not concerned about USB Hosts here.  USB Devices only need to know about their own functions / features.  If they are a serial port device, like the FTDI chip on the Arduino Nano, they only need to "speak" basic USB protocol and the serial CDC USB protocol.  If the USB Device was a keyboard, it only needs to know the basic USB protocol and the HID USB protocol.

In order to offer up a USB port the Arduino Nano uses an FTDI chip FT232RL.  This chip supports a Serial Port USB Device.  It does not appear to support HID USB Devices.  So your decision to use V-USB is necessary not because of power but because the Arduino Nano's built in USB port supports a protocol other than USB CDC.

  What circuit I should use and how to add extra USB port to Arduino
  Nano.

The circuit suggested is on the V-USB web page appears to contain the necessary information:

Of course you will have to do some research into V-USB software to see which are the appropriate pins to use on your Arduino Nano.


Timer function without the use of a library Trying to do my own timer function. I was wondering if there is any other ways to make my code more efficient without the use of a library. I noticed if I only use one timer function, I wont have multiple instances of the timer. My current code works though.

unsigned long previousMillis1 = 0;
unsigned long currentMillis1 = millis();
unsigned long previousMillis2 = 0;
unsigned long currentMillis2 = millis();
unsigned long previousMillis3 = 0;
unsigned long currentMillis3 = millis();

bool timer1(int preset){
  unsigned long currentMillis1 = millis();

  if(currentMillis1 - previousMillis1 >= preset ){
    previousMillis1 = currentMillis1;
    return true;
  }
  else{
    return false;
  }
}

bool timer2(int preset){
  unsigned long currentMillis2 = millis();

  if(currentMillis2 - previousMillis2 >= preset ){
    previousMillis2 = currentMillis2;
    return true;
  }
  else{
    return false;
  }
}

bool timer3(int preset){
  unsigned long currentMillis3 = millis();

  if(currentMillis3 - previousMillis3 >= preset ){
    previousMillis3 = currentMillis3;
    return true;
  }
  else{
    return false;
  }
}

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

void loop() {
  if(timer1(1000)){Serial.println(1);}
  if(timer2(2000)){Serial.println(2);}
  if(timer3(3000)){Serial.println(3);}
}

Your code is not bad in terms of efficiency. You have, however,
duplicated code, which is bad in terms of program size, but also makes
the program harder to read and to maintain. A good rule for programmers
is “do not repeat yourself”. Then, when you find yourself writing almost
identical functions, you should try to find a way to merge them into a
single function.

Here it is easy: the only difference between your timer functions is
that they use a different previousMillis variable. Also, the name of
the currentMillis variable is different, but it being a local
variable, this difference is irrelevant. Then, to merge them into a
single function, you only have to give to this function a reference to
the relevant PreviousMillis.

bool timer(unsigned long &last_time, unsigned long period)
{
  unsigned long now = millis();
  if (now - last_time >= period) {
    last_time = now;
    return true;
  }
  return false;
}

And you use it like this:

void loop() {
  static unsigned long previousMillis1;
  static unsigned long previousMillis2;
  static unsigned long previousMillis3;

  if (timer(previousMillis1, 1000)) Serial.println(1);
  if (timer(previousMillis2, 2000)) Serial.println(2);
  if (timer(previousMillis3, 3000)) Serial.println(3);
}

I took the liberty of making all the previousMillis local to loop(),
since they are only used there. Making them static means their values
are remembered between call to loop(), much like global variables.

In plain C you would use pointers instead of references. It is basically
the same, except that with pointers you are explicitly manipulating
addresses, while this is implicit with references:

bool timer(unsigned long *last_time, unsigned long period)
{
  unsigned long now = millis();
  if (now - *last_time >= period) {
    *last_time = now;
    return true;
  }
  return false;
}

void loop() {
  /* [...] */
  if (timer(&previousMillis1, 1000)) Serial.println(1);
  /* [...] */
}

The next step in code modularity would be to wrap this timer function,
together with the associated data (last_time and period), inside a
class:

class Timer
{
public:

  Timer(unsigned long _period)
  : period(_period), last_time(millis()) {}

  bool shouldRun() {
    unsigned long now = millis();
    if (now - last_time >= period) {
      last_time = now;
      return true;
    }
    return false;
  }

private:
  unsigned long period;
  unsigned long last_time;
};

Then, you would use it like this:

Timer timer1(1000);    // period = 1000 ms
Timer timer2(2000);    // period = 2000 ms
Timer timer3(3000);    // period = 3000 ms

void loop() {
  if (timer1.shouldRun()) Serial.println(1);
  if (timer2.shouldRun()) Serial.println(2);
  if (timer3.shouldRun()) Serial.println(3);
}


Strange artifact in writing to serial while executing loop Hope you can see this.

https://gist.github.com/DevilWAH/60ad144d2858f53845ac2e80f84bb070

The main file in this is "morse-led-rfid" which is taking reading data of an RFID tag and then displaying the text as Morse code on to a APA102 / Dotstar LED strip.

The issue is when the function updatestrip(tempbuffer[i]); is called.

Serial.println(F("\n**Start Reading**\n"));

  for (uint8_t i = 1; i < 15; i++)
  {
   if (i != 3 && i!= 7 && i != 11 && i != 15 ) // Skip the non data blocks
    {
     readblock (i, key);
       for (uint8_t i = 0; i < 16; i++)
         {
      updatestrip(tempbuffer[i]);
      Serial.write(tempbuffer[i]);
        }
    }
  }

This is what I am calling to scroll the LED strip and write the letter in morse. if in the code snip it above i comment out "updatestrip...." then i get the txt from the RFID tag printer to serial as i would expect.

as a soon as i un comment it, the strip displays the morse code but the serial output gets garbled, it misses letters, prints reversed "?'s" and repeats its self?

Good output = "My Bunny is the best"
Bad output = "?Bunny is the ?t" (question marks reversed)

Further investigation i found if i leave it uncommented but go all the way to the bottom of the "more-strip" sheet and comment out the "else statement in the shiftLED function" the serial again displays correctly, but of course the led don't :)

void shiftLED() // shift all LED up 1
  {
    for(uint16_t i = ledCount; i > 0; i--)
    {

      if ((colors[i - 1].red == 0 ) && (colors[i - 1].green == 0 ))
       {
          colors[i] = cblack;
        }
      else if (i > 19 && i < 40)
      {
        colors[i] = cred;
      }
     // else
     // {
     //   colors[i] = cgreen;
     // }
     // }

 }

Can any one suggest why the else statement a few function down is affecting the "serial.write(tempbuffer[i])" in the main loop?

In your code colors is declared as

rgb_color colors[ledCount];

This means that the very first iteration of this cycle in shiftLED

for (uint16_t i = ledCount; i > 0; i--)
{
  // access colors[i]
}

will access ledCount[ledCount] which is obviously out of bounds (and will actually write into that location!). The behavior is undefined after that.

Using unsigned types for "backward" array iteration requires a bit of skill. The common idioms are

for (uint16_t i = ledCount; i > 0;)
{
  --i; // do this ASAP

  // access colors[i]
}

or

for (uint16_t i = ledCount; i-- > 0;)
{
  // access colors[i]
}

or

// Careful: this technique is not usable with unsigned types
// narrower than `unsigned int`
for (uint16_t i = ledCount - 1; i != -1; --i)
{
  // access colors[i]
}

This is assuming that you want to iterate over the whole array: from [ledCount - 1] all the way back to [0].

But if you intended to iterate back to [1] and stop short of [0] (which is apparently the case), then a simple fix for your cycle would be

for (uint16_t i = ledCount - 1; i > 0; i--)
{
  // access colors[i]
}

I.e. simply start from ledCount - 1, not from ledCount.


What is arduino_debug.exe for IDE 1.5.6r2? After installing IDE 1.5.6r2, there are two .exe files, arduino_debug.exe and arduino.exe (which is same name as previously installed IDE 1.0.5).

Windows binaries can either be Window or Console applications. A Window application can NOT produce text output. Text output is the easiest way to gather error messages related to bugs.

Hence, arduino_debug.exe should be used by Windows users that have found a bug in the Arduino IDE and wish to contribute submitting an issue on github.


help compiling code for flora project I'm working on the Adafruit Firewalker shoes.

I can't make my code compile to test my flora project.

This is my error message:

Arduino: 1.6.7 (Windows 10), Board: "Adafruit Flora"

C:\Users\Devi\Documents\Arduino\test_2\test_2.ino\test_2.ino.ino:1:29: fatal error: Adafruit_NeoPixel: No such file or directory

 #include <Adafruit_NeoPixel>

                             ^

compilation terminated.

exit status 1
Error compiling.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

https://learn.adafruit.com/firewalker-led-sneakers/test-circuit

    #include <Adafruit_NeoPixel.h>

const int analogInPin = A9;  // Analog input pin that the potentiometer is attached to
Adafruit_NeoPixel strip = Adafruit_NeoPixel(10, 6, NEO_GRB + NEO_KHZ800);
int sensorValue = 0;        // value read from the pot

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
 pinMode(9, INPUT_PULLUP);
   strip.begin();
  strip.show(); // Initialize all pixels to 'off'

}

void loop() {
  // read the analog in value:
  sensorValue = analogRead(analogInPin);
  // print the results to the serial monitor:
  Serial.print("sensor = " );
  Serial.println(sensorValue);

if (sensorValue < 100){
  Serial.println("leds triggered");
colorWipe(strip.Color(255, 0, 0), 25);
colorWipe(strip.Color(0, 0, 0), 25);
}

}

void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
  }
}

I had the same problem, you just have to download the Adafruit Neo Pixel library:


Can't burn arduino bootloader to atmega8a with usbasp I want to burn the arduino bootloader with arduino IDE, but I cant get it done. And here  is my circuit:
I have marked the way I connect the ISP port and the chip.

I choose Arduino NG/older as the board and Atmega8 as the processor, but when I start to burn the bootloader to the chip the LED on the usbasp just blink once and an error was given:

Arduino:1.6.5 Hourly Build 2015/05/15 06:16 (Windows 7), 板："Arduino NG or older, ATmega8"

avrdude: warning: cannot set sck period. please check for usbasp firmware update.

avrdude: error: programm enable: target doesn't answer. 1

烧录引导程序出错。

avrdude: initialization failed, rc=-1

         Double check connections and try again, or use -F to override

         this check.

What should go wrong? I have check the connection many times and replace a chip as well, and I even add a 12M crystal(with 22pF caps) but things still keep the same.

EDIT

I do the flowing things as advise:

short the jp3 jumper of the usbasp to make a slow commiuncation. And remove the crystal.
I just found the way I connect the isp port might be wrong. so I changed it as flowing

And my actually circuit is like this:

But got no luck, things still the same :-(

Did you set the SLOW SCK jumper on the USBasp Programmer? Completely new ATMegas use the internal RC-Oscillator at a frequency of 8MHz, but the divide clock by 8 fuse is set too. That means that (before burning the fuses) the AVR is running at a clock frequency of 1MHz and the standard SCK clockrate of the USBasp is too high for this clock frequency. Therefore, you need to set the SLOW SCK jumper to get a lower SCK clockrate.


Why do my Hall sensor readings change when I write them to the serial port? I have a small project where I connected a Hall sensor (see picture) to an Arduino Mega. The blue wire is connected to pin 45, the red wire to +5V, and the black wire to GND.

At the beginning I initialize the pin used to read the sensor as follows.
#define HALL_PIN 45

void setup()
{
  pinMode(HALL_PIN, INPUT);
}

I have written a function to read out the sensor. While there is no magnet nearby, the sensor returns HIGH. If a magnet approaches in the correct orientation, the sensor returns LOW. The function should return true if a magnet is nearby, i.e. if the read value is LOW.
I have noticed that my program logic sometimes does not work reliably after seemingly irrelevant changes to the code. After commenting out more and more code to narrow down the problem, I came across the following discovery.
Implementation 1:
In the first implementation, I initially read out the value of the Hall sensor. Next, I send the value to the serial port. The serial monitor in the Arduino IDE outputs the number 1 (HIGH). This is the expected behavior as during testing there is no magnet nearby. Based on the subsequent program behavior I can confirm that the function returns false. I can let the Arduino run for minutes and the behavior remains stable.
bool readHallSensor()
{
  int s = digitalRead(HALL_PIN);

  Serial.println(s); // The serial monitor outputs 1 (HIGH)

  return s == LOW; // Returns false
}

Implementation 2:
With the second implementation I do not write the read value to the serial port. As expected, the serial monitor in the Arduino IDE remains empty. The function, however, now returns true. Apart from commenting out the marked line and flashing the sketch to the Arduino, I did not make any changes (again no magnet nearby). Also in this case I can let the Arduino run for minutes and the behavior is stable.
bool readHallSensor()
{
  int s = digitalRead(HALL_PIN);

  // Serial.println(s); // No output to the serial monitor

  return s == LOW; // Returns true
}

My first suspicion was that the delay caused by writing to the serial port is what makes the difference. I asked an electrical engineer whether Hall sensors might need short breaks between successive readings. He denied my assumption, and indeed, if I simply insert a delay(300); after reading the value (without writing to the serial port) the behavior does not change and is identical to implementation 2.
I can switch back and forth between the two implementations and flash them to the Arduino as many times as I like. The behavior is always as described above for both cases. I cannot make any sense of this, as the behavior seems to lack any (programming) logic. Has anyone ever made similar observations and can give me a hint what might cause this? Thank you in advance.

I haven't found the problem yet, but I have come a step closer. The issue has reappeared in a similar project on the same Arduino. I use a new Hall sensor with pull-up, which is read out wrong again under certain circumstances (always read out as LOW, no matter if a magnet is nearby). The problem seems to occur only when I use a certain pin. The pin in question on my Arduino Mega this time is pin 37. If I connect the Hall sensor to another pin (I have tested 34 and 36), it works fine. If I connect a previously working Hall sensor to pin 37, it will not work anymore (always evaluated as LOW). The only explanations that make sense to me at the moment are that either the Arduino Mega is damaged or that there are side effects, maybe caused by external libraries using certain pins without my knowledge and incorrectly initializing them.

The 3144 requires a pull-up resistor. It only sinks when a magnet is present. It doesn't source, so the pin is floating if no magnet is present.
You can use the internal pull-up resistor by using pinMode(HALL_PIN, INPUT_PULLUP);


How do string pointers work in Arduino? To the best of my understanding, when I declare

String s = "This is a string.";

what happens is that space is allocated on the stack for a pointer which points to some String object which internally contains a char array. My confusion stems from the fact that this pointer seems(I could be wrong) to behave differently than any other type of pointer. For example, if I write

int a = 1;
int* x = &a;
int* y = x;

what happens is that the pointer saved in y now points to the same location in memory as the pointer saved at x. So if I write

String s1 = "This is a string.";
String s2 = "Hello World!";
s1 = s2;

does the pointer saved at s1 now point to the same memory location as s2? Or does s1 copy the char array from s2 into its own separate memory? Further, If I write

String s1 = "This is a string.";
s1 = "Hello World!";

does s1 now point to whatever arbitrary memory location was created for the string literal "Hello World!"? Will this memory location be freed later, or is some sort of smart garbage collector in place which knows that I am using that memory in the heap? Finally, should I never assign a string declared on the stack to a global variable, as this will be referencing a memory location which will be freed soon?

Thank you in advance for your help!

String is not a simple type like an int or a char. It is a class with many member functions and, more importantly, operators.  When you create the object it allocates room for that object either on the stack (for a local variable) or in the global data area if it's a global variable. However that object doesn't contain the memory used to store the actual string data - it only has a pointer. The memory for the string data is allocated on the heap using malloc() and realloc().

Assigning string data to the String object is done through the = operator defined in the class, of which there are a number of overloaded varieties:

String & String::operator = (const String &rhs)
{
    if (this == &rhs) return *this;

    if (rhs.buffer) copy(rhs.buffer, rhs.len);
    else invalidate();

    return *this;
}

#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
String & String::operator = (String &&rval)
{
    if (this != &rval) move(rval);
    return *this;
}

String & String::operator = (StringSumHelper &&rval)
{
    if (this != &rval) move(rval);
    return *this;
}
#endif

String & String::operator = (const char *cstr)
{
    if (cstr) copy(cstr, strlen(cstr));
    else invalidate();

    return *this;
}

String & String::operator = (const __FlashStringHelper *pstr)
{
    if (pstr) copy(pstr, strlen_P((PGM_P)pstr));
    else invalidate();

    return *this;
}

They all, ultimately, call the copy() or move() functions which copy the data from the source into the memory allocated on the heap (increasing the allocation if needed).

Using:

String s1 = "Foo";
String s2 = s1;

s1 has memory allocated on the heap, then Foo\0 copied into it.  s2 then also has memory allocated on the heap, and the data from s1 is copied into it. So you have two separate objects with separate memory allocated for their content.  So then doing:

s2 += "bar";

you end up with:

s1: "Foo\0"
s2: "Foobar\0"

Since it's an object that's allocated on the stack (or in global space) and not a pointer to the object you can get a pointer to it like with an int:

String s1 = "Foo";
String *s2 = &s1;
(*s2) += "bar";

Which gives you just one object and one memory space, but two names for it, and the result is:

s1: "Foobar\0"
s2: "Foobar\0"

This is why it's important to use either pointers or references when passing String objects as parameters to functions, and the constant allocation and reallocation on the heap why String objects are frowned upon in microcontrollers with very limited RAM.


MP3 File through ARDUINO Hey question is that it is possible to play MP3 file in arduino without changing it into .wav file if possible ,then your suggestions are welcome
Thanks

This little device is really good and easy to set up.
https://www.dfrobot.com/product-1121.html

You can use a pin and set it to ground with a resistor between to change songs if you don't need something fancy.


How to upload a sketch via Arduino Nano I have two Nano boards, but the first one seems the CH340 chipset was burn. :( ,

Nano v3, CH340 chipset but unable to identify after connect to my Mac using USB
Nano v3, FTDI chipset and in good condition
USB to Serial module, using FTDI chipset

I am trying to upload a sketch via a USB-to-Serial module OR another Nano board (or UNO board v3) to my CH340 Nano Board.

Question:

How to wire them up?
Is it need upload a "Arduino as ISP" first?
step-by-step tutorial or website talking about this ??

I presume you have boot loader on your Nano, so you can use your USB to serial, just wire (D0)TX->RX(USB), (D1)RX->TX(USB), GND-GND and supply power to the target Nano. You will need to reboot Nano just before the uploading the code. Uploading is same as usual.

Using other Arduino as ISP needs more wires as well as 2nd Arduino, so i would use above method.


Issue with HC-SR505 sensor I have been using a HC-SR501 PIR module with my Arduino Mega and it was tracking presence pretty well.

Because of cost constraints, I decided to go with HC-SR505 sensor - bought a bunch of them. The performance is very bad. It almost seems like it is giving random HIGH and LOW values. Out of the 20 odd sensors I bought, may be one or two are fairly ok - others are all behaving weird. Have someone experienced this kind of behavior with HC-SR505?

Are they highly sensitive to noise in the power supply - is there any workaround to mitigate the effect? Help?

Code:

const int buttonPin = 4;

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

   pinMode(buttonPin, INPUT);
 }
 void loop()
 {
    if (digitalRead(buttonPin) == HIGH)
    {

      Serial.println("Presence Detected");
    }
    else {

      Serial.println("No Presence Detected");
    }

 delay(2000);

 }

You asked if anyone else has experienced this behavior, and from the documentation I can find the answer must be yes.

The 505 holds the HIGH output for a certain amount of time.  None of the documentation I can find on it specifies the amount of time.  So it is very possible that you are operating right near that limit.  If their quality control is not perfect, some might work correctly and some might not.

In other words, I believe the problem is that you are not allowing for the built-in time delay in the SR505.

That is the main difference between the 501 and the 505.  On the 501 it is adjustable in both sensitivity and time delay.  With the 505 those values are preset.

As a workaround, you can try increasing your delay upwards from 2000ms until you find the right value that will work consistently with your batch of them.

The sensitivity cannot be adjusted, either, but this can be an advantage if you are trying to cover a smaller area than you would try with the 501.  They both have the same 90-100 degree width of view, but the 505 is made for shorter range like a doorway, as opposed to the 501 which can cover an entire room.


build simple IR sensor with 220 ohm and 1000 ohm resistors I am brand new to the arduino board and I am trying to build a simple IR proximity sensor. I bought a handful of emitters and detectors from amazon here:

https://www.amazon.com/gp/product/B01HGIQ8NG/ref=oh_aui_detailpage_o02_s00?ie=UTF8&psc=1

I am about to pull my hair out and shoot my board with a 12 gauge shot gun if I don't figure this out soon. Can someone point me to a good SIMPLE tutorial that uses ONE emitter and ONE detector and ONE LED. All i can find are a bunch of complex circuits with multiple sets of sensors or a buzzer or whatever else and anything that is as simple as that has no information on schematic or code. Can someone please post a tutorial link?

You could always start out attempting a simple IR detector circuit.

Google Arduino IR detector brings up several tutorials, such as this one from the Instructables website

You would have to change the buzzer in tutorial for an LED and resistor in series.


Some Blocks of Code gets stuck in a loop, I do not know why The code below Gets stuck at function "Led Off?" & "Check button".
I'm using Blockyduino editor.
The check button code was intended as a toggle switch for the lights. When I deleted "Led Off?" and "Turn off All LED", the code did not get stuck.

int Button_Status;

// Toggle Code for the button.
void Check_Button() {
  Serial.println("Check button Activated");
  if (Button_Status == 1) {
    if (digitalRead(13)) {
      Button_Status = 0;
    }
  }
  if (Button_Status == 0) {
    if (digitalRead(13)) {
      Button_Status = 1;
    }
  }
  LED_OFF_();
}

void Left_Animation() {
  Check_Button();
  digitalWrite(2, HIGH);
  digitalWrite(3, HIGH);
  Check_Button();
  delay(1000);
  digitalWrite(4, HIGH);
  digitalWrite(5, HIGH);
  Check_Button();
  delay(500);
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  Check_Button();
  delay(300);
  digitalWrite(4, LOW);
  digitalWrite(5, LOW);
  Serial.println("Finshed Left cycle");
}

void Right_Animation() {
  Check_Button();
  digitalWrite(8, HIGH);
  digitalWrite(9, HIGH);
  Check_Button();
  delay(1000);
  digitalWrite(10, HIGH);
  digitalWrite(11, HIGH);
  Check_Button();
  delay(500);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  Check_Button();
  delay(300);
  digitalWrite(10, LOW);
  digitalWrite(11, LOW);
  Serial.println("Finished Right cycle");
}

// Main Loop Core
void Main_Loop() {
  while (Button_Status == 1) {
    Left_Animation();
    Right_Animation();
    Serial.println("Finshed Main Loop 1111");
  }
  while (Button_Status == 0) {
    Check_Button();
    Serial.println("Finished Main Loop 2222");
  }
}

// Checks if button toggle variable is off.
void LED_OFF_() {
  Serial.println("LED off? Activated");
  if (Button_Status == 0) {
    Turn_Off_All_LED();
  }
  Main_Loop();
}

// Turns off all LED
void Turn_Off_All_LED() {
  Serial.println("LED Turn off Activated");
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(4, LOW);
  digitalWrite(5, LOW);
  digitalWrite(6, LOW);
  digitalWrite(7, LOW);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  digitalWrite(10, LOW);
  digitalWrite(11, LOW);
  Main_Loop();
}

void setup()
{
  Serial.begin(9600);
  pinMode(13, INPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
}

void loop()
{
  // Start
  Button_Status = 1;
  Main_Loop();
}

You have a problem with infinite recursion in this program: loop()
calls Main_Loop(), which calls Left_Animation(), which calls
Check_Button(), which calls LED_OFF_(), which calls Main_Loop(),
which calls Left_Animation(), which calls Check_Button(), which
calls LED_OFF_(), which calls Main_Loop(), which calls... This will
pretty quickly exhaust the memory of your Arduino.

If you only know about graphical programming, this may not make too much
sense to you. So I ask you to imagine that, in your definition of
Main_Loop() (the big structure titled “to Main Loop”) you replace the
smallish box labeled “Left Animation” by its own definition (the big
structure labeled “to Left Animation”). Within this definition, you
replace “Check Button” by its own definition and so on. You will soon
reach a point where you need to embed the definition of Main_Loop()
within itself. It should then look more or less like this:

Main Loop
│ repeat while Button Status = 1
│ do Left animation
│ │  │ Check Button
│ │  │ │ Serial Print “Check button Activated”
│ │  │ │ ...
│ │  │ │ LED OFF?
│ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ if Button Status = 0
│ │  │ │ │ do Turn Off All LED
│ │  │ │ │ Main Loop
│ │  │ │ │ │ repeat while Button Status = 1
│ │  │ │ │ │ do Left animation
│ │  │ │ │ │ │  │ Check Button
│ │  │ │ │ │ │  │ │ Serial Print “Check button Activated”
│ │  │ │ │ │ │  │ │ ...
│ │  │ │ │ │ │  │ │ LED OFF?
│ │  │ │ │ │ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ │ │  │ │ │ if Button Status = 0
│ │  │ │ │ │ │  │ │ │ do Turn Off All LED
│ │  │ │ │ │ │  │ │ │ Main Loop
│ │  │ │ │ │ │  │ │ │ │ repeat while Button Status = 1
│ │  │ │ │ │ │  │ │ │ │ do Left animation
│ │  │ │ │ │ │  │ │ │ │ │  │ Check Button
│ │  │ │ │ │ │  │ │ │ │ │  │ │ Serial Print “Check button Activated”
│ │  │ │ │ │ │  │ │ │ │ │  │ │ ...
│ │  │ │ │ │ │  │ │ │ │ │  │ │ LED OFF?
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ if Button Status = 0
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ do Turn Off All LED
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ Main Loop
...etc ad infinitum...

Note that it is possible to write programs using recursion, but:

This is kind of an “advanced topic”, not suitable for someone still
programming at a graphic level.
You have to take precautions in order to avoid the program to
infinitely recurse.
On a microcontroller with little memory, you have to make sure the
recursion is always very shallow. Which is hard, so people writing
embedded code tend to avoid recursion altogether.


What kind of data type can be use store a binary bit-stream which is more than 64-bits? I'm wondering if one needs to assign a bit-stream of 78 bits to a variable(later on to be processed), what datatype can be used? What is the max bit can be stored into a variable in C?

There is no builtin data type that can store 78 bits. However, it depends a bit what you want to store. Like the following cases:

If the 78 bits are one 'entity' (e.g. one really big value), you can store it as an array of bytes (10 bytes of 8 bits = 80 bits, leaving 2 bits unused)
If the 78 bits can be split up in smaller parts, you can:

Create a structure or class to contain the sub elements into fields (instance variables), using for each sub type a normal type (e.g. signed/unsigned 8, 16 or 32 bits).
Create bit fields to save some memory if there are small items and memory space is an issue.
Or a combination of the above

If you have many of these items and you want to save space (thus the 2 unused bits of each 80 bits), you can create a big array that contains many items, and use bit operations to get each item. E.g. the first element will be in the first 10 bytes, where the last 2 bits are not part of the element. The second item will use the remaining 2 bits and the following 78 - 2 = 76 bits, etc. This saves only 2/80 * 100% = 2.5% so only use this when really needed.


Enternal Analog Reference mode not compiling in Arduino + Intel Galileo Gen 2 I am trying to use external voltage reference in Intel Galileo gen 2 operating in Arduino mode.

So I created a setup code like this:

void setup() {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);

  // If you want to set the aref to something other than 5v
  analogReference(EXTERNAL); // use AREF for reference voltage
}

I selected the board as Intel Galileo Gen 2 in Tools option. When I compiled I am getting the following error:

LM35_temp_sensor.ino:21:19: error: 'EXTERNAL' was not declared in this scope

But when I change the board to Arduino Uno in Tools option, the program in compiling fine.

This means that Intel Galileo Gen 2 does not support external analog voltage reference?

There is no such thing as an external analog reference on the Galileo.  If you look at the block diagram that is on the Galiley Arduino.cc page you can clearly see that the Aref pin goes nowhere:

So no, it won't support the EXTERNAL analog reference function.


How do I implement reverse enumeration? Basically I'm trying to output a string based upon a value in an array, the following code is what I have come up with to achieve my desired result, but I have a feeling that there is a better way to do it.

String day(int day) {
  if (day == 1) return "Sunday";
  if (day == 2) return "Monday";
  if (day == 3) return "Tuesday";
  if (day == 4) return "Wednesday";
  if (day == 5) return "Thursday";
  if (day == 6) return "Friday";
  if (day == 7) return "Saturday";
  else return "Undefined";
}

void setup() {
  Serial.begin(57600);
  while (!Serial);
  Serial.println(day(1));
}

void loop() {
;
}

This prints "Sunday" in the Serial monitor

I would appreciate any input on how to optimize this code, thank you!

My method makes use of the __FlashStringHelper class:

// For convenience:
typedef const __FlashStringHelper *FlashString;

FlashString reverseEnum(int val) {
    switch (val) {
        case 0: return F("Option zero");
        case 1: return F("Option one");
        case 2: return F("Option two");
        default: return F("Invalid Enum");
    }
}

Printing now is as simple as:

Serial.println(reverseEnum(2));

Because it's a "flash string" the print function is overloaded properly and it performs the proper PROGMEM reading.

You can, of course, assign to a FlashString:

FlashString myString = reverseEnum(2);
Serial.println(myString);

Or if you don't want to use a typedef you can use the raw type:

const __FlashStringHelper *myString = reverseEnum(2);
Serial.println(myString);

It's just much cleaner to use a typedef.


Microphone Data on Arduino to Wav File on RaspPi Working on an Arduino + Raspberry Pi project and hoping that this question fits into this category. I'm recording audio using a MEMS microphone on the Arduino and transmitting it over to the Pi to store in a playable file (WAV).

What I currently have setup is TCP transmission from the Arduino to the RaspPi. This part is fine and dandy for the purpose of seeing the data transmission that I am looking for.

Where my issue lies, is the audio data being recorded on the Arduino.
At the moment, I see data from my analogRead() function displaying like the following:

2035
2046
2030
2031
2044
2038
2034
2031
2034
2019
2028
2030
2024
2032
2028

My question is, what does this mean? How would I translate this, preferably on the Pi, as usable data that I can store in a WAV file?

Any libraries or hints/clues that can steer me in the right direction would be great.

Why use the arduino, when you can use the Pi directly? I would get a high quality ADC, connect the mic to it, and then make the Pi write the value from the ADC directly to file. The arduino simply isn't fast enough for good quality audio recording - the ADC is 10-bit, 9.6 khz. At best you could get a stereo 8-bit 8khz wav file. With a good ADC on the Pi, you would be able to go up to stereo, 16-bit(maybe even 24-bit), 44.1 khz. Also, the Arduino would be massively slowed down by sending the data, so the actual sample rate would be much lower.


Is it possible to power up Arduino upon serial transmission without dropping data? I have radiator valves that send readings about the temperature and valve opening to the serial output: Honeywell HR-25.

I want to collect those readings in a central server at home without flashing the thermostat with a custom firmware.

To do that, I need an Arduino (very bare one) that can receive the serial data, but at the same time I need it to be powered down most of the time, or it would kill the battery life of the thermostat.

Can I wake up an Arduino from power down using the serial transmission, and immediately capture the serial data without dropping bits? how?

I never tried myself, but afaik you can define an wake up/interrupt from USART, meaning that if you get a receiving byte from the UART it will wakeup the Arduino.

When powered up, you can read continuous data. I would be surprised if they make an UART wakeup signal, that bytes would be lost (i.e. that powering up would take too long to miss more UART bytes).


Arduino ESP8266 module communicate through Arduino IDE terminal I am completely new to Arduino and trying to setup the Arduino and ESP8266 module. Thereby I used this scheme to set it up:

Where I use this code:

`#include <SoftwareSerial.h>

const byte rxPin = 1; // Wire this to Tx Pin of ESP8266
const byte txPin = 0; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
}

void loop() {
//  Serial.println("Sending an AT command...");
  ESP8266.println("AT");
  delay(30);
  while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
//     Serial.println("Test: " + inData);
  }
}`

But I am trying to communicate through the terminal in the Arduino IDE want to type AT and it sends me back "OK". How can I achieve this?

While it sounds like you have a serial voltage problem, even with that fixed you still have a conceptual problem with the serial links.

On a traditional Arduino like an Uno, pins 0 and 1 (which are the only hardware UART on the version of the ATmega in use) are already used for communication to the PC and serial monitor.

Thus you cannot use these to talk to the ESP8266, unless you effectively remove either the ATmega or the computer from the situation.  Some people do pull the ATmega out of its socket, or hold it in reset and thus "borrow" the Arduino's USB serial solution to talk directly from a PC to an ESP8266.  And in other cases someone working on a more completed project will forgo the computer serial connection, and use the ATmega's hardware UART to talk to the ESP8266.

But what you are trying to do, in talking to the ESP8266 through the ATmega, is not going to work when both conversations are trying to happen on the same pins.  Your code tries to use a software UART to talk to the ESP8266, which is potentially workable - but it will not accomplish your goal until you move the ESP8266 to different Arduino pins, in both the wiring and the sketch, in order to remove the present conflict over pins 0 and 1.


ESP8266 does not response My wire schema ;

http://bloglug.com/wp-content/uploads/2015/08/Arduino-esp8266-baglantilari.png

And i'm using arduino, it has blank loop. I'm trying AT command by using Serial Monitor and I have no response..

These tutorials often forget to tell you to place the ATmega chip in RESET if you want it to function as a UART-USB-pass-through. This is easily done by connecting the RESET pin to GND with a jumper. Also consider powering the ESP from a more powerful source, like the Arduino 5V pin through an LM1117 regulator. Don't forget to set your Serial Monitor to Both NL & CR. Use a voltage divider between the Arduino's RX pin and that of the ESP, to reduce the 5V signals to 3.3V.


Practicality of recording speech Is it practical to record speech with the Leonardo?

I want to record speech via a MEMS microphone and stream it over a serial connection to a Raspberry Pi for speech-to-text processing.

This article states that the typical bitrate for recording voice podcasts is 64 kbps. The Arduino's analogRead() function has a maximum sample rate of typically 8,600 times/sec for a maximum bitrate of 8,600 samples/sec * 10 bits/sample = 86 kbps, so theoretically, it should be fast enough to record decent voice audio.

However, will the serial connection be fast enough to stream this much data? Theoretically, the Leonardo's serial connection can go up to 115,200 bps, but I've never reliably gotten it to go faster than 57,600 bps, which would mean the serial connection would a bottleneck that would prevent it from sending a continuous stream of 64 kbps, and therefore it would be impractical to record speech with the Arduino.

Am I wrong? Has anyone had success with voice recording while streaming it over serial?

On my page about the ADC converter I attempted to record a 4 kHz sine wave on the ATmega328P with the following code:

const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

// ADC complete ISR
ISR (ADC_vect)
  {
  if (resultNumber >= MAX_RESULTS)
    ADCSRA = 0;  // turn off ADC
  else
    results [resultNumber++] = ADC;
  }  // end of ADC_vect

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);  // WTF?
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

  // wait for buffer to fill
  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
    Serial.println (results [i]);

  }  // end of setup

void loop () { }

The code (rather inefficiently) sends the results in ASCII, like this:

378
710
899
992
966
827
609
367
159
38
35
147
350
593
817
965
1001
917
733
494
259
88
21
76
239
471
711
905
1001
977
839
620
376
164
39

This gave reasonable results:

Now the Leonardo is, of course, a different processor. However it is similar. The ADC on it should be capable of similar performance.

I should point out that this code records first, then sends the data. This is so the recording can keep up. A normal ADC conversion (if you don't change the ADC prescaler) takes 104 µs. To send 10 bits via serial at 115200 baud rate would take 173.6 µs because it would require two bytes per sample (unless you somehow compress each reading). If you could put up with 8-bit resolution (per sample) then you halve that, and can probably just stream the data out fast enough.


How to filter the power supply for an Arduino in a vehicle (car, motorcycle)? I want to use an Arduino (maybe Nano, maybe MEGA) in my motorcycle (a new KTM with lots of electronics).
I checked my test circuit (with the MEGA) and it uses about 100mA (with 5V connected to the 5V pin).

Edit: the bike has a 12v battery and when it's on the generator pushes this up to about 14.3v.

For my first tests I used a 3 terminals DC/DC Regulator with output 5V for the Arduino power supply. If the ignition is on the Arduino works. As soon as I start the bike the Arduino restarts every couple of seconds.

Currently I used the BP5293 DC/DC Regulator because it has 2% precision. Currently I don't have any capacitors on the input or output terminals of that regulator.

I guess I have the following options:

a) Use the BP5293 and add capacitors on the input and/or output terminals. In the datasheet an output capacitor of about 10-330uF is recommended. For the input it recommends a capacitor but without any value given.

b) Use another regulator to 5V

c) Use a regulator to i.e. 7V and then connect that to the Arduino power input and let the Arduino do the filtering of the input.

What is the proper solution and what are suitable values for the capacitors?

I have 100nF ceramic capacitors and Low ESR electrolyte capacitors with 6.3V, 16V and 35V from 68uF up to 3300uF in stock. Obviously I could just try but I prefer to know how it should be done.

The solution depend on what causes the reset.

It might be EMI interference on the RESET, in this case a stronger pull-up might help. The standard pull-up for nano is 1kohm which should be enough but if you use a clone the value might be higher.

If the reset comes from power drops then only a higher capacitor on the regulator input would not be enough since you also have other consumers on the 12V line that will suck the energy stored in the input capacitor.

Feed the capacitor and the regulator input through a diode, anode to 12v, cathode to capacitor/regulator. This will stop the energy stored in the capacitor to go back to the 12V line.


Broadcast data to radius of at least 500 meters I need to broadcast small amounts of data in a radius of about 500 meters to 2 Kms. in real time. Any compatible receiver in the range should be able to receive that data. Is there a suitable module for the same? I am considering HC-12 but don't think it can used for broadcasting data to all the surrounding receivers.

Maybe you can look into the LoPy Microcontroller, a MicroPython enabled controller, that has a 1km WiFi range. It uses the Espressif ESP32 chipset (with 802.1b/g/n 16mbps WiFi) and has Bluetooth (BLE & Classic) integrated into the board.

(Reference: https://www.pycom.io/product/lopy/)


Adafruit Feather 32u4 Bluefruit LE and HC-05 Bluetooth module Is it possible to connect an Adafruit Feather 32u4 Bluefruit LE with an HC-05 Bluetooth module?

I am making a heart rate monitor using an Adafruit Feather, but it is unable to send the data to LABView for processing as it uses BLE. I do not have the means to buy a Bluetooth dongle to work around the issue.

However, I do have an HC-05 Bluetooth module that can be read by VISA on LABView.

Therefore I would like to ask if it is possible to connect my Adafruit Feather to my HC-05 module and send the data through the HC-05 instead of the built-in BLE.

Thank you!

HC-05 does not support BLE as far as I know but you can use a HM-10 if you can get your hands on one; Its almost about the same cost as a HC-05, maybe a little more;


Receiver Module Second Data Pin Many of the receiver modules (MX-05V) working with the Virtual Wire library (I would like to add a link here but it requires 10 reputation, so I'll do that later) have two data pins. However only one of them is used in the examples I have seen so far.

This picture shows a transmitter (top left) and a receiver (bottom right). Apparently the receiver has four pins - two of them are data pins.

Image source

What is the purpose of the second data pin on the receiver module and how to use it?

I would expect only one data line output from the receiver.

Looks like the manufacturer might have just connected the 2 data pins together. You could try using either pin to confirm that the two data output pins are simply connected together.


Arduino Uno with CC3000 WiFi Shield cannot be initialized I am working on an Arduino Uno and CC3000 WiFi shield. I interfaced it over my Arduino and added the SparkFun library SFE_CC3000_Library. Then I opened the TestBoard example, but it hangs on setup in the first command wifi.init().

How can I solve this problem, and how can I enable debug mode?

Here's the code

#include <SPI.h>
#include <SFE_CC3000.h>
#include <utility/netapp.h>

#define DEBUG     1
// Pins
#define CC3000_INT      2   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       7   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno

// Constants
#define FW_VER_LEN      2   // Length of firmware version in bytes
#define MAC_ADDR_LEN    6   // Length of MAC address in bytes

// Global Variables
SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);

void setup() {

  int i;
  unsigned char fw_ver[FW_VER_LEN];
  unsigned char mac_addr[MAC_ADDR_LEN];

  // Initialize Serial port
  Serial.begin(115200);
  Serial.println();
  Serial.println("----------------------------");
  Serial.println("SparkFun CC3000 - Board Test");
  Serial.println("----------------------------");

  // Initialize CC3000 (configure SPI communications)
  if ( wifi.init() ) {
    digitalWrite(13, HIGH);
    Serial.println("CC3000 initialization complete");
  } else {
    Serial.println("Something went wrong during CC3000 init!");
  }

  // Read and display CC3000 firmware version
  if ( wifi.getFirmwareVersion(fw_ver) ) {
    Serial.print("Firmware version: ");
    Serial.print(fw_ver[0], DEC);
    Serial.print(".");
    Serial.print(fw_ver[1], DEC);
    Serial.println();
  } else {
    Serial.println("Could not read firmware version from CC3000");
  }

  // Read and display CC3000 MAC address
  if ( wifi.getMacAddress(mac_addr) ) {
    Serial.print("MAC address: ");
    for ( i = 0; i < MAC_ADDR_LEN; i++ ) {
      if ( mac_addr[i] < 0x10 ) {
        Serial.print("0");
      }
      Serial.print(mac_addr[i], HEX);
      if ( i < MAC_ADDR_LEN - 1 ) {
        Serial.print(":");
      }
    }
    Serial.println();
  } else {
    Serial.println("Could not read MAC address from CC3000");
  }

  // Done!
  Serial.println("Finished board test");

}

void loop() {

  // Do nothing
  delay(1000);
  Serial.println("Loop_Problem");

    }

Solved it, the problem was because the SparkFun library was not working with my shield. I replaced it using the Adafruit_CC3000_Library and now it works fine.


Wire Library send/receive I'm doing a project that includes an Arduino Uno and custom hardware made by me. Everything is working perfectly independently, and I'm trying to implement a way for them (the Arduino and my hardware) to work together. In order to achieve that, I am using the Wire protocol (Arduino side) and I2C (custom hardware side). From now I can send data from my hardware to my Arduino in a master-slave relation, and I have no problem with that. Please take a look at my Arduino code for better understanding:

void setup(void) {
  Wire.begin(7);
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int howMany) {
  int x = Wire.read(); // receive byte as an integer
  Serial.print(x);
  if (x==0)
    state = 0;
}

So far so good. Now I want to send data from the Arduino to my custom hardware full duple, and for that I am adding this code:

void frame(void){
  Wire.write('x');
  Wire.write('\r');
}

void loop() {
  if (state == 0){
    frame();
    state = 1;
  }
}

In order to receive the 'x' char in my custom hardware I have switched the I2C protocol bit from Write to Read using I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, _address, I2C_WRITE); to I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, _address, I2C_READ); in my custom hardware code.

I don't know why, I am not receiving the data from the Arduino. Am I missing any configuration on the Arduino side?

I've not done events on an Arduino so this could be a bum steer, but shouldn't the state variable be volatile and protected with a semaphore?
You are accessing it in the main program and in your event/ISR.

Secondly, no offence intended, could you replace your hardware with a bit of tried and trusted hardware to eliminate the remote possibility that your hardware is at fault.


How to interface DS1801 digital resistor with Arduino DUE SPI interface? What clock rate so use? I am trying to program a digital resistor and set it's wiper resistance. The general circuit looks a little like this where "pot" represents the Maxim DS1801 digital resistor and DUE is, of-course the 3.3v Arduino DUE.

POT       DUE
CLk ----> SCK
D    ----> MOSI
RST ----> CS (ChipSelect) (PIN10)

Now so far, I have sucessfully been able to interface with the DS1801, but I am having issues determining how to properly set the wiper resistance values. The DS1801 datasheet says the it accepts a 16bit input and from application example online it looks like the values range from 0 to 64. Here is my code:

// include the SPI library:
#include <SPI.h>

// set pin 10 as the slave select for the digital pot:
const int slaveSelectPin = 10;
int mute = 64;
int loud = 63;
int soft = 0;

void setup() {
  // set the slaveSelectPin as an output:
  pinMode (slaveSelectPin, OUTPUT);
  // initialize SPI:
  SPI.setBitOrder(LSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(slaveSelectPin,SPI_CLOCK_DIV8);
  SPI.begin();
  delay(10);
   digitalPotWrite(mute, mute);
}

void loop() {

  // Raise the volume from off to loud
for(int i = 0; i <= 63; i++){
  digitalPotWrite(i, i);
  delay(5);
    }
  }

void digitalPotWrite(int left, int right) {
  // take the SS pin low to select the chip:
  digitalWrite(slaveSelectPin, HIGH);
  //  send in the address and value via SPI:
  SPI.transfer(left);
  SPI.transfer(right);
  // take the SS pin high to de-select the chip:
  digitalWrite(slaveSelectPin, LOW);
}

I THINK my issue lies with setting the clock rate for the DS1801. The data sheet say the chip runs at 10MHz which is why I wrote

SPI.setClockDivider(slaveSelectPin,SPI_CLOCK_DIV8);

to divide the 84MHz default speed down to 10MHz.

Anyone have suggestions on why my code is not working??? At the moment, I have LED's connected to chip with series resistors to limit current below 2mA. The resistors just blink randomly with the code posted above.

There is no way in hell you're going to get a 10MHz signal down that line. Shorten it to 3 inches total maximum and reduce the clock rate to 2MHz or lower. It is possible to get a 10MHz signal through, but you'd need to switch to twisted pair wiring and proper termination to even begin to have a chance to get it to work.


Some Arduino components seem ridiculously cheap My project is an Arduino-based device, packed into a box.

It will need to use Speed, Latitude, Longitude and Altitude data to log hills it detects on to an SD. On the press of a button, it will need to upload the hill data to the server via Wi-Fi.

I need the following items:

GPS Module + Antenna
WiFi Module
SD Module
Altimeter
microSD Card
Inline switch for my battery pack

The cost? Well on the Pi Hut it was £120 or so:

  GPS =
  https://thepihut.com/products/sim808-gps-gprs-gsm-shield-for-arduino =
  £42

  WiFi =
  https://thepihut.com/products/wifi-shield-v3-for-arduino-rpsma-802-11b-g-n
  = £54

  SD = https://thepihut.com/products/microsd-card-module-for-arduino =
  £6

  microSD Card = https://thepihut.com/products/blank-micro-sd-cards
  (4GB) = £5

  Altimeter =
  https://thepihut.com/products/adafruit-bmp280-i2c-or-spi-barometric-pressure-altitude-sensor
  = £10

  Switch =
  https://thepihut.com/products/adafruit-in-line-power-switch-for-2-1mm-barrel-jack
  = £2.50

On Bang Good (a really cheap online shop I discovered) it was more like £30:

  GPS =
  https://www.banggood.com/GPS-UBLOX-NEO-7N-Satellite-Positioning-Module-For-Arduino-51MCU-STM32-p-1203610.html?rmmds=cart_middle_products&cur_warehouse=CN
  = £10.54

  GPS Antenna =
  https://www.banggood.com/GPS-Active-Ceramic-Antenna-IPX-IPEX-Interface-For-GPS-Module-p-1203537.html?rmmds=cart_middle_products&cur_warehouse=CN
  = £2.11

  WiFi = https://www.banggood.com/Upgraded-Version-1M-Flash-ESP8266-ESP-01-WIFI-Transceiver-Wireless-Module-p-979509.html?rmmds=cart_middle_products
  = £2.53

  SD = https://www.banggood.com/Micro-SD-TF-Card-Memory-Shield-Module-SPI-Mciro-SD-Adapter-For-Arduino-p-919914.html?rmmds=cart_middle_products&cur_warehouse=CN
  = £1.02

  microSD Card = https://www.banggood.com/4GB-MicroSD-Card-with-Card-Reader-for-RC-FPV-Camera-Quadcopter-p-1050069.html?rmmds=cart_middle_products&cur_warehouse=CN
  = £3.96

  Altimeter = https://www.banggood.com/MPL3115A2-IIC-I2C-Intelligent-Temperature-Pressure-Altitude-Sensor-V2_0-For-Arduino-p-1198222.html?rmmds=cart_middle_products
  = £5.16

  Switch = https://thepihut.com/products/adafruit-in-line-power-switch-for-2-1mm-barrel-jack

  = £2.50 (From Pi Hut, though)

I'm suspicious. I might be inexperienced, and this may be a bad question, but is the cheaper option lower in quality? Is the expensive one over the top? The cheap version really seems to good to be true.

The cheaper option is not always lower in quality. You can find items for sale on Amazon, Ebay and Aliexpress that all have the same "seller name" and a identical picture of the item. The price is usually 5 to 10 times higher on Amazon than Ebay. Aliexpress is usually the cheapest.

During the past year, I've ordered over 100 Arduino related sensors/modules from Ebay and Aliexpress. Four from Ebay and one from Aliexpress were defective. I got a refund for all five items.

If you are going to buy the cheaper products, it's a good idea to order more than you need in case one is defective.

Some items should not be sold at any price. For example, I purchased a DHT11 temperature and humidity sensor when I first started with Arduinos. It's an inaccurate piece of garbage, and that's exactly where it went.


Irrecvdemo program in or remote library gives fatal error #include Whenever I compile irrecvdemo of or remote library it gives error saying that fatal error saying

  no file or directory exists #include <WProgram.h>

#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
}

You are using a very old library on a modern IDE.  The file that was called WProgram.h in IDE version 0023 and below is now called Arduino.h.  You will need to change any references to WProgram.h to Arduino.h instead.

Well written libraries do this with a #ifdef block:

#if (ARDUINO >= 100)
# include <Arduino.h>
#else
# include <WProgram.h>
#endif


Arduino uno + cnc shield v3 + Stepper Motor Driver A4988 + AccelStepper? I successfully run the AccelStepper examples on an Arduino Mega with a RAMPS 1.4 shield, two A4988 stepper motor drivers and two 17HS16-0284S stepper motors.

I used 3 jumpers on the RAMPS to set the microstep resolution to 1/16.

I used this code inspired by the Polargraph Server for Polargraph:

#include <AccelStepper.h>

/*
// for the Arduino Uno + CNC shield V3

#define MOTOR_A_ENABLE_PIN 8
#define MOTOR_A_STEP_PIN 2
#define MOTOR_A_DIR_PIN 5

#define MOTOR_B_ENABLE_PIN 8
#define MOTOR_B_STEP_PIN 3
#define MOTOR_B_DIR_PIN 6
*/

// for the Arduino Mega + RAMPS 1.4
#define MOTOR_A_ENABLE_PIN 30
#define MOTOR_A_STEP_PIN 36
#define MOTOR_A_DIR_PIN 34

#define MOTOR_B_ENABLE_PIN 56
#define MOTOR_B_STEP_PIN 60
#define MOTOR_B_DIR_PIN 61

AccelStepper motorA(1, MOTOR_A_STEP_PIN, MOTOR_A_DIR_PIN);
AccelStepper motorB(1, MOTOR_B_STEP_PIN, MOTOR_B_DIR_PIN);

void setup()
{
  motorA.setEnablePin(MOTOR_A_ENABLE_PIN);
  motorA.setPinsInverted(false, false, true);
  motorB.setEnablePin(MOTOR_B_ENABLE_PIN);
  motorB.setPinsInverted(false, false, true);

  motorA.setAcceleration(100);
  motorA.move(1000);
  //motorA.setMaxSpeed(100);
  //motorA.setSpeed(100);

  motorB.setAcceleration(100);
  motorB.move(1000);
  //motorB.setMaxSpeed(100);
  //motorB.setSpeed(100);

  motorA.enableOutputs();
  motorB.enableOutputs();
}

void loop()
{

  motorA.run();
  motorB.run();

}

I tried to use the same code with the same stepper motor drivers and motors on a Arduino Uno and a CNC shield v3 without success (I also used the 3 jumpers to set the microstep resolution to 1/16). The motors do not work and jitter.

What is wrong with my code?

Bonus questions:
I have taken this setup and code from the Polargraph server but I didn't get how I'm suppose to know how to use setEnablePin() and setPinsInverted() methods. In fact, I have troubles finding documentation about the CNC shield V3 and the A4988 drivers (I only found this page) to work with AccelStepper.

Manually set the ENABLE pins as OUTPUTs, i.e. add in the setup() function:

pinMode(MOTOR_A_ENABLE_PIN, OUTPUT);
pinMode(MOTOR_B_ENABLE_PIN, OUTPUT);


Getting errors i don't understand I was following a tutorial for my class (the tutorial was assigned) and I did everything the guy did to the letter but i got errors he didn't and they were errors I didn't get while programing similar things with the exact same commands as what im getting errors on now.
Code
#include "DHT.h"
#define Type DHT11
#include <LiquidCrystal.h>
int rs=7;
int en=8;
int d4=9;
int d5=10;
int d6=11;
int d7=12
LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
int sensePin=2;
DHT HT(sensePin,Type);
float humidity;
float tempC;
float tempF;
int setTime=500;
int dt=1000;

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   HT.begin();
   delay(setTime);
   lcd.begin(16,2);
}

void loop() {
   humidity=HT.readHumidity();
   tempC=HT.readTemperature();
   tempF=HT.readTemperature(true);

   lcd.setCursor(0,0);
   lcd.print("Temp F= ");
   lcd.print(tempF);
   lcd.setCursor(0,1);
   lcd.print("Humidity= ");
   lcd.print(humidity);
   lcd.print(" %");
   delay(500);
   lcd.clear();

   Serial.print("Humidity: ");
   Serial.print(humidity);
   Serial.print("% Temperature ");
   Serial.print(tempC);
   Serial.print(" C ");
   Serial.print(tempF);
   Serial.print(" F ");
}

Error message
Arduino: 1.8.13 (Windows 10), Board: "Arduino Uno"

DHT_LCD_lab:10:2: error: expected ',' or ';' before 'LiquidCrystal'
  LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
  ^~~~~~~~~~~~~
C:\Users\zacha\Desktop\DHT_LCD_lab\DHT_LCD_lab.ino: In function 'void setup()':
DHT_LCD_lab:24:1: error: 'lcd' was not declared in this scope
 lcd.begin(16,2);
 ^~~
C:\Users\zacha\Desktop\DHT_LCD_lab\DHT_LCD_lab.ino: In function 'void loop()':
DHT_LCD_lab:34:1: error: 'lcd' was not declared in this scope
 lcd.setCursor(0,0);
 ^~~
exit status 1
expected ',' or ';' before 'LiquidCrystal'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

#include "DHT.h"
#define Type DHT11
#include <LiquidCrystal.h>
int rs=7;
int en=8;
int d4=9;
int d5=10;
int d6=11;
int d7=12;
LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
int sensePin=2;
DHT HT(sensePin,Type);
float humidity;
float tempC;
float tempF;
int setTime=500;
int dt=1000;

void setup() {
  // put your setup code here, to run once:
   Serial.begin(9600);
   HT.begin();
   delay(setTime);
   lcd.begin(16,2);
 }

void loop() {
   humidity=HT.readHumidity();
   tempC=HT.readTemperature();
   tempF=HT.readTemperature(true);

   lcd.setCursor(0,0);
   lcd.print("Temp F= ");
   lcd.print(tempF);
   lcd.setCursor(0,1);
   lcd.print("Humidity= ");
   lcd.print(humidity);
   lcd.print(" %");
   delay(500);
   lcd.clear();

   Serial.print("Humidity: ");
   Serial.print(humidity);
   Serial.print("% Temperature ");
   Serial.print(tempC);
   Serial.print(" C ");
   Serial.print(tempF);
   Serial.print(" F ");
  }


Arduino open door (outdoor) tonemelody My problem lies in the fact that I can not stop the "void loop" function and more accurately "StatInDoor". I have to make sure that the "ButtonOpenDoor" works independently of "ButtonCall". If someone presses the "ButtonCall" button then the "ButtonOpenDoor" button must work in progress, and if the "ButtonCall" button is pressed, the "ButtonOpenDoor" button must stop playing the melody.

My idea for this this:

int StatOutDoor = digitalRead(ButtonCall && ButtonOpenDoor);

or:

if(StatOutDoor == LOW && StatInDoor = LOW){
   PlayMelody();
}

But it does not work :(

Full code:

#include "pitches.h"

int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};
int ButtonCall = 4;
int buzzer = 8;
int ButtonOpenDoor = 7;
int RelayModule = 12;

void PlayMelody() {
  for (int thisNote = 0; thisNote < 8; thisNote++) {
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(buzzer, melody[thisNote], noteDuration);
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    noTone(buzzer);
  }
}

void setup(){
  pinMode(ButtonCall, INPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(ButtonOpenDoor,INPUT);
  pinMode(RelayModule,OUTPUT);
}

void loop() {
  int StatOutDoor = digitalRead(ButtonCall);
  if(StatOutDoor == LOW){
    PlayMelody();
  }
  int StatInDoor = digitalRead(ButtonOpenDoor);
  if (StatInDoor == HIGH) {
    digitalWrite(RelayModule, HIGH);
  } else {
    digitalWrite(RelayModule, LOW);
    delay(3300);
  }
}

Can someone help with this? (Sorry for my bad English).

I'm not quite sure I understand the logic of what you're asking. Your description is a little vague. Maybe if you provided more information about what the signals are, what they mean, and where they come from, it may help.

However - if you want the melody to play when both inputs are LOW you should change:

if(StatOutDoor == LOW && StatInDoor = LOW){
      PlayMelody();
}

to:

if(StatOutDoor == LOW && StatInDoor == LOW){
      PlayMelody();
}

Note the use of == not = to denote equality (= is assignment).

Also the use of a 3.3 second delay in your else will show everything down to a crawl when StatInDoor is HIGH.


How do I program my Arduino Yun Shield when I keep getting this AVRDUDE error message? The error message is:

  avrdude: AVR device initialized and ready to accept instructions
  avrdude: Device signature = 0x1e950f
  avrdude: Expected signature for ATmega32U4 is 1E 95 87
  Double check chip, or use -F to override this check.

This error message is thrown when I attempt to upload any program to the Yun shield through an Arduino Bridge between the Uno and Yun shield with the Uno’s ATMega32 shorted into reset mode.
Any advice on how to get this working? Thanks.

Apparently there is no ATMega32U4 on that board but ATmega328P according to the signature 0x1e950f.

Anyway, you may have to change or add new board with correct MCU setting.

Now I can see the difference between Yun and Yun shield. Shield can be connected to any Arduino board and Yun is similar like Shield + Leonardo.

I've found board definition for Arduino UNO:

unoyun.name=Arduino Uno -- Dragino Yún
unoyun.upload.via_ssh=true

unoyun.vid.0=0x2341
unoyun.pid.0=0x0043
unoyun.vid.1=0x2341
unoyun.pid.1=0x0001
unoyun.upload.tool=avrdude
unoyun.upload.protocol=arduino
unoyun.upload.maximum_size=32256
unoyun.upload.maximum_data_size=2048
unoyun.upload.speed=57600
unoyun.upload.disable_flushing=true
unoyun.upload.use_1200bps_touch=true
unoyun.upload.wait_for_upload_port=true

unoyun.bootloader.tool=avrdude
unoyun.bootloader.low_fuses=0xff
unoyun.bootloader.high_fuses=0xde
unoyun.bootloader.extended_fuses=0x05
unoyun.bootloader.file=optiboot/optiboot_atmega328.hex
unoyun.bootloader.unlock_bits=0x3F
unoyun.bootloader.lock_bits=0x0F

unoyun.build.mcu=atmega328p
unoyun.build.f_cpu=16000000L
unoyun.build.board=AVR_YUN
unoyun.build.core=arduino
unoyun.build.variant=standard

More info about it here: https://www.arduino.cc/en/Guide/ArduinoYunShield or similar product http://wiki.dragino.com/index.php?title=Yun_Shield


Cannot upload to Robotdyn Mega 2560 PRO MINI? I get this error trying to upload avrdude: stk500v2_ReceiveMessage(): timeout

It is Robotdyn Mega 2560 PRO MINI and a Robotdyn CH340 which I have connected like this:

I installed the CH340 drivers from here https://sparks.gogo.co.nz/ch340.html and I can see it in the device manager.
Connecting the Mega 2560 Pro Mini lights up the L and On LED but when pressing upload (testing with simple examples as Blink) I get the error and neither RX or TX lights up.

I have tried everything I can think of. What am I doing wrong?

I have confirmed that it is connected to the correct COM-port and I use these settings:

Board: Arduino/Genuino Mega or Mega 2560
Processor: ATMega2560 (Mega 2560)

I have also tried many different USB-cables, short and long, and USB 2.0 and USB 3.0 ports. I use Windows 10 64-bit.

Try placing a 100nf capacitor on RST. That is usually required on an FTDI programmer.

See Edgar's post - https://arduino.stackexchange.com/users/47431/edgar


View Arduino Serial Monitor window after it has been minimised on Mac Big Sur I am using the Arduino SDK on a Mac Mini running Big Sur.  If I minimise the Serial Monitor, I how do I  bring it up to full size again?  The only method I have found so far is to restart the SDK and open the Serial Monitor again.

The app does not have the normal Window top option, but you can use the keys CMD + '`' to cycle through the windows.


NRF24L01+ scanning and connecting to wifi hotspots or creating one I've seen this video so I think I can connect it through my wifi router to any device. How can I scan for and discover wifi hotspots and then connect to it? Or is there a way to create wifi hotspot of it's own?

It does seem possible, check out this thread on Arduino forums, where cpixip worked directly with the NRF24 SPI interface to accomplish that.

Here is the code he published, in case the link won't be available:

#include <SPI.h>

// Poor Man's Wireless 2.4GHz Scanner
//
// uses an nRF24L01p connected to an Arduino
//
// Cables are:
//     SS       -> 10
//     MOSI     -> 11
//     MISO     -> 12
//     SCK      -> 13
//
// and CE       ->  9
//
// created March 2011 by Rolf Henkel
//

#define CE  9

// Array to hold Channel data
#define CHANNELS  64
int channel[CHANNELS];

// greyscale mapping
int  line;
char grey[] = " .:-=+*aRW";

// nRF24L01P registers we need
#define _NRF24_CONFIG      0x00
#define _NRF24_EN_AA       0x01
#define _NRF24_RF_CH       0x05
#define _NRF24_RF_SETUP    0x06
#define _NRF24_RPD         0x09

// get the value of a nRF24L01p register
byte getRegister(byte r)
{
 byte c;

 PORTB &=~_BV(2);
 c = SPI.transfer(r&0x1F);
 c = SPI.transfer(0);
 PORTB |= _BV(2);

 return(c);
}

// set the value of a nRF24L01p register
void setRegister(byte r, byte v)
{
 PORTB &=~_BV(2);
 SPI.transfer((r&0x1F)|0x20);
 SPI.transfer(v);
 PORTB |= _BV(2);
}

// power up the nRF24L01p chip
void powerUp(void)
{
 setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)|0x02);
 delayMicroseconds(130);
}

// switch nRF24L01p off
void powerDown(void)
{
 setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)&~0x02);
}

// enable RX
void enable(void)
{
   PORTB |= _BV(1);
}

// disable RX
void disable(void)
{
   PORTB &=~_BV(1);
}

// setup RX-Mode of nRF24L01p
void setRX(void)
{
 setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)|0x01);
 enable();
 // this is slightly shorter than
 // the recommended delay of 130 usec
 // - but it works for me and speeds things up a little...
 delayMicroseconds(100);
}

// scanning all channels in the 2.4GHz band
void scanChannels(void)
{
 disable();
 for( int j=0 ; j<200  ; j++)
 {
   for( int i=0 ; i<CHANNELS ; i++)
   {
     // select a new channel
     setRegister(_NRF24_RF_CH,(128*i)/CHANNELS);

     // switch on RX
     setRX();

     // wait enough for RX-things to settle
     delayMicroseconds(40);

     // this is actually the point where the RPD-flag
     // is set, when CE goes low
     disable();

     // read out RPD flag; set to 1 if
     // received power > -64dBm
     if( getRegister(_NRF24_RPD)>0 )   channel[i]++;
   }
 }
}

// outputs channel data as a simple grey map
void outputChannels(void)
{
 int norm = 0;

 // find the maximal count in channel array
 for( int i=0 ; i<CHANNELS ; i++)
   if( channel[i]>norm ) norm = channel[i];

 // now output the data
 Serial.print('|');
 for( int i=0 ; i<CHANNELS ; i++)
 {
   int pos;

   // calculate grey value position
   if( norm!=0 ) pos = (channel[i]*10)/norm;
   else          pos = 0;

   // boost low values
   if( pos==0 && channel[i]>0 ) pos++;

   // clamp large values
   if( pos>9 ) pos = 9;

   // print it out
   Serial.print(grey[pos]);
   channel[i] = 0;
 }

 // indicate overall power
 Serial.print("| ");
 Serial.println(norm);
}

// give a visual reference between WLAN-channels and displayed data
void printChannels(void)
{
 // output approximate positions of WLAN-channels
 Serial.println(">      1 2  3 4  5  6 7 8  9 10 11 12 13  14                     <");
}

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

 Serial.println("Starting Poor Man's Wireless 2.4GHz Scanner ...");
 Serial.println();

 // Channel Layout
 // 0         1         2         3         4         5         6
 // 0123456789012345678901234567890123456789012345678901234567890123
 //       1 2  3 4  5  6 7 8  9 10 11 12 13  14                     |
 //
 Serial.println("Channel Layout");
 printChannels();

 // Setup SPI
 SPI.begin();
 SPI.setDataMode(SPI_MODE0);
 SPI.setClockDivider(SPI_CLOCK_DIV2);
 SPI.setBitOrder(MSBFIRST);

 // Activate Chip Enable
 pinMode(CE,OUTPUT);
 disable();

 // now start receiver
 powerUp();

 // switch off Shockburst
 setRegister(_NRF24_EN_AA,0x0);

 // make sure RF-section is set properly
 // - just write default value...
 setRegister(_NRF24_RF_SETUP,0x0F);

 // reset line counter
 line = 0;
}

void loop()
{
 // do the scan
 scanChannels();

 // output the result
 outputChannels();

 // output WLAN-channel reference every 12th line
 if( line++>12 )
 {
   printChannels();
   line = 0;
 }
}

The pinout seems to match the NRF24 library pinout.
Please note that it seems this project does not implement the WiFi stack, but only check a high enough signal ( > -64dBm) for a given channel.

In order to create a WiFi hotspot, implementing the 802.11 stack is inevitable, and it seems like the Arduino core chip (atmega328) is not suitable for implementing it using software and bit-banging, so a dedicated hardware will be necessary.


How to connect MCP4141 digipot and a data logger shield to the same Arduino board The main problem here is that they both need to communicate via the Arduino's SPI bus, and I know that each of the two devices will need its own CS pin (The data logger is hard wired to 10, so the digital potentiometer will need a different one)

This would be fine, except that the digital potentiometer has one pin for both SPI and SDO.
I read that to connect this to the Arduino, the shared pin on the digipot needs to be connected to the MISI pin on the Arduino (pin 12) and then to bridge the MISO pin to the MOSI pin with a resistor.

Would anyone be able to tell if this will work. I do not want to try connecting the two devices like this just in case it breaks something in the board.

Thanks

I have done the same thing in the past for a DS1302 RTC that uses the same communication system.  Yes, it works.  Will it interfere with the other communication though? Quite possibly.  It works fine for half duplex communication, but could cause interference with something else on the bus that is full duplex.

If in doubt, and you're not worried about high speed or high efficiency (you're not changing the potentiometer's value often) then use three other pins and bit-bang your own half duplex serial interface - it's not hard.


Arduino Library to make http post request with bearer authentication I want to make an Http Post request with Bearer Authentication to my api using my Arduino Mkr Wifi 1010, but I couldn't find the appropriate library to do something like this (code generated with one made with Postman):
    POST /api/v1/rilevamento/transaction/commit HTTP/1.1
Host: www.....:8082
Authorization: Bearer eyJhb.......
Content-Type: application/json
Content-Length: 233

{
    "id": 0,
    "dispositivo": "sesto",
    "nomeutente": "MyName",
    "cognomeutente": "MySurname",
    "mailutente": "name@email.it",
    "data": "2020-11-23T09:23:03.142+00:00",
    "temperatura": 37.5
}

Can you tell me where to find this library? I tried WifiNiNa httpClient, ArduinoHttpClient, HTTPClient and other but I couldn't  get any response or even enter in the method of my api on debug.

The "Authorization" is simply an HTTP header.  So add it in your request like:
http.addHeader("Authorization", token);

The value of "token" is just the string "Bearer " followed by your authorization string.  Don't neglect the SPACE after the word "Bearer".  It will look like:

"Bearer eyJhb......"

On the Arduino MKR WiFi 1010 you use the WiFiNINA library which is slightly different.  Here is some example code:
  if (client.connect(server, 80)) {
    client.println("POST /test/post.php HTTP/1.1");
    client.println("Host: www.targetserver.com");
    client.println(authorizationHeader);
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(postData.length());
    client.println();
    client.print(postData);
  }

The variable authorizationHeader will have the "Authorization: Bearer xxxxx...." authorization string.
Or you can replace the client.println(authorizationHeader); by:
client.print("Authorization: Bearer ");
client.print(token);

to avoid dealing with concatenations, etc.
client can be an instance of WiFiSSLClient which works with both WiFi101 and WiFiNINA.


Access method from main sketch inside class I am lost at this one. In Java, I would do it this way:

Inside the main sketch, I would instantiate the object from the class:

do = new DoClass(this);

I would also include a method inside the main sketch:

public void doSomething(){}

Then, inside the DoClass, I would have the following constructor:

    public class DoClass{
       Sketch sketch;
       public DoClass(Sketch skt){
          this.sketch = stk;
       }
 }

Then, at some point, I would call, from DoClass:

stk.doSomething():

which should be the same as calling:

doSomething();

from the main sketch. Any ideas how to achieve that? If yes, could you please show an example of how to achive the above example in Arduino?

Unlike Java, which insists on everything being inside a class, C++
allows “plain” functions which do not belong to any class. In fact,
main() in standard C++, as well setup() and loop() in Arduino
code, are all plain functions. Then, the main program (or “sketch” if
you wish) is not an object, you cannot give it to the constructor of
your class. Instead, you would give it a pointer to the particular
function it needs. This is called a callback, because the library is
calling back something from your main program.

Here is how I would write it in C++:

/*
 * Class definition.
 */

class DoClass {

    // Define a callback type: a pointer to a function taking no
    // arguments and returning void.
    typedef void (*callback_t)();

public:
    // Constructor.
    DoClass(callback_t _callback)
        // Initialize internal callback with the one given as parameter.
        : callback(_callback)
        // empty function body
        {}

    // This class method invokes the callback.
    void doIt() { callback(); }

private:
    // The callback is kept as private internal data.
    callback_t callback;
};

/*
 * Main program.
 */

// This is the function we are going to provide as a callback.
void doSomething()
{
    Serial.println(F("Doing some work..."));
}

// Instantiate the class statically.
DoClass doObject(doSomething);

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

void loop()
{
    doObject.doIt();  // <- this will invoke our callback.
    delay(1000);
}

The class could be instantiated dynamically
(DoClass *doObject = new DoClass(doSomething);).
I prefer to do it statically when possible, because dynamic memory
allocation can easily led to memory fragmentation problems in such small
platforms.


Looking for a cheap small arduino ish board I'm looking for a cheap and small bluetooth board for a project.
I found this one, but I find this one too expensive, are there cheaper alternatives, in similar size?

Thank you!

I'd suggest investigating the ESP32.

It's not only a far more powerful chip than any normal Arduino, but it has both WiFI and Bluetooth Low Energy, all on the one chip.

It's available as surface mount modules, similar to the ESP8266, and there are a number of small development boards that have been created around it as well.


Sending A String from a Website to Arduino I'm quite new to Arduino and have looked at many tutorials featuring an Arduino requesting data from a web server through a Wifi Shield, but haven't seen one featuring the sending of data from a website/server to an Arduino. I'm attempting to use a JavaScript then PHP script to send a string variable to the Arduino, which would then of course run its code at this point. Is this possible if I have a Wifi Shield and the Arduino's IP address?

On the yun, this functionality is built-in via the bridge. Here's an example.

Via the shield, you now end up writing your own webserver and responding appropriately.

I'm guessing it makes more sense to use the client (the web browser) to make the calls than the backend php, but in either case, once the webserver is up and going on the arduino, you're just using it like any other server.


Sending Float values from Python to Arduino via serial communication I want to Control the current flowing through a circuit using an Arduino. I have trained a PID controller for this purpose. I am using a current sensor to determine the error. It runs successful on my Arduino.
In my next step I want build a system where I can send the Current setpoint (deter mined by my python code) value to the Arduino through serial communication. I am able to send integer values to Arduino. But I am unable to send and receive float values from Python to Arduino. I want to know the necessary code to be written in both sender and receiver.
I tried of converting float to string and then send it to Arduino. But I failed. Please help.

Arduino Code(edit- Sorry previous code was an old file. Here is the correct one):

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
//pinMode(13,OUTPUT);
}
float f;

void loop() {
 if(Serial.available())
      {f=Serial.parseFloat();
        Serial.println(f);
      }
    delay(1000);
   }
//count=count+1;
      //delay(1);
//}

Python Code (edit- Sorry, the previous code was from an old file. Here is the correct one):

import serial
import time
import struct

ser = serial.Serial('/dev/ttyACM0', 9600, timeout = 1) # ttyACM1 for Arduino board
data=5.7

while True:
        ser.write(str(data))
        time.sleep(1)
        ser.flush()

When I run this code I get the following output on the Arduino Serial Monitor. As shown in the figure below.

Thank you.

It would seem you managed to solve your problem with
Serial.parseFloat(). This is probably the easiest solution, but it has
one serious drawback: it is a blocking function. Which means, during
all the time needed by the serial port to transfer the number, your
Arduino does nothing but wait for the incoming characters. This is an
issue if your program has other task to do like, e.g., manage a PID
regulation.

I suggest you consider reading the serial port in a non blocking
fashion instead. This should make your PID happier, as it won't feel
neglected while you read the incoming data. Look Alterno's answer is a
good example of a non-blocking function that combines reading and
parsing. However, I would like to point out that you do not need to
implement your own number parser if you don't want to. A very common
pattern is to instead store the incoming characters in a buffer and,
when you see the character chosen as a terminator (e.g. ASCII LF), you
parse the buffer at once using either strtod() or atof(). For
example:

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

void loop() {
    static char buffer[32];
    static size_t pos;
    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\n') {  // on end of line, parse the number
            buffer[pos] = '\0';
            float value = atof(buffer);
            Serial.print("received: ");
            Serial.println(value);
            pos = 0;
        } else if (pos < sizeof buffer - 1) {  // otherwise, buffer it
            buffer[pos++] = c;
        }
    }
}


Stepper motor shield compatibilty question I recently bought Adafruit's motor shield v2 only to find out it can only support upto 12v.

So I'm on the look out for another shield & found this one
Arduino Dual L6470 Stepper Motor Shield

I have an Arduino Mega & the documentation says it is fully compatible with the UNO.

Will there an issue using this shield with a Mega? Or if anyone else can point me at a decent stepper controller?

That is an SPI based device, and it doesn't use the (now considered standard) 6-pin ICSP header for SPI.

Therefore it will only directly work on boards that have the SPI pins available on pins 10-13 of the digital headers.

To use it with other boards you will need to manually route the SPI pins to the right places using wires.


Interaction between Analog Pins when measuring a DC voltage- a common issue? Just set up a replacement "Piduino" - a RPi3 connected by USB to an Arduino Uno.  The previous one was the victim of a Diet Big Gulp - spilled on the voltage divider breadboard.  Whoops.  The tiny breadboard with the voltage divider began to rust inside so it got really difficult to keep it working correctly.

This is for the plot named "Indoor 12V Lighting System" at https://www.SDsolarBlog.com/montage

I built a new Uno/breadboard from scratch and swapped it in with the breadboard stuck onto the plastic case.  All nice and tidy.

But the analog inputs were really strange.  It would read really close, but then minor changes to the software would produce wildly varying results.

Imagine my surprise when this morning I discovered that I had plugged the divider's analog input to A4 instead of to A1 where it belonged.

Now that it has been fixed all is well.  As long as the correct pin is being used in the digitalRead it seems not to matter, perhaps.

Here is the plot from before then after I moved the input to the correct location:

The actual voltage was falling from 12.7 down to 12.5, and after moving the pin it settled down to the correct reading.  Then I turned on the charger while the sun is up.  It is tracking the voltmeters perfectly now.

Clearly, the problem was that I was reading the wrong pin.  My fault, obviously. But it got me wondering just how much they affect each other.

So my question is about why I was getting any readings at all?  I would have hoped that the analog inputs were truly separate from each other.  Instead, it appears as if there is crosstalk of some kind.

Is this a common issue?

New information

I see that it has been pointed out that this was discussed in this Q&A:

Should all unused analog input ports be tied to ground for accurate A2D measurements?

But since that does not call it an imperative, just "one of the problems with using analog" I would have assumed that this is not common, so perhaps there is an implied answer there.

It would be a project all by itself to use half the small breadboard to distribute ground to all the other analog pins.  And I've never seen this referenced in any of the documentation.  Nor is there a tag for crosstalk.

So my question still stands:  Is this common when measuring a DC voltage?

This is normal and expected behaviour.  There are a number of factors that influence it, and it will help to understand the basic internals of the ADC.

In simple terms the front-end of the ADC looks like this:

simulate this circuit – Schematic created using CircuitLab

The MUX selects which pin (A0-A5) is being sampled. Switch SW1 connects the Sample And Hold capacitor C1 to that selected input, which then charges (or discharges) to the same voltage as the input.

After the acquisition period switch SW1 switches position and the ADC circuit is connected to the capacitor.  Over a period of clock cycles the ADC works out what the voltage across the capacitor is and stores the result in the ADCH and ADCL registers.

Now - on a pin that has nothing connected to it, what voltage will be across that capacitor when SW1 is switched to charge it? Well, this is where your strange results come from:

Any charge already in the capacitor will still be there (which is why it can be good to connect the unused ADC pins to ground through a resistor, to remove that charge).
Signals, either in wires, IC pins, or the silicon circuitry in the chip itself, will be capacitively coupled with what is next to it.

That last one is the most critical for your results.  Capacitive coupling.

Place two wires next to each other and they will, through capacitance, try and get the same charge on them. Under most circumstances that attempt to influence the charge is completely swamped out by what is being send down the wire. But, when there is nothing being sent down the wire that charge becomes noticable. A1 will attempt to "float" to the same level as A0, because they're next to each other. A2 will try and float to the same level as A1, A3 to A2, etc.

If you put a signal in to A0 and plot all 6 inputs you will see each has a progressively lower amplitude copy of the signal. It's hopping, capacitively, between the pins. And all because there's nothing to stop it.

If you think "Ah, but it's DC. DC doesn't go through capacitors", then you're wrong.  Wrong in thinking it's DC.  There's a lot of mistaken assumptions about the labels "AC" and "DC".

DC is not what you have.  Yes, there is a "DC component" to what you have (which is manifest as the average of the voltage over time), but there is a large AC component as well.  That AC component is what you are graphing in the form of your changing battery voltage.

Voltage is far more complex than just DC or AC. What you think of as AC is actually a waveform with a fundamental frequency (e.g., 60Hz) and zero "DC offset". Add a DC offset to the signal and it's still AC, but compared to the "lower" end of whatever adds the DC offset, it's just the waveform is "shifted up".

Pure DC, and what doesn't pass through a capacitor, has no signal components. There is only 0Hz and nothing else. Pure DC is almost impossible to create without highly specialized equipment. All voltages in normal life vary, and that variance is the AC component of the signal.