ESP8266 to ESP8266 communication using Arduino IDE

I don't like the order between two statements:

server.begin();
...
WiFi.config(ip,gateway,subnet);

Since you start the server and then modify the IP address, server may be "connected" to the wrong address. Try swapping these two statement groups - start the server after setting the IP address.

I don't know your WiFi router, but it might not like you arbitrarily changing your IP address like that.


How can I tell which fuses are set on an ATtiny?

This seems to be an X -> Y problem, with X being the missing clock source on your ATTiny, which prevents communication.

If you have a second Uno or other AVR device, you can use that to generate a clock signal on any of the digital pins:

void setup() {
  DDRB = 0b00100000;
}

void loop() {
  PINB = 0b00100000;
}

This creates a square(~ish) signal on Pin 13 with a frequency of 1.6 MHz.
Depending on the IDEs optimization level (platform.txt), a frequency of 4 MHz is also achievable (at -O3 instead of -Os).

Connecting this to the XTAL1 pin of your ATTiny85 should allow you to communicate with the board.
Make sure to interconnect all grounds.


The ATtiny85 has no dedicated SPI port. It has, however, an “USI” port
(Universal Serial Interface) that should be able to do the job. The lack
of SPI should not be a problem, but the lack of memory will be a
problem.
Files on an SD card are written one sector (512 bytes) at a time.
For this reason, the SD library uses a 512 bytes buffer in RAM.
That cannot work on an ATtiny85, as the buffer would consume the whole
RAM.
You may be able to do something using the Petit FAT library,
provided you can work around the severe limitations of its write
interface:

The write function has some restrictions listed below:

Cannot create file. Only existing file can be written.
Cannot expand file size.
Cannot update time stamp of the file.
Write operation can start/stop on the sector boundary only.
Read-only attribute of the file cannot block write operation.

The first two points imply that you would have to create the file and
allocate the sectors for it in your computer.
This blog post mentions a port of the library to the Arduino
environment, and its use on an ATtiny84, which has similar capabilities
to the ATtiny85 (only with more pins).


How to check whether my Arduino is working? And how to fix this?

My suggestion is to find someone else with an arduino, and get them to test (with their computer, known to be working) uploading to your Arduino. That way, you can tell if the problem is with your computer or the Arduino.

You haven't mentioned what your first project was. The most common mistake #1 is to light up an LED without a resistor. If you do that for a split second, you might (OR MIGHT NOT!) get away with it. If you leave it running for a few seconds, you are almost certainly going to burn out your AtMega (the IC on the board). This might very well result in the symptoms you describe. If this has happened, and your chip (IC) is removable (some are, some aren't), you should be able to buy a new chip of the same kind. An Arduino Uno has an AtMega 328, you will want a DIP package (they are the removable ones), and you will want one with an Arduino Bootloader pre-programmed. Replacing the chip may OR MAY NOT fix the problem. Make sure you note down the orientation of the broken chip before you pull it out - it will fit in, but won't work (and could burn out!) if you put it in the wrong way. There should be a little dimple at one end of the chip, right on the end. It should look like this (possibly without the pin labeling sticker): http://www.jaycar.co.nz/productView.asp?ID=ZZ8726&w=atmega328&form=KEYWORD

If your chip is not removable, or replacing the chip doesn't help, then you will need to get a new Arduino.


Yes, you may connect all 3V pins together (red) and all GND pins together (black), like so:

In some cases, more wires will improve the circuit. E.g. when you build the Ben Eater 8-Bit CPU, you'll find that connecting power in a ring instead of a line will reduce voltage drop by about 50%.

When first reading your question, I got the impression that you wanted to solder the 3.3 V wires directly to the voltage regulator. Here's my original answer for that:

That's not a good idea: if you connect the same wire to all pins, your're creating a short, typically causing a malfunction if not worse. You may destroy your equipment (external board as well as the NodeMCU v3). Do NOT connect 3.3V to all pins of the voltage regulator.

A voltage regulator has 3 pins:

voltage in (for an unregulated voltage you can't exactly control; typically higher than the output voltage)
voltage out (for the stabilized resulting voltage you want to have)
ground

The only pin to connect the voltage to is the "voltage in" pin (VIN). And typically, a development board has a pin for that:

However, you'll find that the input voltage must be between 4.75V and 10V, so supplying 3.3V from an external board is not sufficient.

If you have regulated (stable) 3.3V already, you can connect that to a pin labelled 3V:

Also, you need to connect the grounds (GND) of both circuits together (GND of external board to GND of NodeMCU), otherwise the current will not find its way back.


KennetRunner already explained what is wrong with your code. Here I will
try to give advice on the proper way to implement the automatic door.

First thing is to get rid of delay(). While your program is inside a
call to delay(), it can do nothing but wait until the delay is over.
This is acceptable if the program has only one single task to perform,
like blinking an LED. As soon as you have two tasks, delay() is a
nuisance because it blocks all the tasks.

Case in hand: after keeping the door open for one minute, your program
would close it, irrespective of whether there is someone in the way. It
could not see the person come because it was busy delaying the closing
of the door.

The standard way to get rid of delay() is to never wait inside
loop(). Instead, if there is something to do right now, do it; if
not, just don't do it, but do not wait. Pseudo-code:

void loop()
{
    if (it_is_time_to_do_foo()) {
        do_foo();
    }
    if (it_is_time_to_do_bar()) {
        do_bar();
    }
    /// etc...
}

You would use the millis() function to know when the time has
come to do some task, as explained in the Blink Without Delay
Arduino tutorial. This is really the second tutorial every Arduino user
should read, right after learning how to blink an LED.

Next, you have to learn how to implement a finite state machine. I
recommend the Finite State Machine tutorial by Majenko,
a regular contributor to this site.

Your problem can be very naturally mapped into a machine with four
states: CLOSED, OPENING, OPEN and CLOSING. You then write the rules
about what to do in each state, and when to transition to another state.
For example:

when the door is CLOSED

if the sensors detect someone, transition to the OPENING state

when the door is OPENING

if it's time to move the servo by one step, do it
if we have already moved all the way to the open position, we can
say the door is OPEN now

when the door is OPEN

if it's time to close it, transition to the CLOSING state
if the sensors detect someone, reset the timer <<<< note this!

when the door is CLOSING

if the sensors detect someone, transition to the OPENING state
if it's time to move the servo by one step, do it
if we have already moved all the way to the closed position, we say
the door is now CLOSED

A few things to note here:

See the line marked by “<<<<”: this will prevent the aforementioned
problem of the door closing into someone.
The first rule for the CLOSING state follows from a similar rationale.
I made up some of these rules, as the job of your program was not
completely specified in your question. Feel free to change those rules
to your taste.

And here is my proposed implementation. Warning: not tested. As
usual with FSMs, it is based on a big switch/case statement going
through all the possible states. However, to avoid repeating rules, I
factored the “if there is someone, start OPENING” rule out of the
switch. I also folded “if there is someone, reset the timer” into the
same rule.

const int position_closed = 0;      // door closed position [deg]
const int position_open = 180;      // door open position [deg]
const uint32_t delay_step = 15;     // delay between servo steps [ms]
const uint32_t delay_open = 60000;  // how long the door stays open [ms]

void loop()
{
    static enum { CLOSED, OPENING, OPEN, CLOSING } state;
    static int position;          // door position
    static uint32_t last_change;  // last time state or position changed
    uint32_t now = millis();

    // When presence is detected, switch to the OPENING state.
    if ((digitalRead(pirPin) == HIGH || digitalRead(pirPin2) == HIGH)
            && state != OPENING) {
        state = OPENING;
        last_change = now;
    }
    else switch (state) {
        case CLOSED:
            break;
        case OPENING:
            if (position == position_open) {
                state = OPEN;
                last_change = now;
            } else if (now - last_change >= delay_step) {
                myservo.write(++position);
                last_change = now;
            }
            break;
        case OPEN:
            if (now - last_change >= delay_open) {
                state = CLOSING;
                last_change = now;
            }
            break;
        case CLOSING:
            if (position == position_closed) {
                state = CLOSED;
                last_change = now;
            } else if (now - last_change >= delay_step) {
                myservo.write(--position);
                last_change = now;
            }
            break;
    }
}


Figuring out IR sensor PWM frequency with Arduino

You mistakenly believe that the carrier frequency of 38 kHz should be available at the data output pin of the infrared detector chip. These chips provide a logic output indicating the presence of 38 kHz. Most are frequency-selective, being more sensitive at one frequency somewhere between 35 kHz - 60 kHz.
A data sheet pulled at random specifies typical pulse bursts that might be used to encode digital data (pulse burst timing highlighted in red):

In your case, \$f_o\$ might be close to 38 kHz. No fewer than six cycles \$t_{pi}\$ are recommended for the length of one baud. Perhaps your transmitter includes a few more cycles (ten or eleven?) to be safe. The receiver circuitry requires about five cycles before commit, \$t_d\$. Hopefully, a similar delay at end-of-pulse occurs, but the graph at right suggests the end-of-pulse extends a little longer than \$t_d\$. However, pulse width is impressively constant over five magnitudes of infrared intensity.
Note that the presence of a burst of 38 kHz from the transmitter most often sends the output of the receiver to a logic low. No optical signal yields a logic high at receiver output, sometimes with a fast false-detect glitch (which should be rejected if its length is short). A large-value pull-up resistor added between output pin and Vdd may be required to ensure that an idle receiver goes to logic high.
You will still have to determine how these pulse bursts are encoded into logical bits. Many protocols exist, some use pulse position, others use pulse length encoding.


How to store an RFID tag number in a string

String rfid_uid = "";
if (rfid.readCardSerial()) {
    String rfid_uid = "";
    for (int i = 0; i < 4; i++) {
        Serial.print(rfid.serNum[i], HEX);
        rfid_uid = rfid.serNum[i];
    }

    Serial.println();
}

This code has multiple problems:

the variable rfid_uid is defined twice, they are overshadowing each other. The inner part only assigns a value to the rfid_uid delcared in the inside of the if statement, the outer rfid_uid will remain empty
As you can see with Serial.print(rfid.serNum[i], HEX);, the element rfid.serNum[i] is an integer, which is printed as hex. (e.g. 123 = 7B), in rfid_uid = rfid.serNum[i]; you however assign the direct numerical value, without converting it to hex

You can try the following, if you want the serial number as a 4 byte hex string:

String rfid_uid = "";
if (rfid.readCardSerial()) {
    for (int i = 0; i < 4; i++) {
        String uid_part = String(rfid.serNum[i], HEX);
        Serial.print(uid_part);
        rfid_uid += uid_part;
    }

    Serial.println();
}
//rest as before

This should construct a String object from the integer in HEX format and append (using the += operator it to the rfid_uid string). Thus, after 4 iterations, the String value is built up and can be used in the request.


Why am I getting this error- "exit status 1 expected ';' before '{' token "

Try parentheses instead of curly braces:

void setup() {

pinMode(13, OUTPUT);

}

void loop() {

digitalWrite(13, HIGH);

}


According to the official documentation, the second parameter of
digitalWrite() should be either HIGH or LOW. Thus, in order to be
compliant with the published API, you are supposed to write:
digitalWrite(12, sensorValue&256 ? HIGH : LOW);

In practice, digitalWrite() interprets any non-zero value as HIGH.
However, its prototype is:
void digitalWrite(uint8_t pin, uint8_t val);

Both parameters have the type uint8_t, which means “8-bit unsigned
integer”. If you provide a value that doesn't fit in 8 bits, the
implicit cast to uint8_t will reduce it modulo 28. Thus,
both 256 and 512 become zero through the implicit cast.


The registers are listed in table 4-1. Clearly enough.

The command byte format is shown in chapter 6. That command byte includes the operation and the register number, as well as upper bits for registers that expect more than 8 bits of data.

Two bytes are needed to set a register.  The first 4 bits are the register number (0000 for wiper 0, 0001 for wiper 1, and 0100 for the TCON register).  The next two bits are the operation as shown in figure 7-1. 00 for a simple write. The next two bits are the upper 2 bits of the data.  Following that are the lower 8 bits of data.

So to write a pot 0 value of 0x23 you would write:

0x00 0x23

To write a pot 1 value of 0x65 you would write:

0x10 0x65

To write a pot 1 value of 0x13D you would write:

0x11 0x3D

You can make a simpler function to wrap it for you:

void writePot(uint8_t address, uint8_t pot, uint16_t val) {
    Wire.beginTransmission(address);
    Wire.write((pot & 3) << 4 | ((val >> 8) & 3));
    Wire.write(val & 0xFF);
    Wire.endTransmission();
}


Problem with passing string pointer from child to parent

The problem here is that alphaName and betaName are member variables. That means they are initialized during the Alpha and Beta constructors. However, the superclass constructor of Parent is always called first, before calling the child class constructors. Result: Parent::Parent(char *) is called with an uninitialized pointer.

Here is your code on the Compiler Explorer: https://godbolt.org/z/otAuQU
As you can see, Alpha::Alpha() compiles to the following:

call Parent::Parent(char*)
ldd r24,Y+1
ldd r25,Y+2
ldi r18,lo8(.LC0)
ldi r19,hi8(.LC0)

.LC0 is the string "ALPHA".

The solution here is to make the names static. That way, they are initialized before the parent constructor is called.

class Parent {
  protected:
    const char *const childName;

  public:
    Parent(const char* childName) : childName(childName) {}

    const char *getChildName () const {
        return childName;
    }
};

class Alpha : public Parent {
  protected:
    constexpr static const char *alphaName = "ALPHA";

  public:
    Alpha() : Parent(alphaName) {
        Serial.print(F("My name is "));
        Serial.println(getChildName());
    }
};

This compiles to:

ldi r22,lo8(.LC0)
ldi r23,hi8(.LC0)
call Parent::Parent(char const*)

As others have mentioned, pointers to string literals should always be const. The only reason this doesn't give an error is because the Arduino folks decided that it was a good idea to compile everything with -fpermissive ...
Mutating a string literal is undefined behavior, so an error.


Neither. First, inputs don't draw current. Whether you're sourcing current or draining it, it will always be an output pin.

The 200 mA rule is probably determined by the bonding wires for the Vcc and ground pins on the die. That means that all outputs which are sourcing current shouldn't source more than 200 mA combined, as this current will have to enter the device through the Vcc pin.
Likewise all outputs sinking current shouldn't sink more than 200 mA combined, as this current will drain through the ground pin.


Don't call portone.listen().  That method is only necessary when you have created multiple SoftwareSerial ports.  It specifies which port you are listening to, because only one of them can receive at a time (you can transmit on any of them at any time).  It also empties the receive buffer so that data from one SoftwareSerial port is not mistakenly returned by another.  In your code, this empties the input buffer before checking portone.available().  Surprise, it's always empty!  ;)

