RGBW LED strip: which components are required?

NeoPixels

The strips based on the WS2812 / SK6812 and similar chips, known by some as NeoPixels, are clever ways of implementing fully-addressable 24-bit colour LEDs.

One of the clever things is that they only require one data wire, plus power and Gnd, i.e.

+5V
Data
Gnd

The pixel information is sent by precisely timed sequences of 24 bits per pixel. The first pixel "peels off" these 24 bits (ie. 3 x red / green / blue) and then passes the rest on to the next pixel, and so on.

Libraries

Various people have written libraries to do this for you including:

Adafruit library
NeoPixels Revealed: How to (not need to) generate precisely timed signals
My own library which uses SPI

Power

Each pixel draws around 60 mA at maximum brightness (showing white) so you need to allow for a heavy-duty power supply. Particularly if you have 5m of 144 pixels/m then that is 720 pixels, which would require 43.2 amps!

According to Adafruit:

  To estimate power supply needs, multiply the number of pixels by 20, then divide the result by 1,000 for the “rule of thumb” power supply rating in Amps.

Even that means you need 14.4 amps for your 720 pixels!

So bear that in mind when sizing your power supply.

Addressing methods

The Adafruit library (as far as I can tell) holds the pixel information in RAM, and then "dumps" it to the NeoPixels in one operation. This lets you do fancy things in memory, and copy the results to the pixels. However that means you need enough RAM for all this. At 3 bytes per pixel (24 bits), if you have 720 pixels, that will be 2160 bytes, which is more RAM than the smaller processors (like the Uno) have.

Larger processors (like the Mega) have more RAM.

An alternative method, as explained here does not keep the data in RAM, but generates the colours "procedurally" on-the-fly. This is much less RAM-intensive, but perhaps less flexible. On that page he links to a YouTube video which shows a humble Arduino Duemilanove (similar to a Uno) driving over 1000 pixels!

Procedural generation however can do quite a lot, for example you can set the entire string to a single colour, change that rapidly, or make a rainbow effect by increasing (say) the red value for each successive pixel. You can also make "chaser" effects quite simply.

The library I wrote is also designed to allow you to use minimal RAM. You could conceivably add in your own storage scheme, perhaps only storing one byte per pixel, with less bits per colour (eg. 2 bits each for red, green, blue) and that would reduce RAM requirements by a third.

Cabling run

You could try sending the data over 2m. I warn you that the timing for a zero-bit is that it has to go HIGH and then LOW within about 400 ns, so you can't afford to have the data signal degrade too much.

When I had a similar string of coloured LEDs set up at Xmas time (not NeoPixels however) I had a long run of a 5V power supply (just using a pair of figure-8 wire), and situated the processor quite close to the pixels. This is probably the safest way of doing it.


Arduino Pro Mini RESET button suddenly stopped working

What do you do? You replace the chip on the board.

By pumping 6.5V through the RESET pin with no power attached you have irrevocably broken the reset pin inside the chip. Way too much current will have flowed through the internals of the pin leaking its way up to the VCC pin and then back down through the rest of the chip to ground, burning out vital parts of the internal logic of the pin.

It's dead, Jim.

Your "fix" basically relies on the fact that the bootloader runs for any kind of reset - be that a RESET pin reset or a POR (Power-On Reset).


Formatting variables from a variadic function

With the format "ci", the argument is interpreted as an integer, and
the output is correct: 49 is the ASCII code of '1'.

With the format "cc", the argument is interpreted as a string (pointer to an
array of chars), which is incorrect.

One (bad) solution is to use the "cc" format and pass &btnPressed as
an argument. The problem with this approach is that the byte in memory
right after btnPressed may not be a zero, and the format expects a
NUL-terminated string.

A better approach would be to have one format for a char and a
different one for a string. I suggest "c" and "s" respectively. But
then you should be aware that there are special promotion rules
associated with variadic functions. When playing with your code, the
compiler reminded me of this one:

  warning: ‘char’ is promoted to ‘int’ when passed
  through ‘...’

So the function should expect an int, and cast it to char in order
to call the correct overload of Serial.print():

void printConcatLine(const char* mask, ...) {
    va_list params;
    va_start(params, mask);

    while(*mask != '\0') {
      if (*mask == 'i') {
          Serial.print(va_arg(params, int));
      } else if(*mask == 's') {
          Serial.print(va_arg(params, const char *));
      } else if(*mask == 'c') {
          Serial.print((char) va_arg(params, int));
      } else if (*mask == 'f' || *mask == 'd') {
          Serial.print(va_arg(params, double));
      }
      ++mask;
    }

    va_end(params);
    Serial.println();
}

Used like this:

printConcatLine("sc", "BtnPressed: ", btnPressed);
// Output: "BtnPressed: 1"


/* SPI kesmesi olduğunda çalışacak fonksiyon */
ISR(SPI_STC_vect)
{
  cli();
 ...
      Serial.print("Aci Degeri Slave= ");
      Serial.println(gelenVeri);

Don't do serial prints inside an ISR.


Connect BotBoarduino with servos and Ultrasonic sensor HC-SR04

You have a misconception, how the Serial interface works.

The Serial interface is basically a stream of bytes (and sometimes start/stop and parity bits, which you normally don't care about) without any structure. This has to be implemented by you.

Also you have to understand, that you don't and cannot know, when a specific byte actually is being send. The fact that you typed a complete string into the serial monitor (or send a string via one call for Serial.println()) does NOT mean, that they are transmitted as a complete packet. The bytes of the string are send one after another and there may be a short delay between two arbitrary bytes. So with your reading while() loop, you are reading bytes until there is a delay long enough for the microcontroller to notice or until the message is send complete. You cannot know, which is the case for this very specific transaction. Also it seems odd, that you are only using the last read byte in your code, since the variable byteRead is overwritten on every while() loop cycle.

Then there is the format, in which you can send data through Serial.

Binary data: Since it is a byte stream, you can directly use the binary values of the bytes to reflect the data. This is easy and good for cases, in which only one value of the size of one byte is transfered every time. So there is no need to distinguish between different parts of the message. In this case you have to use Serial.write() on your sending end. This will write binary data. (You will not be able to see the values in your serial monitor, since it is displaying only ASCII-encoded characters).
ASCII-encoded data string: You are using Serial.println(), which sends an ASCII-encoded string representing the data followed by a NEWLINE character ('\n'). In case of the value 10 you are currently sending 3 bytes: '1', '0', '\n'. In this method, you are using a delimiter character (in this case '\n') to mark the end of a message. On the receiving end you have to read all bytes into a buffer, until you are receiving the delimiter character. Then you can process the message as a whole. In your case you would convert the ASCII-encoded string into an integer variable (for example with the function atoi())

To exactly explain, what is happening with your code: As Chad wrote in his comment, you are trying to use the binary value of a byte, that is an ASCII-encoded character. When looking at an ASCII table, you can see, that there is no printable character with a binary value under 10. So, since you send only printable characters with Serial.println(), There will never be a value, that is under 10.

So now you have 2 options:

Send the variable as binary data in one (!!!) byte (since you are not using distances as big as 255cm the value can fit in there; just make sure, that the byte variable does not roll over) and use every read byte on the receiving end for your code.
Send the variable as ASCII-encoded data with Serial.println() and do the correct processing of the resulting message on the receiving end. Refer to the Serial examples in the Arduino IDE for this. You can directly integrate their code into yours.


GCC msg "note: in definition of macro 'max'" error message

I can reproduce your message easily enough:

#define max(a,b) ((a)>(b)?(a):(b))

void setup() {
 int b = 66;
 unsigned int c = 42;
 analogWrite (3, max (b, c));
}

void loop() { }

I get these warnings:

/tmp/arduino_modified_sketch_857720/sketch_aug31a.ino: In function 'void setup()':
/tmp/arduino_modified_sketch_857720/sketch_aug31a.ino:1:25: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
 #define max(a,b) ((a)>(b)?(a):(b))
                         ^
/tmp/arduino_modified_sketch_857720/sketch_aug31a.ino:6:18: note: in expansion of macro 'max'
  analogWrite (3, max (b, c));

The point is that the warning note: in expansion of macro 'max' is just telling you where the macro is defined, so you can make sense of the real warning. The real warning is: warning: comparison between signed and unsigned integer expressions

So, reading them together, you are comparing (in the macro) a signed and unsigned number, and the compiler is warning you about that.

  The message seems like a red herring, given that there is no problem with the max(a,b) macro definition. I suspect it is being flagged only because it was tangentially involved with a statement in error.

That's right. There is no problem in that macro per se. Macros can generate weird error message because they are just text replacements. For example:

max (the quick brown fox, jumps over the lazy dog);

That will generate a slew of errors, including a "note" to where max is defined. There is nothing wrong with max until you try feeding garbage into it.

Templates

That's one of the reasons I prefer to avoid macros if possible. You can do "max" with a template. For example:

#undef max   // throw away the original macro in the Arduino header file

template<typename T> T max (T a, T b)
  {
  if (a > b)
    return a;

  return b;
  }

Now you get slightly more reasonable error messages:

/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino: In function 'void setup()':
sketch_aug31a:14: error: no matching function for call to 'max(int&, unsigned int&)'
   analogWrite (3, max (b, c));
                            ^
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:14:28: note: candidate is:
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:3:24: note: template<class T> T max(T, T)
 template<typename T> T max (T a, T b)
                        ^
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:3:24: note:   template argument deduction/substitution failed:
/tmp/arduino_modified_sketch_711186/sketch_aug31a.ino:14:28: note:   deduced conflicting types for parameter 'T' ('int' and 'unsigned int')
   analogWrite (3, max (b, c));
                            ^
exit status 1
no matching function for call to 'max(int&, unsigned int&)'

Of course, now you've gone from a warning to an error, because the template wants a single type.

Notice the notes? That's just the compiler trying to be helpful.

You could make the template take two types if you are prepared to guess the return type (will it be the first type, or the second type?):

#undef max

template<typename T1, typename T2> T1 max (T1 a, T2 b)
  {
  if (a > b)
    return a;

  return b;
  }

Now you don't get an error or a warning, however the result will be the first type (T1) which may or may not suit you.


Making a current GPS code run once, and only once, after the code is 'activated'

Put everything from your void loop() into your void setup. Put them AFTER the original setup and you should be good to go.

DO NOT DELETE THE VOID LOOP!! ONLY KEEP IT EMPTY!!

Here, try this:

#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(3, 2);

Adafruit_GPS GPS(&mySerial);

#define GPSECHO  true

boolean usingInterrupt = false;
void useInterrupt(boolean);

void setup()
{

  Serial.begin(115200);
  Serial.println("Adafruit GPS library basic test!");

  GPS.begin(9600);

  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);

  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);

  GPS.sendCommand(PGCMD_ANTENNA);

  useInterrupt(true);

  delay(1000);

  mySerial.println(PMTK_Q_RELEASE);

  if (! usingInterrupt) {

    char c = GPS.read();

    if (GPSECHO)
      if (c) Serial.print(c);
  }

  if (GPS.newNMEAreceived()) {

    if (!GPS.parse(GPS.lastNMEA()))
      return;

    if (timer > millis())  timer = millis();

    if (millis() - timer > 2000) {
      timer = millis(); // reset the timer

      Serial.print("\nTime: ");
      Serial.print(GPS.hour, DEC); Serial.print(':');
      Serial.print(GPS.minute, DEC); Serial.print(':');
      Serial.print(GPS.seconds, DEC); Serial.print('.');
      Serial.println(GPS.milliseconds);
      Serial.print("Date: ");
      Serial.print(GPS.day, DEC); Serial.print('/');
      Serial.print(GPS.month, DEC); Serial.print("/20");
      Serial.println(GPS.year, DEC);
      Serial.print("Fix: "); Serial.print((int)GPS.fix);
      Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
      if (GPS.fix) {
        Serial.print("Location: ");
        Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
        Serial.print(", ");
        Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
        Serial.print("Location (in degrees, works with Google Maps): ");
        Serial.print(GPS.latitudeDegrees, 4);
        Serial.print(", ");
        Serial.println(GPS.longitudeDegrees, 4);

        Serial.print("Speed (knots): "); Serial.println(GPS.speed);
        Serial.print("Angle: "); Serial.println(GPS.angle);
        Serial.print("Altitude: "); Serial.println(GPS.altitude);
        Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
      }
    }
  }
}

