Is two modules using Serial Interface on one Arduino Uno possible?

You are right, that you need one Serial interface for each module. The Uno has only 1 hardware serial interface (hardware means, that the Arduinos hardware will do the communication work in the background and you can let it do other things in the meantime). But you can add more serial interfaces, on other pins, that work purely through software. For this the SoftwareSerial library is meant.

SoftwareSerial comes with some limitation, since the load of communication has to be done in software instead of hardware. For example it becomes unstable at high baudrates. Especially for the HC-05 you should not use baudrates of 115200 baud and higher. Also - since it uses pin change interrupts to work - you can only listen at one SoftwareSerial at any given time.

Since you only have 2 modules, it should be easily possible, to utilize SoftwareSerial and access both of them with the Uno. If you at some time want to use more serial modules, you can still change to a bigger board like the Mega.

Note: Be sure to disconnect the module from the hardware serial, before programming the Uno over the Serial interface (USB), or the programming will fail.


It all depends on how used to you are with using pi or arduino. What you want can be done in both ways.
The displaying of count is common for both. It can be done using a 16X1 LCD display, 5 different 7 segment LED connected via decoders or a graphic display module. Interfacing all these with Arduino will be relatively simpler than Pi.

For the fetching of data and sending it to your device for displaying it. You can use ESP8266 Wi-Fi module with arduino and pull the data. Which is not as simple as it sounds but it is not impossible too.

For pi, (like @max246 said) you can run a python script and use another api to get the data.


How to switch on 32A/240VAC with Arduino?

I don't want to try anything that results in a fire hazard.

That's a good idea.

Besides those toy relays there are real ones:
440 V AC * 63 A (Around there, you can find smaller ones too)

BTW: Don't rely on what's printed on the relay itself, with cheap Arduino relay modules. 230V and some current need proper handling by the PCB board as well (size and distance of the copper tracks on the scondary side)

If you want a solution that could be certified (or certifiable) as "safe" there probably won't be an Arduino involved or being built by anyone asking questions like you do  ;(   (sorry)


Answered by Edgar Bonet

There needs to be an empty line between the headers and the body of the request. Therefore you have to println() (not print()) the end of the last header.

Please accept this answer so the system knows it is the correct one.


How to purge incoming Xbee packets from the buffer?

It means there's a lot of latency between your issuing a command and getting a confirmation of the command's effect. When you send the command, it's best that you wait and read packets until you find the confirmation and then you return from the function or do whatever else you want to do. There is no need for a separate burnSerial() function, nor should you blindly discard data. So basically, the sequence of operations should be:

Send the command
Read packets until you find the 'confirmation' identification marker
Return or exit

This assumes that your transmitter only sends confirmation after it has halted the stream.


Power supply...

I designed a pcb for the ESP module, it works like a charm since then. Used a TC1262 regulator, a 100n ceramic and a 1000u electrolyte capacitor (maybe 100u would have been enough) very close to the Vcc and GND pins.

Seems like the ESP is really sensitive to the power supply stability.


Does data coming in on Arduino serial port store for some time?

Yes.  The serial port uses a ring buffer (also known as a circular buffer) for storing the incoming data until you want it.  That buffer is 16 bytes in size on the smaller Arduinos and 64 bytes in size on the larger one.  A similar ring buffer is used to store transmitted data until the port is ready to transmit it in the background.


There are several audio products/shields.  Because you mention "speakers", the first one listed can come with an on-board amplifier to drive speakers directly.  Most shields just give line-out to drive a pre-amp.

Adafruit Music maker shield plays MP3/WAV/OGG from microSD http://www.adafruit.com/products/1788
Adafruit Wave shield plays WAV files on SD card http://www.adafruit.com/products/94
SparkFun MP3 trigger board supports 256 tracks and a serial protocol for running individual tracks. https://www.sparkfun.com/products/11029
SparkFun MP3 shield board plays MP3/WAV/OGG https://www.sparkfun.com/products/10628


Can I receive data on the Arduino by sending data to /dev/ttyACM0?

Use Serial.read() there are plenty of examples that come with the Arduino IDE, just make sure the baud rates on the Raspberry Pi and Arduino match.


fatal error: avr/io.h: No such file or directory

The Due is SAM architecture. avr/io.h is specific to the AVR architecture of the Uno's microcontroller. The compiler will not look in the avr tools folder for that file and even if it did it wouldn't help because that file is not compatible with the SAM architecture.

This error indicates that part of the code you're attempting to compile (probably a library) is AVR specific. You will need to either port that code to the SAM architecture or find an alternative that is already compatible with Due.


Bluetooth not transmitting refreshed sensor values

That's an incredibly complex way of outputting a floating point number as a string. You may possibly be fragmenting RAM with your use of String, and those String additions. Try replacing:

  uint8_t sendbuffernew_x[20];
  char buff_x[20] = "";
  String xorient = "";
  dtostrf(event.orientation.x, 4, 1, buff_x);  //4 is mininum width, 6 is precision
  xorient += buff_x;

  xorient.getBytes(sendbuffernew_x, 20);
  char sendbuffersizenew_x = min(20, xorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_x, sendbuffersizenew_x);
  memset(sendbuffernew_x, 0, sizeof(sendbuffernew_x));

  uint8_t sendbuffernew_y[20];
  char buff_y[20]= "";
  String yorient = "";
  dtostrf(event.orientation.y, 4, 1, buff_y);  //4 is mininum width, 6 is precision
  yorient += buff_y;

  yorient.getBytes(sendbuffernew_y, 20);
  char sendbuffersizenew_y = min(20, yorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_y, sendbuffersizenew_y);
  memset(sendbuffernew_y, 0, sizeof(sendbuffernew_y));

  uint8_t sendbuffernew_z[20];
  char buff_z[20]="";
  String zorient = "";
  dtostrf(event.orientation.z, 4, 1, buff_z);  //4 is mininum width, 6 is precision
  zorient += buff_z;

  zorient.getBytes(sendbuffernew_z, 20);
  char sendbuffersizenew_z = min(20, zorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_z, sendbuffersizenew_z);
  memset(sendbuffernew_z, 0, sizeof(sendbuffernew_z));

by:

  char buff[10];

  dtostrf(event.orientation.x, 4, 1, buff);
  BTLEserial.write(buff, strlen (buff));
  dtostrf(event.orientation.y, 4, 1, buff);
  BTLEserial.write(buff, strlen (buff));
  dtostrf(event.orientation.z, 4, 1, buff);
  BTLEserial.write(buff, strlen (buff));


Newbe needing help with fixed string length

The printf() family of functions comes handy when you need
this kind of control over the formatted output:

/*
 * Format a number as 5 characters.
 * Returns the string in a statically allocated buffer.
 */
char * format5(int x)
{
    static char buffer[6];  // 5 chars + terminating NUL
    snprintf(buffer, sizeof buffer, "%5d", x);
    return buffer;
}

void setup() {
    Serial.begin(9600);
    Serial.println(format5(15));
    Serial.println(format5(-15));
    Serial.println(format5(-1500));
    Serial.println(format5(1500));
}

void loop(){}

output:

   15
  -15
-1500
 1500


How to find the index of the maximum value in an array?

First of all, do you really need int values for the measurements or not? If not, and you have numbers between 0 and 255, switch the values to byte, your microcontroller will thank you.

Then, there is a problem with the other answers, which is... The variables cannot be left uninitialized!!! You can use this code to get the info you need:

(I also put the size of myMeasurements in a const variable.. You can thank me later for this)

const byte maxMeasurements = 9;
int myMeasurements[maxMeasurements ]={3,4,8,12,7,2,1,67,8};

byte maxIndex = 0;
int maxValue = myMeasurements[maxIndex];

for(byte i = 1; i < maxMeasurements; i++)
{
    if(myMeasurements[i] > maxValue) {
        maxValue = myMeasurements[i];
        maxIndex = i;
    }
}


Is it possible to use two encoders with Arduino Uno?

It is very possible. use a separate interrupt pin for Phase A of both motors, then read phase B from a non interrupt pin in the interrupt handler.
http://www.spiked3.com/?p=5501


ESP8266 Send data to Firebase using Arduino Uno error

1.) Can I input/flash code in my module using my arduino and adapter?

Yes

  2.) Since the button is plugged in the pin 8 of arduino. Does that mean If the code in the module will be successfully inserted. I will still need the arduino to be plugged in the buttons?

The ESP8266 cannot magically know about the Arduino and the Arduino cannot magically know about the buttons. If you have buttons connected to the Arduino then the Arduino needs telling about them. If the Arduino and ESP8266 need to work together then they both need programming to work together. If, and only if, you connect the buttons to the ESP8266 and not the Arduino do you not need the Arduino.

  3.) What could be the reason why the module won't appear in the Port List and generates the errors?

The Arduino is getting in the way. Connect Arduino RESET to Arduino GND to disable the ATMega328p chip which is also trying to use TX and RX and conflicting with the ESP8266. Or better still get a cheap USB to UART cable (just a couple of dollars on eBay) and connect the adaptor direct to your PC without the Arduino.


The problem is that the buffer is not initialized to start with. When
you call parseSerial(), it contains garbage, which is what you see on
the serial monitor. In order to avoid printing out that garbage, you
have to properly terminate the string, i.e. add a \0 after the last
valid character.

You did that after printing the string (you filled the whole buffer
with \0, which is overkill), but that's too late. The subsequent
printouts are OK though.

The recommended way to handle incoming serial data is to look for a
terminating character (\r seems to be what you expect), and buffer
all the incoming bytes until you see it. Don't forget to save 1 byte of
buffer space for the terminating \0:

void parseSerial() {
    static char buffer[20];
    static int count = 0;

    while (Serial.available()) {
        int c = Serial.read();
        if (c == '\r') {           // received complete line
            buffer[count] = '\0';  // terminate the string
            Serial.print(F("You said: "));
            Serial.println(buffer);
            count = 0;
        }
        else if (count < sizeof buffer - 1) {
            buffer[count++] = c;
        }
    }
}

Notice that the buffer here being static, you can accumulate partial
messages through successive calls to parseSerial(). Only when the
message is complete will it print it back.


How to connect an Elegoo Nano to a Raspberry Pi and program it?

The Elegoo website has a downloads page which contains the drivers.

Using the Raspberry Pi, download the zip file containing the drivers.
Unzip the contents to a location of your choice. (Also see here)
Change to the directory containing the Linux driver source files (ie CH341SER_LINUX).
In the terminal type make. Let it compile the driver.
In the terminal type make load.

Done


First I'll tackle what

TCCR0B=TCCR0B&0b11111000|0x01;

means from a pure programming perspective:

Let's break it down into parts:

TCCR0B = TCCR0B & 0b11111000 | 0x01;

TCCR0B is a register. It could be any variable really - it's just "a value" in this context. Just because it happens to control one of the timers is besides the point.

0b11111000 is a binary representation of a value.  It's the same as the hexadecimal number 0xF8.  F is 15.  15 in binary is 1111.  8 is 8 in both hexadecimal and decimal.  8 in binary is 1000.  Put the two together and you have 11111000.  Incidentally, in decimal that is 248.

0x01 is hexadecimal for 1 in decimal - it's also 1 in binary.

Between them are bitwise operators - & is a bitwise AND operation, and | is a bitwise OR operation.  AND calculates which bits in a pair of binary numbers are both on, and OR calculates which bits in a pair of binary numbers are on in either of the numbers.

So take the first one first.  Say the TCCR0B register contains the value 0x6F, which is 157 in decimal, or 01101111 in binary.  The first operation is to AND that with 11111000:

01101111
11111000 AND
--------
01101000

You can see that the last three bits of the value have been cleared because they aren't 1 in both the left and right operands to the & operator.

Ok, so the next operation is to OR it with 0x01:

01101000
00000001 OR
--------
01101001

Effectively the two operands have been overlaid on each other and any bits that are set in either operand will be reflected in the result.

So finally the value is then stored in TCCR0B.

In summary that specific operation clears the lower three bits then sets the lowest bit of TCCR0B.

Now what that actually means with respect to what the TCCR0B register does can be gleaned from the datasheet for the chip.  For instance, take the ATMega328P chip from the Arduino UNO board.  Page 109 of the datasheet describes that register in detail.  The bit-wise overview looks like this:

Those bits all correspond 1:1 to the binary bits from above in the same order.  So the first stage, clearing of the lowest three bits, sets CS02, CS01 and CS00 to 0.  The second stage, ORing 0x01, then sets CS00 to 1.

The datasheet goes on to tell you what those mean:

  Bits 2:0 – CS02:0: Clock Select

  The three Clock Select bits select the clock source to be used by the Timer/Counter.

And a table to show the different meanings of the possible values:

The value that has been masked and created for those three bits is, of course, 001, which in that table is "CLK I/O / (No prescaling)", which is the timer running at the frequency of the IO clock.  If you were to set those bits to 010, you'd get "CLK I/O / 8 (From prescaler)".  So your masking would change to:

TCCR0B = TCCR0B & 0b11111000 | 0x02;

Or more explicitly so you can see the bits easier:

TCCR0B = TCCR0B & 0b11111000 | 0b010;

As to what the "A" and "B" mean (TCCR0A and TCCR0B), there are two registers that are used to control the timer.  They each serve a different purpose.  TCCR0A has bits that control PWM, and TCCR0B has bits that control the timer itself.

Not to be confused with OCCR0A and OCCR0B which are two separate numeric values that are compared to the timer's counter value TCNT0 to provide two separate PWM outputs synchronised from the same timebase.


There was no common GND between the H-Bridge and the Arduino.

The question has been solved.


What is the function of the XBee / USB switch on an XBee shield?

In case someone does ask the same question in the future, this is the explanation for the USB/XBee switch functionality on the XBee Pro Shield V3
The switch serves to connect/disconnect the XBee Pro shield v3 to the Hardware TX->1 & RX<-0 Lines of the Arduino. Moving the switch to the USB side, allows you to disconnect the XBee Pro shield v3 from the hardware serial lines and upload code to your Arduino. If the switch is on the XBee side, this allows your XBee Pro shield v3 to use the TX->1 and RX<-0 lines of the Arduino and if you want to upload code to your Arduino, you would have to remove the shield otherwise it would result in an error trying to upload code.


What does []() argument in function mean?

That is called a lambda expression and it's a way of including the content of a function as a parameter anonymously instead of writing an actual function and using the name of it.

It's shorthand for:

void myCallback(AsyncWebServerRequest * request) {
    // some code....;
    request->getParam("Param1")->value();
}

// ...

server.on("/page", HTTP_GET, myCallback);

It does have a few benefits over traditional functions at the expense of readability, such as the ability to "capture" local variables from the surrounding scope.


uint8_t is an Unsigned 8-bit Integer, and so the range of values it can represent are 0 to 255.

When you typecast your long/large values to uint8_t, you basically only show the least-significant 8-bits.

However, the decryptBlock() and encryptBlock() functions expect an array of bytes, not a single byte.

The library you link to notes, right in the linked position, that the output and input parameters must be at least blockSize() bytes in length. Referencing blockSize(), it notes that this function always returns 16. So you need to pass an array of uint8_ts of at least 16 length.

When you define your variables for the key, plaintext, and ciphertext, you need to not define then as a single byte type, but as an array of bytes:

uint8_t[16] key =    {1,2,3,4,5,6,7,6,5,4,3,2,1,2,3,4};  // This is not a good key, btw
uint8_t[16] output = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
uint8_t[16] input =  {9,1,6,4,5,6,7,6,5,4,3,2,1,2,3,4};