Also, don't set the pin mode of the pins used for the SoftwareSerial object.  The pin modes were set during the constructor of portone, which happens before setup.  You're messing with pins that have been "promised" to that library for its own use and control.

As Edgar suggested, you should consider a more-efficient software serial library.  AltSoftSerial is best, but is only available on certain pins.  My NeoSWSerial library is next best, and works on any two pins, but only at 9600, 19200 and 38400.  Both of those libraries can transmit and receive at the same time, unlike SoftwareSerial.  Here is an answer with all the gory details.

And you really should ditch the String class usage.  You obviously know how to use char arrays (aka "C strings").  We can't see the sending() function, but you can probably just print a few pieces instead of building a complete String and printing it:

    portone.print( '+' ); // leading plus sign
    portone.write( (uint8_t *) customerCode, 13 ); // array of bytes, length

It would be better to terminate the character arrays with a zero byte (NUL-termination) in loop so they can be used as a standard C string instead of a byte array:

    customerCode[14] = '\0'; // NUL-terminate the C string

Then you can use the standard C string print in sending:

    portone.print( '+' ); // leading plus sign
    portone.print( customerCode );

Printing the pieces is always more efficient than building a big buffer with all the pieces.  This avoids copying the pieces and needing twice as much RAM.     :P


Switching between SPI Devices when one is an SD card

with SPI there is an implicit slave select pin on each device that must be pulled low to enable the device.

Connect each slave select pin of the SPI device to their own unused digital pin on your arduino and keep it pulled high until you want to talk to the slave.

However not all SPI devices will properly put the MISO pin into high impedance when SS is pulled high so you may need to use a tristate buffer on that pin or use a multiplexer.

When adding your own tristate buffer (for example a HS125) you need to connect each MISO pin of the SPI device to the input of a buffer, the slave select is then connected to the output enable pin of the tristate. The outputs of the buffers can be connected together along with the MISO pins of the devices that do properly go high impedance to the MISO of the master.

When using multiplexers there are 2 options:

You can daisy chain 2:1 multiplexers by connecting the MISO of the device to the 0-input of the mux and the Slave select to the select input pin of the mux.
you can use a >2 multiplexer to select the correct MISO line based on the address of a set of S lines. Then with a decoder you can provide the actual SS signal to the SPI device. This way you only need 2 SS pins for 4 SPI devices.


You are trying to print 6 characters ("test\r\n"), i.e. 60 bits
including the start and stop bits, 1000 times per second. This requires
a baud rate of at least 60 kbit/s, yet the serial port has been
configured for only 9.6 kbit/s. Something has to give...

As Mikael Patel wrote in a comment, it is generally inadvisable to
Serial.print() from within an ISR. It is supposed to work, though, as
long as you don't fill the Serial output buffer. The problem is that
your code does fill the buffer, as it is writing to it faster than the
UART can empty it. Once the buffer is full, the program will
malfunction.


6 months after figuring out the answer, I found this question again. I solved this question by adding system("ifup eth0") which completely solved the problem.


Multimeters are designed to provide a stable response. It would be averaging the readings.

As far as the difference in voltage reading, if you are using the Arduino board as is the default is to assume a reference voltage for the A/D as being 5.0 volts.(for your calculations) That may not be the case. Also there may be a tolerance issue on the measurement board, but I think the reference for the A/D on the Arduino is the bigger issue.


SPI Temperature sensor interface with Arduino Uno

delay (0.425);// wait for conversion

You can't delay a fraction of a millisecond. You can use delayMicroseconds though:

delayMicroseconds(425);

However, you don't need to sleep at all.

  The conversion clock for the part is internally generated so no
  external clock is required except when reading from and writing
  to the serial port. In normal mode, an internal clock oscillator
  runs the automatic conversion sequence. A conversion is initiated
  every 400 ms. At this time, the part wakes up and performs
  a temperature conversion. This temperature conversion typically
  takes 25 ms, at which time the part automatically shuts down.
  The result of the most recent temperature conversion is available
  in the serial output register at any time.

You have your chip select pin backwards:

  To ensure that the serial port is reset properly
  after power-up, the CE must be at a logic low before the
  first serial port access. The serial clock is active only when CE is
  high. For correct data synchronization, it is important that the
  CE be low when the serial port is not being accessed

So it should start LOW, and be set HIGH before you read, and back to LOW afterwards.

You need to read 2 bytes, not one, then combine them in the right way to make a proper 8-bit value:

digitalWrite(A0, HIGH);
uint8_t b1 = SPI.transfer(0x00);
uint8_t b2 = SPI.transfer(0x00);
digitalWrite(A0, LOW);

int8_t = (b1 << 1) | (b2 >> 7);

The reason for that is that the first bit of the first byte is a "leading zero" so you need to discard it, then add the first bit of the second byte as the last bit of your value, discarding the remainder of the second byte, since you specified only an 8-bit resolution in your question.


Using a resistor is the "Normal" way, yes. 250Ω will give you 1-5V, yes, which means that you get 4/5 of the actual resolution of the ADC at your disposal.

That means instead of 0-1023 you're actually reading 204-1023, or 819 possible values. Spread over 16ma (or 4V, which are the same thing) that gives you about 20µA resolution.

If you really really care about that extra 1/5 of the resolution you can instead use a 300Ω resistor to give you 1.2 to 6V, then pass that through a subtracting amplifier (see this post) and subtract 1.1V from it (you need to create that 1.1V, of course).  That will give you 0.1 to 4.9V, which then covers more of the ADC's available range (20-1002, or about 16µA resolution).

Is it worth it? Probably not. Any increase in resolution will likely be swamped by the inaccuracy of the resistor and potential drift though self heating.


Arduino Pro Mini and GDEW0154T1 ePaper (e ink) display

