Pin Mapping of nRF2401L01+ using Adafruit's nRF24L01+ library

DR1 is MISO
DAT is MOSI

Though I'd advice using the RF24 library, as it's a lot more recent than the one from 2009 you linked to.


Serial, Numbers sent as Floating Point and Characters are different at 1e-8 level

This is a somewhat dumb question but, in case anyone else searches it as pointed out:

  The precision of a float is around 7.2 decimal digits. en.wikipedia.org/wiki/Single-precision_floating-point_format –  BrettAM

So in python the number goes float -> double -> decmial, whereas on the arduino the number goes float -> decimal. The additional step of the double in the case of python causes the discrepancies. But anything after the 7th decimal place is nonesense anyway.


There is a bug in early versions of the Mega2560 bootloader.  It crashes on !!! (or enters some other special state that stops uploading happening).

Your string that contains !!! will be breaking it:

Serial.println("Ended !!!");

Simple solution: don't use so many exclamation marks.


I don't know if I understand your question well, but if what you want to do is reset MCU programmatically, watchdog is good solution.
The orther way is connect IO port and reset port by using wire, and send a signal(send LOW or HIGH voltage to reset port) to reset port.
Or use asm code.


Connect each of the 3 "L" wires to 3 separate digital IO pins of an arduino e.g. D8, D9, D10 via a resistor say 470 ohms but the value is not too critical. Connect VDD to the arduino +5v.
Use the arduino IDE write a sketch that configures pins 8 9 and 10 as outputs and then see what happens when you send these pins HIGH or LOW. Theres lots more you can do. Good luck.


Issues with reading numbers from serial port

The problem here is that Serial.parseInt() stops when it sees the
newline, but it does not consume that newline, which is left in the
input buffer. Thus, at the next loop iteration, Serial.available()
returns true because of this newline and, unless you send another value
fast enough, Serial.parseInt() times out and returns zero.

The easy fix is to consume that newline yourself:

void loop() {
  if (Serial.available()){
    setpoint = Serial.parseInt();
    if (Serial.peek() == '\n') Serial.read();  // consume LF
    Serial.print("Set to: ");
    Serial.println(setpoint);
  }
}

I personally would not use Serial.parseInt() at all, and would buffer
the data myself until I see the '\n'. This way there are
no surprises with timeouts being read as zero.


Getting error while uploading a sketch through Ardunio IDE

Reinstall the bootloader using your ISP programmer.

Installing a sketch using ISP first wipes the chip clean, and that includes the bootloader. Without the bootloader the USB interface won't be able to communicate with the main MCU.


According to the datasheet the LM317 has a minimum Vin to Vout of 3v so you'd only be able to get 2v out of it if you put 5v in.  I'd recommend using either an AMS1117 3.3 or one of the cheap modules based on that chip that has an LED and capacitors on board. They definitely deliver 3.3v from 5v in.


To properly answer this, you first have to determine how long you want your application to be able to run on a full charge. Clearly, it'll run on a 9V battery, but not for very long.

To determine the appropriate power supply, you need to calculate the overall voltage and current requirements for the various components.

The Mega needs a pretty minimal power supply, just 5V @ 200mA.

You don't specify the ratings for your motors. Servos are typically 5-6V @ 500mA, but I'm only guessing. Steppers and DC motors vary quite a lot.

The first step would be to find the specifications for all your motors, and find the maximum values, specifically the operating voltage and stall current. Hypothetically, say the maximum voltage for all the motors is 5V, and the stall currents for the steppers, servos and DC motors are 1A, 1A, 500mA, 500mA, 3A, and 3A respectfully. (Again, this is just an example. Find the true values yourself). That means you'll need a supply that can safely deliver 1+1+0.5+0.5+3+3+0.1 = 9.1A @ 5V or 45.5 watts.

If you want to use a battery (instead of a stationary supply like a DC adapter), you'll need to chose a battery with adequate mAh rating, which is the total number of amps it can deliver in 1 hour.

Perfectly predicting battery life greatly depends on the battery chemistry and your application's average current draw, both of which great very complicated, so I won't go into that here. A battery is considered effectively "dead" when it's depleted to around 80% of it's fully charged voltage. You can lookup the formulas and do the math yourself, or you can use some online calculators to help you estimate discharge times for different battery and load configurations.

However, as a general rule of thumb, you want to select a battery with a voltage greater than the minimum voltage required by any of your components. For your application to run for 1 hour, it's mAh rating should also be greater than your application's total current consumption. To run longer, you'll need to find a battery with a higher mAh rating, or higher voltage that a switching regulator can use to convert that extra voltage into current.

The other important factor, which complicates these calculations, is the type of voltage regulators you use. If you want to power everything from a single battery, you'll definitely need some voltage regulators. Preferably, you should use high-efficiency switching regulators. For this purpose, you can find cheap UBECs used for RC applications on Amazon or Ebay. You should have one for the Arduino and each motor (or pair of motors if you want to save on cost or complexity). Just make sure the regulator's voltage and current requirements are greater than what's consumed by your components.

I find using 2 or 3 Lipo batteries in series, especially 18650 cells, are the cheapest and easiest way to provide power for mobile applications that have high spikes due to motors. For stationary applications, a 12V DC wall adapter with a high current rating would be simpler.

If you want to use akalines, I'd recommend using separate batteries for the Arduino and motors. Akalines aren't well known for being able to deliver high current. Motors can demand a lot of current, and if the battery can't deliver enough, it'll cause the voltage to drop, resulting in the Arduino browning-out. However, lipo batteries, or non-rechargeable lithium batteries are better suited for this.


Programming Arduino Uno R3 to trigger a relay once every 24 hours

Yes, the delay() will work, as will other methods based on the millis() counter. However, delay() will make it impossible to do something else in the meantime.
Look up Blink without delay for an example of how to accomplish such a delay while being able to do other things in your code while waiting.
Casting
When dealing with large numbers such as your 24-hour delay, make sure to explicitly cast those numbers as unsigned long, or expressing them with the "UL" extension (like for example 86400000UL). This explicitly tells C++ to expect an "unsigned long" (which in Arduino Uno terms is a 32-bit unsigned number).
In your case (with such an obviously large number), the compiler will automatically choose the right type. In other cases (for example, if you change the expression to 24*60*60*1000), the compiler will not automatically generate an unsigned long and you need to force it by changing the first part of the expression to an unsigned long: 24UL*60*60*1000 or, alternatively (unsigned long) 24*60*60*1000.
Accuracy
The accuracy of the timing will be dependent on the type of oscillator on your particular Arduino board. Many Arduinos or their clones use a Ceramic Oscillator that generally have an accuracy of about 0.1 to 0.5%, meaning a possible deviation of 43 seconds per day and as such maybe too inaccurate for your purposes. If your Arduino has a Crystal oscillator, it will be much more accurate (to something like 150ppm, meaning a maximum deviation of about 1 second per day under normal conditions).


Reading analog signal from digital pin #6

That is not possible. AIN0 is an input to the analog comparator, not the analog-to-digital converter. Only ADC0 through ADC8 (connected to the internal temperature sensor), the 1.1V reference, and ground can be connected to the ADC.


You're missing closing brackets in the line above your error.

It compiles now, but I have no idea whether it works as you intend.
Try forcing yourself to always open and close brackets when you begin one, and making sure to indent properly.

Also, Arduino code is case-sensitive.

#define pinSom 7
#define pinRele1 2
#define pinRele2 3
#define tempoMaximoDeUmaPalma 150 //milisegundos
#define tempoMaximoEntrePalmas 500 //milisegundos

int contaPalmas = 0;
long tempoEspera = 0;
long tempoEsperaEntrePalmas = 0;

void executarAcao()
{
  switch (contaPalmas) {
    case 2:
      digitalWrite(pinRele1, !digitalRead(pinRele1));
      break;
  }
}

void setup() {
  // put your setup code here, to run once:
  pinMode(pinSom, INPUT);
  pinMode(pinRele1, OUTPUT);
  pinMode(pinRele2, OUTPUT);
}

void loop() {
  // verifica o estado do sensor de som (ele fica normalmente com
  int sensorSom = digitalRead(pinSom);

  //se o sensor detectou palmas
  if (tempoEspera == LOW) {
      //espera um tempo para não detectar a mesma palma mais de uma vez
    tempoEspera = tempoEsperaEntrePalmas = millis();
    contaPalmas++;
  }
  else if ((millis() - tempoEspera) >= tempoMaximoDeUmaPalma) {
     tempoEspera = 0;
  }
    //caso exceda o tempo maximo entre palmas, zera o contador de palmas
  else {
    if ((contaPalmas != 0) && (millis() - tempoEsperaEntrePalmas)) {
      executarAcao();
      contaPalmas = 0;
      tempoEsperaEntrePalmas = millis();
    }
  }
}


Does the StringObject.reserve() function prevent memory fragmentation/leaks?

Reserving space will help reduce memory fragmentation, but much of what else you are doing is swamping that small improvement you have made.

The biggest area of concern is your cutString function, which you have omitted from your code above.  Passing a String as a parameter, modifying it, and then returning it again, ends up in new String objects being created and destroyed multiple times, which will make a mess of your heap.

Instead you should pass a String object by reference, and modify that object in-place. No need to return anything.

void cutString(String &theString) {
    // Modify theString here.
}

Of course, what you do in cutString could cause more problems - you should include that function in your code above so we can check it out.


so i edited code your as below
    #define mySerial Serial1

byte test_data[8] = {0x01,0x03,0x00,0x64,0x00,0x02,0x85,0xD4};

int data_count = 5;

void setup() {

mySerial.begin(9600);
Serial.begin(9600);
delay(1000);

}
int count = 0;
void loop() {

  if(count%10 == 0) {
    Serial.println();
    send_data();
  }

  count++;

  while(mySerial.available()>0)
  {
    byte b=mySerial.read();
    delay(1);
    Serial.print(b,HEX);
    Serial.print(" ");
  }
  //Serial.println(count);
  while(Serial.available())
  {

    byte a=Serial.read();
    delay(1);
    mySerial.print(a);

  }

  delay(1000);

}