(When passing an array, you don't need to dereference the variable, so call aes128.setKey(key, 16);, etc. Omit the &)

Each of the 16 bytes can have a value in the range 0 to 255. They do not have to be limited to single-digit numbers; I just copied/translated what you wrote to demonstrate the example. You could set your key in this way:

uint8_t[16] key =    {66,127,164,72,68,158,148,255,23,36,226,192,198,248,251,221};

You can also refer to bytes with a 2-digit hexadecimal representation:

uint8_t[16] key =    {0xa6,0x09,0x81,0xc5,0xb8,0xf6,0x9a,0x33,0x75,0x24,0xff,0x79,0xd3,0x48,0x4f,0x1d);

UPDATE to address strings

A C-style string is a sequence of bytes, with type char to indicate ASCII data, though any byte-wide type could work in theory. The sequence of bytes ends with a value of 0 (i.e., 0x00, not the ASCII character '0'), so you must remember that the termination byte takes up a byte of memory.

To initialize your key with a string:

const unsigned char[17] key = "helloareyouarehi"; // 16 characters, and 1 byte termination means 17 total bytes reserved in memory.

I have not investigated how the crypto library you are using handles C-style strings, so let's assume it does not acknowledge them at all, and we will have to null-terminate our strings ourselves.

char[17] output = {0}; // Initialized to all zeros
char[17] input = "iwanttoencryptme";

aes128.encryptBlock(output, input);
output[16] = 0x00; // Just to be safe, put the null terminator in the last slot.

Serial.print(output);

If the encryptBlock() function only changes 16 bytes in the output array, then the 17th (zero) could remain from the initialization, but not knowing whether the function preserves strings, it is better to be safe than sorry.


Arduino Nano with CH340 reboots on OS X El Capitan

There is a new signed driver for OS-X El Capitan and Yosemite. This is all you want.

http://kig.re/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html


What are the environmental requirements of an Arduino?

The AtMega32u4 (the chip that drives the Arduino Yun) has an operating requirement of -40 to +85, so if you go outside that range, you will definitely void warranty (which is not to say it will break, of course!). See datasheet at http://www.atmel.com/devices/atmega32u4.aspx

A datasheet for the AR9331 seems to say that it only works down to 0°C ( http://www.eeboard.com/wp-content/uploads/downloads/2013/08/AR9331.pdf page 305, "Commercial Case Temperature") - this seems awfully high for a minimum temperature.

While that does not mean that, inside that range, you are safe, I would GUESS that you probably are - I would guess that the AtMega32u4 or AR9331 is going to be the most delicate part in there.

Of course, to get a definitive answer, you (or someone) would have to check the specs on each part.


SPI doesn't use interrupts.  It references the interrupt flag to know if a transfer has been completed, but it doesn't actually have interrupts enabled:

SPDR = data;
asm volatile("nop");
while (!(SPSR & _BV(SPIF))) ; // wait
return SPDR;

It should be perfectly possible to use SPI within the interrupt - indeed there is portions of the SPI API that deal specifically with this - see https://www.arduino.cc/en/Reference/SPIusingInterrupt for instance.


Unable to tell if error is from receiving or transmitting end

void loop() {
  Serial.println("NEW-------------");
  int x;
  int y[100];
  for(int i = 0; i<100; i++){
    x=RX.read();
    y[i] = x;
  }
...
}

You are reading data without checking if there is any data there. That's like watching the TV without checking if it is turned on. Of course you get weird data.

SoftwareSerial RX(0,1); //(rx pin, tx pin)

Pins 0 and 1 are used by HardwareSerial. Why are you using them for SoftwareSerial?

SoftwareSerial RX(0,1); //(rx pin, tx pin)
...

  Serial.begin(9600);
  RX.begin(1200);

So you initialized HardwareSerial, which now controls pins 0 and 1.

Then you try to initialize SoftwareSerial on those same pins! Would you mind explaining why?

Whatever your explanation is, it won't work.

  I've added in the changes you mentioned, but the data still seems to be skewed.

You've changed things, for sure:

 for(int i = 0; i<100; i++){
    if(RX.available())
      x=RX.read();

    y[i] = x;
    }

Let's see. In a loop of 100 iterations you see if anything is available (and if so, put it into x).

Then, regardless of whether or not you got anything you now assign x to y[i]. So, most of the time, y[i] will have garbage in it.

  the data still seems to be skewed

Not surprised. Do it differently. Only write to the array if you have data. In fact you may want a complete rework. Read this:

How to read serial without blocking

  I have posted the amended code. Change: Only add to the array is data is being read from buffer.

  int y[100];
  for(int i = 0; i<100; i++){
    if(RX.available())
    {
      x=RX.read();
      y[i] = x;
    }
  }

 for (int j = 1; j<=64; j++){
    Serial.println(y[j]);
  }

You still have not fixed it. Let me talk you through what it is doing now.

You are making 100 attempts to read some data. One or two may succeed, and they will be put into the buffer y (funny name for a buffer, right?).

So imagine . is garbage and X is good data, after doing that loop of 100 the buffer will look like this:

........X...........X...........X...X......................X.............................................

So your buffer is still 80% unchanged garbage. Then you print the first 64 elements (why 64 and not 100?) and you get a lot of garbage out. Exactly as expected.

You need to think about what you are doing. Draw it out on a bit of paper, perhaps.

Here is some example code from the page I linked for you, more than once. Please compare:

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop


HTTPS GET request working on esp32 but not on esp8266

I ended up using

ESP8266WiFi.h

instead of

ESP8266WiFiMulti.h

This fixed both my original code and the basic HTTPS example. I still don't understand what difference it made though.


Absolutely you can. Looking at the picture, this is set up for bipolar and a unipolar motor. There you have to wire according to the wire diagram.


What's the benefits between different interrupts on Arduino

Imagine that you have the circuit below:

simulate this circuit – Schematic created using CircuitLab

Let's say that you wanted to catch the user pressing the button. The input signal will go from high to low, which is a falling edge. So you would use a FALLING interrupt to catch this event. Easy, right?

Now let's say you wanted to catch a user releasing the button instead. This time the inverse is true, so you want to use a RISING interrupt.

You should note that since these interrupts are edge triggered, the simple circuit below would not be ideal. Without any debouncing, there may be several edges to trigger from, resulting in repeated interrupts. Also, given the analogue nature of the design, we can't be sure that the rise / fall times will be fast enough to trigger the edge interrupt. We can get around this by adding a 100nF capacitor across the switch and following by a Schmitt trigger (which I can't find a symbol for in the circuit editor!).

So to answer your question, you use the interrupt that is correct for the event you are trying to catch. The Arduino MCU implements both edges for completeness and flexibility in your design, so if this interrupt was coming from an external IC you have no control over the design of, you can easily match the interrupt to its behaviour without having to add in an inverter.


I could not find any info on the full size SD card adaptor, but the microSD adaptor has a 3.3V (LM1117 or equivalent) regulator on it. It, therefore, needs a minimum of 4.5V to operate.

To run the adaptor from 3.3V, you would have to remove the regulator and solder in a piece of wire in its place.


On the Arduino Serial.print() method web page it says:

  Prints data to the serial port as human-readable ASCII text.

...which is suitable for most terminal programs.  ASCII or American Standard Code for Information Interchange is (usually) an 8 bit code for printing characters.  It is not a code which you can do normal math with.  That is the integer 1 (which is, in binary, b00000001) is not the same as the character '1' (which is, in binary, b00110001).

Example: If you want to print "123" on most terminals you can use the Serial class method print:

Serial.print(123);

Now, you have to understand that the Arduino paradigm is to make programming simple.  So the print method in the Serial class will assume you want to see the characters "123" on the terminal.  So, guessing, the print method will convert each decimal number into an ASCII character and print them out as 3 values to the terminal.  That is, the ASCII value for 1, followed by the ASCII value for 2 finally followed by the ASCII value for 3.

If this is not what you want there are other variations for the print method in the Arduino Serial class.  But all tend to print using ASCII codes.

If you want to print out the binary values, see the Serial.write() method.  This method will send the value of the argument to the terminal with out converting into ASCII code.

Example: If you want to print "1" on most terminals you can use the Serial class method write:

Serial.write(49);

...as 49 is the decimal equivalent of the ASCII code for the character '1'.


Servos jitter when powered by power module

Most servos use an analog signal (width of a pulse) for positioning.  Any perturbation in that signal will cause unexpected behavior.  Activating 48 servos simultaneously will likely indirectly or directly affect the analog signal.

The unexpected behavior might be mitigated through changes in software or hardware.  These mitigation efforts may include:

Staggering the servo changes so that only 1 servo moves at a time.
Perhaps less effective but worth trying, staggering the servo changes so only 1 servo starts moving at a time.  In this scenario more than 1 servos may be moving at a time.
Using a power supply which maintains the expected voltage even during events such as all servos starting simultaneously.

These are only 3 options to consider.  Many more exist but may not be pertinent to your situation.  More information is needed.


Externally Powering a 3.3V device (nRL24L01+) with a 5V Arduino Pro Mini?

To connect the nRF24L01+ to a 5V Pro Mini you will need external 3.3V power supply to power the nRF24L01+.  The ground for the Pro Mini and the ground for the nRF24L01+ should be tied together to ensure a common ground reference.

The inputs to the nRF24L01+ are 5V tolerant so you will not need a level shifter to convert the 5V Digital IO on the Pro Mini to 3.3V. Be aware the not all 3.3V devices have 5V tolerant inputs like nRF24L01+.

You might want to look into using a 3.3V Pro Mini with that you should be able to use the regulated 3.3V power on the Pro Mini to power the nRF24L01+. Be aware that the 3.3V Pro Mini only runs at 8MHz instead of 16MHz.


The Serial.print statements show up on whatever terminal program is opened and connected. Their can be only one open at a time, but it could the Arduino IDE built in monitor (ctl-shft-m) or an external terminal program, eg putty, or some other program you wrote that opened the com/serial port the Arduino is on.

Remember though - only 1 can be open at a time. If you use an external program you MUST close the com port before attempting to download a new version of your sketch.  If you use the built in monitor/terminal it will automatically do this for you.


Using ESP8266 Adapter with Temperature/Humidity Sensor

Thank you everyone for the tips. I have found a way to use the esp8266 adapter with the DHT11 sensor. First of all it was on boot mode all along, I had some code mistakes where my target url includes an 'https' tag on it thus not functioning as expected.

For those who would like to use this specific adapter with DHT11 attached in boot mode.

-Connect all female jumper wires end to the Esp8266 and the male jumper ends to the adapter except for the GPI02.

-The GPI02 slot on the adapter will be empty but the ESP8266 GPI02 end must be connected to the data pin of the DHT11.

Make sure that the ESP8266 and DHT11 sensor have enough power for both devices.


The analogWrite() function generates a PWM output signal using a
hardware timer. Output on pin 3 is driven by timer 2, whereas
output on pin 9 is driven by timer 1. Here, you are trying to
use these timers for PWM generation and for your own code timing at
the same time. This cannot work. Either you let the Arduino core library
use the timers for analogWrite(), or you take them for you, but not
both.

The solution to your problem is very simple. Nothing in your code really
requires a timer to start with. You can handle both the brightness
control loop and the value changes using the technique of the Blink
Without Delay Arduino tutorial:

const uint32_t TARGET_CHANGE_PERIOD = 500000;
const uint32_t BRIGHTNESS_UPDATE_PERIOD = 1000;

void loop()
{
    uint32_t now = micros();
    static uint32_t last_target_change;
    if (now - last_target_change >= TARGET_CHANGE_PERIOD) {
        last_target_change += TARGET_CHANGE_PERIOD;
        // Change the brightness targets.
    }
    static uint32_t last_brightness_update;
    if (now - last_brightness_update >= BRIGHTNESS_UPDATE_PERIOD) {
        last_brightness_update += BRIGHTNESS_UPDATE_PERIOD;
        // Update the channel brightnesses.
    }
}


Ams1117 worked fine on battery, up in smoke with 12v power supply

Running an Arduino board with 12V is almost always too much. With only a few leds the voltage regulator on the Arduino boards gets too hot.

The best voltage is 7.5V. Then the voltage regulator has only little power dissipation and it is just high enough to turn off the USB 5V power.
Or power the Arduino board with a 5V (from a USB charger, or USB power pack) to the USB connector.

Never use a power supply that is not certified. It is a safety risk that can be avoided with a few dollars more.
The cheap power supply can have ripples, but it can for example have noise in the MHz range, or a voltage spike when turned on, or voltage overshoot when more current is required.  There can also be a coupling to the mains as @Majenko wrote. I have had a few of those. Nasty stuff!
Even with a scope, you can not tell if the power supply is really okay.

If you have a unreliable power source or a voltage that is too high, then a DC-DC converter can convert it into a nice steady voltage.
However, you should first get rid of that cheap power supply and buy a good one.


What is the maximum current for each I/O pin?

This comes up as first result when Googling your question:

And can be confirmed by page 313 and 314 of the datasheet:

To know where each pin is connected to (on the Arduino Uno) you can look the official (messy) schematic.

I provide an excerpt below that shows the Vin and 5V pins at the headers, and the power barrel connection.

If you want to control a 12V motor or a 12V LED strip or other DC loads you can use the following (which is also easy to find using Google):

*Note that your 12V Gnd and Arduino Gnd have to be connected.

simulate this circuit – Schematic created using CircuitLab


Arduino cannot communicate with PC after running servo

I've had some problems in the past reprogramming my Arduino Uno if it writes to the serial port - I don't know if the problem is the same, but here's how I got around it:

Option 1: Hold down the reset switch, then plug your Arduino into the USB port. Select the right COM port (if needed), compile your code (something ultra simple, e.g. blink led), and then, JUST BEFORE IT STARTS UPLOADING, release the reset switch. Wash, rinse, repeat, until you get it to work, through blind luck.

Option 2: Get hold of a ICSP (such as the one I got, USBASP made by FreeTronics  http://www.freetronics.com.au/products/usbasp-icsp-programmer-for-avr-arduino#.VL8Vv3WjlIc which I am v. happy with), plug it into the serial port, plug the other end onto your Arduino UNO ICSP header (6 pins, opposite end of the board from USB), then select Tools -> Burn Bootloader. Overwrites any program, works 100% of the time. Now you can unplug your USBASP, and plug your Uno back in and program it normally. This is also a great tool if you end up using AtMega (or AtTiny) chips directly (AtMega is the chip used to do all the work on the Arduino).

To avoid this, I have gotten into the habit of putting a 5 second delay as the first thing in the startup code.

FOR FUTURE GENERATIONS: I got mine here in New Zealand, so that will probably not help most people. FreeTronics makes them, and I am very happy I got their one (they have a "slow clock" jumper that is very convenient when programming Atmel chips not on an Arduino board), I expect that any USBASP would do the trick too - in response to the question, Amazon has a couple under $4, and I expect that the price will not go up.

Search for "USBASP". Make sure you get a ribbon cable. For Arduino Uno, you need a 6-pin ribbon cable. It is also possible to use these cables to communicated directly with a running Arduino over these same pins.


What's wrong with my undetected, unresponsive Arduino Robot?

I'm pretty sure and sadly to announce you that the usb communication of your Arduino Leonardo Compatible is dead and the arduino is connecting to the computer just like an alimentation Source no more.
And since Arduino Leonardo based on The ATmega32U4 which has built-in USB communication ,so the Atmedga32U4 is dead(u-processor) too.

It's not a software matter but hardware one.


As noted in the previous answer, being able to upload a new sketch indicates an Arduino is ok in general – in particular has a functioning CPU – but of course that does not test all features.  For example, individual inputs and outputs can be damaged.

You can easily change your sketch so that it drives some range of outputs, as shown below.  Thereafter, try moving the red wire (that now connects on 13) to some other of the outputs in the selected range.

enum { LedLo=2, LedHi=20}; // Set lo and hi limits of range

void setup() {
  for (int led=LedLo; i <= LedHi; ++i)
    pinMode (led, OUTPUT);
}

void loop() {
  for (int led=LedLo; i <= LedHi; ++i)
    digitalWrite(led, HIGH);
  delay(4000);
  for (int led=LedLo; i <= LedHi; ++i)
    digitalWrite(led, LOW);
  delay(4000);
}


How to read bytearray from arduino pin in arduino sketch

I found the answer from forum.arduino.cc
There is a sketch

#include <SoftwareSerial.h>

// TX_PIN is not used by the sensor, since that the it only transmits!
#define PING_RX_PIN 6
#define PING_TX_PIN 7

SoftwareSerial mySerial(PING_RX_PIN, PING_TX_PIN);

long inches = 0, mili = 0;
byte mybuffer[4] = {0};
byte bitpos = 0;

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

  mySerial.begin(9600);
}

void loop() {
  bitpos = 0;
  while (mySerial.available()) {
    // the first byte is ALWAYS 0xFF and I'm not using the checksum (last byte)
    // if your print the mySerial.read() data as HEX until it is not available, you will get several measures for the distance (FF-XX-XX-XX-FF-YY-YY-YY-FF-...). I think that is some kind of internal buffer, so I'm only considering the first 4 bytes in the sequence (which I hope that are the most recent! :D )
    if (bitpos < 4) {
      mybuffer[bitpos++] = mySerial.read();
    } else break;
  }
  mySerial.flush(); // discard older values in the next read

  mili = mybuffer[1]<<8 | mybuffer[2]; // 0x-- : 0xb3b2 : 0xb1b0 : 0x--
  Serial.print("PING: ");
  Serial.print(mili/10);
  Serial.println("sm");
  delay(500);
}


Interacting with a video game - Keyboard & LUFA

It is quite common for games to be quite slow at reading the keyboard.

The Leonardo's Keyboard.write() command is quite rapid. The OS can pick it up with its interrupt driven buffering, but games tend not to use that buffering so they can get more realtime key control.

The trick here is actually to slow down the Leonardo's sending, by not using Keyboard.write(). Instead you need to press the key, wait a moment, then release the key:

Keyboard.press('j');
delay(1);
Keyboard.release('j');

Increase the delay until it becomes reliable. It's hard to say what the delay should be.


How to connect an lcd i2c using only pins A0 and A1 (SDA, SCL, GND, and VCC are given)

You may be finding Connect to LCD via I2C, default address 0x27 (A0-A2 not jumpered) confusing.  These refer to the I2C address selection lines of the IO expander (the PCF8574T) used on the I2C LCD display and not to the A0-A2 analog pins of the Arduino itself.

The note // Wiring: SDA pin is connected to A4 and SCL pin to A5. is referring to the analog pins of an UNO (or Nano) because these pins also happen to carry the ATMega328P's I2C ("Wire") signals.
So there's nothing about using the I2C display that prevents you from using the Analog A0-A2 pins of the Arduino for other purposes.  Only the  Arduino's A4 and A5 pins are used to carry I2C/Wire.


How do I properly use the WiFi capabilities of ESP8266?

The following may not solve of your problems, but just in case it helps...
I was using the ESP8266 both in Station mode and AP. Both worked.
In AP mode, it worked but the ESP8266 ignored my instructions to set name and password for the AP , until I realised the following
. The password must at least be 8 characters long, otherwise the instruction is ignored
. in the IDE, you should erase flash AND WiFI settings, otherwise it will be "lazy" and use previous settings


Assuming they're based on the more recent Arduino Nano 3.x series or later, the microcontroller in your Nanos is probably an ATmega328 running at 16 MHz. That's the same as the Uno, so there should be no major problems hopefully.

It might be worth checking that you've got the latest version of the Arduino IDE though. I seem to remember there was a problem in some older bootloaders which prevented the watchdog from working properly.


The simplest method is to encrypt your communication channel using some secret key.  You could use the built-in AES encryption functionality, which would mean that only people that know the key could encrypt a request in such a way that the device at the other end could decrypt it.

You would think that SSL (HTTPS) would do the job, but that only provides interception security, not authentication. Of course for even more security you can combine both HTTPS and AES encryption.  One for overall encryption, and the other for encryption-based authentication.


RS-485 Serial communication problem with arduino

In modbus there are two pins which are as DE and RE which you need to set and reset while transmitting the data. Also you can check Modbus this library it has some examples which could be useful to you also in arduino Uno don't use software serial for transmitting the data use the hardware serial only I will suggest implement your code on arduino Mega if you have any and then port the code for Uno. Just go through the library you will find some helpful examples and it will solve your issue


What does "Update of OCR1x at" mean in the WGM table of ATMEGA328?

So does "Update of OCR1x at" mean that only when when the pulse wave form has reached the value of BOTTOM (or the end of a period), that's when the value of OCR1x will be passed on to the OCx pins...

Yes, that's what it means. To prevent glitches in the PWM output, you frequently do NOT want the PWM waveform to change immediately the instant you update an OCR1A value, for instance, to change the PWM output on output pin A. So, the PWM value you set is double-buffered and only updates the inner buffer used by the output pins once it finishes its current PWM period and reaches the BOTTOM value again, which would be a counter value of 0 in this case. Now, by allowing a previous PWM period to finish before the hardware reads the latest value from the OCR1A/B register (outer buffer) to its inner buffer (which inner buffer actually determines the pin state), you have a nice, clean, glitch-free PWM transition from one value to the next regardless of when you updated the OCR1A or OCR1B output register.


Do not worry about limiting it to 12 bits, send all 16 and use just the twelve you need.  You never know you may expand the project.  Whatever is on the unused bits is irrelevant. they do nothing.


Confused between which arduino to use for project?

If you want a project that is wireless adding Wifi to Arduino is pointless when the Wifi boards are more capable than the Arduinos, so I would discount the UNOs straight away.

As I understand the YUN is more of a Pi replacement so (if that's right) I would look at that for the 'master controller'.  The ESP32 Is probably not strong enough to act as the master controller, but it has other feature that might mitigate this including hardware support for encryption algorithms which might be useful for authentication the client devices.  Also they are cheep enough to consider a cluster of them (

Purely for their size I would go with ESP8266, you have an 80/160MHz processor with 512kb of RAM (from memory??), OK it only has 10 Digital and 1 Analog pins, but it you want more fork out another $1.50 on another board.  They are small enough to fit in light switches and cheep enough to hide behind a model door.

If you only want to do your model house then I recommend ESP8266 slaves and a Pi or cluster (pair?) of ESP32 for the master.  If you want to do a real house, I'd recommend the same.


Adafruit IO example won't compile, library required is correct version

It turns out that the problem was that I had installed the Arduino IDE through the windows app store. Uninstalling it, downloading it through a browser, and using the same code works just fine.


If I understand correctly, you wrote an example code that switches an
LED between two states (on and off), and you are stuck because the
actual problem you want to solve is more complex than that. And indeed,
it seems to me that you want to manage a system with three possible
states: it can be on or off but, when it is off, it can be ready to turn
on if the humidity is high, or it can be in the five minute wait.
The most natural way to think about this kind of systems is a finite
state machine, or FSM. An FSM is defined by the set of states it
can be in, the conditions that make it switch states, and the actions
performed when doing so. If I correctly understood your specification,
your system can be either READY, RUNNING or WAITING, and the transitions
are:

when READY, if the humidity is too high it switches to RUNNING; it
turns the fan on when doing so
when RUNNING, if it has been running for 3 minutes, it switches
to WAITING and turns the fan off
when WAITING, if it has been waiting for 5 minutes, it switches
to READY

This can be illustrated by the following state diagram:

You should correct me at this stage if I did not fully understand your
specification. Otherwise, if the state diagram matches your
requirements, converting it to code is quite straightforward:
const uint32_t MINUTE = 60000;

void loop() {
    static enum {READY, RUNNING, WAITING} state;
    static uint32_t last_change;
    uint32_t now = millis();
    switch (state) {
        case READY:
            if (humidity_is_high()) {
                turn_fan_on();
                state = RUNNING;
                last_change = now;
            }
            break;
        case RUNNING:
            if (now - last_change >= 3 * MINUTE) {
                turn_fan_off();
                state = WAITING;
                last_change = now;
            }
            break;
        case WAITING:
            if (now - last_change >= 5 * MINUTE) {
                state = READY;
            }
            break;
    }
}


LCD 16x2 shows one line cut and the 7th column also cut

My LCD module looks so similar to yours I decided risk to taking it apart for the purposes of taking pictures for to go along with the description.  It went back to together fine.
The black part I suggested pushing down on I'm going to call a "bezel", even though I'm not sure that's technically the correct term for it.
The pink color showing between the PCB and bezel is probably a "zebra strip" or elastomeric connector.  They conduct signals from LCD controller mounted on the PCB up to the LCD glass itself.  Sometimes they don't make good contact and so some segments of the LCD don't respond or respond poorly.  They may make better contact when you apply pressure to them.  If some or all of the segments start responding when you do that, it's a fairly good indication that this is a problem, though not an Arduino problem as such, it's a problem encountered with some frequency by Arduino users.
If you may need to replace the strips, or clean them, or adjust the bezel to apply more pressure to them.  Or just get another LCD module.
Back of one of my LCD modules that looks a lot like yours:

If you look at the back side of the board you may find that you can unclip the bezel; though it could also be soldered or glued etc.  If/when you do unclip it, the zebra strips and LCD glass will probably come free, perhaps with polarization filters as well.  You'll want to pay attention to the orientation of the everything so you know what you're doing when you put it back together.
I unclipped my the bezel on mine and the zebra strips (pink; they're not always pink) stayed with it. It is no so easy to see the "zebra" pattern on these particular strips.  Often they more alternating gray/white pattern.

Here's the PCB showing the contacts that the zebra strips mate to an the LED backlight spreader. Apologies for the dust.

The strip pattern is a little easier to see in this image.  You can also see the pattern of the conductors on the LCD glass.

You can try cleaning the strips and the glass and PCB where the make contact.  I would be careful what you clean with; look for trustworthy recommendations. In any case, keep your finger grease off of everything, either by using gloves or just washing and drying your hands before working on it.


Can't upload sketches to breadboard Arduino

Answered by Skyler440:

  Never mind, found the problem. My software switched to the bluetooth for some reason after I changed some other settings.

Converted to answer to reduce unanswered questions.


How to use existing (non-arduino-specific) library with subfolders in Arduino IDE?

To utilize subfolders with any name in an Arduino library, you must use the 1.5 library specification.

In libraries folder in your sketch folder, create a folder for the library. In this folder create a src subfolder and put the library source code into that subfolder. Then create a library.properties file in the root folder of the library with some dummy information. Fill the includes key with the main .h file of the library.

Documents/
  Arduino/
   libraries/
     FooLib/
      src/
       subfoldername/
        header.h
        some.h
        some.cpp
       foolib.h
       foolib.cpp
      library.properties

In code then use in #include the path with src folder as starting location.

#include <subfoldername/header.h>


To turn of the WiFi add the WiFi library and use WiFi.forceSleepBegin();

Firmware is the program/sketch that controls a MicroController Unit aka MCU (and in this case a Arduino).
Best explanation I know is here: https://en.wikipedia.org/wiki/Firmware


How would I refactor this code, given how similar most of the lines are?

#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel strip = Adafruit_NeoPixel(9, 2, NEO_RGBW + NEO_KHZ800);
// The maximum pin number for the buttons
const int MaxButton = 11;
// The value if the pin is not connected to an LED
const int NotConnected = -1;
// The connections from buttons to leds.
const int Connections[MaxButton+1] = {NotConnected, NotConnected, NotConnected, 0, 1, 2, 3, 4, 5, 6, 7, 8};

void setup()
{
  strip.begin();
  strip.show();
  for (int pinNumber = 0; pinNumber <= MaxButton; ++pinNumber)
  {
    if (Connections[pinNumber] != NotConnected)
    {
        pinMode(pinNumber, INPUT_PULLUP);
    }
  }
}

void loop()
{
  for (int pinNumber = 0; pinNumber <= MaxButton; ++pinNumber)
  {
    if (Connections[pinNumber] != NotConnected)
    {
        if (digitalRead(pinNumber) == LOW)
        {
            strip.setPixelColor(Connections[pinNumber], strip.Color(20, 55, 0, 0));
        }
    }
  }
  strip.show();
}

I can't test it, so I have no idea if it works, but it should do.


The ClickEncoder library works very well with the Keyes rotary encoder: https://github.com/0xPIT/encoder. The Button reports multiple states: Clicked, DoubleClicked, Held and Released. It uses analog pins A1, A0, A2. You will also need the TimerOne library: https://code.google.com/archive/p/arduino-timerone/downloads.

My keyes rotary encoders have 3 surface mount resistor locations on the bottom of the circuit board. R1 has nothing, R2 and R3 have a 10k ohm resistor soldered in place. Not sure if this makes a difference.


What type of sensor could I use to determine the mass of a small object (under 1 kg)?

Just a little brainstorming:

If you have a spring, then you can easily calculate the physical force (mass) needed to stretch the spring to a certain extent. The law is called:
 Hookes's Law
 - you could then just measure the increase in distance between the initial position and the position with load. Use a servo or any distance measure.


Is it safe to power an MQ-7 gas sensor with a 9V D.C supply?

You can, but you will have to reduce the voltage to the 5V the sensor needs, otherwise you will blow up the sensor.

To that end you require a voltage regulator. You can use a linear regulator like the Arduino has on-board, but they are very wasteful of power and will dissipate the excess 4V of electricity as heat.

Better would be to use a switching regulator (commonly and cheaply available on eBay and other sites) to step the voltage down to 5V more efficiently.


Wifi REST API GET call - how to concatenate and pass URL parameters?

Concatenating the string data in memory before sending it shouldn't be necessary. Instead, you should just be able to use client.print() (or equivalent) to output each part of the request in sequence. For example:

client.print("GET ");
client.print(page);
client.print(" HTTP/1.1\r\n");

client.print("Host: ");
client.print(serverName);
client.print("\r\n");

// etc.

That should let you output any combination of HTTP headers you need.


Arduino WiFIWebSever - why client.println()?

The confusion you have arises from the context of the command.

The server.* commands manipulate the server instance - that is, the actively listening socket that is waiting for connections.

The client.* commands change their meaning depending on if you are a server waiting for connections or a client that is making a connection.

In the latter case client.print() sends data to the server.

In the former case, on a server, the client.* commands refer to a specific client that has made a connection to the server.  Using client.print() in this instance sends data to the currently connected client.

So "client" can be thought of as "the connection between me and the remote end" however that connection was created - either by "me" specifically connecting to the remote end, or the remote end connecting to my "server" instance and a new "client" being spawned from it for this one connection.

Remember - a client can only connect to one server, but a server can have many connections from many different clients, and it is those client connections that you talk to.


BLK is ground.
CTS is generally not used. I leave it unconnected on my boards.
DTR goes to the auto-reset circuit.

Update:

  Can I let DTR directly connect with RESET ?

Auto-reset circuits use a .1uf capacitor between the DTR (or RTS, depends on which one your cable supplies) and the reset pin. (The exact value probably isn't too important). Without it, the reset circuit is likely pick up noise and randomly reset the Arduino.


Your code won't work as is. Each time you assign a value to state you're overwriting it in the next line. You could, for example have multiple int state variables such as state1 for the first line in the loop then state2 in the second etc. Then you need to compare values (don't use = on its own in a compare as it will assign the value being tested - use == instead). This way you gather all the button states first.

Or you could test the state of a button and if pressed add 1 to state:

if (digitalRead(bp1)) {
    state++};

Then you compare the number of button presses counted in state as you were doing and light the LEDs based on that.

However you will likely have a problem with contact bounce on the switches. This happens when a switch is closing and the voltage is not steady for about 20ms (imaging a switch sparking as it is closing). To get around this you'll need either some additional components or add a time delay in your code for each button press to check it several times until the voltage is stable. Do a Google search for 'Arduino contact bounce' for solutions.

R3.


The Nano uses the same chip (ATMEGA 328P) that is on the Uno.  So putting the same code on the Nano should work the same as the Uno.

The Micro uses a different chip.  Whether or not the code from your Uno will work on your Micro depends on what is in the code.  You chose not to show anyone the code so that can't be answered yet.


Set and extract individual bytes of a number (lowByte() and highByte())

Any more sophisticated byte exchange can be done with binary operators.

Extracting information

You'll need some constants like

MASK         SHIFT
0xFF000000   24       (first byte, most significant)
0x00FF0000   16       (second byte)
0x0000FF00    8       (third byte)
0x000000FF    0       (last byte, least significant)

You would binary AND the original value with MASK

     0x12345678
AND  0x00FF0000
 =   0x00340000

and then bit shift it left, e.g.

   0x00340000
>> 16
 = 0x00000034

So from the original value 0x12345678 you have gotten 0x34.

Setting information

The opposite direction is also possible with the same constants but opposite operators and in opposite order:

   0x00000034
<< 16
 = 0x00340000

and then

   0x12005678
OR 0x00340000
 = 0x12345678

Note that the OR operation only works reliably if the corresponding positions are 0x00. That's fine with a starting value of 0x00000000.

If you don't know that or you want to process an arbitrary number, you can introduce a step in between

    0x12??5678   (?? could be anything)
AND 0xFF00FFFF   (which is the inverse of 0x00FF0000 and can be expressed as ~0x00FF0000)
 =  0x12005678   (whatever ?? was, it'll be cleared out)

Actual Code

Tested on Arduino Uno. The long data type is 32 bits or 4 bytes.

The code here may not be the most efficient. Advanced developers would likely not use MASK and SHIFT as arrays like this. This answer focuses more on the educational point.

long MASK[]  = {0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF};
byte SHIFT[] = {24        , 16        , 8         , 0};

// Extracts a byte from a larger data type
// value: larger data type to extract a byte from
// position: 0 based number, 0 = MSB, 3 = LSB
byte getByteAt(long value, byte position)
{
  long result = value & MASK[position];  // binary AND
  result = result >> SHIFT[position];    // Shift right, moving all bits
  byte resultAsByte = (byte) result;     // Convert to an actual byte
  return resultAsByte;
}

// Sets a byte in a larger data type
// value: larger data type where to set the byte
// position: 0 based number, 0 = MSB, 3 = LSB
// newPartialValue: the byte to be inserted
long setByteAt(long value, byte position, byte newPartialValue)
{
  long result = value & ~MASK[position];                       // clear the affected byte so that it is 0x00
  long valueToSet = (long) newPartialValue << SHIFT[position]; // Shift left, moving all bits
  result = result | valueToSet;                                // binary OR
  return result;
}

void setup() {
  Serial.begin(9600);
  Serial.println(getByteAt(0x12345678, 1));       // Prints 52, which is 0x34
  Serial.println(setByteAt(0x87654321, 1, 0xBB)); // Prints -2017770719 which is 0x87BB4321
}

void loop() {

}


How to count the number of rising edges on DS3231 rtc?

I'm not sure why you're getting 0 as such, but your interrupt and variable methodology leaves a lot to be desired (probably the cause of the "tutorials" you followed).

My primary concern is that you are using a 32-bit "long" variable in an interrupt, and referencing that directly outside the interrupt.  The Arduino is an 8-bit system, which means that all accesses to that variable take many instructions to arrange (splitting it down into 4 8-bit values, manipulating it, recombining it, etc).  Because of this no operations on that variable are "atomic".

You need to make them atomic.  If you don't then it's perfectly possible for the interrupt to trigger and modify the value in the middle of you doing something with that value.

The simplest way of making it atomic is to disable interrupts, then copy the value to another variable and/or modify it, and enable interrupts again.

Here's an example that I would consider stable:

#include <DS3231.h>
#include <RTClib.h>
#include <Wire.h>
#include "rtc.h"
#define InterruptPin 3

volatile uint32_t lcnt = 0;

RTC_DS3231 rtc;

void setup() {
  Wire.begin();
  Serial.begin(74880); // init serial port
  pinMode(InterruptPin, INPUT_PULLUP);
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
  attachInterrupt(digitalPinToInterrupt(InterruptPin), fcnt, FALLING);
}

void loop() {
  static uint32_t ts = millis();
  uint32_t a = millis();
  if (a - ts >= 1000) {
    ts = a;
    noInterrupts();
    uint32_t currentCount = icnt;
    icnt = 0;
    interrupts();
    Serial.println(currentCount);
  }
}

void fcnt(){
  lcnt+=1;
}

That should print the number of pulses over successive 1 second periods.


You can't, that's not how the esp8266 works.

The esp8266 is WiFi, so you will either need an access point or nominate one esp8266 module to act as an access point running in softap mode.


Connecting Arduino and Processing, how do I know what COM to read?

Because the two numbers are completely different types of numbers.

The number 4 for COM4 means that it is the fourth serial communications port as defined by which I/O ports are used to communicate with the actual hardware. I.e. you'll have COM1, COM2, COM3 and so on. It doesn't matter if the hardware is actually there or anything is connected - the names are the same.

The number 2 in Serial.list()[2] means that you're selecting the third (!) element of the array returned by Serial.list(). I.e. in this case we're counting from 0 instead of 1.

In addition to that, Serial.list() only returns available ports. I.e. if the hardware for COM3 is not installed physically, it will not be returned by Serial.list(). Also the list is not guaranteed to be sorted in any specific order.

You'll want to print out the contents of the array returned by Serial.list() and let the user select which of the ports he wants to use.


Can I use IR Transmitter/Receiver for heart beat detecting?

No, you cannot.  The sensor you link to has a circuit which attempts to detect IR light modulated at a specific frequency, and produces a digital output.   For a heartbeat sensor you need an analog output to feed into far more sophisticated signal processing - effectively the built-in processing gets in the way and means you cannot use it for this purpose.

Additionally, sensors of this type typically have an automatic gain control which means that they desensitize when subjected to continuous signal - they are designed for sources like remote controls where the modulation is itself pulsed on an off in small fractions of a second, so they interpret constant modulated light as noise and soon turn off their output.


Writing analog voltages on analog pins of Arduino

No. The analogWrite(pin, val) function is reserved to PWM pins (D3, D5, D6, D9, D10, and D11 in Arduino Nano). Pins marked as "ANALOG IN" on the board can work either as analog input (to the Analog to Digital Converter), digital input, or digital output.

It is worth to note that the Arduino Nano (and any other Arduino board I'm aware of) actually doesn't have any 'true' analog output port. When you use analogWrite(pin, val) you are actually telling the Arduino to output a PWM signal with the duty cicle specified by val (100% for val = 255 and 0% for val = 0). If you actually do need a true analog output, you should consider using any form of analog lowpass filter at the specified PWM output port. Depending on how clean you want your signal to be, you could use a single capacitor or any other (a little more complex) filter.

If you don't know anything about filters, this could be a good starting point: ElectronicsTutorials - Passive Low Pass Filter

More insight about PWM in Arduino, here: EAS 199 - Basic Pulse Width Modulation


How to measure electrical conductivity using Arduino?

The answer is Three Dollar EC - PPM Meter [Arduino]. I tried it against a consumer level EC meter and got the same results after calibration. It's cheap and simple.

The only warning is that there is several scales in use to measure EC, so results may not be comparable between diferentes devices and you have to read carefully the EC recomendations for your water solution.

EC units

Electrical conductivity can be expressed using a number of different units, but the typical unit is siemens per meter2 per mole (S/m2/mole) or millisiemens per centimetre (mS/cm). The mS/cm unit is generally used in Europe as a guide to the concentration of nutrients in water. In North America, conductivity is converted into a count of the ions in the water using parts per million (which can also be converted into units including mg/l etc.). This is done by converting the EC into a value based on the ions contained in the solution. Fortunately, there is a fixed calculation for the relationship between all these units, which is given in the table below.

Code for the EC meter

/*
  ElCheapo Arduino EC-PPM measurments

  This scrip uses a common USA two prong plug and a 47Kohm Resistor to measure the EC/PPM of a Aquaponics/Hydroponics Sytem.
  You could modift this code to Measure other liquids if you change the resitor and values at the top of the code.

  This Program will give you a temperature based feed controller. See Read me in download file for more info.

  28/8/2015  Michael Ratcliffe  Mike@MichaelRatcliffe.com

          This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see .

    Parts:
    -Arduino - Uno/Mega
    -Standard American two prong plug
    -1 kohm resistor
    -DS18B20 Waterproof Temperature Sensor

    Limitations:
    -
    -

    See www.MichaelRatcliffe.com/Projects for a Pinout and user guide or consult the Zip you got this code from

*/

#include <OneWire.h>
#include <DallasTemperature.h>

//************************* User Defined Variables ********************************************************//

int R1= 1000;
int Ra=25;          //Resistance of powering Pins
int ECPin= A0;
int ECGround=A1;
int ECPower =A4;

//*********** Converting to ppm [Learn to use EC it is much better**************//
// Hana      [USA]        PPMconverion:   0.5
// Eutech    [EU]         PPMconversion:  0.64
// Tranchen  [Australia]  PPMconversion:  0.7
// Why didnt anyone standardise this?

float PPMconversion=0.5;

//*************Compensating for temperature ************************************//
// The value below will change depending on what chemical solution we are measuring
// 0.019 is generaly considered the standard for plant nutrients [google "Temperature compensation EC" for more info
float TemperatureCoef = 0.019; //this changes depending on what chemical we are measuring

//********************** Cell Constant For Ec Measurements *********************//
// Mine was around 2.9 with plugs being a standard size they should all be around the same
// But If you get bad readings you can use the calibration script and fluid to get a better estimate for K
float K=2.34;

//************ Temp Probe Related *********************************************//
#define ONE_WIRE_BUS 10          // Data wire For Temp Probe is plugged into pin 10 on the Arduino
const int TempProbePossitive =8;  //Temp Probe power connected to pin 9
const int TempProbeNegative=9;    //Temp Probe Negative connected to pin 8

//***************************** END Of Recomended User Inputs *****************************************************************//

OneWire oneWire(ONE_WIRE_BUS);// Setup a oneWire instance to communicate with any OneWire devices
DallasTemperature sensors(&oneWire);// Pass our oneWire reference to Dallas Temperature.

float Temperature=10;
float EC=0;
float EC25 =0;
int   ppm =0;

float raw= 0;
float Vin= 5;
float Vdrop= 0;
float Rc= 0;
float buffer=0;

//*********************************Setup - runs Once and sets pins etc ******************************************************//
void setup()
{
    Serial.begin(9600);
    pinMode(TempProbeNegative , OUTPUT);  //seting ground pin as output for tmp probe
    digitalWrite(TempProbeNegative , LOW); //Seting it to ground so it can sink current
    pinMode(TempProbePossitive , OUTPUT); //ditto but for positive
    digitalWrite(TempProbePossitive , HIGH);
    pinMode(ECPin,INPUT);
    pinMode(ECPower,OUTPUT);//Setting pin for sourcing current
    pinMode(ECGround,OUTPUT);//setting pin for sinking current
    digitalWrite(ECGround,LOW);//We can leave the ground connected permanantly

    delay(100);// gives sensor time to settle
    sensors.begin();
    delay(100);
    //** Adding Digital Pin Resistance to [25 ohm] to the static Resistor *********//
    // Consule Read-Me for Why, or just accept it as true
    R1=(R1+Ra);// Taking into acount Powering Pin Resitance

    Serial.println("ElCheapo Arduino EC-PPM measurments");
    Serial.println("By: Michael Ratcliffe  Mike@MichaelRatcliffe.com");
    Serial.println("Free software: you can redistribute it and/or modify it under GNU ");
    Serial.println("");
    Serial.println("Make sure Probe and Temp Sensor are in Solution and solution is well mixed");
    Serial.println("");
    Serial.println("Measurements at 5's Second intervals [Dont read Ec morre than once every 5 seconds]:");
}

void loop()
{
    GetEC();          //Calls Code to Go into GetEC() Loop [Below Main Loop] dont call this more that 1/5 hhz [once every five seconds] or you will polarise the water
    PrintReadings();  // Cals Print routine [below main loop]
    delay(5000);
}

void GetEC()
{
    sensors.requestTemperatures();          // Send the command to get temperatures
    Temperature=sensors.getTempCByIndex(0); //Stores Value in Variable
    //************Estimates Resistance of Liquid ****************//
    digitalWrite(ECPower,HIGH);
    raw= analogRead(ECPin);
    raw= analogRead(ECPin);// This is not a mistake, First reading will be low beause if charged a capacitor
    digitalWrite(ECPower,LOW);

    //***************** Converts to EC **************************//
    Vdrop= (Vin*raw) / 1024.0;
    Rc = (Vdrop*R1) / (Vin-Vdrop);
    Rc = Rc-Ra; //acounting for Digital Pin Resitance
    EC = 1000/ (Rc*K);

    //*************Compensating For Temperaure********************//
    EC25  =  EC / (1+ TemperatureCoef*(Temperature-25.0));
    ppm=(EC25)*(PPMconversion*1000);
}

//***This Loop Is called From Main Loop- Prints to serial usefull info ***//
void PrintReadings()
{
    Serial.print("Rc: ");
    Serial.print(Rc);
    Serial.print(" EC: ");
    Serial.print(EC25);
    Serial.print(" Simens  ");
    Serial.print(ppm);
    Serial.print(" ppm  ");
    Serial.print(Temperature);
    Serial.println(" *C ");
};

Code for calibration

/*
  ElCheapo Arduino EC-PPM measurments Calibration

  This Script is used for calibration of the sensor and fine tuning of the Cell Constant K
  Submerge the sensor and temperature probe in the calibration solution and leave for a while so the temperature probe can settle
  Change the value of the calibration solution to suit the solutiton strength
  Stir the probe to make sure the solution is well mixed and upload the code to the arduino
  Open the terminal for an update of the estimated Cell Constant K [should be around 3] and use this new value in the main EC code.

  28/8/2015  Michael Ratcliffe  Mike@MichaelRatcliffe.com

          This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see .

    Parts:
    -Arduino - Uno/Mega
    -Standard American two prong plug
    -1 kohm resistor
    -DS18B20 Waterproof Temperature Sensor

    See www.MichaelRatcliffe.com/Projects for a Pinout and user guide or consult the Zip you got this code from

*/

//************************** Libraries Needed To Compile The Script [See Read me In Download] ***************//
// Both below Library are custom ones [ SEE READ ME In Downloaded Zip If You Dont Know how To install Use them or add a pull up resistor to the temp probe

#include <OneWire.h>
#include <DallasTemperature.h>

//************************* User Defined Variables ********************************************************//

float CalibrationEC = 0.762; //EC value of Calibration solution is s/cm

//##################################################################################
//-----------  Do not Replace R1 with a resistor lower than 300 ohms    ------------
//##################################################################################
int R1 = 1000;
int Ra = 25; //Resistance of powering Pins
int ECPin = A0;
int ECGround = A1;
int ECPower = A4;

//*************Compensating for temperature ************************************//
//The value below will change depending on what chemical solution we are measuring
//0.019 is generaly considered the standard for plant nutrients [google "Temperature compensation EC" for more info
float TemperatureCoef = 0.019; //this changes depending on what chemical we are measuring

//************ Temp Probe Related *********************************************//
#define ONE_WIRE_BUS 10          // Data wire For Temp Probe is plugged into pin 10 on the Arduino
const int TempProbePossitive = 8; //Temp Probe power connected to pin 9
const int TempProbeNegative = 9;  //Temp Probe Negative connected to pin 8

//***************************** END Of Recomended User Inputs *****************************************************************//

OneWire oneWire(ONE_WIRE_BUS);// Setup a oneWire instance to communicate with any OneWire devices
DallasTemperature sensors(&oneWire);// Pass our oneWire reference to Dallas Temperature.

float TemperatureFinish = 0;
float TemperatureStart = 0;
float EC = 0;
int ppm = 0;

float raw = 0;
float Vin = 5;
float Vdrop = 0;
float Rc = 0;
float K = 0;
int i = 0;
float buffer = 0;

//*********************************Setup - runs Once and sets pins etc ******************************************************//
void setup()
{
    Serial.begin(9600);
    pinMode(TempProbeNegative , OUTPUT);  //seting ground pin as output for tmp probe
    digitalWrite(TempProbeNegative , LOW); //Seting it to ground so it can sink current
    pinMode(TempProbePossitive , OUTPUT); //ditto but for positive
    digitalWrite(TempProbePossitive , HIGH);
    pinMode(ECPin, INPUT);
    pinMode(ECPower, OUTPUT); //Setting pin for sourcing current
    pinMode(ECGround, OUTPUT); //setting pin for sinking current
    digitalWrite(ECGround, LOW); //We can leave the ground connected permanantly

    delay(100);// gives sensor time to settle
    sensors.begin();
    delay(100);
    //** Adding Digital Pin Resistance to [25 ohm] to the static Resistor *********//
    // Consule Read-Me for Why, or just accept it as true
    R1 = (R1 + Ra);

    Serial.println("ElCheapo Arduino EC-PPM measurments Calibration");
    Serial.println("By: Michael Ratcliffe  Mike@MichaelRatcliffe.com");
    Serial.println("Free software: you can redistribute it and/or modify it under GNU ");
    Serial.println("");
    Serial.println("Make sure Probe and Temp Sensor are in Solution and solution is well mixed");
    Serial.println("");
    Serial.println("Starting Calibration: Estimated Time 60 Seconds:");
};
//******************************************* End of Setup
//************************************* Main Loop - Runs Forever ***************************************************************//
//Moved Heavy Work To subroutines so you can call them from main loop without cluttering the main loop
void loop()
{
    i = 1;
    buffer = 0;
    sensors.requestTemperatures();// Send the command to get temperatures
    TemperatureStart = sensors.getTempCByIndex(0); //Stores Value in Variable

    //************Estimates Resistance of Liquid ****************//
    while(i <= 10) {
        digitalWrite(ECPower, HIGH);
        raw = analogRead(ECPin);
        raw = analogRead(ECPin); // This is not a mistake, First reading will be low
        digitalWrite(ECPower, LOW);
        buffer = buffer + raw;
        i++;
        delay(5000);
    };

    raw = (buffer / 10);

    sensors.requestTemperatures();// Send the command to get temperatures

    TemperatureFinish = sensors.getTempCByIndex(0); //Stores Value in Variable

    //*************Compensating For Temperaure********************//
    EC = CalibrationEC * (1 + (TemperatureCoef * (TemperatureFinish - 25.0))) ;

    //***************** Calculates R relating to Calibration fluid **************************//
    Vdrop = (((Vin) * (raw)) / 1024.0);

    Rc = (Vdrop * R1) / (Vin - Vdrop);

    Rc = Rc - Ra;

    K = 1000 / (Rc * EC);

    Serial.print("Calibration Fluid EC: ");

    Serial.print(CalibrationEC);

    Serial.print(" S  ");  //add units here

    Serial.print("Cell Constant K");

    Serial.print(K);

    if(TemperatureStart == TemperatureFinish) {
        Serial.println("  Results are Trustworthy");
        Serial.println("  Safe To Use Above Cell Constant in Main EC code");

    } else {
        Serial.println("  Error -Wait For Temperature To settle");
        Serial.print("Temp start=");
        Serial.print(TemperatureStart);
        Serial.print(" Temp end=");
        Serial.println(TemperatureFinish);
    }
}
//*************************** End Of Main Loop *******************************************************************//

EDIT:

Make sure to use a factory sealed male plug. If water get inside the plug, the voltage reading will be inaccurate.


Home devices control system using gsm and arduino mega2560

For the 3333 and 4444 you are doing

buffer[m] = char(buffer[m]);

and

buffer[p] = char(buffer[p]);

which does nothing.

You probably meant

buffer_m[m] = char(buffer[m]);

and

buffer_p[p] = char(buffer[p]);


How to interface ESP8266-01 Wifi Module with Arduino Uno


How to trigger an alarm when toilet paper is low?

Bring up several rolls at a time and hang one for use. Put the other two on a short vertical pole within reach of the sitter. Sitter can take another roll when needed.

Mechanically sense lack of weight on the shelf at the bottom of the pole. Alarm triggers when the last roll is removed. No one has to get caught short.

To sense the weight use a force sensitive resistor such as the FSR 400 (see datasheet). Alternatively, you could use a lightweight coil spring to rest the toilet paper on with a micro switch that is released when both rolls are removed. Another option would be an IR beam break detector where the circuit is completed when the last roll is removed.


Collecting data from a timer interrupt and storing it into an array

Storing the data into arrays is not an end in itself. The question is:
what do you want to do with these arrays? The way to proceed depends on
that purpose.
If you want the data acquisition (analogRead()) and the processing
(computation and printing) to proceed in parallel, then you will need
the arrays for buffering the data between those two processes. As
mentioned by Michel Keijzers in his answer, you will have to research
the concept of ring buffer.
There is a ring buffer implementation in the Arduino core you can use as
inspiration: when reading data from the Serial port, the incoming bytes
are received by an ISR and stored in a ring buffer. The
Serial.read() method can then be used to retrieve these bytes
and process them outside the interrupt context.
Another option is to alternate between an acquisition phase and a
processing phase. This can be an interesting approach if the acquisition
rate is too fast for the processing to be performed in real time. In
this case, you do not need a ring buffer. Instead, you have the ISR fill
the arrays and, when they are full, the main program can take on and
start the processing. For coordinating these jobs, you just need a
boolean to keep track of whether you are performing the acquisition
phase or the processing phase. Note that, since accessing a boolean is
an atomic operation, you do not need to disable interrupts for this.
Here is an example implementation of this strategy. The variable
sampling_done is used to coordinate the two processes:
const size_t sample_count = 256;

volatile int gauge0[sample_count];
volatile int gauge1[sample_count];
volatile bool sampling_done = false;

ISR(TIMER1_COMPA_vect) {
    if (sampling_done) return;  // nothing to do

    static size_t sample_idx = 0;
    gauge0[sample_idx] = analogRead(A0);
    gauge1[sample_idx] = analogRead(A1);
    if (++sample_idx >= sample_count) {
        sample_idx = 0;  // prepare for next round
        sampling_done = true;
    }
}

void process_samples(int Gauge0, int Gauge1) {
    // Whatever needs to be done with the samples:
    // computation, printing...
}

void loop() {
    if (sampling_done) {
        for (size_t i = 0; i < sample_count; i++) {
            process_samples(gauge0[i], gauge1[i]);
        }
        sampling_done = false;  // start next sampling round
    }
}

Now some random remarks:

There is no need to sei() in setup(): interrupts have already been
enabled by the Arduino core initialization.

Do not reset TCNT1 within the ISR: this is handled automatically by
the CTC mode. If you do this in software, you risk missing timer
ticks.

Do not store the readings in float variables: they take twice the
memory of an int and all operations on floats are incredibly slow
compared to the equivalent operations on ints.

The scale factor for converting the readings to percent scale is
100.0/1024: the maximum possible analog reading (1023) is one ADC
step below the reference voltage: see the datasheet.

You should remove unused variables as soon as they become unused
(count, num, AVG). Once you do that you should notice you do not
need floats at all.


ATMEL SAMD11 SPI (Slave) With Arduino (Master)

You haven't set your SS pin as an output anywhere in your code.

The arduino page you linked to has a note near the bottom which reads:

  Note about Slave Select (SS) pin on AVR based boards

  All AVR based boards have an SS pin that is useful when they act as a
  slave controlled by an external master. Since this library supports
  only master mode, this pin should be set always as OUTPUT otherwise
  the SPI interface could be put automatically into slave mode by
  hardware, rendering the library inoperative. It is, however, possible
  to use any pin as the Slave Select (SS) for the devices. For example,
  the Arduino Ethernet shield uses pin 4 to control the SPI connection
  to the on-board SD card, and pin 10 to control the connection to the
  Ethernet controller.

The Example code given for the teensy board on the other page you linked has:

pinMode (slaveSelectPin, OUTPUT);

in its setup() function.

So that's what you're missing.
Setting the pin high or low is not going to achieve anything if its not an output.

Remember that SPI can access many diffrent devices using the same MOSI/MISO/SCK pins, but each slave device has its own Slave-Select pin which needs to be individually driven by the master.
Your master can therefore have many different SS pins, all set as outputs - and there is no single standard pin for this.


How do I connect components to the Arduino with a motorshield?

If you are up for a little soldering, look into stackable Arduino headers. (Feel free to shop around for those, adafruit was just the first result.) You could then use male jumpers and a breadboard to connect anything that fits in a breadboard.

Just be careful to avoid pins that the shield is already using.


How can an Arduino-Quadcopter be stabilized?

For stability and tuning you need to make the adjustment cycle time compatible with the physical system.  How fast does this adjustment code get called relative to how fast the physical system oscillates?  Without that under control, tuning the gains will be difficult, particularly for krI and krD.

For instance, if you are updating every millisecond, and it takes a 1/10th of a second to physically flop over from -90 to 0 at the current roll_thrust setting, there's only enough kP to adjust the roll_thrust kP*(RollDelta/2)*DT/dt=0.002*(90/2)*0.1/0.001=9  Is that a sane adjustment for a thrust/motorPower of 1200+?  If you sample fast enough to make it capable of a full-throttle (+/-800?) adjustment with this particular kP, you might need to sample 88x faster (1ms/(800/9)=0.01125ms).  From the other direction, I'd figure out how fast you can sample, then choose a krP that could get you a full-bias adjustment in reasonable time.

Maybe think of adjust as roll_thrust state variable measured in units of ESC_microseconds, and krP is the conversion factor from whatever error you are measuring.  Is it roll angle error? roll rate error? Absolute roll rate error?  It looks like this bit:

float newRate = 2 * (newRoll - currentRoll); // How fast should the drone try to
if (newRoll - currentRoll < 0) {             // adjust, based on the error.
   newRate = 0 - newRate;
}

is essentially:

float newRate = 2 * abs(newRoll - currentRoll);

which might make control discontinuous.  If currentRoll is a positional roll angle setpoint, it won't be able to tell if it is on one side or the other.

If you want a roll angle of -90deg to make full throttle one way and 90deg to full throttle the other, then krP should be on the order of 900us/90deg=10us/degree.   And krI=krD=0 to start with.

I'd code up separate PIDs for thrust, roll_thrust, pitch_thrust, yaw_thrust control variables and then sum them together to get the  {NE,NW,SE,SW}Power outputs.  Then you could monitor and control in {thrust,roll_angle,pitch_angle,yaw_rate} space and the coding will be more straightforward and interpretable.


In C++, you can't use or reference a function before it is declared, that's not Arduino specific, it's how C++ "works"

Moving the callback function above the client declaration won't help, because the callback function references client

The only solution is to declare the callback function before it is referenced in client initialisation, but have the definition of callback after

i.e. add one line

WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int length); // add this in your code
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

Nothing else needs to be changed

Please excuse some terminology mistakes above - it's been a long time since I learned C/C++, while I know how to use it, I don't always know how to describe it :p

  apprently there's some bug in the toolchain - see the comments in the question. However, this is still a valid solution, I guess it works around the bug


I figured it out. I am putting a logic level converter On the 3v pin to step it up to 5v


Converting human readable date to a unix timestamp

After parsing the time into numbers, you can use the standard C time library time.h. More specifically, use the mktime function to convert a struct tm into a time_t, and use difftime to get the seconds since the start of the Unix expoch:

#include <time.h>

void loop() {
    struct tm ltm = {0};
    ltm.tm_year = 2019 - 1900;
    ltm.tm_mon  = 11 - 1;
    ltm.tm_mday = 5;

    double epoch_seconds = difftime(mktime(&ltm), (time_t)0);
    Serial.print("Remember, remember, ");
    Serial.print(epoch_seconds);
}

Note that in struct tm, the year starts at 1900 and the month starts at 0.


digitalRead not reading input pin of ESP8266-01

The expression read3 + " input" performs pointer arithmetic, i.e. you either add 0 or 1 to the start adress of " input", so you get either " input" or "input". Does the leading space disappear when pressing the button?

To correct your code you can print the number separately:

Serial.print(read3);
Serial.println(" input");

You should get rid of the rest and pub-sub code. You can add this later after having solved the problem with the button.

Also note that GPIO03 uses the same pin as RX. The docs state the following:

Serial uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX).

So it should work after disabling Serial and after providing a pull down resistor. The resistor is needed to prevent having a floating input.


Pins 6 to 11 of the esp8266 are QIO SPI pins connected to flash memory of the esp8266. You can't use them.


Yes. Most manufacturers would just require a binary (or HEX depending on MCU) file of your compiled code. If it's not a system they already know how to handle you will also need to provide a procedure for them to follow to program the device. What form that takes depends on the manufacturer.

You can also generally order pre-programmed MCUs and modules direct from the manufacturer where they (for a small fee) will program the chips for you before they are then sent to the board manufacturer for population.

If there is no facility on the MCU manufacturer's website then just email their sales department and I am sure they would be happy to quote you. Again, all they will require is a HEX or BIN file (depending on manufacturer) for programming.


Need help with using pulseInLong to time a sensor

You cannot use pulseInLong() because it is a blocking function. It
waits until the input rises, then waits until it falls again, and only
then it returns a value. While it's waiting, the rest of the program
cannot run. This means you will not be able to actually generate the
signal you are trying to time.

The easiest solution is to time things yourself with micros(). You
have to implement an edge detector, i.e. some logic that remembers the
previous state of the signal and notices when it changes:

static bool is_high;  // is the input currently HIGH?
static uint32_t time_of_rise;  // when did it rise?

if (!is_high && signal_1 >= 200) {  // rising edge
    time_of_rise = micros();
    is_high = true;
} else if (is_high && signal_1 < 200) {  // falling edge
    uint32_t pulse_width = micros() - time_of_rise;
    is_high = false;
    Serial.println(pulse_width);
}


I do not understand, how you initialize the DHT sensor object.
(I wonder why this compiles at all.)
Your way:
//dht11 kodu için ayarlamalar
#include <dht.h>
dht DHT;
#define DHT11_PIN 7

I would use:
//dht11 kodu için ayarlamalar
#include <DHT.h>
#define DHT11_PIN 7

DHT dht( DHT11_PIN, DHT11 );

Don't forget to start the DHT object with:
void setup() {
  // ... code removed for brevity
  dht.begin();
}

Now use the dht object instad of the DHT class.
sicaklik = dht.readTemperature();
nem = dht.readHumidity();

You did not specify what libraries you have used. But I tried all DHT libs I could find and none of them compiled with your code without errors.
The following code compiles on my IDE for an arduino UNO having olivers ug8lib and adafruits DHT sensor library installed. BTW: You even did not mention the Arduino/ESP you used. So I guess it is an UNO.
//dht11 kodu için ayarlamalar
#include "DHT.h"
#define DHT11_PIN 7
DHT dht( DHT11_PIN, DHT11 );

//ekran için ayarlamalar
#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE | U8G_I2C_OPT_DEV_0);
char bufferX [20];
char bufferY [20];
char bufferZ [20];

//fan kodu için ayarlamalar
int mot1 = 8;
int m ot2 = 9;
int en1 = 10;
int dir = 6;
bool state = true;
int nob = A0;
int val = 0;
int fan_hizi = 0;
String faces_str;
int faces;
float sicaklik;
float nem;

void draw(void)
{
  u8g.setFont(u8g_font_unifont);
  u8g.drawStr( 0, 15, bufferX);
  u8g.drawStr( 0, 30, bufferX);
  u8g.drawStr( 0, 45, bufferY);
  u8g.drawStr( 0, 60, bufferZ);
}

void setup()
{
  Serial.begin(9600); //iletişim ve dht11 verisi

  // pin ayarları
  pinMode(mot1,OUTPUT);
  pinMode(mot2,OUTPUT);
  pinMode(en1,OUTPUT);
  pinMode(dir,INPUT_PULLUP);
}

void loop()
{
  //dht11 kodu
  sicaklik = dht.readTemperature();
  nem = dht.readHumidity();
  delay(1000);

  //iletişim kodu
  if(Serial.available() > 0)
  {
    faces_str = Serial.readString();
    faces = faces_str.toInt();
  }

  Serial.print(faces);

  //sınırlar
  if(faces == 0 && sicaklik < 25 && nem < 65)
  {
    fan_hizi = 50;
    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
  }

  if(faces >= 1 || sicaklik >= 25 || nem >= 65)
  {
    fan_hizi = 250;
    digitalWrite(13, LOW);
    digitalWrite(12, HIGH);
  }

  //ekran
  sprintf(bufferX, "Yuzler: %d", faces);
  sprintf(bufferY, "Sicaklik: %d", sicaklik);
  sprintf(bufferZ, "Nem: %d", nem);
  u8g.firstPage();

  do
  {
    draw();
  }  while ( u8g.nextPage() );

  delay(10);

  //fan kodu
  analogWrite(en1, fan_hizi);
  digitalWrite(mot1, HIGH);
  digitalWrite(mot2, LOW);
  delay(1000);
  digitalWrite(mot1, LOW);
}

I do not have the time to assemble the hardware to try it.
So I can say it compiles, but I can not say it works.
EDIT:
Now I found adidax "DHT11 lib". your code compiles with this library. But you forgott to read the values from the sensor, before you read them from the variables.
The following line is missing:
void loop() {
  //dht11 kodu
  DHT.read( DHT11_PIN ); // <-- this line is missing
  sicaklik = DHT.temperature;
  nem = DHT.humidity;
...


Atmega8 with Arduino bootloader - wrong serial characters

Ok I found a solution (rather workaround).

I uploaded the same program to Arduino Uno. It worked perfectly. I transplanted the Atmega328 from Uno to breadboard. Still worked BUT the Atmega328 is using external 16Mhz crystal (which I added to the breadboard).

So what if I uploaded bootloader for 16Mhz external crystal on Atmega8?
It makes it work properly.

So in short:
Atmega8 with 8Mhz internal oscillator doesn't work properly.
Atmega8 with 16Mhz external oscillator works properly.

Don't know why does it make it work. If anyone can think of a reason I would be glad to know it. Thanks for all your help.


How to make an SMS notification to my phone with Arduino Uno?

It is possible if your provider has a sms gateway e-mail-address. Just google which it is for your provider (e.g. number@tmomail.net for T-Mobile (US)). And there should be a lot of tutorial about how to send an email with an arduino.

Every wifi-module with arduino support will work if your WiFi is a standart 3.6Ghz. And yes it should work with any arduino compatible microcontroller.


You're not giving your eyes time to see the numbers change. If you were a pigeon you might just see some numbers flicker past very rapidly, but we mere humans don't have a hope of seeing them - not without introducing some delay.

void loop() {
  // count from 9 to 0
  for (byte digit = 10; digit > 0; --digit) {
    delay(0);  // <--- Number of ms to wait between each digit
    sevenSegWrite(digit - 1);
  }

  // suspend 4 seconds
  delay(0);  // <--- Number of ms to wait between counts.
}


How to properly use volatile variables in Arduino?

You need to learn about critical sections.

What is probably happening is that the variables are being changed by the interrupt routines mid-way through the calculations. Your 'fix' reduces the time spent doing the calculation with the volatile variables thus making it less likely that there is a collision.

What you should do is copy the volatile variables to local variables with interrupts disabled for that brief period.

cli();
int l = encoderLpos;
int r = encoderRpos;
sei();

Because the Arduino is an 8 bit CPU it takes multiple assembly instructions to perform mathematical operations on 16 bit values. Floating point is even worse using many many instructions for a simple addition. Division and multiplication use considerably more. An interrupt has plenty of opportunity to fire during that list of instructions. By doing an assignment like that and then using the new local variables in your calculations the instructions needed to deal with the volatile variables is kept to an absolute minimum.  By turning off interrupts during the assignment you guarantee that the variables can't ever be changed while you are using them. This snippet of code is called a critical section.


How to Connect ESP8266 with ultrasonic sensor and dht11 without breadboard?

If you do not want to use a breadboard, you could solder the wires together of tie them together, so long as none of the wires which aren't supposed to be touching are touching. Or you can also use flex tape! (Don't mind my meme)


The example at the bottom of this Arduino reference page does exactly that. If you want to change the way the value varies, you can just modify the variables in a loop or in whatever approach you prefer instead of analogread'ing it.

https://www.arduino.cc/en/Reference/AnalogWrite


How to program Arduino manually via STK500?

Okay, by comparing the data packets my implementation sends with those from the avrdude log for the same sketch, I finally found the cause of trouble. I was sending the hex file byte-by-byte exactly as it is read from storage. But of course, the metadata needs to be skipped (i.e. the addresses at the beginning of each line, the magic bytes at the end of each line, and the newline). I added this simple fix, and now it works fine.
EDIT: Here is the preprocessing code from my Python3 script:
import codecs

program = b''
for line in open('sketch.hex', 'rb'):
    program += codecs.decode(line[9:-4], 'hex')