You need to build a special driver board.  Most of the drive circuitry is on the main chip built into the display, which is convenient, but it requires a number of capacitors (which are too big to fit into the display itself) on the various voltage pins, and a special power control circuit to ensure that the different voltages get enabled at the right time.

The datasheet details the capacitors that need connecting (Figure 7.5(2)), as well as the power control circuit (Figure 7.5(4)).

There is another small circuit snippet there as well (Figure 7.5(3), temperature sensor) but I haven't worked out the relevance of that yet.

Also you will need the right FPC connector, and a surface mount PCB to solder it on to, as well as the ability to solder it (reflow oven), so it's not a trivial task.  You may be able to find the right connector already soldered onto a breakout board if you look around - but make sure it is the right one, since there are many variations - number of pins, pitch of pins, upper or lower connection, etc.


Warning when verifying sketch with VS code

Thanks to @Majenko I looked some place new:

documented in the arduino plugin of VS Code Arduino Extension there is an option to set an output directory.
Note though that according to this it should not be in the workspace or subfolders.

So in arduino.json settings file add:

"output": "../ArduinoOutput"


This is not gospel, but here is what those terms are generally used to indicate (as I understand it):

compatible: a dev board which is compatible with the Arduino IDE/toolchain. The Arduino UNO uses an ATmega328 MCU, while other platforms may use different MCUs i.e. there are multiple MCUs that are compatible with the Arduino IDE. It may or may not have the same form factor. Keep in mind that this term can also be used for shields, "Arduino-compatible" shields are add-on boards that are meant to mate with an Arduino. The Sparkfun RedBoard is an example.
clone: a dev board which has the same (or very similar) circuitry as an Arduino and the same physical board/layout. They are branded differently, but are, for all intents and purposes, exactly the same as a real Arduino. These boards are permitted under the open-source licensing of the Arduino design. An Freeduino might be an example.
counterfeit: a dev board which is identical to an original Arduino, and is branded and sold as an original Arduino. As I understand it, the open-source licensing does not permit this, however, this does not deter the flood of shops churning out counterfeit Arduinos. A search on eBay or Aliexpress will turn up loads of examples; note the Arduino guide to spotting counterfeits, in general, the silkscreen is blue and the quality of assembly is not quite as good.

The difference between "compatible" and "clone" is a bit blurry, but it's not really important. The main difference between counterfeit and non-counterfeit is that counterfeit Arduinos are boards that are not sold by Arduino but are branded as such.


If you can properly bias your signal, say with a cap and a pot, you
could read it with a digital input. You can then time the rising edges
with micros(), either by polling the pin or using an interrupt. You
could achieve greater accuracy by using the “input capture” feature of a
16-bit timer, if you are using an AVR-based Arduino and are not afraid
of getting your hands dirty with low-level programming.

You need to get the right voltage range for this to work though. On an
Arduino Uno, for example, the thresholds for the input switching from
HIGH to LOW and back are typically around 2.1 and 2.6 V
respectively, so you must make sure that your signal amply covers this
range. If you can get 1 V peak to peak, that should be enough, and
you can then use the pot to tune the offset.


LiquidCrystal_I2C    lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

Are you not using pin 2 in the LiquidCrystal_I2C constructor? So you can't also use it for the DHT sensor.

I withdraw that suggestion.

Can you please try saving some RAM?

Use the F macro with your prints, eg.

  Serial.print(F("Humidity: "));
  Serial.print(DHT_hum);
  Serial.print(F(" %\t"));
  Serial.print(F("Temperature: "));

Ditto with the lcd.print() calls.


There are Uno compatible SD shields which are great for prototyping IF you are using an Uno, they don't work too well with a Nano.  The modules are fine, but you end up with wires everywhere, but they do work with more formats of Arduino.

The ability to do file operations is separate to the protocol you use to talk to the module (SPI).  Lots of device (not just SD cards) use SPI, but not all of them do file operations.  An LCD, a GPIO expander, an EEPROM memory chip are all examples of devices that could use SPI.

What actions the SD module/shield is capable of is really up to the library/software.  The module will have to comply to some set of standards and this will let the caller perform certain operations.  Lets say one of the operations is to read one byte from an address.  This operation would need to be used by the library to read a file, also it would need to use it to find where the file is.  It would also need it when writing a file, because it would need to know what free space was left on the card.  You are shielded from all this by the Library you probably have a read file, write file and delete file function.  (This is an example of abstraction which you will see a lot in programming).

The will also have a set of standards to allow a controller to interface with the module, SPI, I2C, Serial or a proprietary one.  These communication protocols allow the controller to send the file commands to the module, like the read command above, and lets the module return data to the controller.

So to answer your question

If you use a module and shield that use the same IC (chip) to access
the SD card and the same library then they will almost always behave
the same.
If you use two different shield (different ICs) which
need different libraries then they MIGHT have different
functionality.
If you use two different shields which use the SAME library then the MIGHT have the same or different functionality.

Summary : Yes No Maybe :)

If you want something special find a library that does what you want and then find a bit of hardware supported by that library that also does it.  Otherwise, chances are you will be fine.

==== Edit ===

When you think of hardware/software abstraction think of it as a Television.  You deal with the TV at the very highest level, you turn it on/off and change channels.

When you change channel what really happens is the remote control converts your button press into an encoded infra-red signal which hopefully hits the TV and the TV decodes this and executes some code which selects a pre-programmed channel.

Now you don't care about that all you care about is you press the button and you favourite soap opera appears on the screen.

There is another level of abstraction that is happening when the TV selects the pre-programmed channel, it has to convert the signal into some reference to the stored information that produces some information that is passed to the tuner and....  Well it just gets silly, you just want to watch your soap.

So back to the subject in question, you buy a SD reader module, you find a library that works with it and in your code you call WriteFile().  Does it really matter how it does it?  Do you care that the library is scattering you bytes across the SD card? Well as long as it retrieves it no not really?  Does it matter that WriteFile() is actually storing it on the hard disk of a PC somewhere in the world?

Your call to WriteFile() is abstracted away from the underlying process hiding it, because it doesn't really matter.  Most of the libraries use this Abstraction process, look at the code in Wire.cpp, it looks really simple when you are calling read() and write() but it isn't.


Disturbed digital out at 4Mhz on Arduino NANO

This is not a limitation of the Arduino: you can toggle a pin on every clock cycle. It's a synchronization problem between the generated signal and the triggering of the scope. Your scope displays several traces superimposed, and it synchronizes them on the rising edges, but since those are unequally spaced, it gets out of sync with the full period of the signal. By adding a few nops you reached a lucky synchronization in your second version of the code.

The simplest solution is to set the scope mode to Single instead of Normal. Then it only displays a single trace and synchronization is not an issue anymore.

Another option would be to use one of the bits of PORTD as a trigger
signal. This bit should cycle only once inside the loop. PD5 should
work in the current version of your code. Configure the scope for
external trigger and feed this signal into its TRIG input.


AFAIK, it's still available on the arduino store website


Is it possible to make a mathematical function generator using Arduino?

You can generate arbitrary waveforms using either the built-in PWM and a low-pass filter or an external DAC.

You won't get more than 16-bits in PWM ( or AFAIK non-audio DAC with arduino libraries ), so your e^N function will be below your resolution for most of the cycle.

Alternatively, generate a saw-tooth and use an op-amp exponential function


How to apply a programme to all values in a list simultaneously

You have already done it twice, why are you struggling the third time?

for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
}

  // turns all the pins of one at a time

Except that it is happening so fast you can't see then doing it individually. So just do the same but set them to LOW:

for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], LOW); // turns all the pins off one at a time
}

Now you might want to add a delay into the loop that turns them on so you can see them turn on individually instead of all at once:

for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
  delay(50);
}


Powering a 6-12V motor using a lead acid 6V battery with 6Amps of current?

If you take the "full load" to be the "stall current", then you can work out the resistance of the winding.

R=V/I = 12/14 = 0.857Ω

From that you can then work out the stall current at 6V:

I=VR = 6×0.857 = 5.143A

That, being the stall current, is the maximum the motor will draw - the current drawn when it is trying to move an impossible amount of load and the rotor cannot move.  At that current you will melt the motor drivers (or they will go into thermal shutdown).

Of course, with a geared motor, that becomes a (comparatively) massive load and would be quite hard to achieve.  You have a 50:1 gear ratio, so the stall load is effectively 50x greater.

So there is going to be a limit to the load that you can drive with the motor before it becomes a problem for the driver.  There are ways of calculating it from the given torque, gear ratio, load/noload current ratings, etc, but I don't have all that at my fingertips right now.

So you can either "play it safe" and invest in a driver that can cope with the stall current, or experiment and measure what current is drawn by the motor with different loads and see if it stays below the 1.2A limit of the shield.


Creating arduino library linking question

I can't speak for Xcode, but in general with Arduino IDEs (UECIDE excepting) if you use a library within another library, that library also has to be #included in the main sketch.  That is the only way most IDEs determine which libraries need to be compiled into the finished program.

That's one of the first targets I had for UECIDE - to enable fully recursive library compilation.  Any libraries found within the master header of a library will also be included for compilation - and any found in those libraries, etc.  It took a lot of work (and it's by no means 100% perfect), which is why so few others do it and leave it up to the programmer to ensure the inclusion of the right sub-libraries in their sketch.


Why does it skip the first index - shift register issue

The correct way to loop through an array of length 8 is:

for (int counter = 0; counter < 8; ++counter) {
    digitalWrite(2, ledValue[counter]);
    // ...
}

If you want to loop through the array backwards, then:

for (int counter = 7; counter >= 0; --counter) {
    digitalWrite(2, ledValue[counter]);
    // ...
}

This loop will visit, in this order, the indices 7, 6, 5... 1 and 0.

For extra clarity, you could define a constant that holds the length of
the array, then replace the numbers 8 and 7 above by VALUES_COUNT
and VALUES_COUNT-1 respectively.

You wrote:

  If I make it [...] my output is [...]

Not sure what you mean by that. This code should not have much visible
output, as the LEDs are turned off only microseconds after being turned
on. How do you determine what the program's "output" is? Maybe there is
an issue with the way you are trying to diagnose the problem.


Can adjustable constant current/voltage source be made with Arduino?

You are basically describing (if you add an inductor and a diode into the mix) a simple switching regulator.  That is, at its simplist, a PWM signal, some smoothing (inductor, diode, capacitor), and feedback.