void send_data() {
  Serial.println("send data");

  delay(1);
  for(char i=0;i<8;i++){
    mySerial.write(test_data[i]);
    delay(1);
    Serial.print(test_data[i],HEX);
    Serial.print(" ");
  }

  Serial.println();

  delay(1);


Using multiple timers and avoiding conflicts

The problem is the Servo library. This library is claiming all the timers, so you can't use them yourself. What I do to fix this is edit the Servo.h (or ServoTimers.h) file.

#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//#define _useTimer5
#define _useTimer1
#define _useTimer3
//#define _useTimer4
//typedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers }   timer16_Sequence_t;
typedef enum { _timer1, _timer3, _Nbr_16timers } timer16_Sequence_t;

This will remove the 2 timers (4 and 5) for the Mega boards, but you can still attach 24 servo's. If you need more, you should edit this file again.


The basic pattern goes like this:
when you start the timer, you essentially store the current millisecond.
After this, in your loop code, among other things you should check if the time has passed by comparing current millisecond with the stored one. If their difference is equal or bigger of the desired delay interval, then the time has passed.
Make sure you use unsigned long variables to store times and check if time has passed with the condition used below (if(millis() - mark >= interval ){...}) so you will not have problem even after millis() rolls over.
If you need more help, do not hesitate to ask.
unsigned long interval=2000; //2000ms
unsigned long mark;
boolean enabled=true;

void setup() {
    Serial.begin(9600);
    Serial.println("starting timer");
    startTimer();

}

void loop() {
    check();
}

void startTimer(){
    mark=millis();
}

void check(){
    if(enabled){
        if(millis() - mark >= interval ){

            enabled=false;
            Serial.println("time elapsed");
        }

    }
}


The keyboard library just sends key presses to the computer like a keyboard.  From the PCs point of view it's no different from you banging on the keyboard in front of it.  The Arduino can't control anything on the computer and it can't run any code on the computer.  Now if you can do what you want completely from the keyboard then arduino could send those same keypresses.  But the Arduino has no access to the PCs operating system or file system.


How come the console prints error `avrdude: usbdev_open(): did not find any USB device "usb"`?

This is because in the IDE I was using

Sketch → Upload Using Programmer [Ctrl + Shift + U]

However, I should have been using

Sketch → Upload [Ctrl + U]


Trying to save .wav files with new name every loop

I would (and do) use snprintf to format a string as a filename:

// Global scope, or local static
uint32_t myFileNumber = 1;
char filename[12];

// in your function - results in 00000001.WAV
snprintf(filename, 12, "%08d.WAV", myFileNumber);

%08d will allow between 00000000.WAV and 99999999.WAV and always with 8 digits. Any more and it will get truncated and corrupted (100000000.WA) but won't cause a buffer overrun. You will have to take precautions that you never have more than 100 million files ;)


It depends if your module has a battery backup or not. A bare chip, by itself, will loose everything. That's why many breakout boards will have a small lithium cell on them to retain everything when the power is removed.


How to produce multiple DC voltages for a single project

First you want to take a regulated 24V supply. To that you want to add a switch-mode ("Buck") regulator to drop you down to 5V.  You don't want to try using an LDO for this unless you are happy to have a heat sink the size of a small car. A good cheap choice is a "UBEC" that can take 24V in and give 5V out (I use these).

That 5V can then be fed direct into the Arduino.

Depending on what the "LED bank" is you may get away with an 18V (or adjustable) LDO, or an adjustable buck regulator. Or a simple (though high wattage) resistor may be all that is needed. You will have to provide more detail on this to get more help.


How can I make a Parallax Servomotor move a water tap correctly and prevent from vibrations?

When you set a servo motor to be in a specific position it is constantly and actively striving to keep in that position. The feedback from the internal potentiometer is constantly being processed and the motor adjusted to ensure that it remains at the right position.  Potentiometers, of course, aren't 100% perfect, and there will always be a certain amount of "noise" in the signal that means the motor will always be making really tiny adjustments.

That's perfectly normal.

The simple way to stop it trying to keep precisely to one position is to stop telling it to be in that position.

.attach() the motor
Move it to the desired position
Wait long enough for the motor to get to that position
.detach() the motor

When you call servo.detach() the PWM signal is terminated and the motor no longer has a position to keep to - so it just stops doing anything and goes to sleep.

The down-side of this is that if you have a load under tension (for example if you are lifting a weight with the servo) the tension is then free to move the motor.


Arduino screws up trivial program involving enum

You can workaround the issue by putting your enum and function into a namespace. You can even take advantage of C++ unnamed namespaces if you like:

namespace
{
  enum WhatArduinoIs {
    Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
  };

  void TellMe(WhatArduinoIs pls) { }
}

void setup() { }
void loop() { }

It's annoying (as are many things in the Arduino IDE), but it seems to work.

If you're more experienced with programming then you might want to consider using a 3rd party IDE with an Arduino plugin, such as Eclipse. The Arduino IDE is really only designed for beginners.


if it requires seperate programing of the atmega16u2,

It does.  Often an ATMega8U2 is used here instead though.

i'd like to know how.

You might start by having a look at HoodLoader2 and NicoHood's related projects.
This involves replacing the normal Xu2 transceiver firmware with HoodLoader.  There are different ways to do that outlined in the installation instructions.  If you don't have an ISP programmer or a second Arduino to behave as one, there's a method that involved burning an installer-sketch to the 328P which turns around and reprograms the Xu2 chip.
Once you have that done you can use their board definitions for put sketches onto the ATMegaXU2 itself.
Apparently, JP2's layout is flipped on some boards. So, beware of that.  In any case, the header it makes the ATMegaXU2's PB4, PB4, PB6, and PB7 available.  Sketches on the XU2 would use the Hoodloader pin mapping of these:

Arduino Pin No.
AVR GPIO PIN

D4
PB4

D5
PB5

D6
PB6

D7
PB7

Or course, now you need to find some way to coordinate what happens on the ATMegaXU2 with the ATMega328P.

i find my arduino has less pins and jp2 are the only ones left.

There are clever ways to reuse pins on microcontrollers.  For example, it is possible to put an LED and a switch on the same GPIO pin.  And there are GPIO expanders, SPI/I2C ADCs, etc.
Messing with JP2 and programming the ATMegaXU2 and having it coordinate with the 328P may be more trouble than you like just to get a couple extra pins.

but if it is not accessable, why do they have it ?

Just added capability.  Usually that header is unpopulated, so there's no part cost there.

and also , i completely dunno a thing about atmega16u2 . only thing i understand is that it makes the arduino more compatible with the usb input ...

It serves the role of a USB to logic-level-serial converter for connecting to the USART of the otherwise non-USB-aware ATMega328P (you have tagged UNO).  But, it can be made to run sketches.  Usually if you're doing this, it's to get native USB support on an UNO (or Mega, or..), e.g. so you can have your board act as a keyboard, like you might with a Leonardo or Micro or any other board that has native-USB in normal use.  And that's a large part of what NicoHood's project is about.


Can I improve this code (replacing delays with something else)?

You can use millis() to get a timer:
millis() Returns the number of milliseconds since the Arduino board began running the current program.

void loop(){
    if(millis() % 100 == 0){//%(modullo) is the rest of a division. 19%10=9 because10/10 = 1 and the rest is 9
        //you have wait 100 millisecond. When millis()%100 == 0 millis() is a multiple of 100.
    }
}

For your code you can do this:

int LED1 = 3;
int LED1 = 3;
int LED2 = 16;
int LED3 = 9;
int LED4 = 6;

//Ligth on -> 1 light off -> 0
int LED1Stat = 0;
int LED2Stat = 0;
int LED3Stat = 0;
int LED4Stat = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(LED1, OUTPUT);    //every 100 ms
  pinMode(LED2, OUTPUT);    //every 250 ms
  pinMode(LED3, OUTPUT);    //every 500 ms
  pinMode(LED4, OUTPUT);    //every 1000 ms

}

void loop() {
    //for no Delay
    if(millis()%100 = 0){
        LED1Stat = !LED1Stat;
        digitalWrite(LED1, LED1Stat);
    }
    if(millis()%250 = 0){
        LED2Stat = !LLED2Stat;
        digitalWrite(LED2, LED2Stat);
    }
    if(millis()%500 = 0){
        LED3Stat = !LED3Stat;
        digitalWrite(LED3, LED3Stat);
    }
    if(millis()%1000 = 0){
        LED4Stat = !LED4Stat;
        digitalWrite(LED4, LED4Stat);
    }
}

[EDIT]

long prevMillis = 0;
void loop(){
    if(millis()-prevMillis >= 100){
        LED1Stat = !LED1Stat;
        digitalWrite(LED1, LED1Stat);
        prevMillis = millis();
    }
    //...

}


Put ATmega328 in very deep sleep and listen to serial?

A board we make does this.

The RX pin is wired to INT0
INT0 pin set to input or input pullup depending on how the RX line is driven
On sleep, INT0 low level interrupt is enabled

//Clear software flag for rx interrupt
rx_interrupt_flag = 0;
//Clear hardware flag for rx interrupt
EIFR = _BV(INTF0);
//Re-attach interrupt 0
attachInterrupt(INT_RX, rx_interrupt, HIGH);

INT0 interrupt service routine sets a flag and disables the interrupt

void rx_interrupt()
{
    detachInterrupt(INT_RX);
    rx_interrupt_flag = 1;
}

On wakeup, we check for the flag (there are other interrupt sources)

On the comms side of things we use a message protocol that has a start character > and end character \r. e.g. >setrtc,2015,07,05,20,58,09\r. This give some basic protection against losing messages, as incoming characters are not processed until a > is received. To wake up the device we send a dummy message before transmission. A single character would do it, but we send >wakeup\r hehe.

The device stays awake for 30 seconds after the last message is received in case of new messages. If a new message is receive the 30 second timer is reset. The PC interface software sends a dummy message every second to keep the device awake while the user has it connected for configuration etc.

This method gives absolutely no problems at all. The board with a few peripherals uses about 40uA when sleeping. The actual current consumed by the ATMega328P is probably around 4uA.

Update

At look at the datasheet shows that the RX pin is also pin change interrupt pin 16 (PCINT16)

Thus another method without wires may be

Before sleep: Set the port change interrupt mask bit in PCMSK2 for PCINT16, clear the pin change port 2 flag in PCIFR, enable the pin change port 2 interrupt (PCINT16-PCINT23) by setting PCIE2 in PCICR.
Setup an ISR for the pin change port 2 interrupt and continue as before.

The only caveat with the port change interrupt is that the interrupt is shared across all the 8 pins that are enabled for that port. So if you have more than one pin change enabled for the port, you have to determine which triggered the interrupt in the ISR. This is not a problem if you are not using any other pin change interrupts on that port (PCINT16-PCINT23 in this case)

Ideally this is how I would have designed our board but what we have works.


