I have a problem trying to limit motor speed to a certain RPM using a MOSFET trigger switch module

Your problem is that you don't know what ADC value maps to the maximum RPM. If you did you wouldn't need to know the RPM.
What you have here is a "feedback loop", and what you need is some method of using the detected RPM to control the speed of the motor.
You need to decouple the potentiometer from the analogWrite completely - the potentiometer should be setting the desired RPM, not the value being sent to set the RPM.
So if you want an RPM range from, say, 0 to 100RPM you can map() the analogRead() to the values 0-100. Then you can examine the actual RPM and adjust the value you send to the PWM accordingly - if the motor is too fast then slow it down. If it's too slow then speed it up.
There's a special method that is used for this: PID. And there's a library that does it for you too:

https://playground.arduino.cc/Code/PIDLibrary/

The potentiometer provides the "set point", the RPM detection provides the "input", and the PID library gives you the "output" to feed to the analogWrite().  You need to then provide the special magic "tuning" parameters to give the best control over your motor.


List of sketches disappears off the bottom of my screen

That issue has been fixed since the Arduino IDE 1.5.5 release, 4 years ago.

The version of the Arduino IDE you get from apt-get install arduino has not been able to be updated for years due to licensing issues. The versions available from various package managers may also be modified in ways that introduce new bugs. For this reason you should always install the official Arduino IDE version downloaded from:
https://www.arduino.cc/en/Main/Software


How to limit the number of message that an Arduino sends to a phone without terminating it

You use millis() to keep track of time and also prevent blocking. Replicating your program logic:

long soil_timer = 0;
long tilt_timer = 0;
char soil_flag = 1;
char tilt_flag = 1;

void loop() {
    int soilSensor = analogRead(A0);
    int tiltSensor = analogRead(A1);

  if (soil_flag == 1) {
    if (soilSensor >= 10) {
      digitalWrite(22, HIGH);
      Serial.println(soilSensor);
      sendSMS1();
    }
   else {
      digitalWrite(22, LOW);
    }
    soil_timer = millis();
    soil_flag = 0;
  }

  if (tilt_flag == 1) {
    if (tiltSensor >= 100) {
       digitalWrite(led, HIGH);
       Serial.println(tiltSensor);
       sendSMS2();
    }
    else {
       digitalWrite(led, LOW);
       Serial.println(tiltSensor);
    }
    tilt_flag = 0;
    tilt_timer = millis();
  }
  if (millis() - soil_timer >= 60000){
     soil_flag = 1;
  }
  if (millis() - tilt_timer >= 60000){
     tilt_flag = 1;
  }
}


How do I power my Arduino Micro directly?

According to this schematic, VIN goes to the on arduino-micro's 5 and 3 volt regulators.  So you should not need a resistor.

The 5 volt regulator needs a bit more than 5 volts at it's input to do a good job.  That is why the specification calls for 7 to 12 volts.


Sampling/transmission limits for USB and Arduino UNO R3

It is not possible to sample two signals at the exact same time with an
Arduino Uno. The Arduino has only one ADC, so you have to sample one
signal, switch channels, sample the other, switch channels again, etc.
If this is acceptable for your project, then yes, it is perfectly
feasible with an Arduino Uno. But you will have to dig into the
datasheet and program the ATmega328P low-level.

Regarding the sampling rate, you want the ADC to take 9600 samples
per second (4.8 kS/s × 2 channels). This means one sample
every 104 µs. You are lucky: in the default Arduino configuration,
the ADC conversions take exactly 104 µs. frarugi87 and Jot suggest
you reconfigure the ADC for faster sampling. This is useless: the
default sampling speed is already optimal for you application. Leave it
as is.

You also require a fixed sampling rate. This is not possible to do
with software. Configuring the ADC in auto trigger mode is the only
way to get a really steady rate. The ADC can be triggered by a timer,
but in your particular case, it is just simpler to have it trigger
itself. This is called free running mode and it gives a sampling rate
of exactly one sample every 104 µs. Perfect for your application.

Jot also suggests disabling interrupts. Do not do that! Interrupts are
harmless because the ADC manages its own timing. And they are actually
useful: I would use the ADC interrupt to retrieve the conversion result,
send it through the serial port and switch channels in the multiplexer.

If you are happy with 8-bit resolution, I recommend you enable the left
adjust result mode. This way you can retrieve the 8-bit result from the
ADCH register and you won't need to do bit shifts.

  I guess that the transmission rate would be too slow to do this in
  real time. I will have to store this somewhere in the Arduino board so
  it can be transmitted afterwards.

Both options are possible. If you send the data in binary, you will need
a baud rate of at least 9600 bytes/s × 10 bits/byte
= 96 kb/s. You can opt for 115.2 kb/s, which is standard
and widely supported. If you want to store the data, then you will need
9600 bytes/s × 0.1 s = 960 bytes, or about half
the Arduino RAM. This is fine, as the program can be quite simple, so it
won't need more than half the available RAM.

Just to give you some inspiration, I suggest you take a look at this
sound-meter
sketch of
mine. It configures the ADC in free-running mode at 9.6 kS/s and
retrieves the result using the ADC interrupt. I would use the same ADC
configuration for your project, only with left-adjust and with channel
switching performed by the interrupt handler.

Edit: I just wrote a “dual channel oscilloscope” program along the
lines of this answer: dual-scope.c. It's written in plain C, but it
can also be compiled as a regular .ino file. I only tested it with
constant voltage inputs though.

The program ended up being tiny: it uses about 1% of the flash, 1.4% of
the RAM and 3.4% of the CPU power on an Arduino Uno. Meaning you could
add stuff to it if you feel so inclined.


Arduino-like boards with other microcontrollers

You have to define what you mean by "Arduino-like" beyond just not using an AVR.

There's the Arduino Galileo using an Intel chip and supports the Arduino development tools, as well as the Arduino Due which is an Arm-based chip.

There's the Netduino which uses ARM chips (STMicro's) and is pin compatible with Arduino shields, but I don't know what the development framework is (other than it being in .NET), though this doesn't necessarily say much because not even all Arduino boards have the same pin compatibility (Nano boards are much smaller, LilyPad Arduinos which are round and semi-flexible, etc.)

Then there are related boards, but don't support the Arduino environment or any pin compatibility (TI Launchpad springs immediately to mind, but pretty much every manufacturer has some sort of demo board or development board for their MCU's).

There's a huge list of Arduino-like boards here (split into levels of compatibility, includes the official Arduino boards).


A recommendation for a fast-response-time-resolution-mp3-module for arduino

I'm going to suggest that you stay away from these mp3 modules. It is perfectly reasonable to use a stand-alone arduino unit to directly generate sound using the digital output pins with a low-pass filter RC circuit. This is the most efficient way of doing this and will give you a very low activation latency.

https://playground.arduino.cc/Code/PwmFrequency/

The other option is to connect a DAC circuit and simply build a sample table for the wave outputs you need for each tone.


Advice on setting up a real-time audio equaliser

Somewhat possible if you accept that the Arduino won't be doing most of the work:

Yes, the Arduino can sample audio and perform FFT on it, though not fast and not at high frequencies
Yes, the Arduino can decide what to do depending on the power of different buckets
Yes, the Arduino can display the results
No, the Arduino cannot do realtime audio filtering.

If you accept that the filtering will have to be done with a bank of analogue band-cut filters that the Arduino turns on and off as needed then it may be possible.

The Arduino Due might be a more suitable candidate since it will be able to sample and do the FFT much faster so you'll be able to respond to the peaks much quicker, and the displaying won't get in the way so much, but actively filtering inside the chip really requires a DSP.


The use of 4.7kOhm resistor with DS18B20 temperature sensor