Use the Arduino's PWM to switch a P-channel MOSFET in the voltage supply. That switched supply is then fed through an inductor, and then smoothed with a capacitor:

simulate this circuit – Schematic created using CircuitLab

M1 does the switching of the power to charge the rest of the circuit.  L1 + C1 smooths the PWM out giving a constant smooth (ish) voltage. D1 completes the circuit between L1 and C1 in one direction only keeping the charge in the right part of the circuit.

R1 keeps the MOSFET turned off when not being driven.

R2 is a very small "shunt" resistor (maybe 0.1Ω for example).

The size of C1 and L1 are determined by the switching frequency of your PWM and the current demands of the circuit.  The higher your switching frequency the smaller your inductor can be, The higher your current demands the larger C1 needs to be.

Reading A1 gives the output voltage of the circuit, so you can adjust the PWM (using PID would be good) to get a specific voltage.

Reading A0 and A1 and subtracting one from another gives you the voltage drop across R2. From that, you can calculate the current through R2 using Ohm's Law. You can then use that to adjust the PWM to give you a specific current.

Of course, you can't do both at once. You either have a constant current (during the first charging phase to bring the cell voltage up to 4.2V), and then switch to constant voltage until the current drops to around 0.3C.  For dead cells, an initial constant current phase of (IIRC) 0.1C can recover the cell.

Some important notes about lithium cells:

They explode (just ask Samsung), so take care. It can be good to do your experimenting with the cell contained within a fireproof container.
Lithium Ion and Lithium Polymer cells don't like being over-discharged, but as long as they haven't been reverse charged they can generally be recovered.
Cells that are used in a series pack and haven't been charged with a proper balancing charger may well have been reverse charged if the pack has "died".

The reverse charge thing is what actually kills a Lithium cell.  Basically, no two cells will have exactly the same capacity. If you have, say, three cells in series and you discharge the whole pack to below the recommended minimum, once cell will have less charge than the others. If that cell hits zero the current from the other cells will start flowing backwards through it, and that backward current causes copper crystals to deposit on the electrolyte layer between the electrodes. Those pierce the electrolyte layer and short the two electrodes together, and at that point the cell is dead. No amount of recovery charging will get it back, it's physically damaged.

So in summary:

A single cell that has been over-discharged by itself will generally be recoverable.
A series pack of cells that has been over-discharged may well have physically damaged one of the cells in the pack through reverse charge flow.

  Will Arduino be fast enough to control a MOSFET that will pump magic pixies into a capacitor to achieve steady value of voltage on said capacitor?

Sure. You should pre-condition your power so it is always within a tolerable limit (i.e., feed your solar panel power through a suitable 5V buck regulator to give a clean 5V supply). There will always be some latency in the circuit due to how long the inductor "resists" changes in the voltage. A typical Arduino takes ~100µs to sample an ADC. In this kind of environment, that time is negligible since it's generally much faster than a single period of PWM. You can't respond faster than one period of PWM anyway.

  When MOSFET is not saturated state it's resistance is high and a lot of power is wasted as heat. Would it be possible NOT to use PWM to control it, but instead to turn it OFF or ON each cycle to minimize power loss?

That's what PWM does. It's ON or OFF. On at the start of a cycle, then off part way through.  Yes, there is a brief period twice per cycle while it does the switching, but that will be minimal compared to the on and off periods. The losses from that switching will be negligible compared to, say, running a MOSFET as an adjustable resistance controlled from an op-amp with feedback from a current shunt (i.e., a linear regulator).


Sending a string to arduino and is not reacting to it

I also tried to input the numbers in the console manually, and it gets them right and moves the servos but it still doesn't work with the VR.

This implies that the problem is in the code sending the data.  Get a terminal emulator program and hook that up to the code generating the data from the VR headset (you will need 'local echo' turned on).  I suspect you will see the headset is not writing the data in the format you expect.  Also it will let you capture a real sample of data that you can feed into you program to generate a repeatable test.

If this isn't the fault, then please can you post the a few lines of data so we can see whats wrong.


You have two choices:

The Arduino regularly communicates with an external web server, sending data and asking if there is anything to do. This is the way Mitsubishi heatpumps can be controlled from the web. The advantage is that your internet connection does not need to publish a web server. Drawback is that the communication is slow (being dependent on the polling interval), plus the need for a web server to talk to. For instance, to control your Mitsubishi heatpump, you need to create an account on one of their servers for the purpose.
The Arduino exposes a web interface that is then exposed to the internet. This needs configuration of your internet router and preferably a static IP address on the internet. Security is a problem, and I'm not sure that even the Due can do HTTPS plus some form of authentication. I used this method, but fronted my Arduino with an old laptop running Linux and Apache web server. The laptop does the authentication and HTTPS processing. Advantage is near real-time control; disadvantage is the amount of hardware and configuration required.


Can I run arduino on Windows Embedded Compact 2013?

What OS is running on two different devices exchanging messages/signals, does not matter. What matters is the protocol.

You can use a lot of different ones:

Wireless:

IR (infrared)
RF (radio), like 433 MHz, 2.4 GHz
WIFI (internet)
Bluetooth

Wired

SPI
'simple wires' / Wire library
Serial
USB (not on most Arduinos)

This list is not complete, just some examples.

Arduino supports all above (except USB fully), I don't know what Windows Embedded Compact OS supports.


Multiple buttons on single interrupt, how to debounce?

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

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

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


A portion of your code is shown below.

  myFile.setTimeout(2000);
  ....
  while (myFile.available()) {
    index = 0;
    do {
      newChar = myFile.read();
      buffer[index] = newChar;
      index += 1;
    } while(newChar != 10);
   ....
  }

Apparently your code is accepting and printing several lines of option setting text and then hangs up in the code extract shown above.

Suppose, for example, one extra character appears after the supposedly-last linefeed character.  Your while (myFile.available()) loop will run again.  It will store the extra character, then try to read another character.  If another character isn't available, newChar = myFile.read(); will return a -1 that your code will store.  That will happen repeatedly,  clobbering RAM.

To see if this is what's happening, you could change while(newChar != 10); to (eg) while(newChar != 10 && index<36);.  If the code then stops hanging up, look into where the extra character is coming from.


Motor shield and wireless transceiver compete for same pins

This is the core of embedded design and "hacking" and highlights one of my peeves about Arduino design: too much focus on the pin numbers and physical location on the PCBs, rather than the actual functions on those pins.

So? Physically move the pins on the Motor Shield. Here are 3 options in order of the most hack-ish to most-clean:

1) Use an edge cutter to cut the bottom of the pins off the motor shield then solder jumpers to the nub to other pins that are free.

2) Use a hot air station to desolder that header row, solder in your jumpers, and put back only the pins you want. Board designs with such limited foresight (like your situation) is what led me to buy my hot air station. And now I pretty much use sensor shields for my interfacing outside the stack or proto shields to be intermediate layers to translate pins.

3) Cut the trace on the motor shield PCB itself to free the SPI pins. Then find pins that have your function (pwm?) and also are NOT used by any other shields in your "stack". Solder a jumper from the exposed trace on SPI pins to your free "new" pins.

If you stalk through my answers there are write-ups on two test benches I made and you can get ideas from the various work-arounds I have employed to get my hardware working.


How to pass a changing value to a graphic display using Arduino?

You have to first convert the floating point value to a string, then pass the resulting string to the dog_7565R::string() function.

It looks like the standard sprintf() provided by Arduino does not support the %f format for floats, so you may have to find another way to convert it or write your own conversion function.


You got confused here:

Serial.print(data[idx]);

You're printing array slice 5 (the sixth entry in a 5 entry array) 5 times.

You probably meant to write:

Serial.print(data[i]);

To improve clarity you may want to #define it instead:

#define DATA_SIZE 5
uint16_t data[DATA_SIZE];

...

for (int i = 0; i < DATA_SIZE; i++) {
    ....
}

Or you can do it the other way round (get the size from the array):

uint16_t data[5];
#define DATA_SIZE (sizeof(data) / sizeof(data[0]))


How to control two 12 V motors with the dual MAX 14870 Motor Drive Shield for Arduino?

I had attached the screenshot for this

This picture tells you about the Arduino Connection with the with the SHIELD.

EN (Enable Pin) is used to enable and disable the motor drivers. As it is inverted SET this PIN HIGH will Disable the Motors and vice versa.
DIR pinS is used direction of rotation. It highly depends upon your connection, setting this PIN HIGH LOW will make the motor rotation from CLOCKWISE & ANTI CLOCKWISE or vice versa depends upon your hardware connection.
PWM pins are used to control the rotation speed of the MOTOR. Driving PWM signal on this pin will adjust your rotational speed. MAX PWM frequency suggested is 50Hz.
Fault is the INPUT PIN to Arduino with ACTIVE LOW signal indicating some kind of fault is there.


Arduino Mega not flashable with XBee PRO S2B

I don't have a PRO to play with, but I just looked at the datasheet and it appears that it SHOULD timeout after 60 seconds

  If no serial transaction is initiated within a 60 second timeout period, the bootloader times out and returns to
  the menu. If the upload is interrupted with a power cycle or reset event, the EM250 will detect an invalid
  application image and enter bootloader mode.  (page 139)

Also, it seems that it takes a particular set of conditions to get to the bootloader, obviously these conditions are being met:

  XBee modules use a modified version of Ember’s bootloader. This bootloader version supports a custom entry
  mechanism that uses module pins DIN (pin 3), DTR / SLEEP_RQ (pin 9), and RTS (pin 16). To invoke the bootloader,
  do the following:

  Set DTR / SLEEP_RQ low (TTL 0V) and RTS high.
  Send a serial break to the DIN pin and power cycle or reset the module.
  When the module powers up, DTR / SLEEP_RQ and DIN should be low (TTL 0V) and RTS should be high.
  Terminate the serial break and send a carriage return at 115200bps to the module.
  If successful, the module will send the Ember bootloader menu out the DOUT pin at 115200bps.
  Commands can be sent to the bootloader at 115200bps.

  Note: Hardware flow control should be disabled when entering and communicating with the EM250 bootloader.

Perhaps check pins 3, 9 and 16 on boot and see if you can modify their behaviour.


Using atol(String.c_str()) looks OK to me. If there was a String.toLong() it would be written that way anyway.