SIGNAL(TIMER0_COMPA_vect) {
  char c = GPS.read();

#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;

#endif
}

void useInterrupt(boolean v) {
  if (v) {

    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  } else {

    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

uint32_t timer = millis();

void loop()                     // run over and over again
{
}


What does serial data look like on an oscilloscope?

I had these images lying around so here is an example of "Fab" being sent at 9600 baud:

And now a single byte (the letter "F"):

A - no data (Tx is high)
B - The "start bit". The line is taken low to tell the receiver that a character (byte) is commencing to be sent. The receiver waits for one and a half clock times before sampling the line.
C - First character arrives (the letter "F" or 0x46 or 0b01000110). There is no clock bit as such, the incoming data is simply sampled at the baud (transmission) rate. In contrast to SPI communication the data arrives least-significant bit first (in case you are not sending 8 bits per byte). Thus we see 01100010 (rather than 01000110).
D - The stop bit. This is always high, to ensure that we can distinguish between the end of this byte, and the start of the next one. Since the start bit is a zero, and the stop bit is a one, there is always a clear transition from one byte to the next.
E - The start bit for the next character.

The time for one bit is shown on the logic analyzer as 0.1041667 ms (that is, 0.0001041667 seconds). This agrees with the inverse of the baud rate:

1 / 9600 bits per second = 0.0001041667 seconds per bit

Looking at your photo, my guess is you have inverted logic here. That is, RS232 levels (where 5V is a 0-bit and 0V is a 1-bit). Thus (and this is a guess because all the bytes are close together):

I marked the start and stop bits, and put a dot for each bit inbetween.

Also see What is Serial.begin(9600)?


Simulink with arduino : data acquisition

I just made my GY-521(MPU6050) work with Simulink using s-function.
I wish this would be helpful for you.

I am using an Arduino MEGA 2650 board. The sensor data is read in in real time.
Note that currently only Arduino MEGA 2650, Arduino MEGA 2650 ADK, and Arduino DUE support the real time windows target.
If you are using other types of board, this answer may not applied.

Your hardware connection looks correct. But if you have some troubles you can refer to mine for checking:

5v VCC
GND GND
SCL SCL(check the register map of your board)
SDA SDA(check the register map of your board)

Above four connections are adequate if you just read raw sensor data.
INT is needed if you are going to read fused data. But I did not try that.

Next you may write a small program in Arduino IDE to ensure everything works.
You can refer to the Arduino MPU6050 examples.
The code written here will be used to construct your Simulink s-function later.

Now you can start to build your Simulink block using s-function builder.
If you did not do this before, here is a good tutorial:

https://m.youtube.com/watch?v=_OLctOFjjYQ

In our case, you need to copy Wire.h, twi.h and their .c counterparts in your current working directory where your s-function resides.

And do not forget to rename generated .c file to .cpp, and add external "C" declaration. All of these are illustrated in above video tutorial.

After all of above are done, you turn your simulation mode to external, and run.
You can view your sensor data in scope if everything goes right.

Source code and configuration used in my function:
I include all headers in the Libraries panel of S-Function Builder,

#ifndef MATLAB_MEX_FILE
#define ARDUINO 100
#include <Arduino.h>
#include <Wire.h>
#include <Wire.cpp>
#include <twi.h>
#include <twi.c>
#define MPU 0x68
#endif

Wire.* and twi.* files are copied from Arduino IDE's directory. I put these files along with my S-Function block file.

The address of I2C is 0x68 here.

Next, the code for sensor outputs are placed in Outputs panel. And do not forget to add ports in Data Properties panel.

#ifndef MATLAB_MEX_FILE
Wire.beginTransmission(MPU);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU, 14, true);

int raw = Wire.read() << 8;
raw = raw | Wire.read();
ax[0] = (float)raw / 8192.0f;

raw = Wire.read() << 8;
raw = raw | Wire.read();
ay[0] = (float)raw / 8192.0f;

raw = Wire.read() << 8;
raw = raw | Wire.read();
az[0] = (float)raw / 8192.0f;

raw = Wire.read() << 8;
raw = raw | Wire.read();
temp[0] = (float)raw / 340.0f + 36.53f;

raw = Wire.read() << 8;
raw = raw | Wire.read();
gx[0] = (float)raw / 131.0f;

raw = Wire.read() << 8;
raw = raw | Wire.read();
gy[0] = (float)raw / 131.0f;

raw = Wire.read() << 8;
raw = raw | Wire.read();
gz[0] = (float)raw / 131.0f;
#endif

Finally, initialization and configuration are done in Discrete Update panel.

#ifndef MATLAB_MEX_FILE
if (xD[0] != 1) {
    Wire.begin();

    /* Do not sleep */
    Wire.beginTransmission(MPU);
    Wire.write(0x6B);
    Wire.write(0);
    Wire.endTransmission(true);

    /* Gyroscope full scale range: 250 degs/s */
    Wire.beginTransmission(MPU);
    Wire.write(0x1B);
    Wire.write(0);
    Wire.endTransmission(true);

    /* Accelerometer full scale range: 4g */
    Wire.beginTransmission(MPU);
    Wire.write(0x1C);
    Wire.write(8);
    Wire.endTransmission(true);

    xD[0] = 1;
}
#endif

Please refer to your board's datasheet for specific address and LSB scales. I am using GY-521 here.


Sending Integer > 1 Byte from Android to Arduino over Serial

First off, you are only sending one byte from Android:

  public abstract void write (int b)

  Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

OutputStream.write(byte) can never write more than one byte.

Also it's clear you have no clue about what format the data is sent in if you are trying to then read 3 bytes and use Binary Coded Decimal to reconstruct it.

Instead I suggest you work in a purely ASCII format. Forget bytes. Bytes are not what you want, unless you feel like spending some extra time defining, and then implementing, your own protocol.

Start by formatting your data into an ASCII printable string.  If Android Java is anything like normal Java I'd start by turning your integer into a string with proper line endings.  Something like:

String val = String.format("%d\n", angle);

Then get the bytes that represent that formatted string:

byte[] valBytes = val.getBytes();

Now you have a valid byte array containing your textual representation of the data that you can send with OutputStream.write(byte[]).

Now your task is to read that data on the Arduino.  That means reading each byte that arrives in turn storing it away in some form until you receive the \n line ending.  At that point you can take each byte as a string and convert them into an integer again.

It's possible to do that on the fly:

static int angle = 0;

if (Serial.available()) {
    char c = Serial.read();
    if (c == '\n') {
        Serial.print("I got: ");
        Serial.println(angle);
        angle = 0;
    } else if ((c >= '0') && (c <= '9')) {
        angle *= 10;
        angle += (c - '0');
    }
}

Basically, have a variable that stores the incoming angle. For each character that arrives on the serial port - if it's a line ending \n then do whatever with the angle value. If it's a character between 0 and 9 then multiply your angle by 10 (decimal shift left), convert your character to the equivalent integer by subtracting character '0', and add it to your angle.


The Tone library doesn't use the PWM mode timer functions on the atmega, instead it uses an interrupt routine to toggle the pins. You can find the source code for Tone libary here for reference:

https://github.com/johnmccombs/arduino-libraries/blob/master/Tone/


ok so what ive found is that pins are declared in a file, pins_arduino.h. for each board/chip/variant another file is added(or created, if writing your own) to the arduino hardware files. in my specific case the numbers in the graphic are consistent with those listed in the hardware file, so im good


Bootloader difference between Atmel328p(through hole) and Atmel328p au(smd)

The bootloader doesn't care about how many pins the device has. All it cares about is the UART pins, and they are the same.

Internally the two chips are the same, it's just the packaging that is different. They take the same silicon chip and mount it on a different lead frame and encapsulate it in epoxy. Which is why the only pin differences are a couple of extra power and ground pins, and two dedicated ADC pins that they don't connect in the DIP package.  Even the pins are in the same order around the chip if you examine the pinouts in the datasheet.

Whether you use the DIP (Uno) or the SMD (Nano) bootloader it makes no difference (the two bootloaders are the same anyway). There can be no "perform better" anyway, since that isn't a valid concept. Either it is compatible, in which case it will work, or it's not, in which case it won't.

The only real thing of concern is to ensure that your fuses are set correctly for your chosen clock source, and that the bootloader you install is compiled to run at the speed of your chosen clock source. That has nothing at all to do with which chip it is you are using, but how you have designed your circuit.


Debugger with Breakpoint and Variable read/set capability

There is something quite close to what you are asking.
You need either the (more expensive) ICEMKII (iirc) or the (cheaper) AVRDragon.
Then it's possible to use it with gdb.

In practice the AVR supports only one breakpoint, so what happens is that the binary in flash will be dynamically patched.
This will slightly reduce the life of the AVR, but I think it's fairly acceptable. One can always use Arduino UNO with the original DIP package for AVR, mounted on a socket. Then it's sufficient to replace the burnt microcontroller and keep the rest (but it's hundreds of thousands of programming cycles before the AVR fails).


If there is a way to make pin 12 on the Arduino Micro an Interrupt pin

you should take a look at the device datasheet and see what other functionalities pin 12 has.

if it is a pcint pin, you are golden;
if it is a timer input pin or an input capture pin, they can be programmed to act like an interrupt pin as well.

all begins with reading the datasheet.


SendSMS example sketch hangs at PINMUNBER if statement

Try this sketch:

#include <SoftwareSerial.h>

SoftwareSerial gsm(2,3);
void setup() {
  Serial.begin(9600);
  gsm.begin(9600);
  delay(1000);
}

void loop() {
  // put your main code here, to run repeatedly:
  while (gsm.available() > 0)
    Serial.write(gsm.read());
  while (Serial.available() > 0)
    gsm.write(Serial.read());
}

This sketch will help troubleshoot exactly what's wrong with your setup, without the clutter of a library.

Connect the shield's TX pin to Arduino pin 2 and the shield's RX pin to Arduino pin 3. Ensure that all GNDs are connected. Upload the sketch. Set your serial monitor to BOTH NL & CR and the baud rate to 9600. Enter AT from the serial monitor. If you recieve OK, it means comms have been established with the shield. If you receive gibberish, change the SoftwareSerial baud rate to values from 19200, 57600, etc. until you get a legible response.

Then send the command AT+CREG? to check the SIM's registration status. If you get something like +CREG: *, 1 or +CREG: *, 5 (* means 'dont care'), then your SIM has been registered on the network. Report your results here.


How to prevent inclusion of unnecessary libraries?

The Arduino IDE build script will actually copy all core source code file to the tmp directory, compile and generate an archive file. The sketch is compiled and linked with this library. Only the referenced (used) functions and data are linked in the binary.

The size (both program and data) of this blink is somewhat larger than the "standard" blink example but this is due to the publisher-subscriber run-time.

Cheers!

PS: If you google you can find commands to listing what is actually in the generated binary. Here is a starting point.


Unless you feel like starting a fire, none. Find a 220V 2A relay with a 5V coil and use that instead, switching the hot wire and not the neutral.


ws2812b NeoPixel - how to address it? How Arduino knows the correct order of LEDS on the stripe?

The WS2811/2812/2812B is not a 1-Wire device but is in fact a timing-based shift register with 3 LEDs (external in the case of the WS2811) connected to it.

As long as valid bit pulses are sent to the input of one of these devices it will shift the data through it and subsequently out of its data output. Connecting this output to the input of another device will shift data into that device as well, with the latest data sent being transmitted towards the furthest device in the chain.

Provided 24 bits per device are sent before the latch signal, The first 24 bits will be shifted into the first device, the second 24 bits into the second device, and so on until the last 24 bits into the last device in the chain. Once the latch signal is received, the devices will switch to the color indicated by the 24 bits currently shifted into them.

Since all of the devices use the same signaling (the only differences being supply level and the presence of a built-in RGB LED), they can be replaced freely with devices of the same or different make between the three.


How to execute three functions at the same time?

You can implement three functions but you can't able to execute them same time.


How to connect a 5V submersible motor to Node MCU?

I think you have got two issues here.

Firstly, as mentioned in the comments, you are driving the motor off the data pins so it will be getting less than 20mA which is almost certainly not enough to break the stall.  You need to use the digital pins to switch a MOSFET, transistor or relay (Electrical switch) and then that will switch on a larger supply directly from a "battery pack".  Have a Google for 'transistors' or 'relays' and see how they work, then you should get what I mean.

Secondly you seem to be using the pin names D1 and D2. There are a number of Node MCU boards out there but they all seem to have one thing in common and that is the pins labelled D1 and D2 on the board are generally not D1 and D2 in the code.

https://pradeepsinghblog.files.wordpress.com/2016/04/nodemcu_pins.png?w=924

If this is you board then unless you have a header file that does this for you, you should be using GPIO_5 and GPIO_4 for D1 and D2 (respectively).

Oh and the last thing, make sure you sub is leak proof :)


How is it possible that my skin temperature is so constant?

Examine your code closely.  It appears that you are partially implementing extended resolution calculations in this line of code:

  float TemperatureSum = tempRead / 16;

In the DS18S20 specifications the extended resolution equation used is:

 TEMPERATURE = TEMP_READ * 0.25 - ((COUNT_PER_C - COUNT_REMAIN) / (COUNT_PER_C))

Where COUNT_PER_C is a DS18S20 register containing a value of up to 16.  Maybe that is where 16 originated?

I believe what you want to do is divide the recovered value by 2.0 base on table 1 from the DS18S20 specifications:

  float TemperatureSum = tempRead / 2.0;

Don't forget the "." in case the compiler you are using decides to do integer math dripping the "float" part before assigning it to TemperatureSum.


YL-38 output to NodeMCU v1.0 analog input

To my understanding, the NodeMCU A0 pin operates from 0v-3.3v

Incorrect. The ESP8266's ADC can only measure between 0V and 1V.

You need to reduce your output voltage down to that range. How you do that very much depends on the output impedance of the YL-38.

The LM393 that the YL-38 is based around looks to have a maximum output current of 16mA. That should be enough to happily drive a simple voltage divider.  A 4.7kΩ and 1kΩ divider would give you 0 to 0.877v out from a 0-5V input.

simulate this circuit – Schematic created using CircuitLab

An alternative would be to attach an external ADC running at 5V to the NodeMCU. This would give you multiple channels of analogue input with a 0-5V range. I use the MCP3208 running over SPI (I actually bit-bang it on the ESP8266 rather than using SPI, since I haven't yet got SPI to work properly with it).  Ideally, you want a proper logic level translator for the SCK and MOSI signals to boost them to 5V. It all gets a little complex, though.

It has come to light that the NodeMCU includes a voltage divider already. For some reason they chose to use massive resistors, which give far too high an impedance for any reasonable ADC input to accurately work with.  I would suggest, if you can, removing those resistors from the board and replacing them with 4.7k and 1k resistors to form your own voltage divider. Otherwise you're going to have to use a pair of op-amps in inverting mode, one with a fractional gain, and one with unity gain (the second is to "undo" the inverting of the first one) to reduce the signal to 0-3.3V.

TBH I'd be inclined to use an external ADC anyway for this.


You've... misread the datasheet. The '328 input high voltage (VIH) for most pins is 0.6VCC minimum for devices with a 2.4-5.5V supply. This means that a 5V device has a 3V threshold.


I Can't Connect to my MQTT server via arduino

This is the problem:

mosquitto 10436       mosquitto    4u  IPv4   46043      0t0  TCP
127.0.0.1:1883 (LISTEN)

Your MQTT server is listening only on port 127.0.0.1.  That will accept local incoming connections only but nothing from another IP address.
The IP 127.0.0.1 is the LOCAL ONLY IP address.  You need to reconfigure your MQTT server to listen on either IP 0.0.0.0 or whatever that server's actual IP address is.
Check your mosquitto.conf file and look for the line that begins with "bind_address":
listener 1883 localhost

change this to:
listener 1883 0.0.0.0

and restart your MQTT server.


STM32 "Blue Pill" Serial.print freezes Serial Monitor

Have you made sure to modify the board before using it?
This page mentions at least one resistor that you have to replace for the USB to "work".

The USB standard requires a 1.5 kΩ pullup resistor on D+, but this board is known to have a wrong value (R10 on the board). It ships with either a 10 kΩ resistor or a 4.7 kΩ resistor, but it should be replaced with a 1.5 kΩ resistor, or put an appropriate resistor value (e.g 1.8 kΩ) in between PA12 and 3.3V.
It is also true that some PCs are tolerant of incorrect value so, before you change the resistance, you can try if it works in your case.

I have had issues with bluepill boards myself in the past, but never had an issue like yours after fixing the resistor. (before that, I couldn't even flash the bootloader)
Try printing other things with the board, and see if there's any pattern to it cutting out. e.g. a string over and over again, or the same float over and over again.
Try different baudrates, or even SoftwareSerial to another board.


Your sim card is probably protected by a PIN. Easiest way to get it working is to put the SIM into a normal phone and remove the PIN protection.


serial.write() five sensors and Processing

What is happening is you are just spewing out a list of numbers:

4132
132
1928
3240
1239
238
3048
391
... etc ...

There is nothing anywhere to say what anything is.

You need to add that kind of information. Either as a "start of data" tag before each block, or with each line.  For instance:

---START OF DATA---
4132
132
1928
3240
1239
---START OF DATA---
238
3048
391
... etc ...

Or:

0:4132
1:132
2:1928
3:3240
4:1239
0:238
1:3048
2:391

It is then up to your processing application to interpret the data and work out what is what.

Personally I like using the second method since it means you don't have to send all the data every time - you can send different values at different speeds of update and maintain a "current value" at the Processing end. For instance if you have one value that updates frequently and others that don't:

3:4132
1:132
3:1928
3:3240
3:1239
2:238
3:3048
0:391

You don't even have to use numbers, you could use words:

pressure:4132
temperature:132
pressure:1928
pressure:3240
pressure:1239
humidity:238
pressure:3048
rainfall:391


Looking for light-weight Arduino OLED library that supports text and bitmaps

This is supposed to be a small implementation. https://github.com/nicoud/Oled

I have not used it, but it does look interesting. You can pick the bits that you need.

https://www.didel.com/OledLib.pdf


Can I use an AC signal to make an LED light up with arduino?

There's certainly an issue with your optocoupler circuit aside from the fluctuation you observe.

During a negative half-wave of 220V, you expect D1 to block the current through the LED. However, 1N4007 as any power rectifier has significant leakage current, about 5μA at normal temperature and up to 50μA when the diode is hot. This current will go though the LED which may have a much lower admissible reverse current (typical 0.1μA), damaging it. One possible schematic would be:

simulate this circuit – Schematic created using CircuitLab

Note that D1 is here not to block reverse current, but rather conduct it safely, protecting the LED of the optocoupler. Also, consider reducing the value of R2 while realising the bulk of current limitation with a non-polar capacitor: this setup will limit the current just the same but will dissipate 0.5W of heat instead of 2W as your resistor would.

Now, in either case the LED is only active when it's forwad-biased, which is less than half of the time, so it's quite normal that you see this fluctuation. In most cases, it can be reasonably dealt with by software: read your pin 3 times with a 5ms delay after each reading, and make a logical AND of your three readings.

If, for some reason you cannot do that in software, you could implement an envelope detector in hardware. I strongly suggest to do it on the low-voltage side instead of 220V side (as e.g. here)


Wireless Communication Between Raspberry Pi 2 and multiple Arduinos

There's many options you could use.

The simplest, though most expensive, would be to equip all your Arduinos with WiFi shields and connect a USB WiFi dongle to the Pi.  The Pi could run in AP mode (investigate hostapd) so you don't have to connect them all to your internet router.

A cheaper option, though harder to work with on the Pi, would be to use the incredibly cheap but popular nRF24L01+ modules.  There are libraries aplenty for the Arduino, but I am not aware of code for the Pi (though there probably is somewhere if you google for it).

And then there are options in between which vary in price and complexity.

Of course, you haven't mentioned range, only a brick wall.  The right choice could well be affected by the range of communication you need - do you go for the bare nRF28L01+ with a range of maybe 10m, or the one with the power amplifier and SMA antenna with a range of many hundreds of meters? Is WiFi going to be long enough range? Would a 433mHz module be a better choice?  All these questions and more need to be answered, and the best way is for you to describe your setup in detail, including what the longest range is you need to deal with, what amount of data you will be sending, do you need ultra low power to save batteries, etc.


The FILE_WRITE in SD library is 'append' (for historical reasons)

#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)

so use

 File file = SD.open(filename, O_WRITE);


You can use either the internal or external resistor in normal application.

Each method has each own advantages:

Internal resistor

Pros: flexible to change by changing the code
Pros: Reduce PCB size
Pros: Reduce cost (very small)
Cons: It may make MCU hot

External resistor

Pros: Reduce heat for MCU
Cons: Not easy to replace when it is built-in PCB
Cons: Increase PCB size

Besides, Pull-up and pull-down resistors are not only used for INPUT port but also for OUTPUT port. In the case of OUTPUT port. The external resistor has another advantage:  flexibility in connecting devices with different I/O voltages. For example, in I2C hardware see I2C at the Hardware Level.

NOTE: As far as I know, at the writing time, Arduino library does NOT support INPUT_PULLDOWN


how do i know what battery(how much ampere and voltage) my circuit needs to work perfectly?

TL;DR: You really need to know what components you have and you need to find datasheets. In the datasheet, you find what voltage the component requires.

Don't care too much about amperes in the beginning. If you get the voltage right, each component will just draw as much current as it needs.

An Arduino Uno operates from 7 to 12 Volts, so 7.4 V is ok.

"Servo motor" is simply not enough information. There are servo motors for 4.8 V, some for 6 V and others for 12 V. There are even AC servo motors for 240 V~.

DFPlayer is for 3.2 V to 5 V, so it shouldn't be powered directly off the 7.4 V battery. Maybe it can be powered from a 5 V pin of the Arduino. Since they power it from the 5 V pin, it seems to be possible.

Also "LED" is not a term that is good enough. Is it Infrared, Red, Yellow, Green, Violet, UV or white? Depending on the color, it needs something between 1.6 and 3.0 V. Therefore, you need a resistor. What's the use of the LED? Do you need to turn it on and off by Arduino, or can it just be always on from the Lipo battery?

The L298N has a supply voltage from 2.5 V to 46 V, so 7.4 V is fine.

Next, "DC motor" is not specific enough. I have seen 3 V, 5 V, 6 V, 12 V, 24 V.

Also, for ultrasonic, there are SR04 and SRF05. These two operate at 5 V. But if you have a different one, that may not be the case.


Beginner Arduino Project: Drumming Robot

The approach I would take for the arms is to use a servo motor as these are fairly cheap and are closed loop so you don't have to add any extra sensors to check where the current position is.

Types of Motors:

Stepper motors are a type of motor with a special arrangement of coils that allows you to turn a fraction of a degree by sending pulses to the motor. For example, you can buy a 200 step stepper motor that turns in increments of 1.8 degrees. These are somewhat expensive and require somewhat expensive drivers (usually $5-10 per driver). Often used in CNC machines and 3D printers. Continuous rotation.
General DC motors (two types: brushless and brushed, but I won't get into that in here) are a type of motor. Their drivers are often cheaper than one for a stepper motor, but you have little control over their rotation (instead of "take one step which is X degrees," you say , "turn at 25% power clockwise," where you don't know the actual speed). These are sometimes used with rotary encoders or potentiometers to control the speed and position of the spindle. Continuous rotation.
Servo motors are actually not their own type of motors; they are DC motors (not steppers) with a potentiometer built in along with the driver. You send pulses to it (you can use the Arduino servo library for this) to tell it the exact degree to go to. Can only go a limited range: usually either 90 or 180 degree, although you can get special ones that can turn much longer ranges than that.

Using a Servo Motor:

You can hook it up like this:

  From this Arduino Tutorial

And then some very simple code to use the motor:

#include <Servo.h>

Servo myservo;

void setup() {
  myservo.attach(9);
}

void loop() {
  myservo.write(10);
  delay(500);
  myservo.write(0);
  delay(500);
}

Talking with Ruby:

Your best option is to use the serial port on your computer. Figure out how to access a COM/serial port in Ruby. You can then send messages from your computer to the Arduino, but you'll have to figure out a way to structure the messages.


I want a bar type display for my Arduino Project

As Majenko already stated, the second image shows a custom display. It is not pixelated, because each shown element/symbol has it's own element in the LCD. When you have one of these displays, you might be able to reuse it for your project, but that is advanced.
In the case of pixel based displays with a significantly higher resolution than the standard SSD1309 driven LCD or OLED displays, you are mostly out of luck. There might be fitting products, though they most likely will be expensive and are not as easy to drive, as the standard ones. AVR based Arduinos, like Uno, Nano or Mega, are also not really good for driving high res displays.
The way to go depends on your exact requirements.

You could - as Majenko suggested - ditch the Arduino and use an old smartphone. If you need more control over the smartphone for your project, than the standard Andriod gives you, you could install an open source OS on the phone.

You could move to a Single Board Computer, like the Raspberry Pi Zero, and buy a display for it. There are many displays for Raspberry Pis, that should have enough resolution. Though most of them are larger than a normal smartphone display.


Why digital pin not reading ON from push button switches connected to 5V and pull-down 10K resistor?

when the switch on pin 4 is closed the stateDirection variable still reads 0, or open circuit.

you could have pull-up enabled on that pin: with a nominal value of 50k, 10k pull-down is just on the cusp of making it a logic low.

solution?

1) disable pull-up;
2) use a stronger pull-down;
3) get rid of the pull-down and rely on the pull-up alone.
...