ESP8266-12 is showing garbage when RST is given

Espressif says it can not be disabled.

Ref.: https://github.com/esp8266/Arduino/issues/3047


Which transistor I should use to switch 12V 0.8A?

If you look for "transistor" using the search box on this website, you'll find hundreds of results.

Here are a few examples that will answer your question.

Using a MOSFET

Using a TIP120 Transistor


Store data in flash/EEPROM and process it in parallel

A common method of overlapping data input with data processing uses double (or multiple) buffering.  For example, one of two buffers is processed in the foreground (that is, in the loop() routine) while another buffer is filled in background (via interrupt handlers).  Each time a buffer fills, the usage of the two buffers swaps: that which was being processed now refills, while the recently-filled buffer gets processed.  To make this work, buffer processing must take less time than buffer filling.

For recording conversion times, because free-running ADC conversions each take the same amount of time, you can just save fill-start and fill-end times with each buffer, and interpolate to find out reading times.

If you plan to process audio data at near-normal speeds, it's likely most Arduinos won't be fast enough to keep up.  However, using an Arduino Due probably is feasible.  The Due is based on an ARM Cortex M3 processor with 72 MHz operating frequency, 32-bit arithmetic, large RAM (for an Arduino), etc.

An alternative method of processing audio data is to use a frequency analysis chip.   Here is a low-end example:  The MSGEQ7 Graphic Equalizer Display Filter is about $5 in an 8-pin DIP package from sparkfun.com.  Apparently, it continuously measures peak spectral intensity in each of seven frequency bands, and can read the peaks out perhaps a thousand times per second.  Audio goes in on the "Audio in" pin.  A Reset pin resets an output-multiplexor counter to zero.  Each time after you clock a strobe line, a band's reading is presented as an analog voltage on a "DC out" output line; the band's peak reading is decayed about 10%; and the multiplexor advances one band upward in frequency, rolling over from highest to lowest every seven strobes.


Solved: GPS module was broken. Now I use another GPS module, same model. Sorry for my English.


Buzzer interfere with thermistor reading

You can use the output of your regulator as the reference voltage for your analog readings. That way, no matter what the voltage you voltage divider for the thermistor uses, the "upper" voltage that the ADC uses is always the same as the thermistor's voltage.

Simply connect the output of the regulator to the AREF pin, and set the ADC to use the external voltage reference:

analogReference(EXTERNAL);

Now you have the range 0-1023 covering 0-3.3V (or whatever the voltage is the regulator is outputting), and because the output of your voltage divider is just a ratio of that voltage, that ratio will always be a ratio of 1023, regardless of what the voltage happens to be.

You have, in effect, removed the voltage from the equation. All you are left with is the value as a fraction of 1023, which is then directly proportional to the resistance of the thermistor.


Need help with EEPROM not storing array values on ESP8266 after restart

The ESP has no real EEPROM. Instead the EEPROM class for ESPs uses the flash memory. There is a difference in the implementations of this class between Arduinos and ESPs:
On an ESP every data, that you write, will first be placed in a buffer in RAM. You  need to call EEPROM.commit() to actually write that data to the underlying flash memory.
So you need to add
EEPROM.commit();

to the end of your EEPROM_Write() function, or the data will stay in RAM and thus be lost on power cycle or reset.

I think your problem (besides the commit) lies not in your EEPROM_Write() function, but in the EEPROM_Read() function. If it doesn't work correctly, you are just not able to see, if the data gets written correctly. In your code (which can be seen in the edit history), you have this function:
void EEPROM_Read(){
   //load array pwmarray1 with stored values in EPROM
  for (int x = 0; x < pwmarray1Size; x++){
    EEPROM.get(EEPROMStartAdress + (x * sizeof pwmarray1[0]), pwmarray1[x]);
        Serial.print("loading program from EPROM: ");
    Serial.println(pwmarray1[x]);
    }
}

While in EEPROM_Write() you are calling EEPROM.begin(280) every time, you don't EEPROM.end() it there and you are also not begin the EEPROM in the EEPROM_Read() function. I'm not sure about the underlying implementation, but it started to work for me, when I began and ended the EEPROM object in both functions.
I've written a test code, that I composed party of your code and that for me correctly saves and reads an array via the EEPROM object into the flash memory. It keeps the data over resets and power cycles just correctly. You can control it via Serial Monitor. Just type c (for clearing the array to zero), r (for reading the array from EEPROM/flash) or i (for incrementing all array elements and save them to EEPROM/flash).
#include <EEPROM.h>

#define EEPROM_SIZE 280

int array[60] = {0};
const unsigned arraySize = sizeof array / sizeof array[0];

#define EEPROMStartAdress 0

void setup(){
  Serial.begin(115200);
  Serial.println("///////////////////////////////////////");
  delay(2000);
}

void loop(){
  if(Serial.available()){
    char c = Serial.read();
    switch(c){
      case 'c':
        for(uint8_t i=0;i<arraySize;i++) array[i] = 0;
        EEPROM_Write();
        Serial.println("EEPROM RESET");
        break;
      case 'r':
        EEPROM_Read();
        break;
      case 'i':
        for(uint8_t i=0;i<arraySize;i++) array[i] += 1;
        EEPROM_Write();
        break;
    }
  }
}

void EEPROM_Write(){
  EEPROM.begin(EEPROM_SIZE);
  // store values in EEPROM
  for (int i = 0; i < arraySize; i++)
  {
    EEPROM.put( EEPROMStartAdress + (i * sizeof array[0]), array[i]);
  }
  EEPROM.commit();
  EEPROM.end();
}

void EEPROM_Read(){
  EEPROM.begin(EEPROM_SIZE);
  for (int x = 0; x < arraySize; x++){
    EEPROM.get(EEPROMStartAdress + (x * sizeof array[0]), array[x]);
    Serial.print(" ");
    Serial.print(array[x]);
    }
  Serial.println();
  EEPROM.end();
}

Removing begin() and end() from EEPROM_Read() and also end() from EEPROM_Write() gives me the same results, that you described as your problem.


UNO analog input voltage reading not accurate

Your question contains a number of errors and misconceptions.

Firstly the maximum output of a successive approximation ADC (here 0x3ff) corresponds to Vref - 1 LSB
The voltage will thus be sensorValue*5000.0/1024. Note this error is less than the error of ±2LSB.

Measuring your 5V is futile, as this is the default analog reference, so the result must be 0x3ff.

Measuring the 3.3V pin will give a relative value to the 5V reference. Both are produced from commercial grade regulators with a accuracy of ±5%.

You are also confusing the precision of the reading (10 bit) with accuracy which is a best ±5% ±2LSB.

If you really want to measure voltage you should use the internal 1.1V bandgap reference. You would of course need to reduce the 5V and 3.3V to less than 1.1V. This introduces another potential error (even if you use 1% resistors), but would give more accurate results which are directly comparable.


Documentation for creating a Board Manager profile for the Arduino IDE

Documentation is kind of scarce.

Basically there are two aspects to what you want - the board definition and the board manager JSON file.

The first describes the board to both the IDE (entry in boards.txt) and to the API software (definition of what pins are what and what peripherals are where, etc).  The latter is in the file pins_arduino.h.

Then there is the JSON file that describes the whole package to the board manager and is what allows people to download the boards.txt and pins_arduino.h files (and anything else you may require) from your website.

As there is not much documentation you are best off taking an existing set of files that are close to what you want and modifying them.  Most of the time it will be a slight tweak such as re-ordering a few pins in some arrays, or changing the name of the board and maybe an upload command or baud rate setting.


Nano board has a bunch of analog and digital pins. It does good and cheap. But for convenience UNO board is preferable for its large size easy handling and easy pin and wiring management.


16-Channel 12-bit PWM/Servo Shield check if it is powered by adapter

I would propose a circuit like the following:

simulate this circuit – Schematic created using CircuitLab

The voltage divider (consisting of the resistors) will divide the 6V to 5V for the Arduinos digital input. The values are not critical, they can be made higher, but maintain the relationship to still get the 5V. The diode will prevent current to flow from the shield into the voltage divider, when the shield is powered through other means. Now you can simply do a digitalRead() on the corresponding digital input pin of your Arduino, to check, if the power was applied.

Please notice, that the diode will reduce the voltage a little by it's forward voltage (depends on the diode). But that shouldn't be a big problem.


If you power the Arduino with an external power supply the on board regulator has to dissipate the voltage difference between input and 5VDC at the total current you draw from the board.

As Klaus Warzecha wrote in an answer to another question

  The Arduino is just the brain, not the power station.

If the output voltage of your power supply is 12V, then the regulator will be dissipating 12-5V = 7 V at the total current drawn. Total dissipated power for eg. 150mA (just an estimate) would be P = V × I = 7 × 0.150 = 1W
The regulator will be pretty hot from dissipating 1W.

Mind you that the current is not limited to 150mA, enough LEDs can easily increase current and power. If the regulator is stressed (often) enough, sooner or later it will fail. It is better practice to power any load directly from the external power supply, taking the higher voltage into account.


arduino sketch on Win7 vs. MAC op system?

I've had the same issue with Mac OSX 10.6.8 vs Windows XP SP3 using the same IDE version. I don't have a definitive answer for you, but I know that Microsoft has more frequent updates compared to Apple, which could be the reason. I suspect my issue and your friend's issue is the GCC compiler we're using. The compiler would be updated on OSX only when you update your entire OSX version. To get around that, there are third-party package managers: Homebrew and MacPorts that would allow you to just update the GCC compiler for example.


Is the analogread function averaging the samples taken by the ADC?

As far as I understand the analogread() function samples an analog input at 10kHz rate.

No, it samples an analog input at once per invocation. This means that if it is run 10000 times within a second (assuming it can be run that many times within a second) then the code is sampling at 10kHz. But if it's run only twice per second then the code is sampling at 2Hz.


Are there any Wi-Fi modules for the Arduino Uno that may connect to an external Wi-Fi Antenna?

There are variants of ESP8266-based modules which include a connection for an external antenna. The ESP-02, ESP-05 and ESP-07 modules all feature a U.FL socket.

Effectively, they are an ESP8266 mounted on a carrier board with a U.FL socket.

If you already have some code to suit an ESP8266-based module, this will avoid having to rewrite for a different unit.


Corrupted files generated by Arduino with SdFat library. How to avoid that?


How do I know the size of the bootloader of ATtiny? Is it the same as ATMega328P?

1) I want to know how much memory it has taken