In fact, looking at the code for String.toInt() that's exactly what it does:

long String::toInt(void) const
{
    if (buffer) return atol(buffer);
    return 0;
}

So the answer is: use String.toInt().


randomSeed(analogRead(A0)); does the trick well

Better yet, use the lsb of analogreads to seed the random number generator. No repeat patterns any more.


Store 3-dimensional char array in program memory with PROGMEM

Here you have:

const char * const rules [16][5] PROGMEM ={

One const refers to the char* part. It means the pointer value doesn't change.

The other const refers to what it is pointed by. It means the thing this pointer points doesn't change (but the pointer itself can change).

In your sketch the thing that get put into PROGMEM is the pointer array; the texts themselves are still in RAM. Have a look at PROGMEM page and  study this example:

const char string_0[] PROGMEM = "String 0";   // "String 0" etc are strings to store - change to suit.
const char string_1[] PROGMEM = "String 1";
const char string_2[] PROGMEM = "String 2";
const char string_3[] PROGMEM = "String 3";
const char string_4[] PROGMEM = "String 4";
const char string_5[] PROGMEM = "String 5";

// Then set up a table to refer to your strings.

const char* const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};

You need to declare each string by itself, and later put them in an array.

As you can see, pointer are inescapable.

Edit: The F() Macro

Here is a proof of concept of how to manage an array of string (lowercase "s") and strings constants in PROGMEM:

const char uno[] PROGMEM = "1Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";
const char dos[] PROGMEM = "2Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";
const char tre[] PROGMEM = "3Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";
const char cua[] PROGMEM = "4Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";
const char cin[] PROGMEM = "5Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr";

const char * const rules [3][2] = {
 {uno, dos},
 {tre, cua},
 {cua, cin}
};

void setup() {
  Serial.begin(115200);
  Serial.println(F("PROGMEM string test"));
  Serial.println(F("-------------------"));
  for(int i = 0; i < 3; i++){
    for(int j = 0; j < 2; j++){
      Serial.print(i); Serial.print(" "); Serial.print(j); Serial.print(" ");
     Serial.println((const __FlashStringHelper *) rules[i][j]);
    }
  }
}

void loop() {
}

Use the F() macro to put constant strings in PROGMEM. Otherwise, the strings will live in RAM. Are running short of RAM? Put the F() macro around those pesky strings and send them out of your RAM.


That resistor, where positioned, is called a pull-down resistor, and if replaced by a straight wire, that circuit would short out when the switch was closed.

The purpose of this is that when a digital input pin is not connected, it floats, and if the switch were open that pin could see upwards of 2v floating value from external and internal noise. With Digital circuitry, any value in this float range can be invalid and return invalid results.

A pull down resistor will generally have a very high ohmic value >5kohm, as to allow as little current pass as possible. Here, you are shorting the pin to ground through the resistor so it will not have a LOW value when the switch is open, instead of possibly invalid.

When the switch is closed, you will have 5v passing through switch into the pin, to be read as a HIGH value, also sending 5v across a 10k or so resistor to ground, consuming only .5mA of current.

It you want to see what I mean by a floating value, debug the output of any analog pin with a wire going nowhere, and watch as the value changes. Try touching the wire, now add a pull down to ground, or try pulling it up to 5v and observe the behavior.

Happy Arduinoing!


ADC noise when sharing ground from external supplies

You've created what's known as a "Ground Loop".  You have 2 grounds in your circuit, your 24v PS has a ground and the PC supplying 5V to your Arduino has a ground.  They are not likely to be equivalent and will cause many unwanted side effects.

You can reduce some noise using RC or RLC circuits on your power supply pins.  It's probably best to use only a single power supply (and ground).


I want my arduino mega to read from all 4 serial ports at the same time, running sequentially through each one

The Arduino already reads from the 4 serial ports at the same time. Or
at least as close to “at the same time” as possible with a single CPU:
every time a byte is received at one port, an interrupt is triggered
that reads the byte from the UART and puts it into a buffer. You can
then get it from the buffer using Serial.read().

What you now have to do is move the bytes from these buffers (which
belong to the Arduino hardware serial library) into you own buffers for
further processing. You can do this by checking the ports sequentially
and processing each one in turn. Everything will be fine as long as you
do not have blocking code in there. If you do block, then you run the
risk of having one of the library buffers overflow. The code you posted
is non-blocking, so you are fine.

  is it possible to have copy paste

You should avoid programming by copy-and-paste. It's not that it won't
work (it will), but you would be creating a maintenance nightmare.
Instead, put the code you would want to copy-paste into a function, and
call that function as many times as required. For example:

void handlePort(Stream &port, const char *readerName, char *tagString)
{
    boolean reading1 = false;
    while (port.available() > 0) {
        int readByte1 = port.read(); //read next available byte

        if (readByte1 == 2) reading1 = true;
        if (readByte1 == 3) reading1 = false;
        if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
            tagString[index] = readByte1;
            index++;
        }
    }
    Serial.print(readerName); //read out any unknown tag
    Serial.print(": ");
    Serial.println(tagString);

    clearTag(tagString); //Clear the char of all value
    resetReader(); //reset the RFID reader
    }
}

And you call it in loop():

handlePort(Serial1, "Reader 1", tagString1);
handlePort(Serial2, "Reader 2", tagString2);
...


HC-05 with ELM327 mini OBD2 Bluetooth adapter connection problem

I faced a similar problem when working with HC-05 module with an Android terminal application and connection was lost after some time and many it was just not able to connect.
Upon some hit and trials I found that it was just an power issue with HC-05 and as soon as I tried it out by reducing load on HC-05 by connecting it alone on 5V supply from Arduino and switching others to a 3V supply it worked like butter and I didn't faced any problem till now.

This worked for me try this out.


How to convert four uint16_t to double float IEEE754?

Here's a code fragment for converting a uint16_t. Expand this to work with your array of ints from the library.
Remember that on Arduino, - Uno and Mega, at least - doubles are implemented as floats. You won't get the precision you might be expecting.

double xAsDouble;    // ** only float precision despite 'double' declaration
uint16_t xAsInt;

xDouble = xInt;      // the compiler knows how to make this conversion.

Update: After re-reading your question, I realize you're using an ESP8266. My comments about Uno's float precision may not apply.

Update 2: After some discussion, I've learned that the Modbus return is not 4 integers, but a double being passed as 4 words, which need to be reassembled to recreate the original double. The solution will depend on the order in which the words comprising the original double are sent.

Update 3: I suggested the OP try using this general scheme:

// A union lets you look at memory as either (in this case) 4 ints or 1 double
union {
   uint16_t data_out[4];
   double x;
} buffer;

// Assign the data from modbus using the 'int' way of viewing menmory.
// Note I might have the ordering wrong but this is the idea:
buffer.data_out[i] = data_in[i];

Then reading 'buffer.x' would get the 4 words of memory as a double.

... After trying both orderings, the OP reports he is obtaining the expected result,


Can I make the Arduino ignore serial print

If you insist on top performance, the best thing would be to use a macro for that:

#define Sprintln(a) (Serial.println(a))

Then instead of

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

write

Sprintln(F("Hello world!"));

etc. To deactivate the Serial printing, define the macro empty:

#define Sprintln(a)

This will have the preprocessor remove all debugging code defined with Sprintln from your code.

(Of course, there's a huge number of variations on this theme.)


how to change increase pwm frequency by changing resolution?

Here's code for timer 1 on a atmega32u tested in a Teensy 2.0:

void setup() {
  // put your setup code here, to run once:

   // Timer 1 Fast PWM mode *toggling* OC1A at 50kHz with *two* OCR1A counts
   // And 7.32 bits 0-159 PWM on OC1B at 100kHz
   // Output on OC1B
   // Set at TOP, Clear at OCR1B
   // WGM =15 0b1111

   DDRB |= bit(DDB5) | bit(DDB6);  // atmega32u OC1A and OC1B outputs
  // DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)

   TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                          // or 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;           // 10/160 duty cycle
   TCNT1 = 0 ;
}

void loop() {
  // put your main code here, to run repeatedly:
  OCR1B = 160/4 -1 ; // 25% duty cycle.
}

The trick here is using OCRxA to set the TOP value/resolution/frequency of the timer, and then using OCRxB as the PWM-controlled output.  The popular examples aim for a specific frequency with toggling, but often don't go into showing the PWM with the non-TOP OCRxx registers.

If you check the registers for your chip, this should also adapt to the other timers.  Here, I used timer1 to avoid confusing delay() and millis().


Getting "Undefined reference to vtable for {classname}

I don't have the header file for DualMotorRomeo, but the linker is saying that a destructor has been declared (~DualMotorRomeo()) in the class header, but no destructor has been defined. If you didn't write DualMotorRomeo then the library needs to be updated.

Until then, simply add the following to one of your source files:

DualMotorRomeo::~DualMotorRomeo() {
} // DualMotorRomeo::~DualMotorRomeo()

That will also fix the vtable linker errors - the vtable will be included in the compiled file with this declared in it.


Change from using the external crystal to the internal oscillator

What do I need to change to use the internal oscillator?

You'll need to change the fuses on the chip, and you probably want a new 8MHz entry in boards.txt so that timing functions still work as expected.

  Can I leave the external [resonator] in place or do I have to remove it?
  If I do leave the external [resonator] in place and set the fuses to use the internal oscillator, will the [resonator] continue to resonate or does it get powered down somehow?
  (I wish to know this for EMC reasons)

From the datasheet:

  If the Internal Calibrated RC Oscillator is used as chip clock source, PB7...6 is used as TOSC2...1 input for the Asynchronous Timer/Counter2 if the AS2 bit in ASSR is set.

Also:

  When AS2 is set, pins TOSC1 and TOSC2 are disconnected from Port B. A crystal can then be connected between the TOSC1 and TOSC2 pins to serve as an
  independent clock source for Timer/Counter2. The Oscillator is optimized for use with a 32.768kHz crystal.

Therefore if AS2 is not set, the two pins act as normal GPIOs and the resonator is disabled.


Can someone help me with my arduino and relay and switch?

Maybe it's not the only problem, but at least:

int val = ...

and

if (val == "FLUSH")

do not match.

I assume you mean a digit here (0 or 9 to flush)?

Also, you should put your circuit in your question. A reason because of the 'flipping' is that your switch is not pulled down, and it results in undefined behavior.

Another thing you could add is debouncing, when a switch is clicked, it results in multiple 0/1 and 1/0 transitions (although your delay might help too).


Yes, it should work provided that your desired target image is stored in the same form, with correct metadata, and that it is small enough to fit in the programmer device.

The storage format of the payload-to-program could be made more optimal by a factor of almost two; however, for the original purpose of injecting compact Arduino-style bootloaders that is scarcely needed, and would have made preparing payloads more complicated.


Arduino ethernet need help with game logic!

The line

if(millis() - lastTime > 400)

is supposed to test that the button press does not come right after the
LED switches. This means the line

lastTime = millis();

should be right when you change the displayed LED.


Solved it, but here is the solution, so there is an answer available for anyone who might encounter the same problem...

Quality check your protoboards.  This is making me feel stupid.  The protoboard I used had a faulty connection on the blue line I was using, causing an inevitable floating input.  So relieved I found the problem, and yet so annoyed!

Take care you all.


Note, this is not an answer, but I want to show some code examples based on the comment:

You can use as said in the comment:

Remove '== true' in a boolean condition
Replace '== false' by '!' in a boolean condition

You will get this:

  // check if button state has changed
  if (newButtonState != oldButtonState) {
    // if button was pushed
    if (newButtonState == HIGH) {
      // check led state
      if (!ledState) {
        ledState = true;
        blinkState = true;
      } else {
        ledState = false;
        blinkState = false;
      }
      if (ledState && blinkState) {
        newTime = millis();
        if (newTime - oldTime >= 250) {
          state = !state;
          oldTime = newTime;
        }
        digitalWrite(redLed, state);
      }
    }
  }
  oldButtonState = newButtonState;
}