The product page FAQ [https://www.maximintegrated.com/en/support/faqs/ds18b20-faq.html] has an entry:

Q: Is the 4.7kΩ resistor needed for 5V and 3.3V operation?
A: Yes, the 4.7kΩ pullup resistor is required for both 5V and 3.3V applications.

The 1-wire bus requires that the control signal be pulled high so the master device can pull it low to ask for data, and the slave device can pull it low to give the data. This allows you to have multiple 1-wire devices on the same "one wire".

The data sheet notes another purpose:

Another feature of the DS18B20 is the ability to operate
without an external power supply. Power is instead
supplied through the 1-Wire pullup resistor through the
DQ pin when the bus is high. The high bus signal also
charges an internal capacitor (CPP), which then supplies
power to the device when the bus is low. This method of
deriving power from the 1-Wire bus is referred to as “parasite
power.” As an alternative, the DS18B20 may also be
powered by an external supply on VDD.


Arduino Uno and Raspberry Pi USB Serial Communication

Just at a glance:

Your loop consumes the byte and stores it in serialRead, so there is probably no available data at the outer if, so it is never entered.

Try deleting this line:

serialRead = Serial.read();


You have declared WiFiClient client; in the scope of setup() only. Move it's declaration to the global scope by placing it above the declaration of void setup()


This is the code that worked for me:

#include "sha256.h"
void setup(void)
{char encoded[64];
    Serial.begin(9600);

    // this is actually the RFC4231 4.3 test

    Sha256.init();
    Sha256.print("123");
    uint8_t * result = Sha256.result();

    Serial.println("Expect: 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881");
    Serial.print(  "Got   : ");
    for (int i = 0; i < 32; i++) {
            Serial.print("0123456789abcdef"[result[i] >> 4]);
            Serial.print("0123456789abcdef"[result[i] & 0xf]);

            for(int i = 0; i < 64; i+=2)
                {
                  encoded[i] = "0123456789abcdef"[result[i / 2] >> 4];
                  encoded[i + 1] = "0123456789abcdef"[result[i / 2] & 0xf];
                }
    }
    Serial.print("\n");
            for(int z = 0; z < 64; z++)
            Serial.print(encoded[z]);
}

void loop(void)
{}


Arduino + UltraSensor - Serial Monitor outputs garbage

Check your serial monitor baud rate. This is definitely caused by your serial monitor being set to a different baud rate than the 9600 you specified in the program.

If it had anything to do with the sensor than this line would be printed properly Serial.print("Distance: ");

Once you change the serial monitor baud rate then try running this program, to verify that it is set properly:

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

void loop() {
  Serial.println("Hi There!");
}

If that prints "Hi There!" then the program your serial monitor is set up properly.


"variable must be const" fix for Arduino progrem

Using the source from this link I got it to compile following these steps.

Before opening the sketch in the Arduino:

Rename TVB.pde to TVB.ino
Rename WORLDcodes.cpp to WORLDcodes.h

Open the sketch (TVB.ino) in the Arduino IDE

Edit main.h and change:

// The structure of compressed code entries
struct IrCode {
  uint8_t timer_val;
  uint8_t numpairs;
  uint8_t bitcompression;
  uint16_t const *times;
  uint8_t const*codes;
};

to:

// The structure of compressed code entries
struct IrCode {
  uint8_t timer_val;
  uint8_t numpairs;
  uint8_t bitcompression;
  uint16_t const *times;
  uint8_t const*codes PROGMEM;
};

That is, add PROGMEM to the codes line.

Edit TVB.ino and change:

extern PGM_P *NApowerCodes[] PROGMEM;
extern PGM_P *EUpowerCodes[] PROGMEM;
extern uint8_t num_NAcodes, num_EUcodes;

to:

#include "WORLDcodes.h"

This avoids some linker problems in the original code.

Edit WORLDcodes.h and delete the line:

 #include "main.h"

Continue editing WORLDcodes.h and change:

const struct IrCode *NApowerCodes[] PROGMEM = {

to:

const struct IrCode * const NApowerCodes[] PROGMEM = {

And also change:

const struct IrCode *EUpowerCodes[] PROGMEM = {

to:

const struct IrCode * const EUpowerCodes[] PROGMEM = {

It should now compile OK.


Servo issue, won't go into negative range

First of all Servo.write(int) takes a value ranging from 0 to 180 degrees.
Then, servos themselves can only move from 0 to 180 usually. Some can do more, some can do less. But regardless of how much a servo actually moves, you should expect that doing Servo.write(0) the servo would rotate all the way to one side, doing Servo.write(180) it should go to the other side, doing Servo.write(90) it should stay in the middle.

Also, lcd.setCursor(5, 1); is basically useless as the lcd driver itself would advance the cursor as the previous characters are written. Just do lcd.print("= "); if you want an additional space between the equals symbol and the number


I think using an interrupt controlled measurement might provide the best results for you.

Note: you might get more complete feedback using the Arduino forum.

In general the process would look like this:

Set up an interrupt vector for the ADC peripheral (in this case support for ID37).
Setup ADC registers (res, clock etc)
Set up a timer to time the conversion.
Create Active flag and Timer variables for processing inbound timer values.
Start timer and ADC conversion.
Loop waiting for active flag to set (it gets set in the ISR), when detected do average or store timer values, then clear active flag.

This methodology times each individual conversion using a high speed timer, which could mean a lot of values to process. You could equally not time each conversion, but simply set up say a 1 second timer, and count the total number of conversions in 1 second for your particular ADC configuration.

Peripheral ISR

Waiting for Interrupt.
In peripheral ISR, read and store timer value, reset timer, set active flag
Return from ISR


Comparing and contrasting with the SD card file -- I've found that if you comment out the following -- it works. Maybe this will help someone.

//#if !defined(SOFTWARE_SPI)
//#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//  if(chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
//#else
//  if(chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
//#endif
//#endif


In OnReceive, you are concatening a string with a char. This may be the cause of the resets.

As a side note, you don't really need to use strcat, strcpy and other str functions. You can make your sketch lean by accesing the arrays directly, like this:

char _buffer[10];
int index = 0;

bool OnReceive()
{
  bool status = false;
  if (RS485Serial.available())
  {
    digitalWrite(Pin13LED, HIGH);
    char _byte_received = RS485Serial.read();
    if (_byte_received == 'X') {
      _buffer[index] = 0; // Mark the end of string.
      index = 0;
      status = true;
    } else {
      _buffer[index++] = _byte_received;
      // ToDo: check for overflow;
    }
    digitalWrite(Pin13LED, LOW);
  }

  return status;
}
void setup() {
  Serial.begin(9600);
  Serial.println("Restarting...");
  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Receive);
  RS485Serial.begin(9600);
}

void loop()
{
  if (OnReceive())
  {
    Serial.print("value: ");
    Serial.print(_bufer);
    Serial.println("");
  }


How to add a pedestrian button code to a traffic light with ultrasonic sensor?

Thank you for making it clear that this is course work.
You are asking for help to do the extension, but by your own words you don't understand how the core code works.  I have to be honest I can't be bothered to read the code, it looks horrible.  If I was your teacher I would quit, because I have failed to teach you one of the most fundamental aspects of coding.  "You write it once but it gets read many times", it is ALWAYS worth spending a few minutes making the code look pretty!  (If you teacher can't be bothered to read it, you aren't going to get 100%!)

Comments - commenting out code is not the best use for // explaining why you are doing what you are doing is.
Its good that you have defined variables to identify you pins, but you have two identical sets of variables, so you could have used an array, a structure or an array of structures.  (These might be more advanced than where you are at the moment, sorry if that's the case).
Breaking you code down into bite sized pieces make it more readable.  That start of your loop contains some code that could be in a function called getDistance()
Turning the lights on and off in the way you are doing it is open to errors.  You could turn the red light on and the green light on.  If you made a class to represent the lights then you could have a function that turned off all of the lights and only turned on the one you wanted.  You wouldn't need to store the state.

Example code (not tested or compiled)

class Lights
{
  public:
    enum eLight {Red, Amber, Green, GreenArrow, GreenPedestrian, RedPedestrian, eMaxLight};
    Lights(int[] pins)
    {
      for (int l = 0; l < eMaxLight; ++l)
        pinMode (pins[l], OUTPUT);
    }
    ~Lights()
    {}
    void setLight (eLight newLight)
    {
       for (int l = 0; l < eMaxLight; ++l)
         digitalWrite(m_Light[l], LOW);
       digitalWrite(m_Light[newLight], HIGH);
    }
}

You probably want to look at a state machine.  List all the possible LEGAL combinations and then create a enum with each of those states in and then write a function that moves from a state to the next legal state, you will need conditionals for has the button been pressed.  This should give you a working system with a pedestrian button that hopefully you understand.


Arduino Mega + XBee Shield + RAMPS 1.4 Is it possible?

Yes, it would seem like folks on the RepRap forums have gotten this to work with the following setup that should work in general:

  Attach the XBee shield to the RAMPS board by attaching 4 pins on AUX-1 (namely, 5V, Gnd, D1 and D0) to the 5V, Gnd, Rx and Tx pins on the XBee Shield

  Switch the UART / DLINE switch on the XBee Shield to UART

Source: RepRap Forum: Printing completely wirelessly - can it be done?

This forum thread may also be useful.


PROGMEM: do I have to copy data from flash to RAM for reading?

AVR is a modified Harvard architecture family, so code is stored in flash only, whereas data exists primarily in RAM when being manipulated.

With that in mind, let's address your questions.

  Why on earth do I have to copy the damn content to RAM before accessing it?

You don't need to per se, but by default code assumes that data is in RAM unless the code is modified to specifically look in flash for it (such as with strcpy_P()).

  And if this is true, what happens to all the code then? Is it also loaded to RAM before execution?

Nope. Harvard architecture. See the Wikipedia page for the full details.

  How is the code (32kiB) handled then with only 2kiB RAM?

The preamble generated by the compiler copies the data that should be modifiable/modified into SRAM before running the actual program.

  Where are those little goblins carrying floppy disks?

Dunno. But if you happen to see them then there's nothing I can do to help.

  ... are 5, 10 and 7 really copied to RAM before loading them into registers?

Nah. The compiler evaluates the expression at compile time. Whatever else happens depends on the lines of code around it.


Can't power HC-05(5v) with Arduino Pro mini (3.3v)?

It seems like 7.4V DC is greater than the 5V regulator input range on the HC-05.

For example, in the Core Electronics tutorial for the HC-05 (the tutorial PDF calls it a JY-MCU. I can't find any major differences), the pinout table says the voltage should be from 3.6V to 6V DC:

These same values are confirmed by a back-of-the-circuit-board photo from arduino-info.wikispaces:

Components101 says the range is 4V to 6V.

Unfortunately your coin cell voltage is too low. That leaves you with the following options to drop your voltage (if you must use the 7.4V DC battery). Your choice will probably depend on the Wh capacity of your battery, and how efficient you need the voltage drop circuit to be.

Zener diode (few components, inefficient use of power)
Voltage divider with resistors (few components, inefficient use of power)
Linear regulator (few (IC) or many (discrete) components, inefficient use of power)
Switching regulator (many components, efficient use of power (because it does not use a resistor to drop the voltage)

Further details on each of these options are at Lower Voltage Methods Other than Voltage Dividing.


Arduino digital input fluctuates with neighbouring pins

Posting here since it is quite long, but it's not a complete answer, just a few thoughts and a possible improvement.

Ok, so there are a couple of things in your code I don't understand:

1: in the setup()

{
    int i;
    for (i = 0; i < 4; i++);
}
{
    int j;
    for (j = 0; j < 4; j++);
}

What are these for?

2: debouncing

You are not implementing it correctly, at least not for me. You are reading the button every 50ms, without debouncing. Ok, you won't see "bounces", but there are better solutions (see later).

3: modes 1 and 3

They are quite useless. What are they for?

4: pins 6,7,8,9

What are they for?

5: variable laststate

What is it for? You never use it

6: updating one button per loop

Is it needed? I mean, you are just updating one button per loop instead of all of them for each loop.

In the end

Ok, now my suggestions, apart from learning to indent the code (otherwise it's impossible to read it): I always use the bounce2 class to debounce a button, since it contains everything inside and.. Well, it works well. It can also detect the rising and falling edges of the button, thing that you need if I interpreted correctly your code.

One more thing: debounce delay can be lowered (even to just 5ms):

#include <MIDI.h>
#include <Bounce2.h>

int buttonPin[] = {2, 3, 4, 5};
int buttonPinM[] = {6, 7, 8, 9};

Bounce debouncers[4];
Bounce debouncersM[4];

int debounceDelay = 50; // Usually is lower - even 5ms is fine
uint8_t i = 0;

void setup ()
{
    MIDI.begin(MIDI_CHANNEL_OMNI);

    for (i = 0; i < 4; i++)
    {
        pinMode(buttonPin[i], INPUT);
        debouncers[i].attach(buttonPin[i]);
        debouncers[i].interval(debounceDelay);

        pinMode(buttonPinM[i], INPUT);
        debouncersM[i].attach(buttonPinM[i]);
        debouncersM[i].interval(debounceDelay);
    }
}

void loop ()
{
    for (i = 0; i < 4; i++)
    {
        debouncers[i].update();
        debouncersM[i].update();
    }

    for (i = 0; i < 4; i++)
    {
        if (debouncers[i].rose()) // button i switched from 0 to 1
            MIDI.sendNoteOff(i+55, 0, 1);
        if (debouncers[i].fell()) // button i switched from 1 to 0
            MIDI.sendNoteOn (i+55, 127, 1);
        if (debouncersM[i].rose()) // button i switched from 0 to 1
            MIDI.sendNoteOn (i+61, 127, 1);
        if (debouncersM[i].fell()) // button i switched from 1 to 0
            MIDI.sendNoteOff(i+61, 0, 1);
    }
}


Parse an element that consists of an array using ArduinoJson

My code was correct. The problem was that the json array contained an " " as first character. Thats why the parsing failed.


File include error while using Arduino Nano

You have to put the folder with the library files in the folder libraries under your sketchbook folder. Then the IDE should be able to find them.

I think there is also a possibility to save them in the same folder as your .ino file, but it I don't know how exactly you have to do this.


Expected Unqualified-ID Before 'do'(and 'while')

The do whiles are outside of the setup() or loop(), so they won't work.

I would suggest doing a simple C/C++ tutorial like this one to get up to speed with how things work.


What USB to UART chip provides highest data rates with Arduino boards?

Here's my experience with the above chips over the last two years:

FT232R is the fastest, works well with any baudrates. UART adapters with it are sometimes more expensive than alternatives.

PL2303 is good if you don't plan to go faster than 115200. Additionally, it has the strongest 3.3V reference (available on some adapters as 3.3V output) which can be abused as a 3.3V 20mA power supply. Other chips will refuse to work if you draw more than 5mA from the 3.3V reference.

Prolific is currently fighting against clones by making their up-to-date drivers incompatible with non-original chips, so if your adapter won't work in Windows with code 10, take a look at this page.

CP2102 which looks great in theory didn't work well for me (in Windows 10, with driver v10.1.3). Bulk data transfers at 115200 were in some cases 4 times as slow compared to other chips.

CH340G has a sketchy-looking windows driver, but otherwise works quite well and is often the cheapest option available. Unfortunately, it lack the intermediate baud rates, and getting 2Mbps UART link to work may be hard sometimes. Arduino clones which have this chip on-board do work at 2Mbps without issues (the ones I have seen do, anyway).


You can cycle through all the addresses in the EEPROM like a ring buffer.

You'll need to reserve a bit so you can binary search for the head of the buffer during startup.

You can also reduce how often you write in general especially when the count will increment in bursts, try and wait out those bursts instead of writing on every increment.


Relay built in to cable with arduino interface

PowerSwitch Tail is what you are looking for.


Using Arduino To Control Boot Sequence of PC

So it might depend on how you implement it. With an Arduino Uno, your options for creating an HID device are limited to either reprogramming the 16u2 (which will require an ISP) or using a software USB implementation (like V-USB). If you go with the first method I'm pretty sure that will work as it will be a native USB connection. As for the second method, I'm not sure how well V-USB responds to having the USB host turning on while it is running. The best thing to do is just try it and see how well it works.

The bigger challenge you will run into is being able to select your PC operating system. Because this will be a one way connection, there is no way of knowing what state the computer is in and whether or not it is time to press a key yet or not. This means you will have to be timing things fairly accurately, which can be tricky unless you are careful. The internal oscillator is not very accurate (but probably still accurate enough) and interrupts used for communicating with USB can block the main loop. That is not to mention any variations the computer might have in its boot process.

A good alternative method would be to set up a bootloader on your PC that can be controlled via a serial port. GRUB2 is a popular one that does support a serial console. All you would need to do is add a level adjuster to adapt the Arduino UART to RS232, then set up the code to wait for the GRUB prompt and then send the command necessary to select which OS you wish to use.


Have both sync to a master clock using GSM shields. These shields are getting very cheap (as low as $14 on ebay).

The shields receive the time wirelessly from the cellular network and this time base is extremely accurate. Here is some example code to read the current time from the shield...

http://forum.arduino.cc/index.php?topic=163155.msg2102141#msg2102141

Note that you will need a SIM card to get the time, but you should not need an active cellular account.


C(++) does not natively let you "add" arrays like that.  Your code looks like maybe Python.

There are several ways to do what you want to do.  You could make your code which writes the pattern to the array accept an offset - so rather than always starting at position 0, you could tell it where to start.

You could write a function to "concatenate" arrays, or use one someone else has written, if you can find one.  It's pretty trivial to do.

However the method I'd use in your situation, probably just a matter of preference really, is this:

Let's say (for example) you have 6 strips of 10 LEDs each.  You need 60 elements to represent them all.  (I'm assuming each element is an int; I can't remember if it is.)  Create one big array for the whole lot:

int allElements[60];

You might think of the variable allElements as an array, but it is really an int* (a pointer to an int), with that memory address happening to have 59 other memory addresses after it reserved.  C knows that when you say allElements[7] it needs to looks 7 ints on from the address pointed to by allElements.  What this means is that you can create new variables which point to parts of that array, and use those variables as if they were their own arrays.  For example:

int *firstStrip = &(allElements[0]);
int *secondStrip = &(allElements[10]);
int *thirdStrip = &(allElements[20]);
/* ... and so on */

(There is a more idiomatic way to write this which is exactly equivalent, but I think the above is more explicit if you're new to it.)

As an extra improvement you might now notice that you have a load of similarly-named variables with similar functions -- and you might want to put them into an array.

int* strips[] = { &(allElements[0]), &(allElements[1]), &(allElements[2]) /* and so on */};

Now you can use strips[3] to give you the fourth strip.

There are several other ways too, but I think this will get you going.


Can an a Arduino make music or speech without a speaker?

Sound happens because of a disturbance in the air (or other conducting medium). So the short answer is an unqualified "yes." To start making a recognizable "tune" or "voice" you would need to vary the frequency at which you create the disturbance. In the case of a relay, you'd be varying the rate at which you activate it. This would be very possible on the Arduino.

To get recognizable sounds out of a relay you'd need one that can respond in the range of a few hundred Hz (which would give notes around middle C (roughly 260 Hz) up to a few KHz. From what is posted in @CharlieHanson's comments and answers, it doesn't seem like common relays can do that.

A function that takes agreements of pitch and duration, something like:

 note(hz, ms)

would give you a fairly easy way to describe the music you wanted to play.

Just for fun, here are a few examples of "speakerless devices" making music:

Floppy disc drive music
Lotus F1 car plays Happy Birthday


Setting reading frequency SCT013 current sensor code using Arduino Uno

you skip reading when the last read is less than 1000/200 = 5ms ago.

unsigned long lastRead;

void loop()
{
   unsigned long currentMillis = millis();
   if(currentMillis - lastRead >= 5){

      double Irms = emon1.calcIrms(1480);  // Calculate Irms only

      Serial.print(Irms*230.0);        // Apparent power
      Serial.print(" ");
      Serial.println(Irms);            // Irms
      lastRead = currentMillis;
    }

}


Problem Uploading to arduino nano (atmega 328p)

Looking at the error in the end about the invalid library, it seems a configuration problem and not a communication problem.

Try:

Close and reopen the Arduino IDE (and check again)
Remove the library and add it again (in the Manage library options in the menu), close/reopen the Arduino IDE (and check again)
Reinstall the Arduino IDE (and check again)


Updating SPI transfer16 to create Transfer24

You can't.  The teensy 4.0 has hardware support for 8-bit, 16-bit and 32-bit transfers. Not 24-bit transfers.
But at 600MHz the overhead of making a function call is negligible anyway - certainly compared to the speed of SPI which is at best about 30x slower than the CPU operates at.
If you want high throughput you won't be wanting to use the SPI library anyway, instead you'd be using DMA to transfer your data with minimal CPU intervention.


Here is your main problem:

if (mySerial.available()) {
    for(;i < 2;){
        buf = mySerial.read();
        i++;
    }
....

There you are saying "If there is at least one character available in the buffer then read lots of characters from the buffer".

You can't read characters that aren't there yet.

So your stream of data is interspersed with the integer -1 which means "I don't have any data to read!"

I explain it all here: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

By the way - character -1 looks like this: ÿ

You are sending your data as text.  That means, to send the value 348 you are first sending the byte representation of the ASCII character "3", which is the decimal byte value 51.  Then you send the byte representation of the ASCII character "4", which is the decimal value 52, and finally you send the byte representation of the ASCII character "8", which is the decimal value 56.

You look to see if there is one byte available (if(mySerial.available())) and then read that byte into "buf" and increment "i" (by the way, "i" is never reset to 0 - your whole loop strategy is completely wrong, but that's a completely different issue).  You then read a second character and assign that to buf instead.

So if you have the character "3" in the serial buffer you then place that in "buf".  You then read whatever is next in the buffer, which 9 times out of 10 will be nothing, so read() returns -1.  So you just assign that to "buf" instead, replacing the "3" that was in there before.

But "buf" is a character array, and you are assigning a character to the whole array, which makes absolutely no sense (does the code even compile as you have shown it?).

Basically your whole reading routine is completely wrong and can never work no matter how much tweaking and advising we do.

The link I provided above describes not only how you should do the reading on the Arduino, but also how you should do the sending from the other end.  It is vitally important that you send something that says "This is the end of the number I am sending" so that the Arduino knows where one number ends and the next starts.  Normally that is done, when sending a textual representation of the number like this, by adding a line feed and/or carriage return at the end of your number.  So instead of sending "348" you send "248\n".

The Arduino then checks to see if there is one character available, and then it adds just that one character to the end of the buffer.  If, and only  if, that character is the delimiting character then you can take the buffer and translate it into an actual number and reset your buffer to be empty ready to receive the next number.

The link above has good example code showing you exactly how to do that.


It's not a question of voltage. You make a basic mis-assumption:

in Arduino while doing speed control 255 means 5v

No, it doesn't.  255 means "Provide a logic HIGH signal all the time".
128 means "Provide a logic HIGH signal 50% of the time".
The 255 (or whatever number) is the "duty cycle" of a PWM signal. That is a digital signal that can be LOW or HIGH which is switching on or off rapidly. The duty cycle defines the ratio of ON time to OFF time.
You're not providing a voltage - you're providing an ON/OFF signal.
As long as the HIGH voltage of that signal is above the threshold of the receiving device (the L298N in this case) then it will see it as an ON/OFF signal.
According to the datasheet for the L298 the HIGH logic threshold (VIH) is 2.3V. That means anything above 2.3V is seen as ON and anyting below that is seen as OFF (actually there is hysteresis, so it has to drop below 1.5V to switch to OFF).
So your 3.3V from the NodeMCU is above that ON threshold, so the ON/OFF PWM signal is received properly as such.
Incidentally, it's because of this PWM signal that motors make a whining sound when they start up slowly. Because of this most proper motor drivers run the PWM at above 25kHz instead of the 500-ish Hz of the Arduino, so that whine is above the threshold of human hearing.


Malloc with Objects in Arduino libraries

new actually does work in arduino. it is defined in arduino/hardware/arduino/avr/cores/arduino/{new.h, new.cpp} using malloc. It is not part of avr-libc though (which your link concerns) and has not always been added by arduino.

Both of these work for me:

namespace{ //namespace to deal with .ino preprocessor bug
    class foo{
    public:
        int bar;
        foo(int a){
            bar = a;
        }
    };
}
...
//using new
foo *a = new foo[3]{{1},{2},{3}};

//How I would probably do this with malloc
foo *b = (foo*) malloc(sizeof(foo)*3);
b[0] = foo(2);
b[1] = foo(4);
b[2] = foo(8);

Placement new is not defined right now. I know that copying isn't quite the same, but it should work in most cases.

Of course, if you know exactly how long you want the array to be at compile time, you should probably make it a static/global variable so that you avoid using dynamic memory and the sketch ram usage number will be closer to correct.


Arduino Nano ESP8266 software serial problems

Arduino Nano has its tx-rx serial port shared with the FTDI chip used by downloading and serial console. See https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf
This means that if you drive these pins from ESP, it will flash leds, and all communication on these pins will interfere with serial monitor and board programming as well.

You may:

disconnect ESP during program downloading
pick a different board, which has a separate hardware serial port, such as Arduino Micro, Leonardo, or any Pololu A-star 32u4 boards, this way you have a dedicated serial port to control your ESP
wire the tx-rx of ESP to two other pins of your Arduino micro, and use a software serial library to bit-bang serial communication. (Note that serial receiving in software mode may require clever programming - since while your code does something else it can not receive anything).


Want to create bluetooth audio control (volume up/down, play, pause, etc.) for smartphone

Bluetooth supports multiple protocols for multiple purposes.  There is low latency low quality monorail bi-directional communication with a little bit of bandwidth for control for Bluetooth phone calls.  This is called HFE Bluetooth protocol.  If you are interfacing a keyboard or a mouse you would use the Human Interface Device protocol or HID.  If you wanted to listen to music and control it's playback you would use the high latency high quality 2 audio sending channels (stereo) no return audio channel with a little bit of bandwidth for controlling playback called Advanced Audio Distribution Profile or A2DP.

In this specific case we are only interested in controlling playback.  So we could use the HID Bluetooth protocol.  However, the native music players on the platform you are using (Android or iPhone) likely will not be listening to such a device.  In order for this to work you will probably have to write your own Android or iPhone music player.

On the other hand, it is likely the native music players will work with A2DP Bluetooth protocol.  Unfortunately, it is also suspected that once the A2DP Bluetooth connection is established, the phone's speaker will be shutdown and all audio will be diverted to the Bluetooth connection.

Finally, there is the Audio/Video Remote Control Profile or AVRCP.  This protocol is used to control media playback.  There are several versions of this protocol so what features are available for a given device / music-application may vary greatly.


Using the Arduino shouldn't be any different than any other microcontroller.
The IRremote library is my go-to library for any IR related stuff.
Power shouldn't be an issue, look at the Moteino from LowPowerLab and check out his coin cell battery tests. It's definitely possible. Not with a full blown Uno, but with a bare chip, yes.
You want to burn the bootloader on the IC first, before you can start writing Arduino code. Check out this tutorial: From Arduino to a Microcontroller on a Breadboard. It's the same process for an ATTiny, you just have to look at the datasheet to see where to plug things into. Specifically, MOSI, MISO, SCK, and Reset pins. The Tiny AVR Programmer is also a good choice. It's meant for the 8 pin micros but it has an ISP header so you can use it for almost any chip.

This may be useful for more information about decoding IR signals:

EEVblog #505 - IR Learning Remote Control Hack
EEVblog #506 - IR Remote Control Arduino Protocol Tutorial


Combining two codes to jump back and forth between them

The solution in short.

Although the link is very stupid, it shows very well what you have to do.

Pretty much make a code that combines both of them together. Put both setup in the new setup and carry on like that. Note that you have declared the serial monitor at 2 different baud rates so you can only pick one. Don't repeat previously declared things in your new code and you should be good to go.

Simple example:

Code 1:

const int buttonPin = 2;

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

void loop() {
  buttonVal = digitalRead(buttonPin);
  Serial.println(buttonVal);
}

Code 2:

const int potPin = A0;

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

void loop() {
  potVal = analogRead(potPin);
  Serial.println(potVal);
}

Fusionned code:

const int potPin = A0;
const int buttonPin = 2;

void setup() {
  pinMode(buttonPin, INPUT);
  Serial.begin(9600); //go for the lowest baud rate for reliability
}

void loop() {
  buttonVal = digitalRead(buttonPin);
  Serial.print(buttonVal);

  Serial.print("  -  ")

  potVal = analogRead(potPin);
  Serial.println(potVal);
}


How to send sensor data from Arduino through NRF24L01 to Raspberry Pi

As you haven't said or shown which NRF24L01 library you are using, one can't say for sure what the problem is, but in some NRF24 implementations, the write() method accepts (or requires) a second parameter, len, giving the number of bytes to be sent.  If the library you're using doesn't require that parameter, it could be defaulting it to some value, or could be treating the buffer as a string, to be terminated with a null byte.

Either of those cases could produce erratic results.

Instead of leaving off the second parameter, specify it.  For example:

radio.write(&moisture, 2);
radio.write(&temp, 2);


Why use an int variable for a pin when const int, enum or #define makes much more sense

const int led = 13;

That is the correct method. Or even:

const byte led = 13;

How many pins do you have?

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

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

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

Responses to comments

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

In Arduino.h there is this line:

typedef uint8_t byte;

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

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

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

In fact it generates the same code whether the 13:

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

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

Confusing error messages

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

#define LED = 13;

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

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

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

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

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

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


Is it any way to connect ESP8266 to wifi faster?

I have also experienced the inability to connect sometimes. I wait a certain amount of time for it to connect then do a ESP.reset() if it fails.

As for the boot problem it sounds like you are keeping GPIO0 low so it goes back into programming mode. Hold it high and it will run your program instead.


The simple answer is: It doesn't matter.

Both Arduino and the Raspberry Pi, and every other common microcontroller board, are designed to control things, not provide power to things.

Digital IO pins aren't designed to drive heavy loads. Yes, some (like the Arduino) can provide slightly more current, but that is really unimportant for most projects.

Yes, some boards have more powerful power supply circuits on them so you can draw more current from their power supplies, but again that is largely irrelevant.

The one thing that you seem to be forgetting (or haven't realised) is that the microcontroller board does not have to supply all the power.

The Arduino, Pi, Teensy, chipKIT, whatever, is merely a controller. If your system needs more current it is up to you to provide that current. The Arduino etc merely controls the circuit or device that it is connected to.

It is very common to have multiple power supplies in a large project - each providing different voltages, or being used for different specific tasks within the project.

Just one thing you need to remember: Connect the grounds.


Arduino with multiple buttons - will power be an issue?

Yes, it is safe to connect multiple buttons to ground. The pull-up resistors have a fairly high value - about 10 kΩ and we know from Ohm's Law that

I = V / R = 5 V / 10k = 0.5 mA

per button. Your USB power is good for about 500 mA.

Welcome to StackExchange.


How to make an arduino webserver over USB? without ethernet shield nor wifi chip

You cannot change what the Arduino's USB does. The USB is not provided by the ATMega2560, but by the USB to UART interface chip.
On a genuine Arduino that may be an ATMega16U2 which could be reprogrammed, but on Chinese clones it most often isn't.
You would need to start with a board that has a real "native" USB connection, such as the Arduino Leonardo (ATMega32U4) or the much more capable (though deprecated) Arduino Due.
Then you would need to create not only the USB "CDC/ECM" device profile, but also the IP stack on top of it to handle the IP data, then a TCP later on top of that to handle the socket data.
The actual CDC/ECM device itself is very simple - much like the CDC/ACM (USB serial) device it's really just a dumb pipe that sends and receives raw Ethernet frames. Interpreting those frames and managing TCP/IP sessions and streams is a far more involved process and would be the bulk of the work. You'd probably want to take an existing standalone IP stack implementation and replace the existing layer 2 code with the CDC/ECM interface instead.
An alternative, as advocated by @Juraj, is to use IP over Serial. This uses a serial protocol (SLIP) to encapsulate the IP frames and has a rudimentary cut-down IP stack in it. However this is old technology and is not well supported by operating systems any more. For example the home versions of Windows no longer have any SLIP support (it used to be provided through "DUNS" - the Dial UP Network Server - which no longer exists).


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

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


Im just trying to learn AVR programming without the I guess "handholding" of arduino functions/etc.

You don't actually need to do anything. You don't need any breadboard, any programmer, nothing.

You can use the Arduino environment, upload facility, and board to learn low-level AVR programming.

Just because the Arduino helper functions exist it doesn't mean you actually have to use them.

The first step on your progression to professional embedded developer is to get to grips with low-level registers. You can do all that from within the Arduino environment. You have access to everything in the Arduino IDE that you have in any other IDE in the way of low-level chip functions. They are functions of the chip, not the IDE.

If you want to progress to a professional IDE and use hardware debugging you can still use an Arduino board. After all, it's just an MCU on a PCB. Just plug your hardware programmer into the hardware programming connector on the board. Why mess around with breadboards and all the trouble that they give with dodgy connections? Just because an Arduino has an Arduino logo on it you aren't forced to use it with the Arduino IDE.


Writing data from multiple sensors in burst mode to an Arduino Due

What you need to do instead is to declare an array buffer of the data type you need to send, and send it through Serial. The array buffer could be of any length of your choosing, then you reiterate through on a for loop till all the contents of the buffer are read out which is essentially the burst mode you require.


samd21 linking, change the base addresse from the default

A typical LD script consists of two sections - one that defines memory ("MEMORY") regions, and another that defines what to put in those memory regions ("SECTIONS").

To carve holes in an existing memory layout it is usually enough to just change the first section - the part that defines the layout of the memoy. Shrink and move existing blocks of memory and insert new ones.

For example you may have this at the moment:

MEMORY
{
  FLASH (rx) : ORIGIN = 0x00000000+0x2000, LENGTH = 0x00040000-0x2000 /* First 8KB used by bootloader */
  RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000
}

There is a hole already defined of size 0x2000 at the start of flash, and the sketch is loaded from 0x2000 onwards.

You may want to shrink and move that, and add a "user data" chunk. It's enough to just go:

MEMORY
{
  USERDATA (rx) : ORIGIN = 0x2000, LENGTH = 0x1000
  FLASH (rx) : ORIGIN = 0x3000, LENGTH = 0x00040000-0x3000
  RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000
}

(I collapsed some of the maths cus it's pointless).  Now the flash area (where the sketch goes) has been shrunk by 0x1000 and moved an extra 0x1000 up the memory map. A USERDATA chunk has been inserted which you can then use later on if you so wish.

To make things get put in there by the linker script (you don't need to change anything else to move the sketch data...) you can define a new section in the later part of the linker script:

.userdata :
{
    KEEP(*(.userdata))
    KEEP(*(.userdata.*))
} > USERDATA

That should then place anything that you put in a .userdata section (or a subsection within that) within your sketch into the USERDATA chunk of flash - separate from your sketch.

(sketch)
const uint8_t __attribute__((section(".userdata"), used)) data[] = { 10, 100, 123, 177, 221, 49 };

However, if you plan to use it like EEPROM and only write to it using code in your sketch then you don't need to worry about anything like that - just carve out the hole.  You can also provide some globals to help with your code, though:

(linker script)
PROVIDE(userdata_start = ORIGIN(USERDATA))
PROVIDE(userdata_length = LENGTH(USERDATA))

Then you can use those in your program to know where the USERDATA chunk is and how big it is (ideal if you ever choose to change it - no need to change your code, only the linker script).


Trouble with setting the PWM frequency for Arduino Due

There are a few things to do. I've used this successfully in the past with older projects.

As a side note one can very easily change PWM settings on pins with the esp32, a single line of code being ledcSetup(PWM_Channel_Number, Frequency, resolution) without ever having to actually dive into modifying variant.h

To Quote Kerry D. Wong:

  If you take a look at the function PWMC_ConfigureClocks in pwmc.c, you will see that the highest PWM frequency can be accommodated as the function input is 42 MHz, this is because inside the function it calls FindClockConfiguration which in turn ensures that the frequency parameter passed in is less than the MCK frequency. Thus for integer dividers, the highest frequency we can pass in is 42 MHz (with divider 2).

  To achieve the highest output frequency, we can use a one bit PWM which essentially just outputs a square wave with a duty cycle of one. We can then set the prescaler to 2 to obtain an 84 MHz waveform.

#include <Arduino.h>

uint32_t pwmPin = 8;
uint32_t maxDutyCount = 2;
uint32_t clkAFreq = 42000000ul;
uint32_t pwmFreq = 42000000ul;

void setup() {
  pmc_enable_periph_clk(PWM_INTERFACE_ID);
  PWMC_ConfigureClocks(clkAFreq, 0, VARIANT_MCK);

  PIO_Configure(
    g_APinDescription[pwmPin].pPort,
    g_APinDescription[pwmPin].ulPinType,
    g_APinDescription[pwmPin].ulPin,
    g_APinDescription[pwmPin].ulPinConfiguration);

  uint32_t channel = g_APinDescription[pwmPin].ulPWMChannel;
  PWMC_ConfigureChannel(PWM_INTERFACE, channel , pwmFreq, 0, 0);
  PWMC_SetPeriod(PWM_INTERFACE, channel, maxDutyCount);
  PWMC_EnableChannel(PWM_INTERFACE, channel);
  PWMC_SetDutyCycle(PWM_INTERFACE, channel, 1);

  pmc_mck_set_prescaler(2);
}

void loop()
{

  Note that VARIANT_MCK is defined in /arduino-1.5.7/hardware/arduino/sam/variants/arduino_due_x/variant.h as 84000000. PWM_INTERFACE_ID and PWM_INTERFACE are defined in variant.h as ID_PWM and PWM which in turn are defined in /arduino-1.5.7/hardware/arduino/sam/system/CMSIS/Device/ATMEL/sam3xa/include/sam3x8e.h.

  So as the conclusion, the highest stable frequency we can generate using an Arduino Due is 84 MHz. The pictures below show the captured waveforms under different frequencies. For the 21 MHz waveform, pwmFreq is set to 21000000, no prescaler is used. For the 42 Mhz waveform, pwmFreq is set to 420000 with no prescaler. The 84 MHz waveform is generated with set to 42000000 and the prescaler set to 2.

Hope this helps.


How to switch between multiple BMP180 sensors?

The BMP180 uses the I2C bus and you cannot simply turn off the device, since that can block the I2C bus. Also it has only one, not changeable address. Thus you would need one I2C bus for every BMP180.

So know you have 2 ways to go:

You could use a Software I2C library and define one I2C port for each BMP. That would use 12 digital pins and you need to find a fitting library, that supports multiple instances. Due to the timed nature of the I2C bus, you most likely will only be able to service one bus at a time.
You could buy a multiplexer chip for both signal lines. Then you could switch the SCL and SDA lines to each BMP. For that you need the multiplexer chips, 2 pins for I2C and 3 digital pins for input of the multiplexer chips (assumes an 8-channel multiplexer)


Possible to determine at runtime whether a pointer is declared PROGMEM?

Not really, if you are asking whether you can determine (simply from its value) whether 0x100 is in RAM or PROGMEM. Both are possible candidates for a memory location.

The F() macro works around this by changing the type of a variable at compile-time, so that the compiler can select a suitable method of printing. For example:

Serial.println ("Hello, world");
Serial.println (F("Hello, world"));

In this case the appropriate println function is chosen at compile-time by the compiler, based on the type (one would be a const char *, the other a __FlashStringHelper type).

You are best off designing a way (similar to the F() macro) where you can make the decision at compile time.


Arduino Uno, BLE Bluetooth Shield and Braccio Arm Shield

Be aware that the BLE Shield is using  a SPI interface therefore on Arduino Uno the SPI bus uses pins 10 (SS), 11 (MOSI), 12 (MISO), and 13 (SCK) and the Nordic’s ACI requires two hand-shake signals, RDYN and REQN, two additional pins will be used (pins 8 & 9 in the default settings), from BLEshield
Therefore the BLE shield uses 6 pins e the Braccio uses almost all Arduino Uno pins.
Conclusion, you probably can't have both shields together as the Arduino Uno hasn't enough pins.

You can try an Arduino MEGA and adapt the shields connections wiring them together using different pins for the Braccio interface for example


What is the opposite of this data operation?

You are better off making a union, that will be compiler independent, and won't give you the (possibly) odd results that trying to shift a double would give.

Example:

  union
    {
    byte myArray [4];
    double myDouble;
    } foo;

   foo.myArray [0] = Serial.read ();
   foo.myArray [1] = Serial.read ();
   foo.myArray [2] = Serial.read ();
   foo.myArray [3] = Serial.read ();

   double f = foo.myDouble;

Even then be cautious that whatever is sending you this double in 4 bytes is using the same encoding for doubles that the Arduino does. For one thing, double and float are the same on the 8-bit Arduinos (they are only 4 bytes).


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

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

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

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


LED strip brightness decreases when using multiple strips

40 amps is a LOT of current.

24 AWG wire can't handle anywhere near 20A of current, nevermind 40A. (After a little googling, it looks like 24 AWG wire is limited to about 3.5A.)

Think about it. In the US, 15 amp branch circuits require 14 AWG wire. 20 amp circuits require 12 AWG wire. It looks like 40 amps requires 8 AWG, from the googling I did. (Voltage doesn't really matter when considering current carrying capacity.) So if you want to drive 40 amps, you need 8-gauge wire on both the +5 leg and the ground leg to your LED strip.

As I said in my comment, I found some 144 WS2812B LED strips on Amazon that draw 20A just for one strip. You say your strips have 150 WS2812B LEDs on them. Assuming it's 150 vs 144 of the same LEDS, you're going to need almost 21 amps per strip, so 2 strips will slightly exceed the 40A capacity of your power supply, and VASTLY exceed the current handling ability of your wiring. As a general rule you should have a power supply that offers a little MORE current that your max needs, never less.(When a power supply reaches its current limits its voltage may start to droop, or it may be slower to adjust to rapid changes in load.)

In addition, You're gonna need BIG, THICK 5V and ground wires to feed your LED strips, and you should wire the LED stips in parallel. (I suggest 8 AWG wires for 40A. Those are HUGE, but that's what you need for that much current.) You should not connect either the +5V supply or the ground wires through a breadboard.


NodeMCU successfully uploaded sketch but it does not work from Arduino IDE

Fixed it....
turns out that in the tools, the board was selected to be NodeMCU 0.9
when it should actually have been NodeMCU 1.0
so i just changed it to NodeMCU 1.0 and it worked!


How to connect Arduino 5v pin with multiple things?

The simplest way is to just use a breadboard to connect your devices to your Arduino:

I can't read Chinese, so I can't check the specifications of these particular devices, but you need to be aware of the power limitations on your Arduino.

The maximum total current you can draw when the device is powered via external power supply is 1A for the Arduino Uno, 800mA for the Due and 500mA for the Nano. Check the specs for your board on the Arduino site.

Arduino-compatible devices may vary - check the specs for the device you're usiing.

Note: If you're not powering your board via USB, the total 5V current limit coming out of the Arduino is limited by the voltage regulator on your particular board, and/or your input power supply (whichever provides less power).


Designing a robotic arm using Arduino Uno

So you have a total length of your arm of 58cm. The center of mass may be further past the end of the gripper so I am allowing 5cm for that. Total length of 63cm.

Holding torque required just for the load:

Force = mass x acceleration
Torque = Force x radius
Torque = 1kg x 9.8 x 63cm    [in N.cm]
       = 617 N.cm

This is a lot of torque and we haven't factored in the weight of this robot arm.

Some motor datasheets/specifcations:

DC Servo Motors: http://oceancontrols.com.au/datasheet/lea/MOT-2x0_DCM5xxxxd.pdf
Nema 17 stepper motor: http://motion.schneider-electric.com/downloads/datasheets/17_mtr.pdf
Nema 23 stepper motor: http://motion.schneider-electric.com/downloads/quickreference/NEMA23.pdf

Whether you go DC servo motors or stepper motors, you will need to use decent motor drivers hooked up to your Arduino to drive the current needed by the motors.

You will need at least 4 motors for your 4 DOF. Lets assume each gearbox-motor combo weighs 700g. On top of that lets assume that the frame weighs 1kg. Lets assume the center of mass is exactly half way along the arm (ie. 31.5 cm)

Torque = (4 x 0.7 + 1) x 9.8 x 31.5
       = 1173 N.cm

The gripper needs to be decent to hold 1 Kg - so lets assume that it weighs 600 grams. Lets assume the center of mass is exactly in the middle of the gripper (ie. radius = 54 cm)

Torque = 0.6 x 9.8 x 54
       = 318 N.cm

So now lets add the total torque required:

Torque = 617 + 1173 + 318
       = 2108 N.cm
  or 211 kg.cm

The motor closest to the base will need to be the strongest as it needs to provide the most torque. The motors need less torque the further away from the base they are.

If you were to use stepper motors, you will need gearbox assemblies to increase the output torque.  It is even possible to use 2 stepper motors driven in unity to provide double the torque.

If you were to use a stepper motor you will need a motor like this:
http://www.phidgets.com/products.php?category=23&product_id=3334_0

Alternatively, servo motor like this could be used:
http://oceancontrols.com.au/MOT-280.html

Either DC servo motors or stepper motors (with gearboxes) would be OK for this robot arm. I would go with DC servo motors because they are slightly lighter and can handle the torque without needing a gearbox. However the DC servo motor is about 3 times the price of the stepper/gearbox combo.


Connecting Function Generator to Arduino

Sure, you can connect the function generator to an analog pin of the Arduino. The probe and the jumper wires are just wires here, nothing special. You should also connect the function generators ground to the Arduinos ground (!).

But: Be sure to stay in the Arduinos voltage range (0 to 5V) with the function generators signal. If you apply a higher or negative voltage, you can destroy the Arduino. As long, as you stay inside that range, nothing bad will happen.


Simple: random() isn't an Arduino function - it's a standard C function.

  Function random()

  long random(void)

  The random() function computes a sequence of pseudo-random integers in the range of 0 to RANDOM_MAX (as defined by the header file <stdlib.h>).

  The srandom() function sets its argument seed as the seed for a new sequence of pseudo-random numbers to be returned by rand(). These sequences are repeatable by calling srandom() with the same seed value.

  If no seed value is provided, the functions are automatically seeded with a value of 1.

  -- AVR LIBC Manual Page


ESP8266 with Arduino Uno - Problem with AT+CIPSEND

Your GET is incorrect. You have a CRLF between the GET and the HTTP. It should just be a space.

GET /blah/blah/blah HTTP/1.1\r\nHost: BlahBlah.com\r\n\r\n

Of course the \r\n shouldn't be those specific individual characters, but the ASCII codes 13 and 10 respectively, so printing each line with Serial.println() instead of inserting \r\n might be better.


Motor code for the "Pirate: 4WD Arduino Mobile Robot Kit with Bluetooth 4.0", will not work

To formulate my comments as answer:

Your board has some features involving the motors/servos:

Since the PCs USB port cannot provide enough current for the motors, they can be switched off wit the Motor Power Switch. It has to be set to OFF, when you connect the board to an USB port. For operating the motors the board needs it's own power supply (a battery in your case), which can provide enough current. So in this case, you have to switch the Motor Power Switch to ON, to enable the motor drivers. Attention: If you turn on the motors while being connected to the USB port, you can damage your board and also your USB port.
The motors are connected to the pins 4, 5, 6 and 7. If you don't need the motors, you can use these pins for other purposes. For this, the board let's you disconnect the motor driver from these pins. If the jumpers, that are marked with "Motor Control Terminal Jumpers" in the image on this documentation page, are inserted onto the jumper pin pairs (in the image they are already inserted), the motor drivers will be connected to the mentioned pins. If the jumpers are not inserted there, the motors will not work, since they are not connected to the controlling pins.

Note, that you need to use pinMode(pin_number, OUTPUT); in the setup() function for all pins, that you want to use digitalWrite() on, because only this way, the corresponding pin will be set to an output (can only then output a digital signal on digitalWrite()). analogWrite() will configure the corresponding pin for you, but it is a good practice to set it as OUTPUT in setup anyway, to make it clear for readers, that this pin is an output.


MAX7219 library that can compensate for poorly designed/miswired 8x32 panel?

The issue is minor. It looks like the library was designed for a slightly different matrix display / wiring.

Take a look at the library and it likely maps the input buffer to segment / dot-matrix information. Play with that.

The author did 99% of the work for you. You just need to finish the last 1%.


Can't read two bytes through Serial.read - Arduino

There may be a underlying problem with synchronizing the transmitter and receiver.  They both have to agree / know which is a command byte and which is a data byte.

In order to do this, some protocols sacrifice a bit. For example you could set the most significant bit for commands and not set the most significant bit for data. However, that does mean you can only send data in the range of 0 to 127. And it does restrict you to only 128 commands. If you need more, and want to stick to this "most significant bit" approach, you could break your data into chunks and only send 7 bits at a time. The possibilities are many. Use this one or make one up that fits your needs better.

In order to implement this approach, you will need to read and process each byte as it arrives.  You can not wait until you accumulate the expected number of bytes as this assume you are always in sync with the transmitter. Which may not be the case.


That burn is likely the smell of the potentiometer, not the arduino. I would check the arduino with a multimeter set to resistance to make sure that the Vin trace resistance is nominal.


Cloud function getting stopped Parse.com in loop when calling from Arduino-yun

Give this a shot, I really hate String, maybe that 8-times thing has to do with memory issues caused by it.

void loop() {

  char functionToCall[8] = "meeting";
  Serial.println("Start loop");
  demoBasicCharArray(functionToCall, 0);
}

void demoBasicCharArray(char *functionname, int light) {

  Serial.print("In ");
  for (byte i=0;i<sizeof(functionname);i++){
    Serial.print(functionname[i]);
  }
  Serial.println(" Function");

  ParseCloudFunction cloudFunction;
  cloudFunction.setFunctionName(functionname);
  cloudFunction.add("light_sensor", light);
  cloudFunction.add("value", "Arduino Hello");//parameters

  ParseResponse response = cloudFunction.send();
  Serial.println(response.getJSONBody());
}


Make sure u have selected the right COM port
Make sure nothing is connected to the pin 0 and 1 in arduino

This happens because the Arduino IDE could not find Arduino Board Connected to the system.


Can we use serial.begin command anywhere in code?

You cannot call Serial.begin() in a declaration. Like any program
instruction, you can only use it from within a function. As stated in
Juraj's answer, you can call it as many times as you want. However,
most often it only makes sense to do this in setup(), in order to
initialize the serial link once and for all at the beginning of your
program. Why would you ever want to do this initialization multiple
times?

Thinking about it, I can see two possible scenarios:

Your UART is connected, through a suitable transceiver, to an RS-485
bus. You have several slaves on this bus that require different UART
configurations (different baud rates, or number of data bits, or
parity). Then, each time you want to address one slave, you first
set your UART to the configuration suitable for that particular
slave. In this kind of situation, however, it would be more
convenient to arrange for all the slaves to share the same UART
configuration, if at all possible.
Your UART is connected to a device that continually sends data you
are not interested in. This could be, e.g., a GPS module. Since you
don't want your program to be interrupted every time a character is
received, you keep the UART disabled. Only when you do want the data
you enable it with Serial.begin(), you read as much as you need,
then you disable it again with Serial.end().

There may be other situations, but I bet they are all quite atypical
scenarios. The common practice is to call Serial.begin() once in
setup(), and have the UART enable from there on.


Help: convert Arduino code to avr-gcc code

Try this:

#include <Servo.h>

extern "C" void init(void);

Servo myservo;

int main()
{
    init();
    myservo.attach(11);
    for (;;) {
        myservo.write(67);
    }
}

Note that this still needs the Arduino core library, as the Servo
library depends on it, which means all this is an exercise in futility.
If you are using the Arduino core, the simplest thing is to use it the
Arduino way. If you do not want to use Arduino core, then you will have
to partially re-implement the Servo library.


Using WifiUdp.h on Arduino Mega and ESP8266?

the WiFiEsp class for UDP is WiFiEspUDP

#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
#include "AppleMidi.h"

APPLEMIDI_CREATE_INSTANCE(WiFiEspUDP, AppleMIDI);


Is there any way to optimize this code:

Absolutely, yes. Don't use String for this, you are seriously wasting memory. Instead you can use a struct:

struct keymap {
    uint8_t code;
    const __FlashStringHelper *value;
};

const struct keymap keyRemap[] = {
    { 1, F("1") },
    { 2, F("2") },
    { 3, F("3") },
    { 5, F("4") },
    { 6, F("5") },
    { 7, F("6") },
    { 9, F("7") },
    { 10, F("8") },
    { 11, F("9") },
    { 14, F("0") },
    { 13, F("Clear") },
    { 15, F("Enter") },
    { 0, 0 }
};

void loop() {
    int Key = Read_Keypad();

    if (Key != 0) {
        lcd.clear();
        lcd.setCursor(0, 0);

        for (int x = 0; keyRemap[x].code != 0; x++) {
            if (Key == keyRemap[x].code) {
                lcd.print(keyRemap[x].value);
            }
        }

        delay(160);
    }
}


Error 400. The request has an invalid header name ESP8266 (HTTP-POST)

You are lacking the required blank line between the headers and the content. Also your content length is wrong.

Change

client.print(postiu.length());

Into

client.println(Cadenadatos.length());


I found a solution somewhere else on internet...
This portion:
#ifndef MYHELPERS_H
#define MYHELPERS_H

Was not written correctly... "MYHELPERS_H" should've been replaced by the name of my file. Now it works just fine.


esp8266 esp-01 printing garbage values on serial monitor

The "garbage values" are most likely messages from the bootloader, output at 74880bps. Try watching its serial out at that speed. You'll probably see messages that look something like:

ets Jan  8 2013,rst cause:2, boot mode:(3,7)
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d

The rst cause number will give you an indication of why the chip rebooted.

The most common reset causes are

power on
hardware watchdog timer
fatal exception (most likely error in your code or power issue)
software watchdog timer
software reset
deep sleep
hardware reset

If it's a "fatal exception", you should see another line that looks like this:

Fatal   exception   (28):
epc1=0x4025bfa6,    epc2=0x00000000,    epc3=0x00000000,    excvaddr=0x0000000f,
depc=0x00000000

Look up the exception number; if it's not obvious what it means, google it to learn about the causes.


SoftwareSerial + Serial.printlen() not working properly

Are you sure a string like this can be used?

Better anyway to not each time let a dynamic string be created, but use a fixed string e.g.

char TelephoneNumberText[16];

Set the length of the max number, and change other string functions accordingly.


And Arduino should run the last program installed to it when you apply power to the barrel connector. IT powers up, does a reset, and begins executing the sketch that's installed.
As others have mentioned, the small rectangular 9V batteries have very low current output and total power storage. You will run a fresh 9V battery down to nothing in a short time with just an Arduino, and with other components also drawing power it will happen even faster. I suggest getting a ≥ 1 amp 7V - 9V DC transformer and plugging that into the barrel connector.
You need to tell us what components you are using in your project and their current requirements.
If you are just running a "bare" arduino and very little else then you should get like 24 hours out of a fresh 9V battery, as mentioned by @ocrdu


Timer question: Phase Correct PWM at specific frequency

pinMode(3,OUTPUT);

Pin 3 on the Nano is OC2B. It's PWM is controlled by Timer 2. You
want to use pin 5 (OC0B), since you are using Timer 0. Or
switch to Timer 2.

Phase correct PWM with top as OCR0A

Note that this is the description of mode 5. If you want this mode, you
have to set both the bit WGM00 in TCCR0A (which you did)
and the bit WGM02 in TCCR0B (which you didn't). Here you have set
mode 1: phase correct PWM with top = 0xff.


Where to declare timer interrupt variables?

If they are only used in the interrupt then yes they can be declared in the interrupt. If you want them to retain their value from one call to another they must be declared static, and then they will be the same as global variables as far as memory allocation is concerned.


ESP01 connected to Arduino can't read from UART while connected from external power source

Can I just check when you plug your 3.3V ESP into a 12V power supply it stops working?  Is there a burning smell when you do this?  Are you using anything to drop the voltage to 3.3V?

You also say you are connecting the ESP to the Arduino's 5V supply.  Normally that's not a good idea either.

Also have you tied the ground of the Arduino to the ESP/12V PSU?  If the two devices don't share a common ground then they won't agree what 0V and so won't be able to talk to each other over serial.  Just run a wire from the Gnd on the Arduino to the Gnd on the ESP and they will jump into life.


The code you presented does not fit for working with the RF 433Mhz. I'm not sure what you think this code should do, but this is not the way to go with a 433Mhz transmitter.

I would suggest using a dedicated library for transmitting information using the 433. There are many libraries out there for doing that; two popular libraries would be the ManchesterRF and the VirtualWire, both includes code samples.

For example, sending data with ManchesterRF:

#include "ManchesterRF.h" //https://github.com/cano64/ManchesterRF

#define TX_PIN 3 //any pin can transmit
#define LED_PIN 13

ManchesterRF rf(MAN_4800); //link speed, try also MAN_300, MAN_600, MAN_1200, MAN_2400, MAN_4800, MAN_9600, MAN_19200, MAN_38400

uint8_t data = 0;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  rf.TXInit(TX_PIN);
}

void loop() {

  rf.transmitByte(++data, data*data);
  digitalWrite(LED_PIN, digitalRead(LED_PIN)); //blink the LED on receive
  delay(100);
}

In addition, there are many other blogs around going step-by-step how to use 433Mhz Tx/Rx with ATtiny85, google is your friend :)


Why are there two sets of tools and bootloaders in the Arduino IDE?

Arduino IDE comes with a "platform" (the arduino AVR) in the Arduino\hardware folder.
Then you can add/upgrade platforms with the boards manager.
These will be installed in C:\Users\\AppData\Local\Arduino15\packages.
The reason for this is that Arduino IDE wants to be able to "work out of the box".
If they did not deliver the platform inside the installation/zip a "installation finishing" job needs to run after opening the Arduino IDE.


The USB provides the one thing that is missing from your diagram there: the common ground.

The GND pins of the two boards must be connected together. By using USB the USB becomes that connection. As soon as you use batteries there is no connection, so no communication happens.


How do you post json data to HTTPS endpoint from ESP8266MOD?

You are only making an HTTP request to an HTTPS server. It's not going to work.

AFAIK there is no direct support for HTTPS in the ESP8266 libraries, but there is support for SSL, and you can then manually create an HTTP request over that - as detailed in the HTTPSRequest.ino example.


How can I know if I can stack some shield on another shield?

First you have to compare the pinouts of the two shields. If the shields use completely different pins then yes, you can use them together.

However if they share pins then you need to look in more detail at what those pins are and how they are being used.

In your example you have SPI being used (pins 10-13) for one shield and PWM (3/11) and GPIO (8/9/12/13) and analog input (A0/A1) for the other shield.

You can see now that there is a conflict. For instance pin 13 for the SPI clock for the DFRobot shield is also being used for one of the GPIO pins of the Arduino shield. Pin 12 for MISO is being used as GPIO. Pin 11 for MOSI is also being used for PWM.

Those are disparate functions on the pin, so it can never work.

However if the SPI pins were being used for both shields as SPI then that could work. In that case it's only the "chip select" pin that needs to be unique for each shield, since SPI is a Master-Slave Bus protocol which can be shared amongst multiple shields.


So install it?

$ sudo apt-get install libreadline6

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

$ sudo apt-get install libreadline6:i386


Unable to send data from Processing to Arduino through ports

When you open a serial connection to Arduino Uno the atmega328 microcontroller is usually reset(this depends if the OS is configured to toggle the DTR serial control signal on/off when a port is opened). Just after a reset the bootloader (optiboot) runs to see if you are trying to upload a new sketch. If the bootloader doesn't receive any meaningful communication it will start your sketch after ~1 sec. All communication sent to the serial port while the bootloader is running is lost.

When you use the serial monitor you are too slow to notice the 1 second where the board won't respond to your commands. But the processing sketch is another story.

The easiest fix will be to insert a delay after you open the serial port and before you send any data.

// Wait 1.2 sec
int start = millis();
while (millis() - start < 1200);

If you would rather use a hardware fix you can connect a 10uF capacitor between RESET and GND pins that will prevent the board from being reset by the usb to serial converter.


No. That would be like trying to connect your TV to your microwave. Both RF devices, but both work different ways and do different things.

Just because they are both rectangular boxes with a window in the front doesn't mean they are the same.


Logic integrated circuits such as shift registers normally do not contain pull up resistors on their input(s).  This is because they are normally connected to a totem pole driver.  Such a driver eliminates the need to avoid floating inputs.

Also, pull up resistors require current when the input is driven toward the opposite power rail.  Even though adding internal pull up resistors may not change the overall behavior of the chip, designers will avoid parts if they unnecessarily add to the over all power demand.

Based on your comments and your question, consider an old ps/2 keyboard. It is essentially a switch matrix with a built in decoder chip which may fullfill your requirements. The chip scans the switch matrix, debounces the switches and converts button presses & button releases into a serial stream of data.

Added later...

Here is a description about connecting a ps/2 keyboard to an Arduino.  Included are schematics, code examples and supporting library.

(USB keyboards are not well suited for this purpose as they require a USB Host.  As most Arduinos do not have this, a USB Host shield is required.)


Capacitive sensor MPR121 on Arduino Uno—how many will work?

The answer is 4 regardless of the current consumption.

You can have 4 MPR121 devices on an I2C bus (by connecting the ADDR pin to the right place to select 1 of 4 addresses), and the Uno has one I2C bus - so that means 4 devices.

You could use software I2C to add more devices on other pins, but that's slow and clunky.

But that aside, if you used something to increase the number of I2C buses available, according to the datasheet the peak current consumption is 1mA during sampling, and assuming 300mA maximum for the Arduino's 3.3V regulator, that would mean a maximum of 300 MPR121 connected to the Arduino.  Note that, if you could actually get to the Arduino amongst that tangle of wires, you'd find it getting rather hot...


reversing DC motor rotation using TWO limit Switches Problem !! need help

Normally you use state machine for this kind of programming: you have a
state variable that remembers what you are doing, and depending on the
current state you decide what to do next. Below is an example with two
states. I have embedded a few assumptions about the wiring of your motor
and your switches, which may be wrong, so you have to check the code.

void loop() {
    static enum {MOVING_CW, MOVING_CCW} state;

    switch (state) {
    case MOVING_CW:
        if (digitalRead(LM2) == LOW) {  // hit switch
            digitalWrite(CW, LOW);      // stop
            delay(5000);
            digitalWrite(CCW, HIGH);    // restart
            state = MOVING_CCW;
        }
        break;
    case MOVING_CCW:
        if (digitalRead(LM1) == LOW) {  // hit switch
            digitalWrite(CCW, LOW);     // stop
            delay(5000);
            digitalWrite(CW, HIGH);     // restart
            state = MOVING_CW;
        }
        break;
    }
}

This will start in the MOVING_CW state, but you have to actually start
the movement in setup(). It has the drawback of having long delay()s in
the loop, which is undesirable if you have other tasks to perform. These
delays can be removed by “remembering” that you are waiting as two extra
states:

void loop() {
    static enum {MOVING_CW, MOVING_CCW, STOPPED_CW, STOPPED_CCW} state;
    static unsigned long time_stopped;
    unsigned long now = millis();

    switch (state) {
    case MOVING_CW:
        if (digitalRead(LM2) == LOW) {  // hit switch
            digitalWrite(CW, LOW);      // stop
            state = STOPPED_CW;
            time_stopped = now;
        }
        break;
    case MOVING_CCW:
        if (digitalRead(LM1) == LOW) {  // hit switch
            digitalWrite(CCW, LOW);     // stop
            state = STOPPED_CCW;
            time_stopped = now;
        }
        break;
    case STOPPED_CW:
        if (now - time_stopped >= 5000) {
            digitalWrite(CCW, HIGH);    // restart
            state = MOVING_CCW;
        }
        break;
    case STOPPED_CCW:
        if (now - time_stopped >= 5000) {
            digitalWrite(CW, HIGH);     // restart
            state = MOVING_CW;
        }
        break;
    }
}


Problems with using example code for Wi-Fi shield (arduino)

Have you upgraded the firmware in your wifi shield? If not, it will have problems connecting. Compile and upload this sketch. If it shows the firmware version as 1.0.0, then you need to upgrade the firmware. If it shows 1.1.0, then it is current as of today.

#include <SPI.h>
#include <WiFi.h>

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while(true);
  }

  Serial.print("Firmware version: ");
  Serial.println(WiFi.firmwareVersion());
}

void loop() {}

Please Note: The chips are numbered differently but run the same Wi-Fi firmware. You can upgrade the firmware without any worries.


You need to use read the time (millis()) when you start the motor and read it frequently while the motor is running to know when to stop it. You also need to keep track of the sensor, and don't start the motor again until after you've seen the sensor turn off (detect no obstacle). Here is an outline of the logic in psuedo-code; turn this into a detailed loop() function in C++:

if the motor is ON {
  if (millis() - motorStartMillis) > 1000 {
  stop the motor;
}
else if sensor is ON {
  if the sensor was OFF {
    start the motor;
    motorStartMillis = millis();
    sensorWasOn = true;
  }
}
else {      // sensor must be off
  sensorWasOn = false;
}


The NRF24s are great, but limited to communication only.

Digi's XBee 2mW module has got great indoor range, but more to the point it's got 8 I/O lines and 6 10-bit ADCs on board. It's also built for mesh networks (or you can get star-network equivalents) and has security encryption to boot. This means that, for some of your nodes, you don't need any other hardware to have a fully functioning control point (not including relays and sensors of course), so you can ditch having arduinos at every node.

They're so easy to use, very low power, and have plenty of support and documentation available online.

Do it!


Arduino Due ( Atmel Microcontroller) IC Heat up and led goes off

Motor driver boards exist to allow an MCU to control a motor without having to supply its power. If you try to power motors from the Arduino as well, they draw too much current and things get hot or damaged.

The 3.3v pin is only for supplying modest amounts of current at 3.3v from a 5v Arduino. You can not back-power the board with it. I don't know what happens if you try, but I bet it isn't good...


I think you just want a normal USB A-B cable, exactly like you'd use on a PC.

You probably could use the cable you picture, but you'd need a female DB-9 connector.  If you really want to do that for some reason, you need to connect the Tx pin on the DB-9 (pin 2) to the Rx pin on the Mega, and the Rx pin on the DB-9 (pin 3) to the Tx pin on the Mega.


If you have a function that isn't called the compiler will just delete it (optimise it out). It also deletes any functions that the function calls that aren't used anywhere else.

By then calling that function the compiler keeps it, along with any other functions it relies on.

That includes the SDFat library code, much of which will have been removed before.

To make it now fit you will have to optimise your program. Look for blocks of code that do the same thing and replace them with calls to a function. Look for parts that could be replaced by a loop and an array instead of discrete calls to the same function(s) over and over again. Things like that.

Either that or use a board that has enough flash for your project.


cannot convert 'bool' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus) on Arduino Uno Rev 2 Wifi not working

The digitalRead method doesn't return a Boolean value. It returns an Integer.

From what I remember inside Arduino.h values of LOW and HIGH are defined as being simply Integer 0 and 1.

#define HIGH 0x1
#define LOW 0x0

I think that was changed to an Enum called PinStatus but Enum can be treated as an Integer.

This means that you have to store results of digitalRead inside Integer variable.

int value = digitalRead(8);

It was designed that way to easily cast values between Integer and Boolean. By (very smart) design choice Integer value of 0 (LOW) will be cast to false and every other value (for example 1 or HIGH) will be cast to true.

The operator ! (Boolean NOT) can be used only with Boolean variables so the compiler needs to perform several "implicit casts". When it's smart enough it will assume you are know what you are doing and it will add the cast by itself.

By reading the error I see that the issue is happening when compiler tries to convert Boolean value into Integer. So this is implicitly evaluated correctly as a Boolean value

!digitalRead(pin_enable_line)

But when you try to put it inside a place for PinStatus you get the exception

cannot convert 'bool' to 'PinStatus'

Try adding an "explicit cast" to PinStatus:

digitalWrite(pin_enable_line, (PinStatus)!digitalRead(pin_enable_line));

It should fix the issue.
But I suggest splitting the code into several lines and adding a temporary variable. It makes debugging much easier. Trust the code optimizer that's built into the compiler. It will understand what you want to do and actual machine code will be the same.


What is the circular gold pad on arduino mega 2560 v2 and above?

That is most likely a Fiducial Mark for the vision system of a pick-and-place assembly robot to key off of in order to more precisely place the components on their pads.

If you look carefully, you will see a second one located below the DC barrel jack.

Boards like this are manufactured in a gridded panel having a number of copies in each direction, and only cut apart after they are largely complete.  With such a large workpiece, any linearity error in the manufacturing could result in a high-density component being misplaced far enough to cause problems.  Having a pair of fiducials on each individual board in the panel can help calibrate out errors not only which might otherwise accumulate over the large dimensions of the entire panel, but also rotational skew of the panel in its holder.

You can see both on this picture of the Arduino Mega 2560 from the arduino.cc site


Get value from a website using Yún and a RPi

You need to use the Process library that comes with the IDE.

That allows you to execute commands on the Linux portion of the Yun from within your Arduino code, and get data back from it.

You use that class to execute the curl command in Linux to fetch the content of a web page and return that content to the AVR code where you can deal with it.

If the content of the web page is complex it may be worth passing the output of curl through some other Linux based commands first (such as grep and cut or awk) to clean it up and reduce the amount of text you have to deal with at the AVR end.


send values from arduino uno to wemos d1 r1

As I see it, the most straight-forward way to connect 2 Arduinos is using their built-in UART (aka Serial port, TX/RX pins) communication.
There are many tutorials on this on Google, and a similar explanation can be found in this question:
Serial communication arduino mega and D1 Wemos Mini
However, there is a slight difference.
Arduino Mega has built in more than 1 hardware serial ports (I can't recall now if it's full 3 ports, or just 2), what leave one port for debug purposes, and the other - for your communication.
In your case (Arduino Uno) - you have only one serial port, that if will be used for the inter-Arduinos communication - will not be available for debug/console messages.
The solution for this is adding a Software Serial port, also highly available in tutorials over the net, here is one example:
softwareserial between arduino uno and esp8266
Enjoy your project!


Burning bootloader and uploading sketch on ATMEGA328

Use the https://github.com/MCUdude/MiniCore for ATmega328. It has Boards Manager installation. Choose the right options in Tools menu for your ATmega328.

First burn the bootloader using programmer or "Arduino as ISP". Then you can do serial upload as usual.

You can put the ATmega328 on Uno if you want.


Why can the Xbox360 not detect the Arduino Leonardo as keyboard?

Like Juraj and Majenko said. Arduino Keyboard library does emulate "Boot Keyboard".

I use NicoHood HID library and now it works.


move the template method definiton to .h or define it in class. it is not a real function, only a prescription for functions. Like this:
class myTest
{
public:
    myTest();
    template <class T1>
    void funcOne(T1 arg);
};

template <class T1>
void myTest::funcOne(T1 arg)
{
        Serial.println(arg);
}

or this
class myTest
{
public:
    myTest();
    template <class T1>
    void funcOne(T1 arg)
    {
            Serial.println(arg);
    }
};


My code isn't adjusting the speed of one of the motors and i'm not sure why

If the left LDR is picking up more light than the right LDR, the left motor should be assigned a 'speed' of 80 whilst the right motor has a speed of 210. If the right one has more intensity, then the right motor should be assigned a speed of 80 and the left motor assigned a speed of 210.

  If they're both equal each motor should have a speed of 210 (although I dont have that included in the code).

In code you would express this as

void loop()
{
    int ldrReadL = analogRead(leftLDR);
    int ldrReadR = analogRead(rightLDR);
    int leftLDRread = ldrReadL;
    int rightLDRread = ldrReadR;

    digitalWrite(motorDirectionA, LOW);
    analogWrite(motorEnableA, motorSpeedA);
    digitalWrite(motorDirectionB, HIGH);
    analogWrite(motorEnableB, motorSpeedB);

    Serial.print("Left LDR reading: ");
    Serial.println(ldrReadL);
    Serial.print("Right LDR reading: ");
    Serial.println(ldrReadR);

    //assuming motorSpeedA is the left motor
    // left > right
    if (leftLDRread > rightLDRread) {
        motorSpeedA = 80;
        motorSpeedB = 210;
    } else if( leftLDRread < rightLDRread ) {
        //left < right
        motorSpeedA = 210;
        motorSpeedB = 80;
    } else {
        // left == right
        motorSpeedA = 210;
        motorSpeedB = 210;
    }
}

Also note that this is a quite primitive form of a PID controller. You want to respond to environmental influences in some kind of way, for which a PID is for.

You might find these videos interesting:

https://www.youtube.com/watch?v=1pKJ-KcHZ8g
https://www.youtube.com/watch?v=VVOi2dbtxC0

Edit: The code was fixed, a wrong variable was used (the pin number vs the read value)


The proper method to use depends in part on what the data is for, and on what other processing your loop needs to do.  The following example assumes there is nothing to do except compute the difference between the highest and lowest readings from among the most recent 8.

enum { nReads = 8 }; // # of readings = 2**3
enum { rMask = 7 };  // index-mask of 3 bits
enum { aIn = A3 };   // analog input pin #
int reads[nReads];
byte rindex=0;

void loop() {
  int vhi, vlo, vdiff, r;
  r = reads[rindex] = analogRead(aIn); // Analog read takes about .1 ms
  vhi=0; vlo=1024;
  for (byte i=0; i<nReads; ++i) {
    if (r > vhi) vhi = r;
    if (r < vlo) vlo = r;
  }
  rindex = (rindex+1) & rMask;
  vdiff = vhi - vlo;
  //
  // In this section, scale or use or report vdiff
  //   ...
}

An analog read takes about 104 μs.  That, plus any time taken to scale, use, or report vdiff, will be the major determinant of how rapidly loop() runs, because the for loop that calculates vhi and vlo should take less than 10 or 15 μs.

For example, if loop() takes 125 μs per pass, the code will get about one reading per half cycle of input.  (3.3 KHz is 303 μs per full cycle.)  This will produce a steady precession of where the analog readings are taken within the input waveform's cycle.  If that phenomenon is undesirable, you may need to use interrupt-triggered ADC reads.

If you don't need new differences as frequently as the above code produces them, you could instead on demand take several readings in a row and produce a result.  For example:

int getDiff() {
  enum { nReads = 6 };
  enum { aIn = A3 };   // analog input pin #
  int vhi=0, vlo=1024, r;
  for (byte i=0; i<nReads; ++i) {
    r = analogRead(aIn); // Analog read takes about .1 ms
    if (r > vhi) vhi = r;
    if (r < vlo) vlo = r;
  }
  return vhi - vlo;
}

void loop() {
  int vdiff;
  if (readingIsNeededNow) {
    vdiff = getDiff();
    // do stuff with voltage difference
  }
  // etc
}