Will an Arduino Uno be able to read 3x incremental encoders?

Here is an example of some code I used to read two encoders using pin change interrupts.  This is possible to do with one ISR since they all share a common port.  The key is it has to be short.  As long as you can keep all 6 pins from your encoder on the same port, this should be easy to extend to 3 encoders.  It might even work for four on one port.  Or you can make a use a second port and get 3 or 4 more depending on which chip you have.

volatile uint8_t lastPortRead = 0;

volatile int32_t leftCounter = 0;
volatile int32_t rightCounter = 0;

ISR(PCINT2_vect){

    uint8_t portRead = PINC;

    uint8_t whoFired = portRead ^ lastPortRead;
    uint8_t pinsDiff = portRead ^ (portRead << 1); // Will have bits 5 or 7 set if pins on right motor or left motor are diff.  Cleared if same.

    if (whoFired & LEFT_INT_MASK) {
        if (pinsDiff & LEFT_INT_MASK) {
            leftCounter++;
        } else {
            leftCounter--;
        }
    }
    if (whoFired & RIGHT_INT_MASK) {
        if (pinsDiff & RIGHT_INT_MASK) {
            rightCounter++;
        } else {
            rightCounter--;
        }
    }

    lastPortRead = portRead;
}


How to make 1 second delay more accurate?