About the following fragment:

  if (!ledState) {
    ledState = true;
    blinkState = true;
  } else {
    ledState = false;
    blinkState = false;
  }

Since you write ledState and blinkState in both clauses, and the condition is simple (so you don't need to put it in a temporary variable, you can replace this fragment by:

blinkState = !ledState;
ledState = !ledState;

Note you have to reverse the order as blinkState depends on ledState.


Arduino IDE: How to get PROGMEM const length?

Probably the best way would be to define below it

const int eye_len = sizeof(eye)/sizeof(eye[0]);

If the linker does link time optimization, or if you only use it within the same file (and declare it static), it shouldn’t cost any memory, otherwise it will take up two bytes of ram.


You have 4 pins.

Vcc: +5V supply voltage (it stands for Collector Voltage)
GND: Ground.
Trig: Causes an ultrasound pulse to be generated (it stands for Trigger)
Echo: Tells you when an echo has been received.

You can see how to wire and use it here: http://www.instructables.com/id/Easy-ultrasonic-4-pin-sensor-monitoring-hc-sr04/


Rename device name (ch340 usb to serial) Mac OS

I am Antonis from codebender and we recently released drivers for the Mac.

If you want to overcome this problem, without disabling your computer's security settings, maybe I can help you with this! Codebender just released their Mac drivers package, which includes a new driver that supports the CH340G chip, on Yosemite and all other versions of OS X for Mac.

This will help you to install these drivers securely, and
all you have to do is to download and install them.

You can find more information about the drivers in the codebender blog.


Can external power supply above current limit lead to errors/shutdown arduino?

If the incoming voltage drops below 6.6V the MOSFET will activate for the USB power and that will become available. But it's not perfect.

The MOSFET is always "partially" active - that is, the "body diode" is always available, so if the 5V rail drops below the USB voltage minus the forward voltage of that body diode the USB power will take over regardless of what else is happening. That 5V rail then feeds the 3.3V regulator, and
since the ARM chip on the Due is a 3.3V chip, even a dip of a volt or so on the 5V rail should have no effect on the MCU.

So theoretically the chip should keep running fine all the time regardless of what happens with the power.

  Is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?

Not really, no.  You can remove the 12V from the jack though and just power from USB. Connect the 12V to your motor drivers, and link its ground to the Arduino ground. The motors will use the 12V supply, and the Arduino the 5V supply.

  Also, how much current can I safely drive through the VIN Pin?

The diode inline with the barrel jack is rated at a maximum sustained current of 1A. Any more than that and you risk blowing that diode.


you can't cast it. payload is an array of received bytes and length is the size of received data in that array. if the bytes are characters and you would know that there is one more position allocated in that array, you could put a 0 to payload[length] and by cast to char* it would become a zero terminated string. but you can't know if there is that one byte allocated, so you must copy the payload to your buffer of chars and set a zero at the end.


Arduino interrupt not called using PinChangeInterrupt

The attachInterrupt function is only for normal interrupts. Read the reference: attachInterrupt

When you need the Pin Change Interrupts, there is a library for that: EnableInterrupt

Try to keep the interrupt routine as short as possible. Do not use the Serial functions in calc_distance because the Serial functions themself use also interrupts.

The Arduino Mega does not have 'double' floating point variables, the compiler changes it into 32-bit 'float' variables. You are reading the interrupt pin for a test ? I don't understand why you do that. Please make "distance" a volatile variable. In the loop function, the interrupts should be turned off when reading "distance". Because "distance" is a 4 bytes 'float' variable and the Arduino Mega is a 8-bits microcontroller. An interrupt could occur when the "distance" is only read for a part from memory.


ATMega328P not running sketch in standalone (works in Uno R3 Board though)

I found the solution by accident.

While I used my multimeter to measure the voltages between GND and the Pins (for the last fact), I noticed the program running at weird speeds. I. e. the LED started blinking.

What did I measure?

Actually I was just measuring one of the crystal pins (Pin 9 or 10). The sketch went running for a few seconds and very different speeds and then stopped.

This small change in voltage gave the ATMega the clock signal it needs to step through the program.

Maybe I need less capacitance of the two capacitors as mentioned in the comments. I will update the answer with more information later on.

The perfect solution

As pointed out in the comments, I really chose the wrong capacitors. It worked without, but we want the stability so use a bright light and a magnifying glass if you are unsure. Really, do it.


FlySky TH9X with Arduino: cant get pulseIn() function to return sensible values for any channel

I would not recommend using pulseIn for reading values from the receiver.  pulseIn blocks the program until a signal is received, which is almost always undesirable.

An alternative approach would be to use CHANGE interrupts.  You get an interrupt when the signal goes high and low.  You take note of the time that each change occurs with millis and compare the times to get the duration of the signal.

Here's an example - you can add more channels if you'd like.  Note, this is using the EnableInterrupt library.

#include <EnableInterrupt.h>

#define SERIAL_PORT_SPEED 57600
#define RC_NUM_CHANNELS  2

#define RC_CH1  0
#define RC_CH2  1
#define RC_CH1_INPUT  A0
#define RC_CH2_INPUT  A1

uint32_t last_update_time = 0;
uint16_t rc_values[RC_NUM_CHANNELS];
uint32_t rc_start[RC_NUM_CHANNELS];
volatile uint16_t rc_shared[RC_NUM_CHANNELS];

void rc_read_values() {
  // read the values out of the shared, volatile array (which can change at any time)
  // and into an array that we only will only change when we call this function

  noInterrupts();
  memcpy(rc_values, (const void *)rc_shared, sizeof(rc_shared));
  interrupts();
}

void calc_input(uint8_t channel, uint8_t input_pin) {
  // This is the interrupt.  If the pin is high, we record the start
  // time of the pulse.  If the pin is low, we compare the start time
  // to the current time in order to get the length of the pulse.

  if (digitalRead(input_pin) == HIGH) {
    rc_start[channel] = micros();
  } else {
    uint16_t rc_compare = (uint16_t)(micros() - rc_start[channel]);
    rc_shared[channel] = rc_compare;
  }
}

void calc_ch1() { calc_input(RC_CH1, RC_CH1_INPUT); }
void calc_ch2() { calc_input(RC_CH2, RC_CH2_INPUT); }

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

  pinMode(RC_CH1_INPUT, INPUT);
  pinMode(RC_CH2_INPUT, INPUT);

  // set up CHANGE interrupts, so that we get notified when
  // each signal goes high or low.
  enableInterrupt(RC_CH1_INPUT, calc_ch1, CHANGE);
  enableInterrupt(RC_CH2_INPUT, calc_ch2, CHANGE);
}

void loop() {
  rc_read_values();

  Serial.print("CH1:"); Serial.println(rc_values[RC_CH1]);
  Serial.print("CH2:"); Serial.println(rc_values[RC_CH2]);

  delay(200);  // just so serial log doesn't flood
}

For a more detailed explanation, take a look here:  http://rcarduino.blogspot.com/2012/01/how-to-read-rc-receiver-with.html


Portable power for an UNO with a nrf24l01+ attached?

I've used the usb battery chargers (marketed to recharge cell phones) with great success on many different Arduino boards. They come in a variety of mAH capacities and are easily recharged with any powered USB port/power adapter.