Look to see how big the bootloader is. If it's a HEX file you will either want to load it into a HEX (Intel HEX, not hexadecimal representation) file editor, or convert it to binary with avr-objcopy.

$ avr-objcopy -I ihex <hex file> -O binary <bin file>

  2) and if this bootloader is the same code of a bootloader used in the 328P or other chips

No, each chip requires its own special bootloader - simply because all chips are different: that's why they exist.  If they were all the same there would only be one chip.

  3) Can I see this code in any way, to know how it works ?

If it's open source and you download the bootloader from wherever it's stored (probably Github somewhere), then yes, you can. Of course, that also assumes that you would understand what you are seeing which, judging by this question, is not that likely.


Some good results you can get with optocouplers.

It's electrically disconnects one part of your circuit from another.

For example, here is my IoT-ish device, which is detects water leaks in my bathroom:

I use the transformer (T1), which have two separate output windings, so, that windings does not connected electrically, only magnetically. The block in border "Sensing unit" doesn't have any wires with other scheme - only magnetic field, which is gives it power, and infrared light in the optocoupler (u2, PC817), which informs ESP01 about leak presence.

How does it work? Very simple! When the water shorts JP1 (long naked wires on the floor), Q1 opens and lights-up the IR diode in PC817. Light from this diode opens another transistor - and pulls the RxD PIN of ESP01 down.

Small sketch, written on Arduino for ESP8266 periodically sends pin state by HTTPS on my web server, where monitor software, Nagios, checks the information age and the pin state, and send to me notifications, when something goes wrong.


what is fastest allowable serial baudrate?

The Arduino Mega 2560 runs at 16 MHz. There are online calculators making this easy, as the calculation is not a straight and simple formula.

http://wormfood.net/avrbaudcalc.php

which shows using 16 MHz

Baud Rate   UBRR(dec)   UBRR(hex)   % of error
300 3332    0x0D04  0.0
600 1666    0x0682  0.0
1200    832 0x0340  0.0
2400    416 0x01A0  0.0
4800    207 0x00CF  0.2
9600    103 0x0067  0.2
14400   68  0x0044  0.6
19200   51  0x0033  0.2
28800   34  0x0022  0.8
38400   25  0x0019  0.2
57600   16  0x0010  2.1 - Barely OK
76800   12  0x000C  0.2 - GOOD
115200  8   0x0008  3.7 - BAD
230400  3   0x0003  7.8 - BAD
250000  3   0x0003  0.0

Where it is noticeable that the Mega's Arduino boot loader uses

mega.menu.cpu.atmega2560.upload.speed=115200

which is above the acceptable 1% error rate.

While it is possible to support different baud rates than stated above, it is not advisable, as the above values are the standard values. Values in between are very atypical and likely not trustworthy on the corresponding other side of the connection.

As I see your above example is 1024000, it is also worth noting that HardwareSerial.cpp implements a method to convert the requested baud rate to configuration of the USART, and I would not necessarily trust it for non-standard baud rates, especially on older version of the Arduino IDE. You may want to try the latest 1.5.8+ and verify the rate.


Analog input weirdness (barrel connector vs USB power)

Looking at the schematic the barrel plug has a couple of linear voltage regulators (top left of schematic), while the USB input just has a couple of MOSFETs (bottom right of schematic) which are basically just there to switch off the USB power if there is something plugged into the barrel jack (and also maybe provide a little input protection). So the Arduino is relying on the USB power to be pre-regulated. For the most part this is correct, but USB voltage can vary widely depending on the cable length (voltage drop), the power source it is connected to (no two computers or wall warts are the same), and how many devices are the same hub (if connected to a computer or hub). I would not rely on the two power sources being matched at all.

The flicker you are talking about sounds like the power coming from USB could have significant ripple. I doubt that the USB power is allowing you to "oversample". The way ADCs in AVRs work is they have a reference voltage and when sampling, will give you a reading of where the voltage is between 0 and the voltage reference. With a 10-bit ADC there are ~1000 steps, so to measure 100uV changes, you would have to have a 100 mV reference voltage, which according to the datasheet (p.379), the minimum is 1.0 V. Basically, it is physically impossible for the Arduino Mega to measure those kinds of changes.

What is more likely to be happening is that you are probably getting some weird aliasing between the ripple frequency of your USB voltage and the sampling frequency of your code. The best way to debug this kind of thing would be to pull out an oscilloscope and check if and how much ripple is coming off the USB power.

If accuracy is important to your project, and being able to accept both power inputs is a requirement, you might look into maybe getting your own external voltage reference and piping it into VREF. Otherwise, I would stick to only using the barrel plug as it is regulated and will be consistent.


On a quick test build for an ATmega328p type Arduino, the implementation of random() and its unique dependencies seems to be about 180 bytes, so you might see if there's a more compact way of achieving your need there, perhaps using the low byte of some mathematical expression of the time, and just retrying until you get an in-range value.

Of course if you get really stuck, you could remove the bootloader and program it with ISP from an ordinary Arduino or something like that.


Fail to convert time_T from past to tm struct

replacing gmtime(&timeinfo) with localtime(&timeinfo) in myIOT32::convEpoch passes definition of time-zone as needed.
for more information in this cpluspls site


I need help purchasing components for my Arduino project

I would rather go with ESP8266. You can program that from the Arduino IDE. You don't need anything else than a programming cable (an USB-UART adapter), and you can connect the force sensor to the analog input with one pullup resistor.

There is a similar idea with one button here:
https://www.hackster.io/noelportugal/esp8266-ifttt-easy-button-888a87

You can build your own force sensor:
http://www.todayifoundout.com/index.php/2010/01/how-to-make-a-ridiculously-cheap-analog-pressure-sensor/

If you don't really need to measure the force, there are much easier solutions to detect weight of a person. These give a simple contact once pressed, and can be used like a button (see the first link in my answer).
http://learning.media.mit.edu/projects/gogo/documents/making%20sensors.html#Paper and Aluminum foil.

It is not really possible to buy everything as one batch :) I would say you need:

connection wires
plyers
some cheap multimeter
you may wish to power your device from a battery, so you may need a battery holder and batteries
battery voltage may not be a perfect match for ESP8266, so you might want to get a board with internal regulator, such as https://www.adafruit.com/products/2471
it is handy to start with a breadboard with jumper wires, something like https://startingelectronics.org/beginners/start-electronics-now/tut1-breadboard-circuits/building-cct-step5.jpg

I suggest you to find an ESP8266 based tutorial, Adafruit has a lot of those, and then you'll have an understanding about the tools and components needed.

If you buy some Arduino, consider buying the ones using 32u4 chip, such as Arduino Leonardo or Arduino Micro. The 32u4 chip has more memory, and more performance than the original Arduino Uno, plus it can work as an USB mouse or an USB keyboard too.

For infra (do you mean a PIR which detects humans, or a reflective sensor?) you have quite a lot of possibilities. In case of using ESP8266 directly, check that the sensors work on 3.3V. Some stuff works on 5V, others on 3.3V. You can interface them easily, but this is just another extra thing to cover, so better go with a dedicated 3.3V sensor.

Ultrasonic sensors are coming also in a lot of varieties. Do you need something ridiculously cheap? A sensor with a short range? A sensor with a longer range? I think you have to set up your goal first.

The Leonardo and Uno and Micro boards work both with 5V and 3.3V sensors. Driving these sensors are quite standard, you need to power them with two wires, and have one wire which goes from 0V to 5V (or vice versa) when something is detected. Ultrasonic sensors vary: there are sensors with one analog output, giving a voltage between 0V and 5V propoprtional to the distance. However most of ultrasonic sensors are simple as the ultrasonic principles: they have one input what you drive, and will give one output of the recived echo signal. In this case you have to measure the time elapsed between the drive signal and the echo, which depends on the distance of the object from the sensor.


I doubt you have misunderstood the way ultra sound works.  You send a pulse and then go quiet waiting for a reply.  The time it takes to send the pulse is the minimum distance you can detect things at.

If you are not getting returns left and right then it could be there is nothing there or turning the head is breaking a connection.

Firstly jack the vehicle up off the floor so it doesn't go anywhere.
Place a solid object (book) in front of the vehicle and make sure it detects it.
Now place the same object to the right of the vehicle, do it detect it?
Stop the US sensor when it is looking right (by killing the power) and check that it is looking horizontally.  Check the connections, are they being pulled loose?

Your code looks fine, you US works forwards so I think it is a mechanical issue with your car.


Run website / Javascript game from a Arduino UNO device?

The Arduino cannot run Javascript, no.

It could serve Javascript from an SD card to a web browser running on a PC / Pi / Phone, etc, but there is no way it can run it itself.


Sleep and Wake Arduino according to LDR interrupt

I want to replace the conditional check with interrupt.

Why? If it is awake it might just as well be testing the pin as doing anything else.

If you make it an interrupt, in the ISR interrupts will be off. Then if you go to sleep it will never wake.

So, your current design is the correct one, except:

attachInterrupt(0,wakeUpNow, RISING); function

What is function doing there?


It is a simple schedular. It only changes to another task when yield() is called. The delay() function uses yield() and a lot of code and libraries use delay().
That means that if you code does not contain a delay() then you need to call delay() or yield() now and then, or other tasks will never execute.
It is probably safe to use the same function, but every time a delay() is used, an other task could run or another task will continue from there.


Unexpected results and hard crash when modifying and addressing arrays & variables within a struct

You are not specifying a size for your readings array:

unsigned int readings[][28];

That is not saying "Give me an array of an unknown number of chunks, each of 28 values", it is actually saying "Give me a pointer to a block of memory (which I will provide later) which is arranged in rows of 28 values".

In C you must either provide a size for an array, in which case the memory is statically allocated for you, or manually allocate the memory at a later date.

unsigned int readings[16][28]; // 16 rows of 28 int values

Or, for dynamic allocation:

unsigned int readings[][28];

// allocate the memory ...
blah.readings = malloc(16 * 28 * sizeof(int));
// do things with your array ...
// and free up the memory when finished:
free(blah.readings);

On an embedded system it is generally to know how many readings you will be taking beforehand. That way you can allocate the correct number of rows to the array before you compile the program, which makes many things more efficient.


Not able to control DC motor speed with l298N & pwm pins

Try to use this code, without the library, and be shure to connect every pin to the correct arduino output! If everything is ok it should work! Check a tutorial here