Majenko is perfectly right: you cannot expect much accuracy from an
Arduino clocked by a ceramic resonator. Typical drift is of the order of
1,000 ppm, and is affected by temperature and aging. You can,
however, get a delay which is pretty close to the CPU's idea of one
second. In other words, you can get something that is really close to a
perfect period of 16,000,000 CPU cycles. If that is what you want,
your best bet is to use a timer.

In your overflow ISR, you wrote:

  Serial.println(millis());

There are two issues here. The first is the use of Serial.println()
within an ISR. This should normally avoided: since Serial relies on
interrupts, using it with interrupts disabled can lock your program if
you ever fill the output buffer. In this particular instance, it happens
to be safe, because at this rate you are never going to fill the output
buffer anyway. However, while it can be OK to do that in a small test
program like yours, I would advise you against doing it in production
code.

The other issue is the use of millis(). This function does not provide
true millisecond resolution: it is a counter that is updated every
1024 µs. Every now a then it is updated by 2 ms at once in
order to compensate for the drift. Thus, you should think of millis()
as being good to within ±2 ms. If you need anything better, use
micros().

  TCNT1 = 3036;

This should be avoided. Dispatching an interrupt takes time, and this
time depends on whether there is already an interrupt handler (or other
critical section) running. If the timer happens to increment after the
interrupt fires but before you have time to execute the line above, then
you miss a timer tic. It has been suggested to you to move this line
before the Serial.println(). That would certainly reduce the risk, but
it will not completely prevent it.

The right thing to do is to never reset a timer if you want it to have
time continuity. Instead, set it to CTC mode (clear timer on compare
match) and let it reset itself when it reaches a value of your choosing.
In this case, you would have it repeatedly count from 0 to 62,499
instead of from 3,036 to 65,535.

Here is a modified version of your program illustrating the points
above:

void setup()
{
    Serial.begin(9600);
    TCCR1A = 0;            // undo the Arduino's timer configuration
    TCCR1B = 0;            // ditto
    TCNT1  = 0;            // reset timer
    OCR1A  = 62500 - 1;    // period = 62500 clock tics
    TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
           | _BV(CS12);    // clock at F_CPU/256
    TIMSK1 = _BV(OCIE1A);  // interrupt on output compare A
}

ISR(TIMER1_COMPA_vect)
{
    // OK in test code, don't do this in production code.
    Serial.println(micros());
}

void loop(){}

The output is as follows;

1000048
2000048
3000048
...
58000048
59000048
60000048  // 60 seconds


On a normal Arduino board, no, it's not possible from a sketch POV. With a Leonardo or similar ATMega32U4 based board it may be possible to give it a unique VID/PID combination, and even possibly custom manufacturer and product strings. You may be able to do it by creating a custom board definition in boards.txt (or maybe manipulation of the AVR core) - but I have never tried that sort of thing with Arduino, so I cannot vouch for how easy it would be.

However (shameless self-promotion coming here...) if you were to switch away from Arduino and use a chipKIT board like the Lenny (or any of the other chipKIT boards with a direct USB connection, such as the Fubarino boards) then it is possible to craft a completely custom USB profile from within your sketch, including VID/PID, Manufacturer and Product strings, and even what devices the board implements. For example:

USBFS usbDevice;
USBManager USB(usbDevice, 0xf055, 0x1234, "Espentech", "My Little Widget");
CDCACM USBSerial;

void setup() {
    USB.addDevice(USBSerial);
    USB.begin();
}

void loop() {
    USBSerial.println(millis());
    delay(1000);
}

Which results in:

[  661.328155] usb 2-1.2.7: new full-speed USB device number 10 using ehci-pci
[  661.458613] usb 2-1.2.7: New USB device found, idVendor=f055, idProduct=1234
[  661.458616] usb 2-1.2.7: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[  661.458619] usb 2-1.2.7: Product: My Little Widget
[  661.458621] usb 2-1.2.7: Manufacturer: Espentech
[  661.458623] usb 2-1.2.7: SerialNumber: CK2660A05312F3
[  661.459181] cdc_acm 2-1.2.7:1.0: ttyACM0: USB ACM device


Is this circuit risky for an Arduino Uno?

That circuit is fine as long as the input signals don't go above 12.5V.  You can protect it further by adding a 5.2V zener diode across each of the signals as they enter the Arduino:

simulate this circuit – Schematic created using CircuitLab

Why is this circuit not going to burn my Arduino if it is using 12V?

Because it uses a voltage divider to reduce the voltage to 4.8V.


Receiving Multiple data on Arduino Serial

You send a string "A"

However, to denote the end, a carriage line (code 13) + line feed (code 10) is sent.

So what is sent is actually an 'A' character followed by a return.
This way you also know when a new line starts

Just strip off the return (13,10) items if you do not need them.

If you do not want to send the return, try sending 'A' (which is the character A, and not the string A.

Update

You can ignore them by:

     if ((incomingByte != 10 && (incomingByte != 13))
     {
        Serial.print("I received: ");
        Serial.println(incomingByte);
     }

If you only want printable characters, check if you can use the isprint function (isprint function

so it should look like

    if (isprint(incomingByte))
    {
        Serial.print("I received: ");
        Serial.println(incomingByte);
    }


Arduino Pro Mini (3.3V version) input voltage range / tolerance

The genuine Pro Mini's use a MIC5205 regulator which should accept up to 16V at it's input normally, with an absolute maximum of 20V. It's unlikely that the regulator would be damaged by 15.1V.

However, the component you have indicated that has blown is a capacitor. SMD capacitors are available in different voltage ratings, typically 4V, 6.3V, 10V, 16V, 25V, 35V and 50V (and above, but let's ignore them for this). It's rare to see any intermediate values.

SMD capacitors are very intolerant of being used at a higher voltage than specified. This is especially true of electrolytic and tantalum capacitors. The blown capacitor on the genuine Pro Mini's is polarised (the grey band not he package and the schematic indicates this), so we can infer it is either electrolytic or tantalum. A 10µF SMD electrolytic is unlikely to be in this package, so it is almost certainly a tantalum.

Sparkfun sell 10µF tantalums, and they are rated at 16V. It's quite likely these are the same ones used on the Pro Mini. 15.1V is very close to 16V - in fact, if this is a poorly smoothed power supply, the meter might show 15.1V but the peaks could well be 16V or even 20V. It is recommended that you de-rate the voltage ratings on tantalums by 50% at least.

It's really important to realise that most low-cost DC power supplies are not regulated and produce a very bumpy output voltage with no regulation:

Tantalums also have no tolerance for reverse voltage, so if you did apply reverse voltage, it would pop.

So it is quite likely that you over-volted the cap and blew it. You could replace them with higher rated capacitors - I would go for 35V ones if you want to supply 15.1V. Desoldering and desoldering a single capacitor is relatively easy as long as the pads haven't been damaged. Realistically, you could use a normal leaded 10uF electrolytic between RAW and GND instead of the SMD one.

EDIT: However, looking at the data sheet for the regulator, it shouldn't really matter if that 10uF is there or not:

  A 1μF capacitor should be placed from IN to GND if there is more than
  10 inches of wire between the input and the ac filter capacitor or if
  a battery is used as the input.

Some regulators absolutely require an input capacitor, with others it is just advisable. This looks like it is just advisable. So if it isn't working on external power now, you may have blown the regulator as well.

Even if the clone board uses a different SMD regulator, their characteristics are all very similar. As stated, some do need a capacitor on the input to work, so replacing it might fix it.

There is a further consideration that dropping from 15.1V to 3.3V on a SMD regulator is not a great idea. You will need to burn off a lot of power.

The MC5205 can dissipate 455mW with a minimal PCB footprint (which the Pro Mini has) with a 25°C ambient:

So, we know the maximum power we can dissipate, and we know the voltage drop - we can then calculate the current:

P = (Vin - Vout) * I

0.455 / (15.1 - 3.3) = I

I = 38.5mA

This isn't very much at all. You might want to consider regulating off the board, and probably with a switching regulator rather than linear regulator.

I also note your PS:

  the ground of the 12V PSU is shared with Arduino ground pin, not sure
  if this might be the cause.

If they weren't shared, there would be no way that this could work. They need to be shared otherwise the Vcc from the power supply is not referenced to anything and may as well not be there.


It sounds to me like an Arduino Uno clone.

  Why it says "For Arduino UNO R3"?

I would read that as "For Arduino UNO R3 projects" (ie. Uno-compatible).

  Isn't it actually an "Arduino UNO R3

No, it's a clone. Or not really a clone (see below) because they used different hardware. It is compatible with the Uno in most respects.

  What are MEGA328P?

That is the main chip on the board (actually an Atmega328P).

  and CH340?

They have saved money by using a CH340 USB-to-serial chip instead of the Atmega16U2 used on genuine Uno boards. You may need to install a different driver to make that work. I disagree with the other answer(s) that this is a separate board or chip. It is clear from the photo of the chip near the USB socket that it is a CH340 chip there. See, for example https://hackaday.com/tag/ch340/ from which I quote:

  The cheapest USB to serial chip on the market appears to be the CH340G, available for 20-40 cents apiece from the usual retailers. There is, however, almost no English documentation, and the datasheet for the CH340 family doesn’t include this chip

They used it because it is cheap.

  Does "Arduino UNO R3" comes with other chipsets?

Yes the genuine one comes with an Atmega328P (main processor) and Atmega16U2 (USB interface).

Having said all that, the Uno is a good all-rounder starting board to get going with Arduinos.

Note that they are using the SMD (surface mounted) main processor chip. If you fry it you need to replace the whole board, not just the chip. However the entire board is quite cheap. :)


Erasing 1 byte of external Flash memory (winbond)

For a flash chip, no it's not possible to erase a single byte.
The closest you can do is to read an entire sector into memory, erase that sector, modify your in-memory copy, then write the sector back.
You would be better using an SPI SRAM or PSRAM chip instead of a flash chip.


Getting different values inside vs. outside a function while using global array

It is not a good practice to reserve memory for a string with a constant string. Allocate an array of char arrays with:

char parameters[PARAM_AMOUNT][PARAM_LEN];

Now with "0" you allocate 2 bytes for each string. The '0' and a terminating 0.

Then in splitter function you write 3 bytes into one of the parameters with value "20". This writes outside of the 2 bytes of memory reserved for the string.

strcpy(parameters[i], pch); will copy the token returned by strtok into your array. pch points into inputstr and the delimiters in inputstr are replaced by 'strtok' with zeros


What if Ultrasonic sensor doesn't detect object?

What type of Ultrasonic sensor do you have?

I'll go with HC-SR04, since I've got one of those laying around here. The other ultrasonic sensors should be working in the same way.

Before you start!

Read the datasheet. A fast search on google with: "[manufacturer][device id][device description] datasheet .pdf" will do good.

Example: http://www.micropik.com/PDF/HCSR04.pdf

The datasheet will tell you important things/values and sometimes even interfacing examples or code.
Like:

Max input voltage
Max current
Pin-out diagrams
How to interface with the device
Min/max operating temperature

Wiring up

The datasheet will tell you what to connect, to which pins.

We've got 5V, Trigger (input), Echo (output), 0V (ground).

(As per datasheet)

It's best to do the wiring before you put power on it, because you can accidently short it when moving wires around.

Interfacing

I would recommend checking some code examples before you attempt to roll your own. Or just start from an example and edit it to your specifications.

The timing diagram shows us it needs a 10uS pulse on the trigger input.
And the duration of the echo will show the distance (58 uS per cm or 148 uS per inch).

The datasheet also suggest to use over 60ms measurement cycles.

Code

Taking all that into account:

#define trigPin 13
#define echoPin 12
#define led 11
#define led2 10

const unsigned long timeout = 400*58; //Max of 400CM, adjust this to your own max.

void setup() {
  Serial.begin(115200);//Stop using 9600 as default, it's not fast.
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
}

void loop() {
  unsigned long distance;//unsigned, since we don't get negative distances.
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); //10 uS pulse.
  digitalWrite(trigPin, LOW);

  distance = round(pulseIn(echoPin, HIGH,timeout) /58);//Distance in CM's, use /148 for inches.
  if (distance == 0){//Reached timeout
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(60);//Wait 60 ms for next cycle.
}

To be honest, I'm not even slightly sure if this code is working.
I modified this code: http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/

So that you're actually using the timeout right, and do the timing according to the datasheet.


How can I convert PID correction values to an PWM brushless command?

you have to do that yourself. you have to figure out first how to correct a pid value directionally. for example, should you increase the duty cycle if pid is positive or negative?

after that, you will need to map the pid value to a range for your pwm dc.

basically, it is application / task specific, and you are in complete charge.


Talking to Eurotherm 2416 temperature controller over modbus rs232

You could also take a look at this github project:
https://github.com/ukos-git/arduino-eurotherm2416

It is specifically designed for the purpose you ask for.
It basically includes Module named Temperature and a possibility to set or read it:

Temperature.set(100)
t = Temperature.getTemperature()

Look at https://github.com/ukos-git/arduino-eurotherm2416/blob/master/app/app.ino.


How to get the weather kit with anemometer working using arduino (UNO)?

According to the above setup only rain bucket unit works.

And as jsotola mentioned both the anemometer and the rain bucket sensors are simple switches, so a simple sketch can be written that reads the switch state and light LED (pin13) if the switch is activated and turns off LED if switch is not activated and that can be done for each of the switches separately.

But instead I took a shortcut.

Fixes:

The wind vane part (on analog pin A0) starts working only when I connect the I2C vcc pin to 5 volts pin instead of 3.3 volts pin of UNO.
Had to ditch the https://github.com/switchdoclabs/SDL_Weather_80422 library's wind_speed reading method and adopting and merging into the http://cactus.io/hookups/weather/anemometer/davis/hookup-arduino-to-davis-anemometer-wind-speed code and adding up the wind_gust function from https://github.com/sparkfun/Weather_Shield/blob/master/Firmware/Weather_Shield_Weather_Station_V12/Weather_Shield_Weather_Station_V12.ino makes the anemometer with rain-bucket with the exact same setup fully functional.


Few questions related to programming microcontrollers

The Arduino IDE uses C++ primarily, which it preprocesses in order to make compilable. But you can still for the most part use C in the Arduino IDE and it will just work as normal; there's nothing requiring you to use C++ or the Arduino libraries (or even the Arduino IDE) for most tasks.
Not touching this one. And in the end it doesn't matter terribly since they're very close.
Any of the ATmegaXX8 or ATmega8 chips will fit the socket. Note that they will require separate cores if you're using the IDE. And you can use any chip without the board in the IDE as long as you can find a core for it.
Not if you use a traditional compiled language to program it. If you use a VM then you conceivably could, but you'd have the source on your system regardless.


Linux can not open arduino IDE - java.lang.NullPointerException

I had to install arduino-avr-core package:
sudo pacman -S arduino-avr-core

Now it works fine


Arduino Newbie: Solderless Breadboard Alternate

Breadboards are for development and testing. When you are OK with your circuit, then you solder it.

Your alternatives:

Point-to-Point

Just solder directly component to component. You can arrange your component for minimal space and minimal wiring length. Can be very elegant (depends on your abilities) and doesn't require any board.

Perforated board

For personal projects, you can use a perforated board to put all your components. Requires some planning in components placement and wiring (you can paint yourself in a corner). Easy to do.

Expansion Shield

It's a perforated board on a shield, so you just plug it over your Arduino Uno. Great if you need easy access to lots of Arduino pins. Cons: little space for components. There are versions with a mini-breadboard instead of a perforated board.

PCB

You can make your how PCB, but it's hard and too much work. Use it only for high volume production. It require lots of preparation and dangerous chemicals.

Useful links (YouTube)

Review of some prototype circuit building methods
Perfboard Prototyping
Breadboards & Perfboards


OK if this helps anybody, they give you constants for every pin that look like PC14 for the one that says C14, so you don't need to worry about the integers that they assign to the pins.
I mean there are constants named for the yellow boxes on the above diagram.


Neo 6m outputting something i as a noob can't understand

someone on ublox portal recommended me to connect the boards vcc to 5v's and when i did that, it stopped rebooting, and after 20 mins got a lock, thanks for your help.
the guy on ublox portal

Post a photo of the board and a link of where you bought it so that we can point out that 5V is needed.
The reboot symptom is usually caused by an inadequate voltage source --- when the 6m starts, current draw is low, when it finishes initial startup, it goes to work looking for sats and current draw jumps up. The higher current draw on a poor power source causes supply voltage to drop too.low which then causes the 6m to reset and restart and will happily repeat the cycle forever.
Use a good DVM or oscilloscope to verify the inadequate voltage source.

after connecting the board to 5v supply the problem seemed to be fixed


How to avoid that my arduino clicks eternally?

Hold the RESET button as you plug the Arduino in and keep it pressed all the time it's plugged into your computer.  Load Blink.ino into the IDE and compile it.  Press the UPLOAD button in the IDE and move the mouse to somewhere "safe".  Release the RESET button.

Do those last three steps in rapid succession and you should be fine.


When debouncing buttons it is easiest to think of a 4 state machine.

The button is open and you will not jump to the next state until you see the button closed.
You saw the button closed.  Now you need to wait until the button stops bouncing open and close.  After about 100ms, if the button is still closed, jump to the next state.  Otherwise go back to state 1.
You are sure the button is closed.  Do the stuff you want to do when the button is pressed.  Now wait in this state until you see the button is open.
You saw the button open.  Now you need to wait until the button stops bouncing open and close.  After about 100ms, if the button is still open, jump to the first state.  Otherwise go back to state 3.

It is good practice to code this up.  However, there is an existing Arduino (de)bounce library to do this for you.


Make lights come on and off depending on which button is pressed

Can someone please just point me in the right direction?

what is "right" is highly subjective. I would consider a good solution to be one where the functionalities desired is broken down into natural modules that are then integrated to perform the desired functions. By that (highly subjective) standard, the solution posted earlier would be a poor one -> due to its tightly coupled / inter-mingled approach.

if I were to take a shot at this, I would consider the implementation below:

  key_state = read_keys(); //read keys / buttons, with or without debouncing
  led_process(key_state);  //process the key_state, and light up / off leds based on key_state

Essentially, you scan the keys / buttons, and based on that, turn on / off the leds.

All you need to do after that is to implement the individual functions based on your particular hardware design, or even software approaches: for example, read_keys() can be implemented in the isr, as can led_process().

A solution like this is highly portable: it works on pretty much anything that supports a C compiler, and is implementation-independent: the logic holds true, and all you do is to change the two functions to perform different kinds of lighting.

To me, modulizing your code is a huge advantage for a high-level language like C, and vital in taking on a real life project of moderate complexity.


Powering potientiometer/button with a digital pin

You can likely use an I/O pin as an output to "power" fairly high-impedance devices such as pullup resistors for buttons, or even potentiometers of moderate to high total resistance.
A reason you might wish to do so would to be able to stop the device from draining power while the entire system is in a low-power sleep mode, or to otherwise disable it beyond merely ignoring its input.
However, it's worth noting that powering an analog device such as a potentiometer from an I/O pin is likely to inject noise and full scale voltage uncertainty into the signal so derived, as the output voltage under load may be neither the same as the supply rail, not "quiet".
And, of course, you must not attempt to use an I/O pin to power lower-impedance (aka more "power hungry") loads via an output pin.  Generally, active devices should not be powered in this way - especially ones such as radio transmitters, other microcontrollers or complex logic functions, ultrasonic transmitters, and definitely not motors, relays, or solenoids.


Powering Arduino with 110v and controlling relay

In these cases where power must come from mains, my preferred solution is to buy a cheap phone charger+usb cable from ebay. They are sealed and safer than do-it-yourself solutions. The power adapter is barely larger than a normal plug for mains.

If you absolutely need to reach the arduino with only one cable, you can still use the solution i gave, only use a power cord to reach the contraption, then use a socket expander for mains and very short usb cable.


There are several ways to achieve what you want:

The way that does not work

Did you try to compile the code you gave in the question? Then you
probably noticed it does not compile. I tried and got: “error: expected
primary-expression before ‘]’ token”, meaning the compiler expected
return array[some_index];.

The way that almost works

Remove the brackets and just return array:

int *function()
{
    int array[3];
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

This may work, or not, depending on the surrounding code, on how the
optimizer processes your program, and on how lucky you are when you test
it. It is called “undefined behaviour” and is something you should
always avoid.

Here is what happens: in C (and C++) you cannot return an array. The
identifier array “decays” to a pointer pointing at its first element.
Then return array is essentially equivalent to return &array[0]. The
problem is that, since the array is allocated in the function's stack
frame, it ceases to exist when the function returns, thus the caller
gets a pointer to an area of memory that is not allocated anymore.
Likely memory corruption ahead. The compiler warned me when I tried to
do that: “warning: address of local variable ‘array’ returned”. It's a
very serious warning that should never be ignored.

The simplest fix: make the array static

As suggested by Chris Stratton in a comment, you can make the array
static, so it will be allocated for the whole life of the program:

int *function()
{
    static int array[3];
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

The only catch is that the function is now not reentrant, meaning that
every time you call it it will clobber the same array it returned on the
previous calls. Depending on your use case, this may not be an issue,
but it's something you need to be aware of.

Have the caller manage the allocation

A safer (reentrant) way is to have the caller provide the memory needed
for the array. This is a very common method in C, and is suggested both
by Harper Shelby's answer and Chris Stratton's comment:

int *function(int array[3])
{
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

The caller can allocate in static memory, or in it's own stack frame, or
on the heap... but you do not care, the allocation is the caller's
problem now.

A couple of things to note here:

The prototype is equivalent to int *function(int *array): the
function receives only a pointer. Writing array[3] instead of
*array has the sole effect of documenting that the function
expects the pointer to point to somewhere with room for 3 values. You
could document that in a comment instead.
The function could return void, since the caller presumably knows
the address it is giving you. Returning that same address is just for
convenience, as it can help you chain calls like
another_function(function(array)).

Return the array in a struct

One may wonder: why can't we return an array in the first place. I do
not know for sure why the authors of the language made this choice, but
one possible explanation is that it is expensive to return a big array
by value, as it involves copying the whole of it. Now, if your array is
really only three ints, then that argument does not apply, and you may
reasonably want to really return the whole array by value. This can be
done by embedding it inside a struct:

// Struct definition.
struct Array3 {
    int array[3];
};

Array3 function()
{
    Array3 a;
    a.array[0] = 19;
    a.array[1] = 7;
    a.array[2] = 69;
    return a;
}


can I create an on/off switch for my Arduino using the reset pin?

Tests show that connecting Reset to Ground on a Uno reduces the power consumption from 47 mA to 41 mA. So it is hardly "off".

All that would do is stop the currently-loaded sketch running, and save a few milliamps.


Error in my Arduino code " error: expected unqualified-id before ‘if’ "

C is procedural language and code is compiled. You cannot put code beyond procedure as you try to do in mentioned if. Remaining code following this point is nonsense. Do you mean you can put second loop() based on if condition ? I recommend to start learning programming C before using Arduino. In C you can do such a idea using preprocessor directives IF, ELSE, ENDIF.


You will likely find the best accuracy is derived from a laser-based measurement. My Bosch is laser only, no ultrasound component and has 1/16" resolution. For your application, the six inch minimum distance limitation of the Bosch is outside your specifications.

Because laser measurement devices use time versus distance, it's possible you could construct a mirror chamber with front-surface mirrors that would cause the laser to travel six inches before exiting the chamber, overcoming that limitation. The calibration should be straight-forward, as you'd place the chamber flush and adjust your mirror placement until you read the exact expected compensation distance.

You would need only small mirror panes, which would not "break the bank," but if you find a discarded large-screen projection television, the mirror within is front surface and quite large. Front surface mirrors should not have contamination from touching and should be cleaned with care, as you can erode or otherwise degrade the reflective surface.

I found this site:
http://blog.qartis.com/arduino-laser-distance-meter/
which looks promising for a different model of laser rangefinder, although the creator has run into a stumbling block or two.

It would appear that the key is to overcome the minimum distance limitation, perhaps as I suggested above, and interfacing with serial communications of the arduino.

One of the links I pursued involved the creator contacting the technical support of the manufacturer. The support ticket was closed as "resolved," in the manner of advising the user that the warranty was void by opening the case. Yeah, like that matters to makers and hackers!


How do I properly receive MIDI with Arduino, with 6n138?

Most start at the midi site at playground.arduino.cc.  But there are numerous web sites across the Internet.  It is important to understand that the MIDI interface uses a current loop to send and receive data.  While the Arduino normally uses voltage levels to communicate.  As such, an electronic interface needs to be built or bought to convert between these two types of signals.  Some interface designs are simple and limited.  Others are complex and robust.


Error when compiling code NODE MCU ESP8266-12E module in Arduino ide

The section

void loop() {
}

Is missing in the code, add it and recompile and.....


Switching lights by Harry Potter themed voice commands

This might be a hard project to start with.

First, you need to process the 'voice' from the microphone. This will be probably impossible on an Arduino.

Than you need to program everything, can be quite complicated (for a beginner).

Making something respond to 'any' sound is easier and can be done by Arduino and limited programming. Voice recognition is completely different.


control a jack/cylinder to open/close a window

Check out this instructable - for opening a window for a cat :)
The guy used a servo, Towerpro MG995 with 10 kg torque for opening/closing the window, and a 10cm distance sensor for sensing the cat (he used Pololu Carrier with Sharp GP2Y0D810Z0F Digital Distance Sensor, but I believe that any proximity sensor will do).

This is a pictrure of the mechanism, seems quite robust:


Arduino Uno CTC mode interrupt is not tiggering

There are a few issues with your code:

First, you should completely overwrite the timer control registers
rather than changing single bits. For example, when you write

TCCR0A = TCCR0A | (1<<WGM01); // Clear counter on compare match mode

You end up with a timer mode that results from the combination of the
bits that were already set there and the ones you are setting. Judging
from the comment, you assume that this will be CTC mode, but this is not
granted, because the Arduino initialization routine has already set some
bits in this register. Since you are taking the timer for your own
usage, just overwrite all the control registers:

TCCR0A = (1<<WGM01); // Clear counter on compare match mode

and same for TCCR0B and TIMSK0.

The second problem is that you misread the “Clock Select Bit
Description” table from the datasheet. Your timer is being clocked from
an external clock source on T0 pin. Presumably you have nothing
connected there, so the timer does not increment. You probably meant

TCCR0B = (1<<CS00) | (1<<CS02);  // Prescaling by 1024

A smaller issue is your delay loop. The program would be easier to
understand if you instead use a proper delay function. The Arduino
delay() will not work, as you have reconfigured Timer 0, but you can
use _delay_ms() from the avr-libc if you #include <util/delay.h>.


Getting stable measurements with the BNO055 IMU

Try a permanent calibration. From the Adafruit forums:

  You'd basically need to read and write data registers 55-6A. In both cases, you have to set the sensor in CONFIG_MODE. There's more information on page 48 of the datasheet.

The magnetometer is influenced by surrounding magnetic sources like motors. You might be able to tell the extent of the effect using the following method:

  The System Calibration Status will start out at 0 and will go to 3
  when the sensor is calibrated. For example, the mag calibration status
  will go to 3 if you do some figure 8s. If you put a piece of metal
  near the sensor, the calibration status will drop to 0. But when the
  metal is moved away, it will go back to 3. You may be able to use this
  value as an indicator that calibration is lost. I have found that once
  it's calibrated, it seems to hold calibration well.

For getting solid readings out of the gyroscope, this might be helpful advice:

  I don't worry about scaling the gyro output on a per-sample basis. I simply sum the output into a 32 bit (or larger) integer register. I do subtract-out a null value at each sample, which I will talk about later. But essentially, if you sample your gyro at 1kHz, and sum the output into an accumulator, you will see that the value of that accum at any time will be directly proportional the angle of rotation. If your rate is set for 250 deg/sec, then a rotation of 180 deg will result in approximately 23330000 in the accumulator. I call that the GYRO_CAL number. So, at any given time the angle, in degrees, is deg = accum / GYRO_CAL * 180.

  Since the gyro output is linear, the accumulator is insensitive to
  whether the rotation is fast or slow (as long as the max deg/sec isn't
  exceeded).

  Here is my basic routine for each gyro reading:

void read_FIFO(){
       sample = read_value_from_FIFO();   //read the latest z-axis sample. I use the fifo, but that isn't necessary
       accum += sample - null;           //add the sample to the sum and subtract the null
       if((accum > GYRO_CAL) -= GYRO_CAL*2;  //roll the accumulator at +180 deg.
       if((accum < -GYRO_CAL) += GYRO_CAL*2; // roll the accumulator at -180 deg.
       angle = accum/GYRO_CAL * 180;   // convert to degrees
}

  I calculate the null at the beginning of each run. I sum 1000 readings
  and take the average. The gyro has to sit still for 3 or 4 seconds for
  this. The GYRO_CAL value can be calculated by summing the output while
  you rotate the gyro by 180 deg. Or you can sum over many turns, and
  divide by the number of 180 deg turns for a more accurate value.

  You could probably use a 64-bit FP for the accumulator, but since
  arduino only supports 32 bit FP, I found it absolutely necessary to
  use a 32 bit integer to avoid roundoff and other errors.

  If you follow that general outline, I promise you will get rock solid
  performance out of the gyro. There are a few other small optimizations
  that I make, which I can discuss later.


Is there an alternative to strtok_r in extracting words from char?

The function you are looking for is strstr(), which takes two strings, and returns a pointer to where the second string appears in the first (or NULL if it doesn't appear).

You could use it something like this:

void setup() {

    Serial.begin(15200);
    Serial.println("Load");

    char *p = strstr(payload, "ssid=");
    char *q = strstr(payload, "pass=");
    char *r = strstr(payload, " HTTP");

    char *ssid = NULL;
    char *pass = NULL;

    if (p == NULL || q == NULL || r == NULL) {
        // One or other (or both) missing - what to do?
    } else {
        *r = '\0';  // Terminate the last string

        // If this really is an HTTP query string, we don't know
        // if ssid or pass will be first
        if (p < q) {    // Terminate the first string
            *(q - 1) = '\0';
        } else {
            *(p - 1) = '\0';
        }

        ssid = p + 5;
        pass = q + 5;

        Serial.println(ssid);
        Serial.println(pass);
    }
}

Note, however, that your payload string looks like an HTTP query string.

These are defined so that they are split at the & characters, and if a & needs to appear in one of the values, it should be percent encoded (where the & would appear as %26, and would need to be decoded afterwards).

However, that wasn't your question...


The library just calls os_timer_setfn and os_timer_arm which will call the callback function after some time. To add the feature to see how many remaining time there is, you would need to extend the library (the Ticker class, specifically) to save a timestamp when the timer was started. You can then write a function which returns for how much time is remaining or has passed by doing uint32_t remaining = timestamp_now() - timestamp_started.

A good function to hook would be the _attach_ms in Ticker.cpp. Add a uint32_t timestamp_started variable in the Timer.h header for the class. Then set timestamp_started = system_get_time() (from user_interface.h). Then write a function uint32_t remainingUs() { return system_get_time() - timestamp_started; }. Beware of integer overflows -- system_get_time returns passed microseconds since µC startup.


Details about SPI at SPI - Serial Peripheral Interface - for Arduino

This isn't right:

  SPI.transfer(CMD_ADC_READ); // send ADC read command
  SPDR = SPI.transfer(0x00); // send 0 to read 1st byte (MSB)
  ret = SPDR;
  temp = 65536 * ret;
  SPDR = SPI.transfer(0x00); // send 0 to read 2nd byte
  ret = SPDR;
  temp = temp + 256 * ret;
  SPDR = SPI.transfer(0x00); // send 0 to read 3rd byte (LSB)

The SPI library handles SPDR for you. Writing to it yourself will corrupt its behaviour.

It should be more like:

  SPI.transfer(CMD_ADC_READ); // send ADC read command
  ret = SPI.transfer(0x00); // send 0 to read 1st byte (MSB)
  temp = 65536 * ret;
  ret = SPI.transfer(0x00); // send 0 to read 2nd byte
  temp = temp + 256 * ret;
  ret = SPI.transfer(0x00); // send 0 to read 3rd byte (LSB)

Ditto for elsewhere.


W5100 Ethernet shield DHCP fails with a Switch

A certain way to debug this is to use tcpdump to capture network packets from both Arduino and your laptop and check the differences. I would start by looking for DHCPDISCOVER packet that Arduino should be sending.

A simpler way would be to check DHCP server logs to see how the communication looks like from server's perspective. Here, you should be looking for lines which have the MAC address of your Arduino shield. The success of this approach will depend of the verbosity of the DHCP server you're using.


The DS18B20 is a 1-Wire device and doesn't require a multiplexer, each device has its own address on the bus and you can connect a lot of them with a single wire. Depending on the humidity sensor you pick you may be able to use the same bus for it as well.

It is harder to find 1-Wire humidity sensors, but you could use a DS2438 Smart Battery Monitor which also includes an ADC to give you values from an analog humidity sensor.

The challenge of designing your project will be setting up an easy to understand display and controlling how/when it changes.


Change first line:

    // Set PB1/2 as outputs.
    DDRB |= (1 << DDB1) | (1 << DDB2);`

to the

     // Set PB5/6 as outputs. [**Digital pin 11,12 on Arduino Mega!**]
    DDRB |= (1 << DDB5) | (1 << DDB6);

Now your PWM should work, but on digital pins 11 & 12 [Arduino Mega].


Is there complex application examples out there that can be considered best practice material?

If you are used to OO (which I guess since you like separation of concerns), do not use the Arduino IDE, since it is very hard to work with multiple files. Instead use e.g. vMicro for Visual Studio.

Separation of concerns (using C++) for the Arduino is not much different than in other languages. C++ has the notion of classes, and fields/functions can be made private, protected and public (simplified).

However, C++ itself is not so easy to learn, mostly because of pointers and related issues. However, it's something to dive in when you want to learn something new.


Library, instantiation of a class object

The statement

Minimal_library obj(BUF_SIZE, buff);

means “create an object named obj, initialized by calling the class
constructor with the supplied parameters”.

On the other hand,

Minimal_library obj = Minimal_library(BUF_SIZE, buff);

means “create an unnamed object initialized as before, then copy it
into an object named obj, then delete the unnamed object”.

The compiler would normally optimize the second form into the first one.
It is even allowed to do so in some weird cases where they may not be
equivalent. In the end, it's mostly a matter of style. I prefer to do
the optimization myself and write the first form. But if you find the
second form more readable, go ahead: you can normally trust the compiler
to optimize out the unneeded copy.


Detect certain characters and if not a consequence

I would rewrite that as something like this:

void lerRespostaUtilizador(){
  while (!Serial.available());
  switch(Serial.read()){
    case 's': // Mostrar sinais de controlo
      mostrarSinais();
      break;
    case 'v': // Mostrar variáveis do sistema
      mostrarVariaveis();
      break;
    case 'r': // Mostrar conteúdo de registos
      mostrarRegistos();
      break;
    default:
      Serial.println(F("Podes visualizar: (s)inais de controlo, (v)ariaveis do sistema e conteudo de (r)egistos."));
    }
}


Assuming you understand how the ternary operator works, the statement is simply toggling the currentmode between its two possible settings.

if you do not understand ternary operators, it can be re-written as:

if (currentMode == MODE_IDLE) {
  currentMode = MODE_RUNNING;
} else {
  currentMode = MODE_IDLE;
}

You should read up on the ternary operator.  It appears in several languages in various formats and can come in handy in a variety of situations.

In general terms the ternary operator is of the following form (as used in an assignment):

result = (booleanExpression) ? (value if true) : (value if false);

but you can use it in other contexts for example in a function call:

someFn(booleanExpression ? trueValue : falseValue);


Yet another basic and silly question about C++ strings

The return value of strcmp does not have boolean semantics, as you seem to incorrectly assume.

strcmp is a tri-state comparator, which returns negative, zero or positive value. For equal strings it returns zero, which means that an equality comparison with strcmp should normally look as follows

if (strcmp(str1, str2) == 0) Serial.println("Equals");
else Serial.println("Different");

while your original code actually does the opposite.

There's a moderately widespread ugly habit of writing such comparisons as

if (!strcmp(str1, str2)) Serial.println("Equals");
else Serial.println("Different");

(note the application of ! operator). It works properly, but it has poor readability. Avoid it. For tri-state comparators is a much better idea to spell out the comparison with 0 explicitly.

And you made exactly the same mistake with memcmp. memcmp is also a tri-state comparator, so it should be

if (memcmp(str1, str2, sizeof str2) == 0) Serial.println("Equals");
else Serial.println("Different");

The same applies to strcoll.

P.S. And in fact such zero-terminated strings represented by char[] arrays are called C-style strings, not C++-style strings.


Debouncing results in no reaction at all

It's difficult to tell without seeing your circuit, but it looks like there could be a mix up between pin 12 and pin 8.  Can see that you initialize the pinMode for pin 12 in setup, but it isn't used in the loop.  You didn't initialize pin 8 (not completely necessary) in setup, but it is used in the loop.  If you don't feel this is relevant, please provide some more detail.


Is it possible to program an ESP8266 12F using an Arduino Nano?

Yes, you can program it with Arduino but its a bit complex that way. You will need a separate Linear Regulator with Adjustable Output to get it hooked up with the Arduino.
 Its way better to have an FTDI adapter to program it.

But if you still want to know, there is a tutorial below,

Upload Bareminimum sketch so that no program is running on the Arduino.


Connection problem with Arduino Mega 2560 and GSM shield ( official M10)

I have done this, and had (some limited) success.

A couple of your connections are wrong;
Connect both the pin 7s on the shield and MEGA, not the pin 4s. Pin 7 is the reset pin - I think that GSM.begin resets the shield before doing anything. This might help with Q1.

Make sure that you use the regulated 5V output on the MEGA, and not the Vin to power your shield. Vin is whatever voltage is connected to the MEGA power socket, and could damage your shield. I personally have not noticed any difference when powering the MEGA+Shield from USB or external 12V supply.

I had problems with interference when I used wires to connect shield to MEGA. The stacking seems to have reduced this problem, but not eliminated it by any means...

The GSM Web server is unlikely to work except maybe from within your SIM provider's own network. Some of the limitations are mentioned here;
https://www.arduino.cc/en/Tutorial/GSMToolsTestWebServer


ATTiny 85 analog input pin number problem

See the analogPinToChannel function.

static const uint8_t A0 = 6;
static const uint8_t A1 = 7;
static const uint8_t A2 = 8;
static const uint8_t A3 = 9;

...

#define analogPinToChannel(p)   ( (p) < 6 ? (p) : (p) - 6 )

Using A2, which is 8, will return 2 (8-6) from the analogPinToChannel function.

Using 4 will give 4. There is no (useful) analog channel 4.


How to detect Genuino 101 from inside the code?

Arduino defines some macros so you can use conditional compilation. For example these are from boards.txt:

use ARDUINO_AVR_PROMICRO if it's specific for board variant
use ARDUINO_ARCH_AVR if it's specific for Arduino with AVR

Also avr-gcc defines macros according to cpu settings (this should be similar for other platforms too):

use __AVR_ATmega32U4__ if it's specific for only one MCU
use __AVR__ if it's compatible with all AVR based MCUs

And code examples:

#if defined(__AVR_ATmega88__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__)
// something for ATmegaXX8 family...
#else
// ...
#endif

#ifdef __AVR__
// Code related to AVR
#else
// Code for other architectures
#endif

More about predefined macros in avr-gcc.


One of the LEDs on my Arduino is very dim

You need to add this line for the other LED pin:

pinMode(ledPin2, OUTPUT);


TimeAlarms stops working when using setSyncProvider(RTC.get) DS1307

Problem existed in the TimeAlarms library,

Q: How many alarms can be created?
A: Up to six alarms can be scheduled.
The number of alarms can be changed in the TimeAlarms header file (set by the constant
dtNBR_ALARMS,
note that the RAM used equals dtNBR_ALARMS  * 11)

so how I fixed it was to edit #define dtNBR_ALARMS 6  // max is 255 to #define dtNBR_ALARMS 14   // max is 255 in the TimeAlarms.h file.


All numbers are integers?
If yes, you can use toInt() function.

int secondValueInt, thirdValueInt;

secondValueInt = secondValueInt.toInt();
thirdValueInt = thirdValue.toInt();


Arduino Mega Timer1 in pure C problem - doesn't work

I work with documentation program doesn't work completely.

simple:

1) check out the datasheet;
2) identify those registers needed to get tmr1 to work;
3) set or clear, as appropriate, ALL bits that are needed. Do NOT rely on default values.
4) done.


Audio Frequency White Noise generation using Arduino Mini Pro

I don't know that you need all that - just an Arduino and a piezo speaker and a pot if you want to play with the volume.
void generateNoise() {
    unsigned long int newr;
    unsigned char lobit;
    unsigned char b31, b29, b25, b24;
    b31 = (reg & (1L << 31)) >> 31;
    b29 = (reg & (1L << 29)) >> 29;
    b25 = (reg & (1L << 25)) >> 25;
    b24 = (reg & (1L << 24)) >> 24;
    lobit = b31 ^ b29 ^ b25 ^ b24;
    newr = (reg << 1) | lobit;
    reg = newr;
    digitalWrite (speakerPin, reg & 1);
    delayMicroseconds (50);  // Changing this value changes the frequency.
}


Your problem stems from you starting out with 30 values of 0 which you include in your average.  You have to take that into account and ignore those values, dividing your total by only the number of actual values you have.

I have a library that does it all for you that would make things easier for you:

https://github.com/MajenkoLibraries/Average


Utilizing two different serial ports simultaneously on a due

You can't use MIDI on Serial and use Serial.print at the same time. You can though use MIDI on Serial1 and use Serial.print at the same time (or Serial2 etc).


Based on your description, the program needs to know only the new target setting and the current position. That means you need two variables. Algorithmically, it would look as follows (written in C-like pseudo-code):

// initialize global variables (might need float instead of int)
int target_pos = 0;
int current_pos = 0;

void setup() {
    // add code to set up pin IO mode, prepare communication with the sensor...
}

// function to read the sensor
int ReadSensorFunc(void) {
    int reading = 0;   // local variable to store sensor reading
    reading = ...;     // add code to read sensor
    return reading;
}

// function to adjust the motor position
void AdjustStepMotorFunc(void) {
     // add code to to adjust the stepper to (target_pos-current_pos);
}

void loop() {  // repeat forever
    target = ReadSensorFunction()   // call sensor read function
    AdjustStepMotorFunc()           // call position adjustment function
    current_pos = target_pos        // update current position
    // add code to delay for 10 minutes
}

This code initializes the position as zero. In case it's not zero when the controller is turned on, you'll need additional code in setup() to assign current_pos the correct value based on user input.


Your function is only returning a value when everything works OK. If an error occurs, the problem is reported to serial but it doesn't return anything. It seems likely that this could cause stack corruption which could make the program stop.

A simple solution would be to put return 0; (or some other number) just before the end of the function.


How to select hardware for my Arduino board?

For your first project, power the Arduino Uno with the USB cable and use everything at 5V.
There are tutorials which guide you step-by-step to make something. The Adafruit tutorials are very good.

The HDC1080 is a sensor that works at 3.3V and at 5V. That means you can use it with the 5V Arduino Uno without problem.
This Tindie HDC1080 module points to a HDC1080 library on Github. I suggest you try to make that work.

If you can not get data out of the sensor, then you should start with something very simple. A few leds (with series resistors) or a LDR light sensor is fun to start with.

As soon as you start using higher voltages (for example 12V) you might consider buying a spare Arduino Uno, because the Arduino Uno will be blown when 12V touches one of the pins.

Be also careful with sensors that can only handle 3.3V and not 5V. Since the Arduino Uno runs at 5V, a pin of the Arduino could feed 5V into the sensor and damaging the 3.3V sensor.


Seems like there is a problem in your wall wart, actually some people are having problems using wall wart with arduino. The problem is with the circuit of thre arduino regulator and with sime ripple variances with de wall wart, i sugest you to setup in your project a regulator (7805) and see if the problem is gone. This is by far problem not just with grounding, but with the power suply in general. I was used to make PIC projects and once it was happening exatly the same that happaned to you but the microcontroller started to work when i put my hand or finger close without even touching it :x. Crazy thing. If the power supply isn't well suited, the arduino enter in continous reset looping because of supply noise. So just put an external regulator, an maybe an extra capacitor (generally 10 nF) in arduino micro power supply rais (VCC-GND). Here's my tip. Good look man, tell me if it worked :)


Good way to get automatically generated code into a sketch

According to the release notes starting with V1.5.2 of the IDE you can verify and upload from the command line.

You could use your favorite editor and then use the command line to do the arduino build/upload instead of the IDE.

See: https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc

I have not used it so I can't say if it work well or not.


The documentation implies you have to combine pins 3 and 4.
Here is a circuit diagram:
https://www.pjrc.com/teensy/gui/img/pwmdualcircuit.jpg

Source:
https://www.pjrc.com/teensy/gui/?info=AudioOutputPWM


Arduino due erase button and power switching

The asker posted the same question and received an answer here
There is discussion regarding the purpose of the Erase switch here


As you say, SIM800L default baud rate is 115200. So, you have to set that baud rate on arduino side. And yes, it is possible to run an ATmega328P at a baud rate of 115200 baud.

You can use the SoftwareSerial library and define your own tx and rx pin and set baud rate according to your requirement.

#include <SoftwareSerial.h>   // SoftwareSerial library
SoftwareSerial mySerial(2,3); // RX, TX for your module

void setup()
{
   mySerial.begin(115200);      // Set your buad rate
}

And you can also do without this library.

void setup()
{
  Serial.begin(115200);        // Set your baud rate
}