Here's a link to one I've used. (I'm not affiliated with Duracell in any way).

http://ww2.duracell.com/en-US/product/instant-usb-charger.jspx


Arduino Serial Communication Between 2 Uno

Your slave is sending an array of characters and your master is reading the ASCII values of those characters.

If you send 25.43, Serial.println will send 7 characters 2, 5, ., 4, 3, carriage return and a newline.

The master will read them as 50, 53, 46, 52, 51, 13 and 10. Your code then prints:

50.00
53.00
46.00
52.00
51.00
13.00
10.00

On your master, the loop() should look like:

void loop() {
  if (Serial.available()) {
    char c = Serial.peek(); // just look at the next character on the serial buffer
    if (c == '\r' || c == '\n') // ignore the carriage return and newline characters
      Serial.read(); // remove the character from serial buffer by reading it
    else {
      tempC = Serial.parseFloat(); // read and parse the string representing the float value
      Serial.println(tempC);
    }
  }
}


How to pass non-static class member to callback?

Yes, a callback can be a member function. The error in your std::bind call is that while you do bind the first hidden this paramater to an object instance, in this case this object, you must also use placeholders for all your other function parameters.

Since you declared

void incomingEventHandler(WStype_t type, uint8_t *payload, size_t length)

You must bind as

webSocket.onEvent(std::bind(&MyClass::incomingEventHandler, this,  std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

Note that this webSocket.onEvent call only works if you are on a non-AVR platform, because the library defines

void WebSocketsClient::onEvent(WebSocketClientEvent cbEvent) {
    _cbEvent = cbEvent;
}

with

#ifdef __AVR__
        typedef void (*WebSocketClientEvent)(WStype_t type, uint8_t * payload, size_t length);
#else
        typedef std::function<void (WStype_t type, uint8_t * payload, size_t length)> WebSocketClientEvent;
#endif

i.e., it is a raw function pointer in __AVR__ but a std::function on non-AVR platforms -- std::bind will give you a std::function. Since you're on an ESP8266, this should work fine.

Refer to https://en.cppreference.com/w/cpp/utility/functional/bind (and maybe my old question)


High precision timing on Arduino for serial communication

Use a timer and ISR (interrupt service routine) to make timing more accurate.

Take a look at my 1ms timed interrupt Proof of Concept. The idea is to have a reasonably accurate 1ms 'heartbeat' in the system that can be used to trigger other events. In the PoC it is used to blink an LED at ½Hz, but having access to the new variables millisecondCounter and secondCounter enables you to trigger events in the main loop at arbitrary (but accurately timed) moments.


The wording on this particular eBay item is pretty poor but there are plenty of similar products with better descriptions that are photographically identical... example that make a little bit more sense.

Anyway, I don't think this gives an analog value output, the LM393 is a comparator, so I think the blue dial sets the 'threshold level' and any sounds over that level cause a logic low. i.e. it compares the audio level and the dial and when one exceeds the other it gives a signal.

The features also say "The output effective signal is low level" which is probably Chinglish for the signal is a logic low, i.e. when the sound is heard it goes to 0V rather than 5V which is what I think you were expecting.

In summary: This device is is more like a Clapper, it detects a loud noise and sends a digital low signal.

Try making a loud noise with the same setup you already have, and if not try adjusting the potentiometer by turning it, but not too far! It probably only turns 180-270º.


Why the two string is equal?

        uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)str.c_str();

Both p1 and p2 point to the same string so of course they will always compare equal.

Do you mean:

if (str == card)
   // do something


The solution is called a pull down resistor and it's exactly the same as when you are using a button - the button is what connects the pin to +5V. The pull down resistor (usually around 10kΩ) connected to ground is what makes the pin read LOW at other times.


Why does Adafruit guide for motors use transistors on ground rather than modulating the power source

Your schematic
The blue line in your first schematic "going up" that you marked GND, is not really GND but one of the motor connections. If you look at the Adafruit schematic you can see this.
The motor in the Adafruit schematic in the link you provided is connected between 5V and the diode's Anode (and the transistor's collector).
Flyback diode
The diode is a so-called "flyback diode", connected between the motor connections to "soak up" back-EMF that occurs when the motor is turned off and its magnetic field collapses. If the diode would not be there, there would be a voltage spike on the transistor's collector, possibly damaging it.
Low-side switching
The "Adafruit" solution uses an NPN transistor as a switch on the low side of the motor when the I/O pin is high, like the schematic on the right. This is a very common setup as it has almost no disadvantages.
High-side switching
Your own suggestion (called high-side switching, shown on the right) would work as well (with the addition of a flyback diode) but it would need a different type of transistor, a PNP transistor. Also, the I/O inputs would work in an inverted way: when the I/O pin is low, the motor will be on and when the I/O pin is high, it will be off.
Note that high-side switching will only work when the supply voltage is lower or equal to the voltage that's on the I/O pins. You can't turn on a 12V motor this way, for example. With low side switching, you will not have this problem and you can switch higher voltages.

simulate this circuit – Schematic created using CircuitLab


Arduino Libraries: Declaring variables as public?

Classes are used to hide away the complexity of a certain task. The user of the class should not worry about how the library exactly works in the inside, but instead only worry about how it should be used. In many cases directly writing to a member variable can be not only convenient, but hurtful if a wrong value is set. If you instead use a function to set the variable, the author can add code to prevent wrong values from actually being written to the variable. Also there might be some other logic involved, that is not triggered, if you write directly to the variable. So - for the ease of use - the users might want the library to be responsible for this, not themselves.

If you write a library, you have thought about how it should be used. Hiding other ways away is a common way of leading the user through the usage. Ways of usage, that don't go along with the purpose of the library can be hided away to make the correct way clearer. A manufacturer of a saw doesn't give the user instructions how to use the wrong side of the blade, because it doesn't help you with sawing.

This does not mean, that you shouldn't make variables public at all, but only if it makes sense. For example: If you are defining a class, that just represents a point in a coordinate system without hooks to other code, it is totally OK to make the coordinates public. But if you defined the class, so that the point is directly shown on a display, you might want to change the position on the display, whenever one of the coordinates is changed. In this case you can use a set-function to trigger the display update, when a new value was given for the variable.


Simplify if then else statements for Neopixel/compass project

You don't use the correct syntax. I assume you mean:

// NeoPixel Display
if ((counter >=3) && (counter <=9))
{
  strip.setPixelColor(0, 255, 0, 0); //set pixel number 1 and set color to red
  strip.show(); //send color to pixel 1 on NeoPixel Ring
}
else
{
  strip.setPixelColor(0, 0, 0, 0)
  strip.show();
}

And similar for the other colors.

First you see there are a lot of occurences of calls to setPixelColor and show. We make a function of this, where the color and the red value is parameterized:

void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
}

Now we can write your code as

// NeoPixel Display
if ((counter >=3) && (counter <=9))
{
  setPixel(0, 255);
}
else
{
  setPixel(0, 0);
}

void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
  strip.show();
}

And similar for the other colors.

Now we get rid of the if statements. For the first color this will become:

// NeoPixel Display
setPixel(0, ((counter >= 3) && (counter <= 9)) ? 255 : 0);

Combined with the other colors we get

// NeoPixel Display
setPixel(0, ((counter >=  3) && (counter <=  9)) ? 255 : 0);
setPixel(1, ((counter >= 10) && (counter <= 15)) ? 255 : 0);
setPixel(2, ((counter >= 16) && (counter <= 21)) ? 255 : 0);

void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
  strip.show();
}

However, the conditions can be simplified by adding them into the function. So we get

// NeoPixel Display
setPixel(0, counter,  3,  9);
setPixel(1, counter, 10, 15);
setPixel(2, counter, 16, 21);

void setPixel(int pixelNumber, int counter, int lowValue, int highValue)
{
  strip.setPixelColor(pixelNumber,
     ((counter >= lowValue) && (counter <= highValue)) ? 255 : 0,
     0, 0);
  strip.show();
}

If you need to have more checks if a value is in range you can make it a specific function. This will increase the code, but makes it easier to reuse code. So you will get:

// NeoPixel Display
setPixel(0, counter,  3,  9);
setPixel(1, counter, 10, 15);
setPixel(2, counter, 16, 21);

void setPixel(int pixelNumber, int counter, int lowValue, int highValue)
{
  strip.setPixelColor(pixelNumber,
    inRange(counter, lowValue, highValue) ? 255 : 0,
     0, 0);
  strip.show();
}

int inRange(int counter, int lowValue, int highValue)
{
   return ((counter >= lowValue) && (counter <= highValue));
}


I take this to mean that you do not want to have to ask the user of the code to configure a boolean flag.
The ESP8266 Arduino package provides -DARDUINO_ARCH_ESP8266 -DESP8266
command-line options these while calling g++.  These effectively #define feature test macros as though they were at the beginning of the source code.
For ESP32 it does likewise with -DARDUINO_ARCH_ESP32 -DESP32
You could perform tests in your code such as:
#if defined (ARDUINO_ARCH_ESP8266)
// do one thing
#elif defined(ESP32)
// do another
#else
#error Architecture unrecognized by this code.
#endif

There are likely also macros like these that are predefined by the xtensa g++ compiler.


Using SPI and 2 shift registers WITHOUT libraries

My strategy: Write the sketch using the standard Arduino library. The goal is have the LED lit up, as you need.

Then, change all standard function calls in your sketch (like digitalWrite) with your own (called it digitalWrite2).

Now implement digitalWrite2 using register manipulation.

Pros:

Divide and conquer. You know have two independent smaller problems (LED and registers).
When is time to implement digitalWrite2 you can learn from your classmate how to do that. I bet that they will start with the hard part (register manipulation).
It makes for a easier debuging. You can compare your own implementation against the standard implementation just by deleting/adding a single "2" in the call.

Of course, taking a look at the Arduino source code will made things trivial :-)
Is that cheating? No, we learn from others, we learn reading other people's code.

Edit: Step by Step Example

Let use Blink to show how to do it:

Original

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

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

For the new version I will replace pinMode and digitalWrite for the my own  implementation them. How?

Go to the directory where you put your Arduino binaries, which include the source code. There is a subdirectory with the sources (mine is ~/bin/arduino-1.8.3/hardware/arduino/avr/cores/arduino).

There is a file (wiring_digital.c) where I found the source code for pinMode and digitalWrite. Without any shame, I copy-paste and rename.

Note: the original includes a call to turnOffPWM, which I simply comment out, because we will not use it here and I want to cut it short.

That's all.

New version

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