int IN3 = 5;
int IN4 = 4;
int ENB = 3;
void setup()
{
 pinMode (ENB, OUTPUT);
 pinMode (IN3, OUTPUT);
 pinMode (IN4, OUTPUT);
}
void loop()
{

  digitalWrite (IN3, HIGH);
  digitalWrite (IN4, LOW);
  analogWrite(ENB,55);
  delay(2000);
  analogWrite(ENB,105);
  delay(2000);
  analogWrite(ENB,255);
  delay(2000);
  analogWrite(ENB,0);
  delay(5000);
}


You forgot the -c flag to your first command. That means you have first compiled your program into a full elf file. Then you try to link that elf file with the standard startup libraries again (it already contains them) into another new elf file.

And so you get duplicate entries in it.

Add -c to your first command, which means "compile only, don't link" to create object files not an elf file.


ADS1115 : measuring 5v voltages and powering with 3.3v

Is your arrangement bsafsm Yes, perfectly.

Is your arrangement a good idea? No, it is not.

When the ADS1115 is run at 5V it needs at least 3.5V on the I2C bus to properly register a HIGH.

However you can pull up to 5v instead and you won't have a problem.  Not only is the esp8255 tolerant of 5v, but that 5v is severely limited in current by the pull-up resistors, so even non tolerant inputs would have a hard time complaining. Worst case scenario, the ESP8266 pulls the bus down to maybe 3.8v (3.3v plus an ESD diode drop) which is fine for a logic high on the ADS1115.

However, if you want to do things properly, you really should use a proper I2C level translator.


Reading names of files on sd card returning odd file names

That's the way the FAT filesystem works.

On the page you link to there's a link to a page on SDCardNotes.

  FAT file systems have a limitation when it comes to naming conventions. You must use the 8.3 format, so that file names look like “NAME001.EXT”, where “NAME001” is an 8 character or fewer string, and “EXT” is a 3 character extension. People commonly use the extensions .TXT and .LOG. It is possible to have a shorter file name (for example, mydata.txt, or time.log), but you cannot use longer file names.

When you wrote the files to the file system you were on an OS that supports longer filenames. When filenames are too long there's an 8.3 name created automatically with chunks of characters removed and replaced with ~.


Bit Number to Byte Value conversion (AVR Docs)

The bits within a byte are numbered 0 through 7 from right to left. The
rightmost (least significant) is bit 0, next is bit 1... and the
leftmost (most significant) is bit 7.

The expression _BV(3) builds a byte where bit 3 is set (is 1) and all
other bits are clear (are 0). In binary it looks like this:

position:   7  6  5  4  3  2  1  0
bit value:  0  0  0  0  1  0  0  0

The macro expands to 1<<3, which takes the integer 1 (0b00000001 in
binary) and shifts all its bits by three positions to the left. The
result can be written 0b00001000 in binary, 0x08 in hexadecimal, and 8
in decimal.


Arduino's ESP8266 support includes an example sketch called CheckFlashConfig. This probes the board, and prints the flash memory size.


Sometimes it helps just adding the tags.....

The Blend is a Arduino Leonardo Chip -
and as Lady Ada helpfully points out, you need a special SD Library to use this. The advice on https://learn.adafruit.com/adafruit-data-logger-shield/for-the-mega-and-leonardo is everything I needed to get the cardinfo working, especially the     while (!card.init(SPI_HALF_SPEED, 10, 11, 12, 13)) {
part.