void loop() {
  digitalWrite2(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite2(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

void pinMode2(uint8_t pin, uint8_t mode)
{
  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *reg, *out;

  if (port == NOT_A_PIN) return;

  // JWS: can I let the optimizer do this?
  reg = portModeRegister(port);
  out = portOutputRegister(port);

  if (mode == INPUT) {
    uint8_t oldSREG = SREG;
                cli();
    *reg &= ~bit;
    *out &= ~bit;
    SREG = oldSREG;
  } else if (mode == INPUT_PULLUP) {
    uint8_t oldSREG = SREG;
                cli();
    *reg &= ~bit;
    *out |= bit;
    SREG = oldSREG;
  } else {
    uint8_t oldSREG = SREG;
                cli();
    *reg |= bit;
    SREG = oldSREG;
  }
}

void digitalWrite2(uint8_t pin, uint8_t val)
{
  uint8_t timer = digitalPinToTimer(pin);
  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *out;

  if (port == NOT_A_PIN) return;

  // If the pin that support PWM output, we need to turn it off
  // before doing a digital write.
  // if (timer != NOT_ON_TIMER) turnOffPWM(timer); By Look Alterno

  out = portOutputRegister(port);

  uint8_t oldSREG = SREG;
  cli();

  if (val == LOW) {
    *out &= ~bit;
  } else {
    *out |= bit;
  }

  SREG = oldSREG;
}


Powering Arduino and transistors with one power supply > 12V

The voltage regulator (on the Vin pin) is supposed to be provided with 12V at max, since it is not cooled (it is a linear regulator, that dissipates the excess voltage as heat). If you have significantly more, you should at best buy a little switching regulator, to directly get a regulated 5V to feed to the 5V pin of the Arduino (that's what I suggest). Be sure to use a regulator, that can provide the needed current (which also depends on what else you provide over the Arduino).

If you really don't want to use an extra regulator and you don't have much more than 12V (maybe like 15V), you might get away by cooling the voltage regulator on the Arduino. The voltage regulator on a genuine Arduino will go into emergency shutdown, if it overheats, but it will not be damaged easily. Here you could try a bit. But be careful to not stress it too much. The clones from china often have different/cheaper regulators, that will mostly be fried if you overheat them. But they are very cheap.


What's the best way to operate a remote control circuit board?

All the right sides of the buttons are connected to the negative of the battery (that is ground). So you connect the remotes GND to the Arduinos GND.
Next solder five wires to the left side of the buttons. You can do this by scraping away a bit of the green solder mask that's on top of the trace going to that button pad. Or find out which pin on the IC goes to the button, and solder a wire to that leg.
I wouldn't mess with the black stuff (graphite?) on top of button pad. That way you can always return the remote to it's original function.
Then connect those wires to the Collectors of NPN transistors. The Emitters all connect to GND. The Bases (via a resistor) to the Arduino pins.
Alternatively, you can connect them directly to the Arduino pins. But you'd have to be careful to never set the pin to HIGH, as the remote won't like 5V on it's input pins while it is itself running on only 3V. You "press" the button by setting the pin to OUTPUT. After a "press" you set it back to input.
To prevent accidentally supplying 5V to the button pin, you can also use diodes (instead of transistors described above). Put the diode between the Arduino pin, and the button wire, pointing towards the Arduino. That way current can only go towards the Arduino. Then you can safely use digitalWrite.


PubSubClient: Subscription working, but callback never called

nknolleary, the owner of the library, correctly identified the problem:
You need to call mqttClient.loop() in you main loop. Without that, you are never giving the client a chance to check for any incoming messages.


Arduino to breadboard with LM35 temp sensor

Check the baud rate of your serial monitor matches what you have set in your setup() function.  In the above code that is 9600.  If the baud rate is incorrect you typically get rubbish output in the serial monitor.

You may also want to change the Serial.print(tempC) to

Serial.println(tempC,2);

To get some decimal places.

As for the circuit ~

You don't need ARef connected.
The LM35 VCC should be connected to Arduino 5V
The LM35 GND to Arduino Gnd (any of them)
Finally LM35 signal (Vout) to Arduino A0.


WS2812B strip stopped responding to control

Did you follow the Adafruit NeoPixels best practices guide?

You may have zapped the first NeoPixel in the group. You should be able to, fairly easily, bypass that. Each NeoPixel has to "reshape" the data for the next one along, so if you damage the first one, no data will reach the others.

I strongly suggest you follow the guidelines in the link, including the capacitor and resistor.


Help putting an Arduino project on the Internet

What would be the most efficient, easy to use and reliable system?

What seems to me is that you need what is called Unified Application Routing. There are various technologies to do that but what I suggest is WAMP  (Web Applicaton messaging protocol, do not get confused with wamp server stack) but you can check this comparison table and select the one that most helps you. Based on that what I suggest is crossbar.io. Is open source with a lot of examples, runs on small devices (raspberry pi for example) and is intended for the use you propose, connect devices and let users/apps to get/give information from them. You can publish/subcribe to topics and all devices or apps connected with that topic can read it. Imagine something like an arduino is reading temperatures from a room and publish that data to topic "Temp1". All devices(other arduino, servers, esp8266)  or apps(websites, programs, what ever you clients you imagine) that also are connected at that moment to topic "Temp1" will get that update and act like you want. Wamp also provides a nice feature that is called RPC (remote procedure call). Imagine that you want some real nasty thing in your arduino but it lacks memory or is too slow for that. You can create a program that is, lets say in a raspberry, just waiting for that calculation and returns the result to arduino.

Take a look at this video as an example of what you can do with this ttype of techonologies. A lot of demos also in crossbar.io page. The beauty is that you can program in almost any language you are familiar with. They rely on websockets for the majority of things but crossbar is not restricted to it only, you can even use raw sockets.

As for the second part.

If you create your on server (crossbar lets say) inside the lan you have to forward the port he is listening in your router so other outside your network can access it( and possibly will need to get some kind of Dynamic DNS service if your internet provider do not have statics IPs). Or you can host your server outside your network (crossbar has a tutorial for Amazon EC2 and for Microsoft Azure I think). You only need to port forward server ports.
Hwo do you connect arduino? Use ethernet shields, esp8266, choose a yun or make a combo like arduino with usb + raspberry. That way you can also use your raspberry as a crossbar server.

Here is an example of my home made crossbar.io server using 2 python programs , 1 rboard and a raspberry pi has a host to manage my home heating system and the webpage is being accessed from internet, not local lan.


How to read CPU temperature into Arduino?

Here is a simple way to send CPU temperature reading data via serial port, under Windows.

As answered in the question Batch-file get CPU temperature in °C and set as variable, it is possible to build batch file (*.BAT) to get the readings and output to console. I took following option and built the BAT file.

wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature

Now, to redirect the console to serial port, use > symbol. Try following and receive it in your Arduino or use serial port monitor to check (in my case it works):

mybatfile.bat > COM1

Alternatively, you can use

wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature > COM1

inside your BAT file.

Next, we have to specify the serial configuration, make it EXE file so it can run under Administrative account. I used Advanced BAT to EXE converter. In the tool, specify the commands:

@echo off
mode COM1 BAUD=38400 PARITY=n DATA=8
wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature > COM1

Convert it to EXE using File->Build EXE...

And finally, you can create Scheduled Task to run your newly built EXE application periodically.

BTW, WMI is a powerful interface, it is possible to retrieve many other metrics and configuration data.


Is it possible to use Pi's output signal as Arduino's input signal?

This way is fine: the Pi is a 3.3V based board, so connecting one of the GPIO pin from the pi to an Arduino will not damage it. Furthermore, the 3.3V are sufficient to be considered as HIGH even on a 5v Arduino like the UNO.

The other way around: connecting the output of a 5V Arduino to the input of a pi, will very likely damage the raspberry Pi!

So beware of your Pinmode before doing such a connection!


Sorry for the Late reply, I had the same issue.
You cant have anything connected to pin 15 or 2 during flash


How to store values inside an empty array and get the average integer? [UPDATED QUESTION]

The error message is correct. You did not define the size of the array.
You have 3 choices:

Declare it with a constant length

int foo[10];
Declare it and initalize it

int foo[] = {0,1,2,3,4,5,6,7,8,9};
Declare it dynamic as pointer and alloc or realloc the mem by yourself (this is not recommended (realloc) because of possible heap memory fragmentation)

int foo;
int size = 10;
foo = (int)malloc(size * sizeof(int));
free(foo);

As reference:
http://www.arduino.cc/en/pmwiki.php?n=Reference/Array


How to use an PCF8574P with the simplest code possible

Have you given Rob Tillaart's library from the Arduino Playground a try? The demo sketch might look a bit overwhelming, but at it's simplest, all your sketch should need to have to make a led blink like the standard arduino 'blink' sketch is

#include "PCF8574.h"
#include <Wire.h>

// adjust addresses if needed
PCF8574 PCF_38(0x38);  // add led to P0 (pin 4) (used as output)

void setup()
{
//your setup code here
}

void loop()
{
    //turn P0 (pin 4) of the I/O expander on and off once a second
    PCF_38.write(0, 1);
    delay(1000);
    PCF_38.write(0, 0);
    delay(1000);
}

I don't have any of these parts handy so I can only give generic advice.


It looks like Sparkfun probably only put the bootloader on the board. The tutorial is written in a way that suggests the need to flash the board.

Also the board does not imediatly work with the 12V inverter. If you have the battery you should attach it and see the PWR LED turn on.

The inverter only provides voltage to the EL wire and not the Microcontroller, power to the microcontroller is provided by way of a regulator(U2), not the LM317 the last quote from the one comment shows how you can connect to the 12V inverter.

What you should do instead of having to go the route of all the wiring is to connect both the battery to BATT IN and the inverter, but ensuring that the microcontroller is programmed before hand.

  Arduino Code

  Once you have all of your hardware hooked up properly, it’s time to
  program your Sequencer to run the EL Wire display as you want. You
  will need to download the Arduino code in order to follow along with
  the example.

  You can also download the most up-to-date code from the EL Sequencer
  GitHub repository.

  We will be working with the “SparkFun_EL_Example.ino” example. If you
  need a review on how to upload Arduino code to your board or using the
  Arduino IDE, please check our tutorial here. Also, if you are unsure
  about installing the FTDI drivers, please check out this tutorial.

Also from one of the Tech support notes:

  Using 12V to Power Both the EL Inverter & Microcontroller

  If you are using a 12V wall adapter to power the 12V Inverter, you
  would still need to provide power to the microcontroller side. One
  solution with your 12V wall adapter to provide power to the 12V
  inverter and Atmega328P is to get a barrel jack adapter to 2 pin JST
  adapter [ https://www.sparkfun.com/products/8734 ], thus connecting
  the 12V wall adapter to the “BATT IN.” This is assuming that your wall
  adapter is using a center positive barrel jack.

  From there you can connect the 2 pin JST labeled “DC Out” to the 12V
  inverter’s input voltage. To connect, I recommend using the male DC
  barrel jack adapter [ https://www.sparkfun.com/products/10287 ] and a
  2pin JSt jumper wire [ https://www.sparkfun.com/products/8670 or
  https://www.sparkfun.com/products/8671 ]. You will need to wire strip
  the cable to be able to connect it to the screw terminals.

  Lastly, you would need to add a solder jumper to SJ1 so that you
  bypass the voltage regulator between your external power (“BATT IN”)
  to provide power to the inverter’s “DC OUT”. This will provide power
  to your 12V inverter’s input.

Warning: if SJ1 is closed, inverter will see 5V with FTDI plugged in and switch at USB