Also, the I2C Pins for the RTC Clock are not the "standard" Analog Pins 4 and 5, but D2 and D3 (see http://arduino.cc/en/Reference/Wire)


Arduino Nano and SIM300 module for http calls for location

Not really.

Module can read the cell ID by below command. However, only phone company has the list of cell ID and their location. This information is only accurate to serving range of a cell, mostly in range of, 0.1 to 15km, from very dense city to country

Module can also read network ID and know, from public information, the country and network operator name.

Example taken from web:

AT+CREG?

This should give you a result like:

+CREG: 2,1,"1030","639E"

Working through the 4 returned values, the "2" reflects the
current "+CREG" setting (2 means "Enables unexpected network
registration and location information messages"), "1" indicates
that the phone is registered with the network, "1030" is the
Location Area Code (LAC) in hex (4144 decimal), and "639E" is the
CellID (CI) in hex (25502 decimal).


Why my Arduino Uno R3 doesn't work with a recompiled optiboot with BAUD_RATE=57600

Chris Stratton's comments helped me find a workaround for my problem. It looks like the version of optiboot I was working with (see source-code here) doesn't work properly at 57600 BAUD with Arduino Uno without modifications (that I don't know how to make). So I compiled the bootloader with 76800 BAUD, configured the IDE accordingly, and all my boards started to work fine with it.

It is still unclear to me the reason I one can't use 57600 BAUD, but I'm too pragmatic and too little knowledgeable to go after the true answer. So, I'll take Chris' word for it. He said this:

  Basically, 57600 does not divide in 16 MHz nicely when the 8x or 16x oversampling of the hardware UART is taken into account. My gut feeling is that different implementation are using different approximations. If they used the same approximation then even if "wrong" things would be basically fine (especially as the hardware design is similar), but if they are are off in opposite directions it could be unreliable. If you post the exact bootloader source you used we can see for sure - some optiboot source I just looked at seems to actually be using a software UART for 57600.

That's the end of it for me.


EDIT: As noted by Klaus Warzecha, the SD library may only support 8.3 format filenames (i.e. 8 characters for the name, 3 characters for the extension). The solution may in fact be to ensure that the years is only 2 digits, resulting in names like: 20-12-14.csv

From what I can see in the SD library code, the open() method isn't designed to accept a String object as a parameter. It only wants a plain old C-style string (which means a char array). That explains why your first example doesn't work -- it's trying to pass a String object.

The second example unfortunately is invalid C++. You simply can't initialise an array like that. What you want to do instead is to build the String object, then extract the characters out using String::toCharArray().

Something like this should work:

String filename = String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv";
char str[16] = {0};
filename.toCharArray(str, 16);
dataFile = SD.open(str, FILE_WRITE);

I'm not sure what your now.year() returns; i.e. if that's a 2 digit or 4 digit year. I've assumed 4 digits, so I've made the char array big enough for 15 characters in total, plus an extra null terminator (which is essential for C-style strings).


Wemos Mini & Pro Micro Serial connection

You don't need a logic level conversion between 5 V Micro Arduino and 3.3 V Wemos D1 mini. The 5 V ATmega 328p reads 3.3 V as HIGH and the esp8266 can tolerate 5 V logic level for tests. For long term connection you can add logic level conversion with a voltage divider to convert the 5 V of ATmega TX to 3.3 V of esp8266 RX.
RX/TX pins on Arduino Mini are Serial.
RX/TX pins on Arduino Micro are Serial1.
Serial is only USB on Micro.


After update via ICSP can't use usb for Serial Reading and Usb for programming board

Assuming you have reprogrammed the Arduino Nano's Atmel processor (an ATmega328) directly using the processor's ICSP pins, you may have erased the Arduino boot loader from the processor.  In such a case you no longer have an Arduino.  Rather you have an ATmega328 processor surrounded by some hardware.

To recover you need to reprogram the ATmega328 processor with the Arduino boot loader.


In UART, what mechanism sets the "new data received" flag back to 0?

The ATmega328p data-sheet describes the setting of RXCn:
Bit 7 – RXCn: USART Receive Complete

This flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled, the receive buffer will be flushed and consequently the RXCn bit will become zero. The RXCn Flag can be used to generate a Receive Complete interrupt (see description of the RXCIEn bit).

The hardware seems to keep a register the size of the receive buffer. Incremented when received and decremented when read. It is only one level so the size is 0..1, i.e. one bit.
Actually there is two registers; one for possible incoming data and one for the latest data until read.
Cheers!
More details in ATmega328p data-sheet, chap. 19 USART0


Problem while writing sketch for GSM module sim800

You misspelled the variable senderNumber. Correct it. Also you aren't reading the SMS properly or comparing the phone numbers properly. Your code should be like this (using the examples):

#define MAX_MSG 50

char senderNumber[20];
char sms_buf[MAX_MSG];   // a buffer for your sms, max len = 50

if (sms.available()) {    // this part should be in loop()
  sms.remoteNumber(senderNumber, 20);
  if (strcmp(senderNumber, "09432167015") == 0) { // compare numbers
    while (sms.available() == 0);   // wait for a char
    char i = 0;
    while (i < MAX_MSG - 1){    // till max len is reached; 1 byte for null
      c = sms.read();
      if (c == '\0')  // assuming the modem terminates sms with null
        break;
      sms_buf[i++] = c;   // write char to the buffer
      while (sms.available() == 0);   //wait for a char
    }
    sms_buf[i] = 0;   // terminate the string, just in case
    if (strstr(sms_buf, "yes") != NULL)  // look for 'yes' in buffer
      alarm_police();
  }
}


Do I need the Ground and 5 V pin connect to Led?

I think it is not a good idea to power the LED strip via USB.

Normally USB delivers a maximum of mA  (see below). Assuming you have 30 LEDs (minimum for a normal LED strip), and each LED gives 40 mA (maximum), this is already more than what most USB ports can deliver. This can ruin your USB port.

For the Arduino Nano you can use the 5 V, and you should connect all GNDs together.

But you will need a decent adapter anyway for the LED strip, so than you can power your Arduino Nano from the adapter you use for the LED strip.

Update

According to Wikipedia USB power

  Low-power devices (such as a typical USB keyboard) may draw at most 1
  unit load (1 unit load is 100 mA for USB devices up to USB 2.0, while
  USB 3.0 defines a unit load as 150 mA), and all devices must act as
  Low-power devices when starting out as unconfigured.

  High-power devices (such as a typical 2.5-inch USB Hard Drive) draw at least 1 unit load and at most 5 unit loads (500 mA) for
  devices up to USB 2.0 or 6 unit loads (900 mA) for SuperSpeed devices.


Multiple Buttons to control the same led for different on off times

You're making your program too complex for its own good.

Instead of changing your blink code depending on which button is pressed, just make the button change the blink code's parameters, and stick to just one blink code.

That means having just one set of blink variables which your blink code uses, and your button code then just changes what values those variables contain.


On UNO, when serial.print to UART pin 11, nothing comes out of pin 11

Of course it's only coming out on the serial monitor - you are printing it to the hardware UART which comes out on the serial monitor.

You have created a SoftwareSerial object which you are then completely ignoring and then using the HardwareSerial UART object instead, which is on pins 0/1.

If you want to use a SoftwareSerial object you should actually use the SoftwareSerial object.

Replace all the references to Serial with mySerial instead.


Wire over 1ft does not work with sensors SRF02

Using the internal pullup resistors for I2C is not recommended.  Arduino are very wrong in providing those as the default option and basically "hiding" the fact that I2C needs decent pullup resistors from you.

The internal pullup resistors, because they are so weak (i.e., a high resistance, typically > 50KΩ), do not pull the clock and data lines up adequately, and as such are only suitable for very short connections (in the order of a few inches).  Anything longer and the induced noise and inductance and capacitance of the wires will corrupt the I2C waveform.

I2C requires pullup resistors in the range of 2.2KΩ to 4.7KΩ.  As you can see that is more than 10x the pullup strength of the internal resistors.

For off-board connections (i.e., wires) you want the lower end of that range.  So add a 2.2KΩ resistor between SCL and +5V and another between SDA and +5V and you should find it works much better.


Johnny-five driving LCD Matrix or call Arduino library from Johnny-five

After research, it can't be done, as J5 use firmata to drive the Arduino, the only way is to write a library to use with.


As @timemage explains in a comment, you cannot pass a capturing lambda
to a function that expects a plain pointer to function. There is,
however, a way out of this: the Ticker class provides an overload of
the attach() method that allows you to provide a parameter of any type
to tour callback:
template<typename TArg>
void attach(float seconds, void (*callback)(TArg), TArg arg)

You can use this version of attach() and provide it both

a non-capturing lambda that gets a pointer to systemManager
that pointer as a third argument.

Edit: I did a few tests, and it seems my compiler cannot properly
perform template argument deduction in this case, but the approach works
if you explicitly specialize the template. Namely:
tickerSystemManager.attach<typeof systemManager>(
    1000,
    [](typeof systemManager p){ p->sync(); },
    systemManager);


Arduino Command Line Interface - How to change boardsmanager.additional.urls

Found the solution:

arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json"


Connecting an AB phase encoder motor to arduino

It's just a regular motor, with a (optical) rotary encoder inside. So the first two motor pins are to run the motor. So connect to VCC and GND, or GND and VCC, if you want to run it in reverse. (VCC doesn't have to be 5v; it can be 3v to 30v).

Connect A and B to a digital input pin. You can see what kind of signal you can expect in the screenshot of the oscilloscope, attached to the ebay-listing. So you can measure the speed, and relative position of the motor-shaft.


How can I stop someone from hacking in to my Arduino via Bluetooth?

Configure your Bluetooth module to AT Command Mode

Then use AT+PIN Command to change the default PAIRING PIN of the Bluetooth Module.

Visit this link for more information about how to configure bluetooth to AT Mode


If the pinout is what the Ethernet shield expects, then yes. The rows of holes at an odd angle are designed for a POE board similar to that. I can't vouch for whether the pinout is correct though.  It looks ok, but it depends on the dimensions of the board whether it fits the existing pinout.


Why does controlling power with a transistor interfere with MHZ19B's serial communication?

Just guessing but I suggest you use a level translator. Also when you power off the sensor the serial output should go to ground disabling that channel.  Check your voltages and put a bypass cap on the transistor for the sensor. You can use a simple P channel Logic Level fet,only a 50 ohm resistor in the gate to prevent oscillation.  Your output will now be active low instead of active high. If you stay with transistors make R2 & R3 510 ohm so you have enough drive for the transistor and be sure it is NOT a darlington device, if it is you will not have enough voltage for the sensor.


What happens when you call malloc()/free()/new/delete?

There are some hardware-specific abstractions (they mostly define the maximum memory available), but otherwise these are functions are implemented by the C/C++ runtime (on arduinos an implementation called "NewLib") and usually "just work". You might want to take a look at this question, where quite a bit of background is given on the SAM implementation of the hardware abstractions (because it's broken).
And yes, of course using malloc/free has some considerable overhead, which is one reason why it's not the recommended way of allocating memory on microcontrollers. But the logic behind it is mostly the same whether there's 2k of memory or 2G. And the memory model of modern microcontrollers (at least the 32 bit ones) is very similar to the one seen in 32 bit Windows or Linux apps.


I found a solution in this video:

https://www.youtube.com/watch?v=cebMSJrNntI

Adding:

##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.board=AVR_ATMEGA328BB
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

to /hardware/arduino/avr/boards.txt


Is it necessary to set a function with always_inline attribution when the function would work maybe once?

Here I am only addressing question number 2. The others have already
complete answers.
The choice to whether a function should be inlined or not is a
speed/size trade-off. There is a cost to calling a function. On AVR, for
example, the call instruction takes 4 CPU cycles, and ret takes
another 4. Inlining the function removes this cost. On the other hand,
you end up with as many copies of the function as places where it is
inlined, and this in turn costs flash memory.
The compiler is usually smart enough to make wise decision regarding
function inlining. In this case, it is not obvious what decision it
would make on its own. On the one hand, the function is used multiple
times in the code, which makes a good case against inlining it. On the
other hand, the body of the function is tiny: only setting up some
registers (the two parameters of SPIClass::beginTransaction(),
including the implicit this) and jumping to another function,
so the cost of inlining is small.
For this library, the programmer happened to have a strong opinion on
this matter, and he though inlining was really the best option. Also, he
did not thrust the compiler to make the good decision. This is the
reason why he used the gcc extension:
__attribute__((always_inline))

And no, it is not necessary, it is just an optimization choice.


Don't use SoftwareSerial on the HardwareSerial pins.  Instead of this:

#include <SoftwareSerial.h>
SoftwareSerial GSMSerial(15,14);    // RX, TX

Just do this:

#define GSMSerial Serial3


From your schematics it looks like:

you connected the power supply backwards (on both schematics actually, I wonder how come you did not fry your Arduino)
the external supply and the Arduino do not share a common ground as they should.

Edit: about the orientation of the power supply:

the (−) side of the supply (and GND of the Arduino) should be connected to the source of the N-MOSFET
the (+) side of the supply should be connected to the cathode of diode (the side identified by the small white bar)


is it necessary to include libraries that are specified in the header file already?

Historically it was necessary, yes. In times past the IDE would look only in your sketch to find the list of libraries to compile and link. However much progress has been made in recursive library searching, whereby the IDE can now find libraries that are included by other libraries.
I am not sure when that change was implemented, but it was a long time coming and is only recently that it's worked.
So if you are distributing code for other people to use then it's a good idea to still add the libraries in the sketch - just in case they're using an older version of the IDE that can't find the libraries included by other libraries.


You need to manually split your values into bytes. You can either do that by storing them as individual bytes (as shown by Ignacio), or by using bit shifting:

Serial.write(mem_freq[mem_index] >> 16);
Serial.write(mem_freq[mem_index] >> 8);
Serial.write(mem_freq[mem_index]);

That sends the bits 16-23 (0x12) then bits 8-15 (0x10) followed by bits 0-7 (0x50).


Error when using USART with Arduino Mega 2560

The compiler/linker is providing the answer. There are at least two definitions of the ISR for UART0 RX. One in your code and one in HardwareSerial.


How to bootload a atmega328-pu using arduino uno?

Hi friends thanks for your support. It worked well as it is. No external capacitor I used.
I made the connection as shown in the above picture taken from LINK1.
I modified the file "boards.txt" and "avrdude.conf" as given in step 4 of LINK2
I first uploaded the ArduinoISP sketch to the board on the left.
And then I opened an "EMPTY ARDUINO SKETCH".
From that empty sketch I made the following changes
     Tools->Board = "Arduino328"
            Port  = COM4 in my pc
            Programmer = Arduino as ISP
Last step "Burn Bootloader"
Ta Da....
It worked. When I posted this question I burnt the boot-loader having the arduino ISP sketch opened. Only thing I changed now is I opened an empty sketch and hit burn from that sketch. Anyway.. thank you all. I dont think I wasted your time. If so, I apologise.


Would an infinite loop inside loop() perform faster?

The part of the code on an ATmega core that does setup() and loop() is at follows:

#include <Arduino.h>

int main(void)
{
        init();

#if defined(USBCON)
        USBDevice.attach();
#endif

        setup();

        for (;;) {
                loop();
                if (serialEventRun) serialEventRun();
        }

        return 0;
}

Pretty simple, but there is the overhead of the serialEventRun(); in there.

Let's compare two simple sketches:

void setup()
{

}

volatile uint8_t x;

void loop()
{

    x = 1;

}

and

void setup()
{

}

volatile uint8_t x;

void loop()
{
    while(true)
    {
        x = 1;
    }
}

The x and volatile is just to ensure it isn't optimised out.

In the ASM produced, you get different results:

You can see the while(true) just performs a rjmp (relative jump) back a few instructions, whereas loop() performs a subtraction, comparison and call. This is 4 instructions vs 1 instruction.

To generate ASM as above, you need to use a tool called avr-objdump. This is included with avr-gcc. Location varies depending on OS so it is easiest to search for it by name.

avr-objdump can operate on .hex files, but these are missing the original source and comments. If you have just built code, you will have a .elf file that does contain this data. Again, the location of these files varies by OS - the easiest way to locate them is to turn on verbose compilation in preferences and see where the output files are being stored.

Run the command as follows:

  avr-objdump -S output.elf > asm.txt

And examine the output in a text editor.


Differences between nodemcu and arduino processer

Camera doesn't send data via Analog to Arduino.
A5 and A4 are I2C bus beside Analog.

NodeMCU has Software I2C protocol bus too, You can use D1 (GPIO 5) as CLK, and D2 (GPIO 4) as SDA.

see : https://github.com/esp8266/Arduino/blob/master/doc/libraries.rst#i2c-wire-library


DF Robot W5200 Ethernet Shield for an Arduino Uno not working?

Don't use the MAC address of your computer read from ipconfig output. It creates a conflict on LAN. Use the MAC address from examples.

To troubleshoot Ethernet shield, use the Ethernet library newest version 2.00. It supports W5100, W5200 and W5500 and has better diagnostic in examples.

And to troubleshoot, always connect the LAN cable to router or switch, not to computer, because direct connection to computer requires manual setup of addresses (no DHCP).


Arduino: Read frequency of input from audio jack

You can measure a single "pure" frequency by counting the number of times that the pin changes, by using the inbuilt timers. Here is a sketch from my page about timers that accomplishes that:

// Timer and Counter example
// Author: Nick Gammon
// Date: 17th January 2012

// Input: Pin D5

// these are checked for in the main program
volatile unsigned long timerCounts;
volatile boolean counterReady;

// internal to counting routine
unsigned long overflowCount;
unsigned int timerTicks;
unsigned int timerPeriod;

void startCounting (unsigned int ms)
  {
  counterReady = false;         // time not up yet
  timerPeriod = ms;             // how many 1 ms counts to do
  timerTicks = 0;               // reset interrupt counter
  overflowCount = 0;            // no overflows yet

  // reset Timer 1 and Timer 2
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR2A = 0;
  TCCR2B = 0;

  // Timer 1 - counts events on pin D5
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // Timer 2 - gives us our 1 ms counting interval
  // 16 MHz clock (62.5 ns per tick) - prescaled by 128
  //  counter increments every 8 µs.
  // So we count 125 of them, giving exactly 1000 µs (1 ms)
  TCCR2A = bit (WGM21) ;   // CTC mode
  OCR2A  = 124;            // count up to 125  (zero relative!!!!)

  // Timer 2 - interrupt on match (ie. every 1 ms)
  TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

  TCNT1 = 0;      // Both counters to zero
  TCNT2 = 0;

  // Reset prescalers
  GTCCR = bit (PSRASY);        // reset prescaler now
  // start Timer 2
  TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
  // start Timer 1
  // External clock source on T1 pin (D5). Clock on rising edge.
  TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
  }  // end of startCounting

ISR (TIMER1_OVF_vect)
  {
  ++overflowCount;               // count number of Counter1 overflows
  }  // end of TIMER1_OVF_vect

//******************************************************************
//  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
//  16Mhz / 128 / 125 = 1000 Hz

ISR (TIMER2_COMPA_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // see if we have reached timing period
  if (++timerTicks < timerPeriod)
    return;  // not yet

  // if just missed an overflow
  if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
    overflowCopy++;

  // end of gate time, measurement ready

  TCCR1A = 0;    // stop timer 1
  TCCR1B = 0;

  TCCR2A = 0;    // stop timer 2
  TCCR2B = 0;

  TIMSK1 = 0;    // disable Timer1 Interrupt
  TIMSK2 = 0;    // disable Timer2 Interrupt

  // calculate total count
  timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
  counterReady = true;              // set global flag for end count period
  }  // end of TIMER2_COMPA_vect

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");
  } // end of setup

void loop ()
  {
  // stop Timer 0 interrupts from throwing the count out
  byte oldTCCR0A = TCCR0A;
  byte oldTCCR0B = TCCR0B;
  TCCR0A = 0;    // stop timer 0
  TCCR0B = 0;

  startCounting (500);  // how many ms to count for

  while (!counterReady)
     { }  // loop until count over

  // adjust counts by counting interval to give frequency in Hz
  float frq = (timerCounts *  1000.0) / timerPeriod;

  Serial.print ("Frequency: ");
  Serial.print ((unsigned long) frq);
  Serial.println (" Hz.");

  // restart timer 0
  TCCR0A = oldTCCR0A;
  TCCR0B = oldTCCR0B;

  // let serial stuff finish
  delay(200);
  }   // end of loop

Feeding in a 1 kHz sine wave (from 0V to 5V) I get this output:

Frequency Counter
Frequency: 1000 Hz.
Frequency: 1002 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1002 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.

There is the occasional mis-reading but it looks accurate enough. You might sample a few times, and if you get something between 990 and 1010, five times, you might consider that a match.

You will need to make sure that the input is in the range for triggering the input circuitry of the Arduino. It should be around 4 to 5V, and not higher than 5V (for a high). It also should not go negative.

Something like this will protect the input pin:

Warning - audio from an audio jack will be AC and it will go negative. Make sure you use a suitable input protection.

Amplification

After looking at Wikipedia - Line level it seems likely that the output from your phone will not be high enough (around 700 mV probably). Therefore a simple transistor amplifier will probably be required to raise it to a level that can be detected.

Inspired by this post on Electronics Stack Exchange, I made up a simple amplifier:

Testing out with around 500mV peak-to-peak input indicates that it successfully amplified it to 0 to 5V DC:

Alternative method with analog comparator

Based on suggestions by Chris Stratton, there is another way of doing this.

You can use the analog comparator to detect an analog signal passing a threshold, like this:

I have set up the voltage divider to trigger at 0.265V, so that a 500 mV signal should provide an acceptable triggering range.

As for the sketch, at these frequencies we can do something simpler than what I posted before:

volatile bool counting;
volatile unsigned long count;

ISR (ANALOG_COMP_vect)
  {
  if (counting)
    count++;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

unsigned long startTime;

void loop ()
  {

  if (!counting)
    {
    startTime = micros ();
    count = 0;
    counting = true;
    }
  else
    {
    // is a second up? (1000000 microseconds)
    if (micros () - startTime >= 1000000)
      {
      counting = false;
      Serial.print (count);
      Serial.println (F(" Hz."));
      }  // end of a second being up

    }  // end of if

  }  // end of loop


Bootloader and Boards Definition for Atmega2560V-8AU at 8 MHz / 3.3v

I have used megacore bootloaders, and it solved the problem


The servo can't move back and forward in 40 milliseconds. It'll be more like tremble between both.
Try something like this:
// keep sending 0 position for about 400ms
for(int i = 0; i<20; ++i) {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  digitalWrite(PB1, LOW);
  delay(19);
}

// keep sending second position for about 400ms
for(int i = 0; i<20; ++i) {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(2000);
  digitalWrite(PB1, LOW);
  delay(18);
}


How to control two devices with Arduino?

Connect both of your appliances i.e AC and Humidifier to 2 different relays. Connect the relays to the Arduino Uno digital I/O pin using a small current amplifier circuit or a Darlington Transistor pair that will amplify the current going to the relay.

Relay circuit

Darlington Pair

Now the connection of your sensor with arduino.

In your code you have to use DHT library i.e.

#include <dht11.h>

define your DHT11 object as

dht11 DHT11;    //(class object;)

define your DHT11 sensor pin like this

DHT11.read(dht_output_pin);

You can the similar code to control your relay according to the temperature and humidity here. Simply first check the AC temperature and switch on/off the AC relay and then check the Humidifier humidity and switch on/off the humidifier relay.

*** Connect your sensor output to the Digital Pin of the Arduino


Locking ATmega328 from reading back the hex file

Locking out programming prevents writing, and locking out verification prevents reading, via all programming methods.

Note that there is no way to prevent erasing the chip, which will clear both the lock bits and the flash.


Flickering LCD when using > 5v power supply on a Pro Mini

If the LCD has a backlight you are absolutely over heating the regulator on that board by running it at 9 or 12V: At 12V with 100mA for the backlight and using 175C/W thermal resistance for the regulator:
Tj = 25C + ((12V - 5V) x 100mA x 175C/W) = 147C
That regulator goes into thermal limit at 125C.


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

Any floating pin will act as an antenna, and may interfere with values around it, this is one of the major disadvantages of using analog.

To get the most accurate readings with minimal amount of interference, you can pull all unused inputs to ground.

The accuracy will not change, as the accuracy is determined by the sensor itself. However it will reduce the amount of noise / interference, which will give you more accurate readings.

These pull to grounds can be accomplished by configuring the unused analog pins as digital outputs, and setting them low.

pinMode(A1, OUTPUT);
digitalWrite(A1, LOW);


How to send Serial.Print only If Serial Connection is open?

The Arduino Mega's "serial" connection comes from an external chip implementing USB-serial conversion.  While this chip knows if a session is open with a host, the standard design has no way to share that information with the main ATmega.

In contrast, on a Leonardo type board the main processor implements the USB interface, so it does know.

Your options include changing the requirement, having the PC program send some data to the Arduino, changing the processor to an ATmega or ARM with integrated USB, or perhaps modifying the USB implementation.


The problem is in the logic, basically your statement:

    if (cMillis - pMillis > interval)
    {
       pMillis = cMillis;
       digitalWrite(ledPin, HIGH);
        Serial.println("On");
        Serial.println(interval - cMillis);
    }
    else
    {
       digitalWrite(ledPin, LOW);
       Serial.println("Off");
    }

will always be true, this is as the difference in time, cMillis - pMillis is always greater than interval.

This means that it never enters the else statement to turn off the LED, and thus means the else statement is usually the first thing that rune at ledMode = 3.

What you need to do as the simplest fix is to change your comparison, change > to <, in the is statement:

if (cMillis - pMillis > interval)

to

if (cMillis - pMillis < interval)

this will ensure the LED is always on during the 5000 mS and then as soon as it is greater it will definitely go to the else


Programming ATtiny85 with Arduino-IDE and an 8MHz external oscillator

If you look at the Digispark Schematic you'll see resistors and Zener diodes attached to XTAL1 and XTAL2:

These are for the USB D+ and D- signals that the Digispark bit-bangs.  I deeply suspect that the crystal is just not going to resonate with these parts connected.
To get back to a working Digispark you'll probably have to inject signal onto XTAL1 again and reprogram the fuses to internal OSC.


Assuming you have triple checked all your wiring before posting this question you should add a small capacitor between Vcc and GND near the nRF24: anything between 10uF and 100uF will do.

Rationale: these devices draw quite a decent amount of current when bootstrapping and transmitting and if they don't receive enough juice they just reset themselves showing those all zeroes settings.

They are pretty robust devices, not that easy to fry.


tCAN will be a struct that defines the structure of the CAN message being sent.  The name tCAN is not a standard and will have been chosen by the author of the library you are using.  At a guess it's using a variant of Hungarian Notation, and the t prefix means type - so it's probably been typedef'd from a struct to a type name.

I am not familiar with CAN, but if there are standard message formats this struct will correspond with one of them.  You can find the actual structure within the header file for your chosen library (or maybe in the example sketch code itself?).


Using shiftin() and shiftout() with the same circuit - what to consider?

I have a post here about using an I2C 16-port port-expander: http://www.gammon.com.au/forum/?id=10945

That would use 4 wires for I2C (power, ground, SDA, SCL) or there is an SPI version which would require an extra wire (power, ground, SCK, MOSI, MISO).

I'm not sure about noise over your cable runs, on a bicycle presumably electrical noise is low, so either one might suit. This is the chip that  Ignacio Vazquez-Abrams mentioned in his comments. Any of the 16 ports can be configured as inputs or outputs as you desire, plus it can raise an interrupt on a change on an input pin.

You might find that the maximum current limits for output may not be adequate for your LEDs (the datasheet says maximum of 25 mA per output pin, plus a maximum of 125 mA for the whole chip). You could work around this with driver transistors on the chip output, but this is more complexity.

There are higher-powered shift registers (eg. TPIC6B595) which can handle more per pin than the 74HC595.

  Can I use any pin I want? Or is it required to use specific pins?

If you want to use I2C there are two specific pins dedicated to the I2C hardware. If you want to use SPI there are dedicated hardware pins as well (different ones) but you can also "bit-bang" SPI if you want.

See:

http://www.gammon.com.au/i2c

http://www.gammon.com.au/spi

  Is there a through-hole version of that?

All the chips I mention here have through-hole versions.


Maybe this question is too old and the API has changed, so my answer is reference.

The ModbusMaster constructor does not accept parameters.

From reading the source code, the method begin(uint8_t slave, Stream &serial) just initializes variables and can be called again with a new slave value without the need to destroy the ModbusMaster object.

Reference:

[1] https://github.com/4-20ma/ModbusMaster/blob/master/src/ModbusMaster.cpp, line 61.


Getting an error while uploading code to Arduino when ESP8266 is attached

First off you have the wrong board selected. It's the Arduino Uno that you are programming, not the ESP8266. Just because you have connected an ESP8266 to the Arduino doesnt't magically change what the Uno is.

Secondly you cannot have anything connected to pins 0 and 1 of the Arduino while programming. Those pins are used for communication with the PC. As a general rule it is best to never use ghem for anything.

To communicate between the Arduino and the ESP8266 you should either pick two other pins and use SoftwareSerial or invest in a board that has at least one independent UART (such as the Mega2560 or the Leonardo).


How can I remove the delays in this code for sweeping the servo?

From your code it seems like you are doing all the servo movement before you read the distance and report back. A lot of code is commented out, so it's a bit difficult to follow. What I would do is something along the line of:
[...]
int servoStart=0;
int servoEnd=90;
int servoPos=0;

[...]
void setup() {
    [usual setup stuff like you do it now]
    myServo.write(servoPos);  //start at pos 0
    // Maybe a delay here to make sure we are at pos. 0
}

void loop() {
    //Switch direction if we reach end
    if (servoPos+servoStep < servoStart || servoPos+servoStep > servoEnd)
        servoStep = -servoStep;
    servoPos += servoStep;
    myServo.write(servoPos);
    //Small delay?
    //Read distance
    //Send distance to seraial
    //Buzz buzzer if needed
}


SIlly PID question using the PID library

See PID Library - SetOutputLimits() - you can change the limits.

For a meaningful result you need to make the output do something reasonable to the speed. Since your detected speed is lower than the desired speed, you have found it outputs a positive value, which is good, as far as it goes. But you have to interpret that in the context of what you are currently sending to the motor. If you are using PWM to control the motor you could feed the output (40 in this case) to the motor. If that makes it go even slower hopefully the PID library will compensate.

It's hard to make more suggestions without seeing the code.


Your title is about “setting a timer”, but your actual question is about
measuring the length of a pulse. There are two functions provided by the
Arduino IDE for this purpose, pulseIn() and pulseInLong():

pulseIn() is based on a carefully timed delay loop. It
has a resolution of the order of one microsecond, but will not count
the time spent servicing interrupt requests. It works best for very
short pulses timed with interrupts turned off.
pulseInLong() is based on micros(). It has a
resolution of 4 µs and will not work properly if interrupts are
turned off. It works best for longer pulses where its limited
resolution and interrupt latency are tolerable.

Both of these are blocking functions: they completely block your
sketch while they perform the measurement. If you don't want your sketch
to be unresponsive during this time, you can write a non-blocking
version of pulseInLong() using a finite-state machine like
this:
// Measure the length of a pulse in a non-blocking manner.
// Returns 0 if no measurement is available at the time of the call.
void get_pulse_length() {
    static enum {
        INITIAL_WAIT,    // wait for the first (partial) pulse to end
        BETWEEN_PULSES,  // wait for the pulse to start
        WITHIN_PULSE     // wait for the pulse to end
    } pulse_state = INITIAL_WAIT;
    static uint32_t pulse_start;  // when the current pulse started

    uint8_t pin_state = digitalRead(pulse_pin);
    uint32_t now = micros();
    switch (pulse_state) {
        case INITIAL_WAIT:
            if (pin_state == LOW)
                pulse_state = BETWEEN_PULSES;
            break;
        case BETWEEN_PULSES:
            if (pin_state == HIGH) {
                pulse_start = now;
                pulse_state = WITHIN_PULSE;
            }
            break;
        case WITHIN_PULSE:
            if (pin_state == LOW) {
                pulse_state = BETWEEN_PULSES;
                return now - pulse_start;
            }
            break;
    }
    return 0;
}

Note that this measures high pulses. You will have to swap HIGH and
LOW if you want to measure low pulses. You would use it like this:
void loop() {
    uint32_t pulse_length = get_pulse_length();
    if (pulse_length) {
        // handle the pulse
    }
}

The resolution of the measurement is the execution time of loop(), so
you have to make sure there is nothing blocking there, and specially no
calls to delay(). If you need a better resolution from a non-blocking
method, you can use interrupts to trigger the measuring process:
volatile uint32_t pulse_start, pulse_length;
volatile bool pulse_valid;

void on_rise() {
    pulse_start = micros();
    attachInterrupt(digitalPinToInterrupt(pin), on_fall, FALLING);
}

void on_fall() {
    pulse_length = micros() - pulse_start;
    pulse_valid = true;
    attachInterrupt(digitalPinToInterrupt(pin), on_rise, RISING);
}

uint32_t get_pulse_length()
{
    if (!pulse_valid) return 0;
    noInterrupts();
    uint32_t pulse_length_copy = pulse_length;
    pulse_valid = false;
    interrupts();
    return pulse_length_copy;
}

void setup() {
    attachInterrupt(digitalPinToInterrupt(pin), on_rise, RISING);
}

This should give you the resolution of micros(), i.e. 4 µs, but
occasionally you may get results that are slightly off if interrupts
happen to be disabled when the input transitions. If this is
unacceptable, the only other options I see is to use a hardware timer
with input capture capability. You will have to look at the datasheet
of your microcontroller to see how it works, and maybe do a Web search
for “Arduino input capture”.


Reading bytes from a file on SD Card - Understanding Buffer

You don't have to, it's just one way of doing it.

Basically the read function needs a pointer to a buffer to store the data in.  By using an array with one entry you get a pointer to a buffer that is big enough for one (32-bit) integer. And you then get an "easy" way of accessing that one integer within that buffer.

Another way would be to just use a simple integer and pass a pointer to that integer to read:

uint32_t width; // Use a fixed size integer for portability
bitmap.seek(18);
bitmap.read(&width, sizeof(width)); // Use sizeof for portability
Serial.println(width);


what happens on Arduino power-on, and how long does it all take?

This is something that is far far easier to measure than to try and calculate.
Here's an Arduino Uno R2 with a simple sketch that just turns on D2.  Green is the power (7V to the barrel jack) and yellow is D2.

As you can see it takes 1.544 seconds (according to the resolution of my oscilloscope which, over those time scales, isn't that great) before D2 is driven high.
The sketch is simply:
void setup() {
  pinMode(2, OUTPUT);
  digitalWrite(2, HIGH);
}

void loop() {
}


Some Blocks of Code gets stuck in a loop, I do not know why

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

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

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

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

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


How do I use an image sensor with an arduino uno?

You need to find markings on it and figure out what the component actually is.  Then you can maybe find a datasheet for it that explains how it works and commmnicates.  Once you know that you can decide if that's something you can do with an Arduino.  Be prepared to learn that Arduino might not be big enough or fast enough to do anything with that particular sensor.


connection issues with 3 arduinos any suggestions?

it's been a while but a long time later I found that the cable I was using was broken. A different cable worked.


Unable to upload sketches after little oopsie (reversed input polarity)

The atmega328 that runs the sketch is fine, but the communication is broken somehow.  See the steps in https://arduino.stackexchange.com/a/13293/6628


Multichannel communication with Arduino and HC-12 transmitter

I believe you are misunderstanding what it means by channels. The HC-12 can transmit on up to 100 channels, which means different frequencies under the 433 MHz band. For example 433.05 MHz or 433.15 MHz. This is so multiple HC-12 modules can be used next to each other and only the module receiving on the channel of the transmitter will receive the data broadcast.

What you need to do for your quadcopter is send an array of bytes that begins with a constant, followed by the data you need (a packet). Example:

byte packet[] = {0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}

// in your loop
packet[1] = ; HOW MUCH THE ENGINE IS THROTTLED
packet[2] = ; HOW FAR THE CONTROL TO GO FORWARD IS DEPRESSED
// etc

Iterate through this array writing the data through the serial port to the HC-12. Whenever your receiver detects the constant (in this case 0x00) read the values that follow as the controls for the quadcopter.


Arduino Uno R3 not recognized by computer, TX and RX not blinking, neither are lit. Is it dead?

There is a chance that your bootloader is not working anymore. You can burn a new bootloader to the device with another Uno, there are nice guides on the Arduino-Website.


Having an issue running an Arduino sketch

I don't know how you came up with that location as the right place to put libraries. It is wrong. Oh so very wrong.

Libraries go in ~/Documents/Arduino/libraries as stated in the first hit for "arduino macos libraries" on Google.


How to get arduino to always be connected as /dev/ttyUSB0 and with chmod 0777?

Have you considered not trying to force ttyUSB0 but instead creating a symlink to whatever tty is assigned? Your software then just uses the symlink.
A problem with forcing a particular tty is what if you boot without the Arduino but another device is attached? You then need to convince the other device to skip ttyUSB0.
If you would consider a symlink then something like:
ACTION=="add", KERNEL=="ttyUSB*", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", SYMLINK+="arduino"

might get you started. Check the VID and PID using lsusb or similar. To set permissions as well you can use e.g. MODE="0777" as you already have.
There is an example at https://wiki.debian.org/udev that might give more background.


How can I send and receive data from an Arduino MEGA 2560 and Python?

Your problem is that you aren't sending the values from python in bytes. A more reliable way is to send the data in bytes like dat.write(b'1') and then receive it on the Arduino using Serial.readString(). I also had many issues with this and this is the best solution. "https://roboticsbackend.com/raspberry-pi-arduino-serial-communication/#:~:text=The%20easiest%20way%20is%20to,Arduino%20IDE)"
If not, you can use the I2C interface. Just be careful, the logic level if your Python is running on a Raspberry Pi.


First you have to grant permission to the user!

Type the query in MySQL like:

GRANT ALL ON test_arduino.* TO root@'192.168.0.102' IDENTIFIED BY 'fifa2005';