Wrong data receiving in my Arduino by bluetooth

Well, after a lot of research, it seems that my main problem was that I´m receiving and sending information at the same time. And with the library Softwareserial, only 1 can be active at the same time.
I found two solutions, but to be honest I'm not complete satisfy with neither of them. However, for my application will work.
The first solution: Is to used the HardwareSerial (pin 0,1) itself, instead of using the pin 2 and 3. When I used those, it didn't have any problem. Although I decided no to used because it help me debugging my code.
The second solution: Is to decrease the frecuency of what I´m sending. For me its ok I send the data every second. So my code would be like this:
#include <SoftwareSerial.h>
#include <TimerOne.h>
SoftwareSerial hc06(2,3);

char command;
String string;
boolean ledon = false;
const byte MAX_STRING_LEN = 40;
const int  BLINK_INTERVAL = 1000;

char inputString[MAX_STRING_LEN];  // a string to hold incoming data

int BatteryPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
float BatteryCar = 0;
int PercentageBatt = 0;
int intensidad = 0;
byte strLen   = 0;                 // current length of rec'd string

#define led 11
void setup()
{
  Serial.begin(9600);
  hc06.begin(9600);
  pinMode(led, OUTPUT);
  Timer1.initialize(1000000);
  Timer1.attachInterrupt( SendVoltage );
}
void loop()
{

  sensorValue = analogRead(BatteryPin);
  BatteryCar = sensorValue * (5.0 / 1023.0);
  if (hc06.available() == 0)
  {
    analogWrite(led, 0);
    delay (10);
  }
  while(hc06.available() > 0)
  {
    command = ((byte)hc06.read());
    if((command == '\n') || (command == '\r'))
    {
      command =='\0';
      break;
    }
    else if (command == 'O')
      analogWrite(led, 255);
    else
      analogWrite(led, 0);
    delay(10);
    Serial.println(command);
  }
}

void SendVoltage ()
{

  PercentageBatt = (BatteryCar * 100)/4;
  hc06.println(PercentageBatt);
}

I have read about this library (AltSoftSerial), but I couldn't get it work. I have usde the pin 8 and 9, but nothing.


Can I connect a voltage, higher that the 1.1V bandgap voltage, to an ADC pin

Yes, you can go above VRef.

  Voltage on any Pin except RESET

  with respect to Ground ................................-0.5V to VCC+0.5

And as the ADC reference says anything above VREF will give you the maximum value (it will saturate).

So powered from 5V you can apply anything from -0.5V to +5.5V safely. That's basically the supply voltage plus one diode drop for the ESD protection diodes within the pin.

The ADC is just comparing two voltages. The VREF isn't used to power anything.


How can you speed up the ADC on an ATtiny85?

The ADCs in the ATtiny85 and ATmega2560 (the chip powering the Arduino
Mega 2560) are pretty similar, except for the Mega having more inputs.
In particular, the way you set the clock prescaler is the same, namely
the bits ADPS2:0 in the register ADCSRA. You could use the same code to
set the prescaler on both chips, but you probably don't want to unless
your ATtiny is clocked at 16 MHz, like your Mega. I would normally
just set the control register to the value I want, rather than
touching only a few bits, but that is a matter of personal preference.
So, to set the ADC clock of the Mega to 1 MHz, I would

ADCSRA = _BV(ADEN)    // enable the ADC
       | _BV(ADPS2);  // clock at F_CPU / 16 = 1 MHz

The same code would do the same thing on an ATtiny clocked at
16 MHz. If the ATtiny runs at 8 MHz, I would instead

ADCSRA = _BV(ADEN)    // enable the ADC
       | _BV(ADPS1)   // clock at
       | _BV(ADPS0);  //     F_CPU / 8 = 1 MHz

If you want to be generic:

#if F_CPU >= 12000000
# define ADPS_SETTING _BV(ADPS2)                 // F_CPU / 16
#else
# define ADPS_SETTING (_BV(ADPS1) | _BV(ADPS0))  // F_CPU / 8
#endif

ADCSRA = _BV(ADEN)      // enable the ADC
       | ADPS_SETTING;  // clock somewhere near 1 MHz

As bigjosh explained in comments, the prescaler setting is a trade-off
between speed and accuracy. I recommend you read the article on the
Arduino ADC by Nick Gammon. He did some tests at various speeds
which showed that you can get decent results with clock speeds up to
1 MHz, then it becomes pretty bad at 2 MHz and mostly
useless beyond. You may want to run the same tests with your particular
setup.

Except for the very first conversion, which takes longer, an ADC
conversion takes 13 cycles of the ADC clock. If you run that clock
at 1 MHz, that is 13 µs per reading. If you get the readings
with analogRead(), you won't get one reading every 13 µs, because
the CPU needs extra time to execute the code you have between successive
calls of analogRead(). You can save time by having the CPU and the ADC
work in parallel, maybe along these lines:

ADCSRA |= ADSC;     // start the first conversion
for (int i = 0; i < NB_READINGS; i++) {
    loop_until_bit_is_clear(ADCSRA, ADSC);  // wait for the ADC
    uint16_t reading = ADC;     // get the reading
    ADCSRA |= ADSC;             // start the next conversion
    process(reading);           // process the reading we have
}

This way you process one reading while the ADC is taking the next one.
Or you can set the ADC to “free running mode” (where it takes one
reading after another without ever stopping) and get the readings in an
interrupt service routine. Whichever method works best depends on your
particular application: the amount of works your CPU has to do while
reading the ADC and whether you can afford to do the whole series of
readings with interrupts disabled.


Performing multiple Wire.writes() - does endtransmission slow things down?

No, Wire.endTransmission() doesn't "slow things down". It is, however, critical to the operation of the Wire library.

When you do a Wire transaction all the data you send is first buffered in an internal array. Only when you call Wire.endTransmission() does that data actually get sent out. The actual Wire.endTransmission() doesn't add anything extra to the transmission though.

In your example you are sending a total of 5 bytes (address + 4 data bytes) plus start/ACK/stop bits. In general most devices require you to send specific numbers of bytes in a specific order - the most common being a register address followed by the content of that register. That means 3 bytes. Any more bytes after that in the same transaction will either be ignored or would overwrite the first bytes.

Some devices though would allow <address><value><address><value> to be sent, thus removing the need for the repeated I2C address byte for the device each time. Many won't though.

Other devices (most notably flash memory or SRAM chips) would allow you to do page mode accesses, which would be <address><data1><data2>...<dataN> where the address would automatically increment for each data byte. Again, some may, some won't.

It is entirely down to the device you are sending data to as to whether you are able to batch together multiple blocks of data, and the form that batching has to be in if it is supported at all. So you should look in the datasheet for the device to see just what it can support.


Arduino analogWrite source code explanation

Look at the init() function in wiring.c.  All of the timers get set up there depending on which chip is selected.  I don't know if some might also be done by initVariant().  But all it leaves for analogWrite to do is set the bit in the COM register to enable the PWM.


I would take a simple n-channel MOSFET like this one. At 5V on the gate it can drive up to 8A (so you have plenty of space to connect other motors as long as your power source can handle this) and because it is a MOSFET you don't have to draw much current from the Arduino (only enough to load the gate of the MOSFET). You can also hold the current under the critical value for your motor with a simple resistor (fit for the resulting power dissipation) in series.

Yes, the output of the PWM is 5V - the operation voltage of the Arduino. The whole point in PWM is to use only the digital values (here 0V and 5V) and varying so fast, that slow systems as the motor cannot follow this motion, but summing over the impulses. So the motor gets only very fast kicks. And for a normal motor you don't need fast PWM. This only increases the frequency response from the MOSFET.

The code seems for to me.


changing analog pins data logging using sdFat library

in case someone has the same problem
it seems like after you initialize an array this way

uint8_t PIN_LIST[3] = {};

you won't be able to assign all the values at once:

PIN_LIST[] = {i,i+1,i+2};
instead you assign each individual value

PIN_LIST[0] = i;
PIN_LIST[1] = i+1;
PIN_LIST[2] = i+2;

and now it worked : )


Pattern library for addressable LED strips

I have never found a single pattern repository, however FunkBoxing has a fantastic sketch with 30 or so patterns well documented. http://funkboxing.com/wordpress/?p=2154

He uses the Fast_SPI (now FastLED) library, which is truly exceptional!

https://plus.google.com/u/0/communities/109127054924227823508


On extending scrolling 8x8 bitmap to 32x32 or 32x64 (see clip)

I've looked at your code briefly, long enough to get the impression that each array like rus5[] contains 32 groups of 4 bytes each, with each 4-byte group representing a row of a character.  [If not, let me know.]  Also, I read the question a time or two, but don't see specified what direction you want to scroll, and whether you will scroll a string of characters or just one character.  Anyhow, in following I suppose you want to scroll a string horizontally with characters entering at the right end of the display and scrolling off the left end.

To support horizontal scrolling, arrange your bit maps such that each group of 4 bytes represents the 32 bits of a single column of the display.  Regarding four bytes as an unsigned long, suppose the LSB (least significant bit) corresponds to the top LED in a column.  Use code like the following to set pixels, supposing cn = current column number; d = number of character columns already scrolled off, in range 0 to 31; maxCol = number of display columns; and t[] is a three-character string corresponding to three characters currently on the 64x32 display.  [That is, a right-hand part of t[0] is at the left end of display; then all of t[1] appears; then a left-hand part of t[2].]  [Generally, where this sets cc=0, you would set it to point at a current-character in a longer string, instead of at the first character in a three-character array t[]; and would advance one character each time d gets up to 32.]

cc = 0;     // index of first character to display
c = t[cc];  // first character to display
e = d;      // how far we have scrolled so far
for (cn=0; cn<maxCol; ++cn) {
  unsigned long colData = pgm_read_dword(charData[c][e]);
  for (ro=0; ro<32; ++ro) {
    matrix.drawPixel(cn, ro, (colData&1)? cchsv : black);
    colData >>= 1; // discard used-up bit
  }
  ++e;
  if (e >= 32) {  // Done with current character?
    c = t[++cc];  // Set c to next character
    e = 0;        // Start with leftmost col of character
  }
}

Edit 1: In the code above, charData[c][e] is an unsigned long int.  Its 32 bits represent column e of ascii character c, with the LSB representing the top-row pixel.  To create charData[][], write a program on your development system that reads whatever bitmaps you have now and writes out code to properly set up charData[][] in ProgMem.

Note, for initial scroll-testing, you could skip writing a development-system program to re-orient characters and instead test with character-data arrays as they are.  Characters might display sideways or upside down, but would scroll ok anyway.  Or, if bytes are not in proper Endianness to be an unsigned long, they would display in four mis-ordered slices.

Edit 2 With the following code,

void  scroller (const PROGMEM byte bildo1[][4],const PROGMEM byte bildo2[][4],int maxCol, word cchsv) {

int d = 0;
int cc = 0;
unsigned long c[32];

for(int ii=0;ii<32;ii++) {
  c[ii]=0;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][0]))<< 24;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][1]))<< 16;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][2]))<< 8;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][3]));
}
int e = d;      // how far we have scrolled so far
for (int cn=0; cn<maxCol; ++cn) {
  unsigned long colData = c[e];
  for (int ro=0; ro<32; ++ro) {
    matrix.drawPixel(cn, ro, (colData&1)? cchsv : black);
    colData >>= 1; // discard used-up bit
  }
  ++e;
  if (e >= 32) {  // Done with current character?
    for(int ii=0;ii<32;ii++) {
      c[ii]=0;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][0]))<< 24;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][1]))<< 16;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][2]))<< 8;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][3]));
    }
    e = 0;        // Start with leftmost col of character
  }
}}

chrisoutwright reports getting an image like the following [cropped from a larger dropbox.com image]:

Cutting this into 4 equal-size horizontal slices and swapping slices top to bottom, we get:

That image suggests packing the bytes in reverse order, eg via

c[ii] += (long) pgm_read_byte(&(bildo2[ii][0]));
c[ii] += (long) pgm_read_byte(&(bildo2[ii][1]))<< 8;
c[ii] += (long) pgm_read_byte(&(bildo2[ii][2]))<< 16;
c[ii] += (long) pgm_read_byte(&(bildo2[ii][3]))<< 24;

Continuing on, if we rotate the left half of the above 90° then flip the rotated image left to right we get a reasonable facsimile of the letter 春 :

The "flip left to right" amounts to reading bits out MSB first instead of LSB first.  During testing, one might do that by saying

matrix.drawPixel(cn, ro, (colData&(1<<31))? cchsv : black); colData <<= 1;

instead of

matrix.drawPixel(cn, ro, (colData&1)? cchsv : black); colData >>= 1;

but in the longer run, a development-system program should be used to re-orient characters instead of using up MCU memory space and time for bitmap organizing.

To make the characters scroll, add a parameter (eg, byte escroll) to the calling sequence.  Discard variable d if it isn't used within scroller, and instead of initializing e to d (which is always zero hence does not allow for scrolling) initialize it via

e = escroll;

In the routine that calls scroller(), say something like

byte es=0;
while (scrolling) {
  scroller(bildo1, bildo2, maxCol, cchsv, es);
  delay(msPerScrollStep);
  ++es;
  if (es >= 32) {
    es = 0;
    // do stuff here about next characters to display
  }
}

That is, call scroller() within a scroll-timing loop (or perhaps put the timing into scroller(), whichever meshes better with overall design).

Note, with the code as it stands, plus suggested changes, bildo2 will scroll in a second time1 unless a third character is supplied to scroll in.

1For example, with maxCol of 64, if es is 16, whenscroller() is called, e will go from 16 to 31 displaying the second half of bildo1, then from 0 to 31 displaying all of bildo2, then from 0 to 15 displaying the front half of bildo2.


Here you can use a loop. a classic for loop in C++ looks like this

for (int i = 0; i < n; i++)
{
    // content in between these brackets
}

where n is the amount of times you want to loop

you can also instantiate the i before the loop.

int i;
for (i = 0; i < n; i++)
{
    //content here
}

The code below should work. Toy around with it and see what you get.

int ledPin = 13;
int delayPeriod = 500;

void setup(){
    pinMode(ledPin, OUTPUT);

    for (int i = 0; i < 3; i++){
        digitalWrite(ledPin, HIGH);
        delay(delayPeriod);
        digitalWrite(ledPin, LOW);
        delay(delayPeriod);
    }

another approach you can do is using a while loop. These kinds of loops will loop until a given parameter has been met. In your case you want an LED to stop blinking after 3 times.

int start = 0;
int stop = 3;

while (start <= stop){
    //content here
}

While loops will continue to go as long as the parameter is true. This means something like while(1) will continue to run forever.


Arduino mini pro as ISP for Atmega329P-PU serial monitor failing

As you can see at image from linked instructables, they've connected TX pin from Tiny to TX pin on UNO through 220R resistor. This is extremely lousy idea as UNO and Tiny are both driving TX pins.

On the other side you've connected TX Output pin from Target CPU into RX Input of the Arduino ISP (pro mini). Arduino ISP returns some error responses from its TXO pin directly into the monitor. And it's at different speed I suppose, as default baud rate is 19200 in Arduino ISP sketch.

Also using internal 8MHz oscillator and: atmega328bb.build.f_cpu=16000000L means you are running at half speed as compiler and everything else expects. All speeds will be at half rate. Delays twice as long and so on.

Anyway, you can disconnect your USB to Serial converter and connect it directly to the target CPU. Or use two of them. Or just upload bootloader and get rid of ISP.


Are there any signal smoothing libraries for Arduino?

Microsmooth is a lighweight signal smoothing library currently being developed by me.

It is still being worked on and the aim is to make it lightweight in terms of memory and fast. The library provides multiple filters for smoothing:

Simple Moving Average
Exponential Moving Average
Cumulative Moving Average
Savitzky Golay Filter
Ramer Douglas Pecker Algorithm
Kalmogorov Zurbenko Filter

To use the library, download and add it to the source directory. Also, add the following line to your source file:

#include "microsmooth.h"


How do I reset my libraries back to original condition?

Delete the Documents -> Arduino -> Libraries to remove all your libraries.
Delete the User -> AppData -> Local -> Arduino15 folder to remove all the preferences.
Uninstall Arduino IDE.
Install a fresh one.


Hi Lefteris the builder,
StackExchange is about questions and answers.
Arduino is about learning and fast prototyping.

For guidance with your project, the forum at http://forum.arduino.cc/ is more appropriate.

I suppose that a number of us have read the code that you use. We really do read code.
That code is not bad, but there are a few weak spots in that code:

Not enough comments to explain what is going on.
Many conditions with flags. That is okay,
but the flags are sometimes a boolean and
sometimes a byte, and there is no explanation what the flag is
used for.
Many checks for isnan(). Does that indicate that
a floating point "nan" problem might pop up
at any time in the sketch?
Most of the code is in the loop(). I don't mind that, but
others prefer to put large blocks of code in functions.

It seems that your hardware is working okay.

It is hard to confirm that the code for the Holt-Winters algoritme is working.

All this together is too confusing for us at the moment.

I have changed my answer, the hardware seems to be working.

Below is the changed sketch to test it without extra hardware.
I use the serial monitor. The sadw keys (followed by enter) are the cursor keys and the space bar (followed by enter) is select.

#include <avr/wdt.h>
// #include <Servo.h>
// #include <LiquidCrystal.h>
// #include <DHT.h>
#include <EEPROM.h>

// stty -F /dev/ttyACM0 115200 cs8 cread clocal -hupcl time 30 && tee incubator.log </dev/ttyACM0

#define WDT_TIMEOUT WDTO_8S // if defined, enable hardware watchdog
#define DHTPIN 3 // data pin of the DHT T/H sensor
#define T_OFFSET 0.9 // temperature sensor offset
#define FAN_PIN 2 // fan tacho signal pin
#define FAN_THRES 500 // fan alarm threshold
#define BEEPER A2 // pin where beeper is attached
#define BRIGHTNESS 10 // display brightness pin
#define HEATER A1 // heater MOSFET pin
#define DELAY 2000 // loop delay in ms
#define TS_ADDR 0 // temperature set point EEPROM address
#define HS_ADDR 4 // humidity set point EEPROM address
#define HC_ADDR 8 // humiditiy control mode EEPROM address
#define TI_RESET 1 // integral reset threshold, set integral to 0 when T error greater than this
#define HI_RESET 5 // integral reset threshold, set integral to 0 when H error greater than this
#define ALARM_T 2 // temperature alarm threshold, alert if T error greater than this
#define ALARM_H 8 // humidity alarm threshold, alert if H error greater than this
#define H_AUTO_THRES 3 // disable vent control in auto mode if H error < this
#define H_AUTO_COUNT 200 // disable for n cycles
#define HWAT 0.25 // holt winters parameters for temperature smoothing
#define HWBT 0.2
#define HWAH 0.7 // holt winters parameters for humidity smoothing
#define HWBH 0.5
#define A 0.005 // long average parameter
#define VENTCLOSED 80 // consider vent closed if under this angle
#define VENTOPENMS  480000L // open vent if closed longer
#define VENTRESETMS 600000L // reset vent after this time (>VENTOPENMS!)

// Servo vent;
// DHT dht(DHTPIN, DHT22);
// LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

#define RIGHT 16
#define UP 8
#define DOWN 4
#define LEFT 2
#define SELECT 1
#define NO_KEY 0

// added define to show messages on serial monitor.
#define lcd Serial

byte getKey() {
//  int key = analogRead(0);
//  if (key < 50) {
//    return RIGHT;
//  } else if (key < 150) {
//    return UP;
//  } else if (key < 300) {
//    return DOWN;
//  } else if (key < 500) {
//    return LEFT;
//  } else if (key < 800) {
//    return SELECT;
//  } else {
//    return NO_KEY;
//  }
  if (Serial.available() > 0) {
    int inChar = Serial.read();
    switch (inChar)
    {
      case 'w': return UP;
      case 'a': return LEFT;
      case 's': return DOWN;
      case 'd': return RIGHT;
      case ' ': return SELECT;
    }
  } else {
    return NO_KEY;
  }
}

void eeread(int address, int length, void* p) {
  byte* b = (byte*)p;
  for (int i = 0; i < length; i++) {
    *b++ = EEPROM.read(address + i);
  }
}

void eewrite(int address, int length, void* p) {
  byte* b = (byte*)p;
  for (int i = 0; i < length; i++) {
    EEPROM.write(address + i, *b++);
  }
}

void write_byte(int address, byte &value) {
  eewrite(address, sizeof(value), &value);
}

byte read_byte(int address) {
  byte value;
  eeread(address, sizeof(value), &value);
  return value;
}

void write_int(int address, int &value) {
  eewrite(address, sizeof(value), &value);
}

int read_int(int address) {
  int value;
  eeread(address, sizeof(value), &value);
  return value;
}

void write_float(int address, float &value) {
  eewrite(address, sizeof(value), &value);
}

float read_float(int address) {
  float value;
  eeread(address, sizeof(value), &value);
  return value;
}

void heater(boolean on) {
//  digitalWrite(HEATER, !on ? LOW : HIGH);
}

boolean heater() {
//  return digitalRead(HEATER) == HIGH;
  return true;
}

volatile int fancount;

void count() {
  ++fancount;
}

void beep(unsigned long f, unsigned long l) {
//  pinMode(BEEPER, OUTPUT);
  byte v = 0;
  f = 500000 / f;
  l = (1000 * l) / f;
  for (int i = 0; i < l; ++i) {
//    digitalWrite(BEEPER, v = !v);
//    delayMicroseconds(f);
  }
//  pinMode(BEEPER, INPUT);
}

float Ts, Hs; // set points
byte Hcontrol; // H control mode
byte Ts_changed, Hs_changed; // setpoint changed flags
float ET, dETdt, IETdt; // prop/diff/integ terms for T
float EH, dEHdt, IEHdt; // prop/diff/integ terms for H
float T, Tavg = NAN, Tvar, Tstd;
float H, Havg = NAN, Hvar, Hstd;
float Hpower, Hduty; // heater current power, average duty cycle
unsigned long t0, Hon, talarm, tventclosed;
byte displayMode;
byte key, bri = 255, alarm;
boolean ventclosed;
int fanrpm;

void setup() {
#if defined(WDT_TIMEOUT)
//  wdt_enable(WDT_TIMEOUT);
#endif
  Serial.begin(9600);
  Serial.println("Egg Incubator");
  Serial.println("Use wsad and space is select");

//  pinMode(HEATER, OUTPUT);
//  heater(0);
//  pinMode(BRIGHTNESS, OUTPUT);
//  analogWrite(BRIGHTNESS, bri = 255);
//  lcd.begin(16, 2);
//  lcd.noCursor();
  lcd.print("Incubator 0.7");
//  lcd.setCursor(0, 1);
  Serial.println();
  lcd.print(__DATE__);
//  dht.begin();
//  vent.setMinimumPulse(800);
//  vent.setMaximumPulse(2600);
//  vent.attach(11);
  //  write_float(TS_ADDR, Ts=37.8);  write_float(HS_ADDR, Hs=55);
  Ts = read_float(TS_ADDR);
  Hs = read_float(HS_ADDR);
  Hcontrol = read_byte(HC_ADDR);
//  pinMode(FAN_PIN, INPUT_PULLUP);
//  attachInterrupt(0, count, FALLING);
//  sei();
//  beep(800, 100);
//  beep(1000, 100);
//  beep(1200, 100);
//  beep(1600, 100);
}

void loop() {
  unsigned long t1 = millis();
  int dt = t1 - t0;

  if (!key) {
    key = getKey();
  }

  if (key) {
//    analogWrite(BRIGHTNESS, bri = 255);
  }

  if (t1 - Hon > Hpower * DELAY) {
//    heater(0);
  }

  if (Hcontrol && Hcontrol < H_AUTO_COUNT) {
//    vent.refresh();
  }

  if (alarm && !(alarm & 8)) {
//    beep(1000, 50);
//    beep(1414, 50);
  }

  if (dt > DELAY || key) {

    if (!key) {
      //    beep(2000, 50);
//      T = dht.readTemperature() + T_OFFSET;
      T = 30.0 + T_OFFSET;             // set to fixed value !
//      H = dht.readHumidity();
      H = 60.0;                        // set to fixed value !

      if ((isnan(T) || T < 10 || T > 60) || (Hcontrol && (isnan(H) || H < 5 || H > 95))) {
//        heater(0);
//        lcd.clear();
        lcd.print("SENSOR ERROR!");
//        lcd.setCursor(0, 1);
        Serial.println();
        lcd.print("T=");
        lcd.print(T);
        lcd.print("C H=");
        lcd.print(H, 1);
        lcd.print("%");
        beep(2000, 1000);
        return;
      }

      float dts = dt * 1e-3;

      if (dt > DELAY) {
        fanrpm = fancount * 60 / dts;
        fancount = 0;
      }

      if (fanrpm < FAN_THRES) {
        alarm |= 4;
      } else {
        alarm &= ~4;
      }

      // temperature Holt-Winters smoothing
      float E0 = ET;
      ET = HWAT * (T - Ts) + (1 - HWAT) * (ET + dETdt * dts); // smoothed T error (deviation from set point)
      dETdt = HWBT * (ET - E0) / dts + (1 - HWBT) * dETdt; // smoothed derivative
      IETdt += ET * dts; // integral of error
      if (abs(ET) > TI_RESET) // reset integral on big deviation
        IETdt = 0;
      float pidT = 1.1765 * (ET + 0.010526 * IETdt + 23.75 * dETdt); // PID value, adjust coefficients to tune
      Hpower = fanrpm > FAN_THRES ? max(0, min(1, -pidT)) : 0;
      heater(Hpower > 0.1);
      Hon = millis();

      if (abs(ET) > ALARM_T) {
        alarm |= 1;
//        vent.write(ET < 0 ? 0 : 180);
        if (Hcontrol > 1) {
          Hcontrol = 2;
        }
      } else {
        alarm &= ~1;
      }

      // humidity Holt-Winters smoothing
      E0 = EH;
      EH = HWAH * (H - Hs) + (1 - HWAH) * (EH + dEHdt * dts); // smoothed H error (deviation from set point)
      dEHdt = HWBH * (EH - E0) / dts + (1 - HWBH) * dEHdt; // smoothed derivative
      IEHdt += EH * dts; // integral of error
      if (abs(EH) > HI_RESET) // reset integral on big deviation
        IEHdt = 0;
      float pidH = 0.1176 * (EH + 0.09091 * IEHdt + 2.75 * dEHdt); // PID value, adjust coefficients to tune
//      vent.write(pidH * 180);

      if (Hcontrol && abs(EH) > ALARM_H) {
        alarm |= 2;
      } else {
        alarm &= ~2;
      }

      boolean ventclosed0 = ventclosed;
//      ventclosed = vent.read() < VENTCLOSED;
      ventclosed = VENTCLOSED;

      if (ventclosed && ventclosed != ventclosed0) {
        tventclosed = millis();
      }

      boolean openvent = ventclosed && millis() - tventclosed > VENTOPENMS;
      if (openvent) {
//        vent.write(180);
        if (millis() - tventclosed > VENTRESETMS) {
          tventclosed = millis();
        }
      }

      if (Hcontrol > 1) {
        if (abs(EH) > H_AUTO_THRES || openvent) {
          Hcontrol = 2;
        } else {
          if (Hcontrol < H_AUTO_COUNT) {
            ++Hcontrol;
          } else {
            IEHdt = 0;
          }
        }
      }

      // long term averages
      Tavg = A * T + (1 - A) * (isnan(Tavg) ? T : Tavg);
      Tvar = A * pow(T - Tavg, 2) + (1 - A) * (isnan(Tvar) ? 0 : Tvar);
      Tstd = sqrt(Tvar);

      Havg = A * H + (1 - A) * (isnan(Havg) ? H : Havg);
      Hvar = A * pow(H - Havg, 2) + (1 - A) * (isnan(Hvar) ? 0 : Hvar);
      Hstd = sqrt(Hvar);

      Hduty = A * Hpower + (1 - A) * Hduty;

      if (Ts_changed) {
        if (Ts_changed-- == 1)
          write_float(TS_ADDR, Ts);
      }

      if (Hs_changed) {
        if (Hs_changed-- == 1)
          write_float(HS_ADDR, Hs);
      }
    }

    if (key & SELECT) {
      displayMode = ++displayMode % 8;
    }

//    lcd.clear();
    Serial.println();
    lcd.print("T=");
    lcd.print(Ts + ET);
    lcd.print("C H=");
    lcd.print(Hs + EH, 1);
    lcd.print("%");

//    lcd.setCursor(0, 1);
    Serial.println();

    float uptime;
    char unit;
    switch (displayMode) {
      case 0: // raw values
        lcd.print("T=");
        lcd.print(T);
        lcd.print("C H=");
        lcd.print(H, 1);
        lcd.print("%");
        break;
      case 1: // temperature setpoint
        if (key & (UP | DOWN | LEFT | RIGHT)) {
          Ts = max(20, min(50, Ts + (key & (UP | RIGHT) ? +1 : -1) * (key & (UP | DOWN) ? 0.1 : 1)));
          Ts_changed = 10;
        }
        lcd.print("Ts=");
        lcd.print(Ts);
        lcd.print("C");
        break;
      case 2: // humidity setpoint
        if (key & (UP | DOWN)) {
          Hs = max(10, min(90, Hs + (key & UP ? +1 : -1)));
          Hs_changed = 10;
        }
        if (key & RIGHT) {
          if (Hcontrol < 2) {
            Hcontrol = ++Hcontrol;
          } else {
            Hcontrol = 0;
          }
          IEHdt = 0;
          write_byte(HC_ADDR, Hcontrol);
        }
        lcd.print("Hs=");
        lcd.print(Hs);
        lcd.print("% ");
        lcd.print(Hcontrol == 1 ? "on" : (Hcontrol > 1 ? "auto" : "off"));
        break;
      case 3: // average temperatur
        lcd.print("Ta=");
        lcd.print(Tavg);
        lcd.print("C (");
        lcd.print(Tstd);
        lcd.print(")");
        break;
      case 4: // average humidity
        lcd.print("Ha=");
        lcd.print(Havg);
        lcd.print("% (");
        lcd.print(Hstd);
        lcd.print(")");
        break;
      case 5: // heater duty cycle
        lcd.print("Hd=");
        lcd.print(Hduty);
        lcd.print(" Hp=");
        lcd.print(Hpower);
        break;
      case 6: // air vent
        lcd.print("V=");
//        lcd.print(vent.read() / 180.0);
        lcd.print(" F=");
        lcd.print(fanrpm);
        break;
      case 7: // average humidity
        uptime = t1 * 1e-3;
        unit = 's';
        if (uptime > 60) {
          uptime /= 60;
          unit = 'm';
          if (uptime > 60) {
            uptime /= 60;
            unit = 'h';
            if (uptime > 24) {
              uptime /= 24;
              unit = 'd';
            }
          }
        }
        lcd.print("Up=");
        lcd.print(uptime, 1);
        lcd.print(unit);
        break;
      default:;
    }

    Serial.println();

    if (alarm & 7) {
      if (!talarm) {
        talarm = millis();
      }
      // sound on persistent alarm and fan failure
      if (millis() - talarm > 300000L || alarm & 4) {
        alarm &= ~8;
      }
//      analogWrite(BRIGHTNESS, bri = 255);
//      lcd.setCursor(0, 0);
      if (alarm & 1)
        lcd.print("T ");
      if (alarm & 2)
        lcd.print("H ");
      if (alarm & 4)
        lcd.print("F ");
      lcd.print("ALARM!          ");
      if (!(alarm & 8) && key) {
        alarm |= 8; // alarm acknowledged
        talarm = millis();
      }
      if (!(alarm & 8)) {
//        lcd.setCursor(0, 1);
        Serial.println();

        lcd.print("T=");
        lcd.print(T);
        lcd.print("C H=");
        lcd.print(H, 1);
        lcd.print("%");
      }
    } else {
      alarm = 0;
      talarm = 0;
    }

    if (key) {
      delay((key & SELECT) ? 500 : 200);
    }

    if (bri) {
//      analogWrite(BRIGHTNESS, --bri);
    }
    key = 0;
    t0 = t1;
  }

#if defined(WDT_TIMEOUT)
  wdt_reset();
#endif
}

@Lefteristhebuilder, you have selected that sketch, but the sketch might not handle problems very well.

Anyone can write code for Arduino and put it online.
At least at Github it is possible that others can write an issue (as you did). The project at Github has 9 stars and the creator showed the project at the Arduino "Project Hub". That is all good, but I'm not very happy with the code itself.


waking up arduino mini with a external signal

Arduino Mini has only two interrupt capable pins: 2 and 3. You have to move your sensor to other pin.

From the AtMega328p datasheet:

  If a level triggered interrupt is used for wake-up from Power-down,
  the required level must be held long enough for the MCU to complete
  the wake-up to trigger the level interrupt. If the level disappears
  before the end of the Start-up Time, the MCU will still wake up, but
  no interrupt will be generated. The start-up time is defined by the
  SUT and CKSEL Fuses.


Connecting E-paper display (GD) to Arduino?

E-ink displays require high voltages to operate them. They are electrostatic devices and the pixels need charging up to a high voltage (high compared to what an Arduino runs at) to attract the pigment powder (basically the same as laser printer toner) to create an image.

While it is possible to make your own board it's not something that is simple and straight forward. Designing boost converters requires a certain base level of knowledge and expertise to get it right. Not something I would recommend a beginner attempting.

Even though a display may have the same pin number as another it doesn't follow that the pins are in the same order on the connector. There is no standard and each display from different manufacturers (and even different displays from the same manufacturer) will have a different pin-out. You will need to compare the datasheets for the two displays to see if the pin-out is the same and if it isn't you would have to somehow map from one to the other on the driver board.

The simplest option is to just order the correct driver board for that display.

(Note: in this context it is called a driver board not a breakout board. A breakout board is typically a passive circuit board that converts from one hard-to-use connector or footprint to a simpler, say 0.1", header. A driver board contains active electronics, in this case a boost converter, to drive the device it is connected to.)


Arduino Nano, DS3231 RTC clock module and 4 cascaded FC-16 led matrix modules

how do I display the time from the DS3231 clock module on the FC-16
  led matrix modules?

You can use the DateTime::toString() method to convert the
current time to a string in the format of your choice, then P.print()
to display that string on the LED matrix:

void loop() {
    DateTime now = rtc.now();
    char buffer[] = "hh:mm";  // hours and minutes
    P.print(now.toString(buffer));  // display
}

  how do I use that hour of the day so that the microcontroller knows
  what text it should display next?

Condition your logic on now.hour().


Arduino Mega Pins for SoftwareSerial (vs. AltSoftSerial)

From what I've read it appears that SoftwareSerial will not support simultaneous reads from different inputs

Correct. You can only listen() on one instance at a time.

AltSoftSerial can only support 1 instance, but allows simultaneous transmit and receive, and doesn't block the whole system while either transmitting or receiving.

So the best you can hope for is 4 hardware UART and one AltSoftSerial for 5 ports.

I would suggest looking into the possibility of using multiple Arduino Mega boards with 4 ports on each (4 boards would give 16 ports in total) and have them communicate with each other through some other protocol (SPI or I2C for instance).


Sending arduino signal to another arduino

An arduino may not be as fast as a PC or phone, but it is VERY fast indeed (16,000,000 operations /sec). Unless the code for arduino #1 is incredibly complex, the one arduino should be able to do it all on its own.
P.S. Please post the code for Arduino #1


How can I make motor vibrate using arduino depending on the ultrasonic distance?

You could just replace the "50" in the first delay with the ultrasonic distance variable, I'll explain a bit more below.

Let's assume your ultrasonic sensor outputs an analogue value between 0V and 5V. The output is connected to analog pin A0. Then you just set pinMode(A0, INPUT) and analogRead the value from the pin and store it in the variable X or whatever. Then you just use the variable X as a delay and it will do what you want. The higher the value gets the longer it will vibrate. Something like this:

[...]
val = analogRead(A0);
digitalWrite(5, HIGH);
delay(val);
digitalWrite(5, LOW);
[...]

Second option, if you only wish to turn it on if it is above or under a certain limit, would be using an if condition.

For example:

if(variable > 50){
  // if the variable named variable is over 50 this code is going to be executed
} else {
  // If the variable is below 50 this is executed
}

If you are unfamiliar with if conditions then I suggest reading this too.


how can i achieve a TTL pulses with duration of 1ns and what board do I need

You can create narrow pulses from the 20 kHz rising edge, maybe down to a few ns, and occurring a few ns after the rising edge, with a couple of logic parts,by taking advantage of their propagation delays.  Say 74AHC04 and 74AHC08.

http://www.ti.com/lit/ds/symlink/sn74ahc04.pdf

http://www.ti.com/lit/ds/symlink/sn74ahc08.pdf

You can investigate other logic families to see it there is anything faster.

20 kHz = 50 µs period, you can create that with an Uno using the micros() times.

Something like this in loop:

void loop() {
  oldTime = micros();
  while (1) { // avoids jitter from the loop behind the scene actions
    timeNow = micros();
    if ((timeNow - oldTime) >= halfPeriod) {
      PINB = PINB | 0b00000001; // toggle D8 by writing a 1 to the Input port
      oldTime = timeNow;
    } // end time check
  } // end while
} // end loop

Check the timing with a scope, might have to shorten halfPeriod a little to allow for the time checking and the port manipulation.


Will Arduino Mega support stepper motor NEMA 24, NEMA 34

I'm using 4x Nema 24s for a CNC project of mine.  They only need a couple of signals/pins each from the Arduino to work, the rest is up to the stepper controller board.

For my steppers, I'm using TB6600s, since I need ~3.5 amps per motor/channel.  There are others out there that'll work, but it's what I saw other people at my maker space using.

Nema34s would probably need higher rated amps, so that would determine what controller you need to use.

In fact, every motor is rated for different amps and voltages, so that will always determine what motor controller you use.  Since you need a higher voltage to run the motor controllers than the Arduino, using a separate stepping power supply is a requirement.

The Arduino gets hooked to the step/pulse and direction pins of the motor controller and the other pins on the motor controller go elsewhere.  The CNC motor controller shields you normally see are for lower amp controllers and do most of the pin connections for you.  With the higher amperage motors, you'll have to do this yourself.

When you determine what motor controller you are going to use, find a wiring diagram for it (and maybe a friend) to figure out how it should be wired.


You want strlen.

char foo [100] = "bar";
Serial.println (strlen (foo));   // --> prints 3


The Arduino Leonardo, in the same way as any keyboard, just sends keystroke data. It is down to your computer's operating system to translate those into individual letters and symbols. The Leonardo (and indeed any keyboard) has no say over how the operating system does that translation.

A brief google search (which led back to Stack Exchange) found me this project which may be of some interest. It allows you to automatically change the selected keyboard language depending on which keyboard is being used at any one moment in time.


Joysitck with servo, LED array and buzzer

You have a distinct set of requirements that you could turn into a sketch yourself.  I'm guessing you have never written a program before, in which case the problem really is you don't know how to do what you want to.

So, break the problem down into small chunks.  The less complex a problem the more likely you are to find a generic solution on the web that you can 'borrow'.

How do you turn a servo?
How do you read the position of a joystick?
How do you light a LED bar graph?
How do you sound a buzzer?

I'm pretty certain that you can find pages that tells you how to do each of those in separate sketches.  Once you have each of those working you need to merge the setup functions, making sure they don't over write each other and then tackle the loop functions (which will be more difficult).  BUT I know there are posts on here about how to merge two sketches into one.

I'm 99% certain you will not find a sketch that does what you want.  I'm 99% certain you will be able to coble together a solution that will do what you want if you break it down.

If you get stuck, post the code you have and explain your problem and people will help.

Good luck.


How to fix compilation error for tone() using same timer as other function

It looks like the Tone library uses Timer 2, and it looks like your other code also uses Timer 2, hence the error message. Vector 7 would be the TIMER2_COMPA_vect (Timer 2 compare "a").

Pins 3 and 11 are from Timer 2.

I wrote a small library that generates tones using the hardware PWM and not interrupts. You can read about it here.

Example code:

#include <TonePlayer.h>

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (220);  // 220 Hz
  delay (500);
  tone1.noTone ();

  tone1.tone (440);
  delay (500);
  tone1.noTone ();

  tone1.tone (880);
  delay (500);
  tone1.noTone ();
  }

void loop() { }

Library can be downloaded from http://www.gammon.com.au/Arduino/TonePlayer.zip

This uses Timer 1 (so that won't interfere with Timer 2) and no interrupts.


How to send string over bluetooth LE from Arduino

I've used a HC-O6 Bluetooth device connected to pins 2 & 3.  After setting up SoftwareSerial to use those pins, I sent my messages to that SoftwareSerial using the normal method as a "string"/character array.

I would assume this would work the same with a BLE device that used a serial connection.

I'm not familiar with the AdaFruit Feather, but it looks like it's supposed to be a direct Arduino Nano competitor.  You might need to use a different library, but the idea should still be the same.


Cannot bootload again after changing the board?

Not only that I got an error, now, I can't bootload the internal clock again !

You need an external clock source, such as a crystal and two capacitors. Once you switch the fuses to the external clock it won't work any more unless you have such a clock.

I have a bootloader uploader sketch that also provides a clock signal if you need it.


Making an automated watering system with Arduino

Problems with your setup:

Your pump is connected to pin 11 but you are controlling pin 13 (int led = 13;)
You have an LED in line with your transistor base. That should be a resistor, and the LED should be in parallel with the base (with its own resistor).
Your transistor is wired wrong. According to the datasheet the pins are C-B-E as viewed from the angle in your wiring diagram. You have the Arduino connected to E instead of B, the pump connected to B instead of C, and ground connected to C instead of E.
You don't have a flyback diode across the motor.

simulate this circuit – Schematic created using CircuitLab


The Uno cannot be used as a HID device through the on board USB. You might be able to use the V-USB Library to be a HID device using the digital IO pins. See this tutorial.

There are several arduino compatible boards that do can act as a HID device natively. Most boards built around the ATMega32u4 can be a HID device.  For example the Arduino Micro

See this question about the Raspberry Pi.


Will a magnetometer give distorted values if there is a magnet near?

Yes, effectively.

In fact no, as the reading it gives WILL BE the field at that point BUT the field will be distorted compared to what you would see when the magnet is absent.

The effect of magnets at a distance is a somewhat complex subject - especially when there are several presnt and/or where ther are "magnetic materials" present but, as a guide.

At a distance large compared with magnet dimensions the field falls as the cube (not square) of the distance.
Very rough but useful rule of thumb: A top-end rare earth magnet will produce a field of about 1 Tesla at a distance of  1/2 it's thickness from the centre of its pole face. So eg a 20mm thick circular magnet will produce ABOUT 1 T at 10mm from the centre of its pole face. This is more useful in motor or alternator applications than when using magnetometers.


How to send and receive hex or binary numbers via BLE UART?

ASCII is just a pattern of 0s and 1s, and can therefore be represented in binary, hex, octal, or decimal. The interpretation is entirely up to you in your code.


Thank you for your answer. The code is as follows:

#include <SoftwareSerial.h>

String Arsp, Grsp;
SoftwareSerial gsm(12, 8); // RX, TX

String GET = "GET /bakalarka.php/? HTTP/1.1\r\nHost:84.42.xxx.xx\r\n\r\n";

void setup() {

  Serial.begin(115200);
  Serial.println("Testing GSM SIM800L");
  gsm.begin(19200);

}

void loop() {

  AT("AT+CFUN=1");
  AT("AT+CSTT=\"internet\",\"\",\"\"");
  AT("AT+CIICR");
  AT("AT+CIFSR");
  AT("AT+CIPSTART=\"TCP\",\"84.42.xxx.xx\",80");

  int get_length;
  get_length = GET.length();

  AT("AT+CIPSEND=" + String(get_length));
  AT(GET);
}

void AT(String AT){

  gsm.println(AT);

  if(gsm.available()){

    Grsp = gsm.readString();
    Serial.println(Grsp);
  }
}

I was thinking about a couple of things that could cause this.
1. Hardware design - some noise could cause a freeze of the GSM module while getting the answer from the server. After thinking through I don't think it's likely to be that. The power supply is made to be really beefy and there are enough bypass caps to reduce the noise and provide enough energy during current spikes. Also, the module doesn't freeze. It's still connected to the server, after a couple of seconds it closes the connection exactly as it should be.

Serial buffer gets somehow full. This was just a quick thought. The buffer of Arduino could get somehow full so it's not able to save any more incoming data. I think it's nonsense, but...

Thank you for your answers.

Krystof


Can i store a SqlLite DB into an (old) ESP32? (not using SD card)

I found these two post to be a useful answer to my question:

ESP32: Best way to store data frequently?

Sqlite3 Library for ESP32 Arduino Core


ESP32 partition table and writing location

0x1000 is the "second stage" bootloader. This is the code that is responsible for loading the code according to the layout specified in the partition table.

In ESP-IDF, the binary image which resides at offset 0x1000 in flash is the second stage bootloader. Second stage bootloader source code is available in components/bootloader directory of ESP-IDF. Note that this arrangement is not the only one possible with the ESP32 chip. It is possible to write a fully featured application which would work when flashed to offset 0x1000, but this is out of scope of this document. Second stage bootloader is used in ESP-IDF to add flexibility to flash layout (using partition tables), and allow for various flows associated with flash encryption, secure boot, and over-the-air updates (OTA) to take place.

0x8000 is the partition table itself.

Second stage bootloader reads the partition table found at offset 0x8000. See partition tables documentation for more information. The bootloader finds factory and OTA partitions, and decides which one to boot based on data found in OTA info partition.

All this is detailed in the ESP-IDF manual.


You will need a crossover cable to connect two Ethernet shields peer to peer.

Then you configure the Ethernet library to use static IP address. Use 192.168.1.1 and .2 address. (Or other 192.168.x.x address). Set subnet 255.255.255.0. Gateway should be the IP address of the other Arduino.


Bluetooth hc-06 and Standalone Atmega168(possible?)

The HC-0x Bluetooth transceivers are a drop-in replacement for a serial connection. Once the transceiver is configured (with baud-rate, device name, and pairing PIN #) you can plug it in in place of a serial line and expect to communicate. The device will take care of pairing and accepting a connection from the master device with no need for any code support from the AVR.

I use a separate program on an Arduino or a breadboarded AVR to configure my HC-06es. They retain their configuration across a power-down, and in fact, there is no hardware support for resetting them to a standard configuration; you need a program that figures out their current baud-rate in order to reconfigure them. It can save a bunch of hassle if you write down their configurations whenever you change them.


Use Arduino to detect low battery state and shut it down

It is not entirely beyond possible, in fact quite possible in theory.

I think the saying 'in theory, theory and reality are the same, but in reality they are not' is appropriate here.

So to monitor voltage, a simple voltage divider circuit can be used, and the Arduino can monitor that, and release a relay controlling the power line. The same relay could be wired to also reconnect when voltage reaches a threshold. I think the circuit actually requires 2 (or more) relays, and technically is it a kind of sensor, but since you indicated a relay was ok, it could work. So given those requirements, do you really need someone to draw it out, or were you just curious?

Simple battery monitoring from http://arduinotronics.blogspot.com/2012/04/voltage-monitor.html


See SoftwareSerial Write to return Read in Serial Monitor? - SoftwareSerial cannot both read and write at the same time.

However HardwareSerial can.

  Could this be achieved by using SoftwareSerial with one and the hardware serial port with the other?

Yes.

  So, likewise, there is no way to read from both devices using only SoftwareSerial?

That is correct. Not at the same time. SoftwareSerial uses an interrupt to detect the start bit of incoming data. So far so good. But once it gets it, it leaves interrupts disabled while it goes into a timed loop to read all the bits.

Thus, it is impossible for it to react to another incoming byte on another pin at the same time.

Still, you could receive on SoftwareSerial on one pin, and HardwareSerial on another. With HardwareSerial the hardware will run in the background, receiving the byte.


Which Arduino board to select for designing a Quadcopter?

The right board for you is the board that best fits your design.  Leave the Arduino as a "black box" in your design and don't worry about it.  Once you know what you need from your Arduino board in the way of control interfaces, IO, processing power, etc, you (and we) will be in a better position to choose a suitable board.

Until then you're basically asking "I want to take my driving test. What kind of car should I buy?", which makes absolutely no sense.


please tell me what's wrong.

I'm sorry to say, but pretty much everything. You need to rethink your program flow from the ground up.

Separate out the button from the LED actions. The button should only control the counter. The counter then makes the decision what to do with the LEDs.

Also you have to learn about the concept of change with the button. You don't want to be doing something if the button is high, since that will be being done all the time the button is pressed. Instead you need to learn how to do something only at the moment the button changes from low to high.

As a rough outline to how your program could look, here's a pseudo-listing:

Set the counter to 0
If the button changes from LOW to HIGH

Increment the counter

If the counter is greater than 3

Set the counter to 1

That would give you a sequence of 0-1-2-3-1-2-3-1-2-3 for the counter as you press the button.

Next you have a separate section in your loop to deal with what the counter is.

If the counter is 0

Turn off all LEDs

If the counter is 1

Control the red LED and turn off the others

If the counter is 2

Control the green LED and turn off the others

If the counter is 3

Control the blue LED and turn off the others

If you implement that properly you will have created a finite state machine.


how to prevent IR signal to go through 3d printed plastic?

You can not use common modulation remote control receivers as they contain an ACG feature which will likely "turn up the volume" until it detects even a weak reflected signal.  Instead consider if this reflective sensor, which does not contain an AGC feature, is appropriate for your design.

Alternatively you might explore the response time of the AGC feature to see if you can defeat its intended purpose.  That is to say, rapidly switch between IR transmitters in order to keep the AGC level at low gain.  Essentially blinding it from weak reflected signals.

You might also transmit continuously on all IR sources and determine if the AGC will put the weak signals below the noise floor.


Running Arduino code for Bluefruit LE on bare ATMega328

The UNO is basically just an ATMega328(P). So you can run the same compiled code for the UNO just fine on a bare ATMega328.

You don't have to worry about the P versus non-P version. They are basically the same except for some minor differences concerning low power settings.

You can just select the Arduino UNO board as you target. Select the avrispmkii as programmer. Then instead of Upload, choose Upload using Programmer (in the Sketch menu).


Why is delay(1000) breaking my serial communication?

NEVER use delay() in a loop - its a bad habit you get used to and then you return later on with complex code asking why nothing is happening or your webserver is dead for 10 seconds every time you receive a request.

So instead of

void loop() {
  if(Serial.available() > 0){
    Serial.println("Hello world from Ardunio!");
  }
  delay(10000);
 }

you would do

unsigned long timerStart = 0;
unsigned long myTimer = 10000;

setup(){....}

 void loop() {
  if(Serial.available() > 0 ){
     if(millis() - timerStart > myTimer){      // non blocking
       Serial.println("Hello world from Ardunio!");
       timerStart = millis(); // reset timer
     }
   }
 }

What your code does at the moment is enter the IF clause if exactly in this millis the buffer is filled, then wait for ten seconds ignoring whatever you do. Next chance tohit and so on. Delay() is blocking processing => not a good thing todo in communication scenarios,


This line:
if (legThreeBrightness = 255){

assigns the value 255 to legThreeBrightness.  That is non-zero so it enters the block and runs the fade now that the variable has been set to 255.
If you just want to compare the value to 255 then use:
if (legThreeBrightness == 255){

and that way when the loop function repeats it isn't there setting the value back to 255.  This way it will stay at 0.


Synchronous communication between two Arduino boards using two ESP8266 modules

The esp8266 WiFiMulti system allows to configure more access points and with the rigth code in loop it always searches the best AP.

Configure one of the esp8266 as AP and setup the other with WiFi Multi only for this one  access point.

You can then use events like onStationModeConnected to handle data exchange if the connection is established.


There are many options for executing a task periodically. The most
straightforward is to use a slight variation of code given in the Blink
Without Delay[] Arduino tutorial:

const uint32_t PERIOD = 150000;  // 150 ms

void loop() {
    static uint32_t last_time;
    if (micros() - last_time >= PERIOD) {
        last_time += period;
        do_periodic_task();
    }
    do_other_tasks();
}

Note two changes relative to the code in the tutorial:

This is using micros() instead of millis(). This way the timing
resolution is 4 µs instead of 1 to 2 milliseconds.
last_time is updated as last_time += period instead of
last_time = micros(). This way, even if the periodic task got
delayed by the other tasks, these delays don't add up.

The timing will not be perfect: you will have both drift and jitter.
The drift comes from the inaccuracy of the ceramic resonator clocking
the microcontroller. These resonators have typically 0.5% frequency
tolerance, although the typical frequency error is more likely to be
around ±0.1% (i.e. 0.15 ms error in a 150 ms period). Note
that a poorly written code would add it's own drift, e.g. if you do
last_time = micros(), but this does not.

The jitter comes from the fact that the clock is checked only once per
loop iteration, and your periodic task can then be delayed by the other
tasks. The amplitude of the jitter is the maximum time taken by a loop
iteration.

Despite these imperfections, this would be my first choice unless I
really needed better timing accuracy.

If you need lower drift, one option is to calibrate your Arduino clock.
You measure how fast or slow it is, and you tweak the PERIOD constant
accordingly. For example, if you measure the clock to be 700 ppm
slow, you would fix it like this:

const uint32_t NOMINAL_PERIOD = 150000;  // 150 ms

// Adjust the period to account for clock drift.
const float FREQUENCY_OFFSET = -700e-6;  // -700 ppm
const uint32_t PERIOD = NOMINAL_PERIOD * (1 + FREQUENCY_OFFSET);

This technique allows you to tune the frequency with about 6.7 ppm
resolution, for a period of 150 ms. You cannot reasonably expect
anything better, as the frequency of the ceramic resonator is not very
stable anyway.

If you need lower jitter, one option is to perform a blocking wait:
you ask the processor to do nothing but wait until it's time to perform
the periodic task. This is similar to the code you posted in your
question:

void loop() {
    static uint32_t last_time;
    while (micros() - last_time < PERIOD) ;  // busy wait
    last_time += period;
    do_periodic_task();
}

This will not completely suppress the jitter, but it will reduce it to
just the time taken by the while loop. However, there is a big issue
with this way of coding: now your processor does nothing but the
periodic task. It may not be a problem right now, but as your project
grows, it is more than likely that at some point you will want to handle
extra tasks like, e.g. responding to some user input.

If you want to avoid completely blocking the processor on the busy wait,
yet you want the smallest possible jitter, you could try some sort of
compromise: you let the processor take care of other tasks until it is
almost time to perform the periodic task. Then you switch to the
blocking mode where the processor does nothing but wait for the clock.
Here, “almost time” would be defined by the maximum time your loop can
take:

const uint32_t MAX_LOOP_TIME = 2000;  // assume 2 ms

void loop() {
    static uint32_t last_time;
    if (micros() - last_time >= PERIOD - MAX_LOOP_TIME) {
        while (micros() - last_time < PERIOD) ;  // busy wait
        last_time += period;
        do_periodic_task();
    }
    do_other_tasks();
}

Another option, that has been mentioned in comments, is to trigger the
task by a timer. This will work if it is a very short task that can
safely be run with interrupts disabled. You have four 16-bit timers on
your Mega, so you can presumably spare one for timing this task. This
could be done with Timer 1 as follows (warning: untested code):

const int TIMER_PRESCALER = 64;
const float F_TIMER = F_CPU / TIMER_PRESCALER;
const float PERIOD = 150e-3;
const uint16_t TIMER_PERIOD = F_TIMER*PERIOD + 0.5;  // round to nearest

void setup() {
    TCCR1B = 0;            // stop the timer
    OCR1A  = TIMER_PERIOD - 1;
    TIFR1 |= _BV(OCF1A);   // clear TIMER1_COMPA interrupt flag
    TIMSK1 = _BV(OCIE1A);  // enable TIMER1_COMPA interrupt
    TCCR1A = 0;            // no PWM
    TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
           | _BV(CS10)     // clock at F_CPU / 64
           | _BV(CS11);    // ditto
}

ISR(TIMER1_COMPA) {
    do_periodic_task();
}

Note that TIMER_PERIOD will be 37500. If you want to tune it to
account for an inaccurate clock frequency, your tuning resolution will
be about 26.7 ppm.

The interrupt technique should get you sub-microsecond jitter most of
the time. However, every now and then the Timer 0 interrupt (the
one responsible for updating the millis() counter) will delay your
interrupts for a few microseconds. Beware also that some libraries can
delay interrupts for excessive amounts of time. Software Serial is an
infamous offender.


Same Arduino Sketch when uploaded from a Linux machine does not work

Got this sorted.

The issue was that different versions of the library was being used in both the PCs. One we made sure that the Linux PC used the same as the MAC one it all worked fine!!!

Thanks Guys


I had the same problem and this seems to work. If you right click on the Kickoff Application launcher and open 'edit applications' with KDE Menu Editor, you can 'add new item' where you want and give it a name (ArduinoIDE) and then just put arduino (small case) in the 'command' box, and shut down KDE Menu Editor, it should appear in the menu where ever you placed it. At least it did for me.


The idea of that particular servo shield is that it provides 16 PWM (pulse width modulation) channels. These are all operated simultaneously with no additional processing overhead on the Arduino.

The Arduino Uno itself does not offer 16 (or 18) hardware PWM channels but only 6 (see here). So driving 18 servos without an additional shield would require software PWM which requires some of the Arduino's ressources to be devoted doing the calculations. This may or may not interfere with the rest of your program.

Furthermore the Uno does only provide 14 dedicated digital GPIO pins in total (+6 multiplexed digital/analog pins, as ZS6JMB's answer points out), so additional hardware would* be required either way - or using an Arduino with more pins (such as the suggested Mega). The Mega however offers only 15 hardware PWM channels, leaving you with soft PWM again. (* assuming some pins will be needed for sensors or user interfacing).

An alternative is this board or, uhm, well, cheaper clones if you like. It features the same chip as the shield but with a PCB half the size and thus skipping the "free use area". I expect it to behave the same way like the shield and operate with the same libraries as the both the shield and this board communicate only via I2C. Both can be chained (or stacked for the shield if you will) for up to 992 PWM outputs (62 boards).


How can I pass a char array as the parameter to a function?

There are one or two things missing in your code. Where is setup() and loop()? Or is it just a snippet?

But answer to the question first. This is not right:

newVar = adjust(String(options4[option%4]), variable);

Should be:

newVar = adjust(options4[option%4], variable);

You want to index the vector of strings and pass one of the elements to the function.

Cheers!


If the motor you are using has only two wires, and as you described it's response to the direct connection to the power, it can't be a servo. The motor is a normal dc motor.
If you want to control the amount of the turns on your rc car you should try to play with the pwm signal, I don't know if it will work or not but at least you will have tried. And remember not to connect the motor directly on the micro's pin if there no motor pins on your red board.


Is it possible to query (or otherwise detect) if Arduino is connected to 60 NeoPixel strip vs 144 strip?

Neopixels only have one-way communication. Some possible ways to detect the quantity are:

Bring the Data-Out of the last pixel back to the arduino and activate an interrupt on an input pin connected to that. If you write 144 LEDs worth of data to the 144-LED strip, the pin doesn't change. If you write 144 LEDs worth to a 60-LED strip, the pin changes. So your code has a startup routine to write data and detect it. You can even write all "black" colors, since the data will still have HIGH and LOW values, and your detect routine won't show any light patterns.
Pass the ground line that goes to the LED strip through a low-value resistor (A current-sense resistor) and use an analog input to read the voltage across the resistor. Write an all-white color to all NeoPixels and sense the current draw. Pre-calculate the 144-LED current draw and 60-LED current draw and set a cutoff value for knowing which strip is connected.
Make your LED-strip connector to have more pins than necessary strictly for the LED strip connections. For example, have 1 extra pin. On the 144-LED strip side of the connector, tie this connection to the 5V line. On the 60-LED strip, connect it to GND. Read HIGH or LOW on an extra digital input on your arduino.


Short answer: Yes. After all, Arduinos are made by starting with an ATMega (or other AVR) IC.

Longer answer: People - including myself - routinely build with a bare ATMega328p (or other MCU), programming them off-board on another system, or providing connections to allow programming them in place. Beyond that you only need the soldering skills for the chip you choose (if you're building the boards yourself). I use DIP ICs and off the shelf through-hole PCBs and hand-build one or a couple at a time. Quad Flat-Package or Surface-Mount chips are another step up in complexity for the hand-builder.


Serial Print, String And Variable On Same Line

int Var = 55;
//Do it in 2 lines e.g.
Serial.print("L ");     // String
Serial.println(Var);    // Print Variable on same line then send a line feed


How to connect a 2 cell LiPo batter to Arduino Motor Shield?

From the Motor Shield page,

  External (non-USB) power can come either from an AC-to-DC adapter
  (wall-wart) or battery. The adapter can be connected by plugging a
  2.1mm center-positive plug into the Arduino's board power jack on which the motor shield is mounted or by connecting the wires that lead
  the power supply to the Vin and GND screw terminals, taking care to
  respect the polarities.

So they provide the screw terminals for a battery, you should be able to insert two wires from your battery/pack into the terminals. If your battery has a connector on it, you'll need to either cut it off or find an adapter.

Be extra careful: if you have exposed leads from your battery and they touch, it'll get extremely hot and possibly catch fire.


A for statement repeats everything between { and }, (or just the next line if there is no { and } a certain number of times.  It's not as simple as you might at first think, but it makes more sense if you write it out as a while loop explicitly.

For instance, for (a; b; c) { ... } could be re-written as:

a;
while (b) {
    c;
}

So if you had:

for (int i = 0; i < 100; i++) {
    Serial.println(i);
}

it could be re-written as:

int i = 0;
while (i < 100) {
    Serial.println(i);
    i++;
}

The two mean exactly the same thing.  A for has the three elements - initializer, comparison and iterator.  The initializer is run before the loop starts, the comparison is used to work out when the loop should finish, and the iterator is used to move through each iteration of the loop.

To re-write your specific example:

for(int r = 0; r < 8; r++){
    for(int c = 0; c < 8; c++){
        lc.setLed(0, r, c, HIGH);
    }
}

You would end up with:

int r = 0;
while (r < 8) {
    int c = 0;
    while (c < 8) {
        lc.setLed(0, r, c, HIGH);
        c++;
    }
    r++;
}

Now, if we were to do away with the loops altogether and write it all out longhand, what would it look like?  Well, let's start with the inner c loop.  That loops from 0 to 7 (while less than 8), so replacing that loop with 8 discrete calls to the function replacing c each time would end up with:

int r = 0;
while (r < 8) {
    lc.setLed(0, r, 0, HIGH);
    lc.setLed(0, r, 1, HIGH);
    lc.setLed(0, r, 2, HIGH);
    lc.setLed(0, r, 3, HIGH);
    lc.setLed(0, r, 4, HIGH);
    lc.setLed(0, r, 5, HIGH);
    lc.setLed(0, r, 6, HIGH);
    lc.setLed(0, r, 7, HIGH);
    r++;
}

We could take it a step further and unroll the outer r loop.  A subset of what you would end up with would be like this (note, I have skipped a lot of the middle ones):

lc.setLed(0, 0, 0, HIGH);
lc.setLed(0, 0, 1, HIGH);
lc.setLed(0, 0, 2, HIGH);
lc.setLed(0, 0, 3, HIGH);
lc.setLed(0, 0, 4, HIGH);
lc.setLed(0, 0, 5, HIGH);
lc.setLed(0, 0, 6, HIGH);
lc.setLed(0, 0, 7, HIGH);
lc.setLed(0, 1, 0, HIGH);
lc.setLed(0, 1, 1, HIGH);
... skipped a lot ...
lc.setLed(0, 6, 6, HIGH);
lc.setLed(0, 6, 7, HIGH);
lc.setLed(0, 7, 0, HIGH);
lc.setLed(0, 7, 1, HIGH);
lc.setLed(0, 7, 2, HIGH);
lc.setLed(0, 7, 3, HIGH);
lc.setLed(0, 7, 4, HIGH);
lc.setLed(0, 7, 5, HIGH);
lc.setLed(0, 7, 6, HIGH);
lc.setLed(0, 7, 7, HIGH);

There would, of course, be 8 × 8 = 64 entries in there.

for loops can be used in lots of other fun ways too.  It's not just a simple "run this X number of times".  For instance, you can loop through a C string until you reach the NULL character at the end of the string:

for (char *p = str; *p != 0; p++) {
    ... do something with *p
}

You can iterate through the entries in a linked list:

for (struct mylist *scan = myListHead; scan; scan = scan->next) {
    ... do something to scan->whatever ...
}

You can even embed functions in there:

for (char c = 0; c != '\n'; c = Serial.read()) {
    ... Do something with character `c` until `c` is a line feed ...
}

As you can see for is an incredibly powerful and flexible tool that is often overlooked in favour of the more explicit while.


What are the better options to the basic Arduino Serial Plotter?

Custom devices require custom solutions.

I suggest using Python (don't be scared).

This tutorial shows us how to read data from serial and save it to .csv file. You don't have to use a file. For example you can modify it to use an in memory list, and save just values from last 30 seconds. You can also read several values, and not just one.

import serial
import time
import csv

ser = serial.Serial('/dev/ttyACM0')
ser.flushInput()

while True:
    try:
        ser_bytes = ser.readline()
        decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
        print(decoded_bytes)
        with open("test_data.csv","a") as f:
            writer = csv.writer(f,delimiter=",")
            writer.writerow([time.time(),decoded_bytes])
    except:
        print("Keyboard Interrupt")
        break

This tutorial (and this one) shows you how very quickly to show a sophisticated plot of the data you collected. You can even make a plot that shows several graphs and updates in real time.

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

Don't be scared it's not black magic. It just takes few days to understand how things work.


Is there any problem in running Arduino logic to 12V LEDs?

The signalling of those LEDs is 5V and the power supply 12V. Basically you have a 5V-powered chip with constant current sinks driving LED chains that are powered from 12V. The 5V power for the chip is created from the 12V power for the LEDs. So, you need to:

Provide +12V and GND to the chain of LEDs from a 12V power supply
Connect the data line to an Arduino
Connect the GND connection to the Arduino as well.

Nothing more is needed.


How to increase the volume in speaker using talkie library in arduino uno...?

Your sample values (that is, the speech[] array) range from 0x00 to 0xfe, using 99.6% of the total range of possible values.

Thus, there is no software solution to increase the volume, as you are only 1 bit away from the maximum output level (0xff is the max, and one less is 0xfe).

This requires a hardware solution. One easy way is to use a commercial audio amplifier or a powered speaker (a speaker with a built-in amplifier).


Show images on a monitor using Arduino via Wifi

I have somewhere in my stash a shield that enables an Arduino to overlay graphics on the screen. But it is kinda crude and low-res. What you're trying to achieve is definitely not for Arduino, it is way underpowered.

You'd better look into doing this with something like a Raspberry Pi.


how much current does Arduino Nano draw when only using 8 digital pins?

I would guess around 50 mA, to power the processor and the USB converter. I notice that this question suggests more like 20 mA.

To be certain, you could measure it, but probably 20 to 50 mA would be a ball-park figure.


Unable to compile c++11 libraries despite having added -std=c++11 in platform.txt

The AVR-based Arduinos don't come with anything close to a full C++ standard library implementation.  They have avr-libc which is fairly complete to at least the C99 standard, that is the C standard from 1999, not C++.  What you're doing with -std=c++11 is influencing the standard used by the compiler to interpret the C++ language itself.  This does work fine on AVR based Arduinos, but is not going to give you the sort of C++ containers you may be used to on a desktop or larger embedded system, like an ESP8266.
Much of the C++ standard library would be completely out of place on an AVR based Arduino, particularly those parts that make use of dynamic allocation like unordered_map in your error message.
There are some parts of the C++ library implemented via Arduino STL.  Whether or not you should be using containers from it is another question.
If you do try to use Arduino STL, I'd encourage you to use more conservative parts of it.  Something like an unordered_map, but with less (or no) dynamic allocation could be implemented by using Arduino STL's std::array and functions from its <algorithm> header, like their std::find or std::lower_bound, etc.  Trying to use a C++ map or vector container or something of that sort is kind of asking for trouble, more so on the more common AVR-based Arduinos with only roughly 2 Kbyte of RAM.


Sending over a number from Arduino to Attiny85

As Look Alterno stated it would be easier to directly use an LCD display. But if you really want to use the 7 segment display and the ATTiny85 you can use I2C to send the number to the ATTiny. There are libraries, that can use the USI hardware ot emulate a (nearly) full I2C bus. For example my TinyWire library, that I composed from the previous TinyWireM and TinyWireS libraries. I2C needs only 2 pins (pin 0 as SDA and pin 2 as SCL I think), so you still have your 3 pins left for the display.

Then you would make the Arduino master and the ATTiny slave. Use the examples, that come with the library to learn it's usage. Note, that currently you can use the write() function only with one byte, so if you need bigger datatypes you need to split them to byte-level on your own.


You do not need a resistor in the circuit. Just connect the devices together directly as shown in the tutorial you link to. They are both 3.3V devices and operate perfectly together with no additional components.
Reading an analog value from a clock signal is pretty meaningless anyway, so there's really no point in your experiments at the moment. They prove nothing.
As to why the light came on - that is most likely because the ESP is configured to use that LED to indicate the WiFi status or something similar.  The thing with an ESP32 is there is a whole lot more going on than just your code. Your code is just one thread in a complex system.


You really can't expect this to work unsoldered. The contacts will be at best intermittent, and poor contact. Even a 'dry joint' where the pin is mostly surrounded by solder doesn't work well, these are the ultimate examples! You could however use an edge-connector, if you can find one; not something you see often nowadays.


Rc car controller using the RC-switch library

As you wrote in your comment, you didn't use  pullup or pulldown resistors for connecting the buttons. In this case the pin is floating, whenever the corresponding button is not pressed. It will pick up random noise from the environment and change it's state randomly.

A pullup or pulldown resistor defines a specific value for the pin, if the button is not pressed (LOW or HIGH). The value of such is a resistor is not critical, as long, as it isn't a too big load. Pick some value in the kiloohms (for example 10kOhm).

But you don't need external resistors for this. The Atmega328, which is the heart of the Arduino Nano, already has buildin pullup resistors for each digital output pin. You can activate them by using

pinMode(pin_number, INPUT_PULLUP);

In this case you will have to change the if-statements to check for LOW instead of HIGH and connect the button to ground instead of 5V, because with a pullup resistor in idle state the pin will be pulled up to 5V and the button can then pull it down to ground.


KY-022 IR receiver, LED always on, no output

The first thing to look at is the circuit board. Are they using the resistor and LED to indicate the board is receiving power? The data sheet has a schematic showing several passive components in the "3. ApplicationCircuit" section. Here is a copy of the schematic I have used that worked with the IRremote library (Version 0.1 July, 2009 - Copyright 2009 Ken Shirriff).


Convert ASCII output to human readable form and assign to a variable

I don't think it is possible.

The Arduino is 8-bit microcontroller, and can't handle integers larger than 32-bit. The maximum value for a unsigned 32-bit integer is 4294967296. This is a smaller number than your readblock, so it wil never fit.

If you want to do this with smaller numbers, you can use these 2 function:

atoi -> convert char array to integer
atol -> convert char array to long integer


Why we need to add 10kOm resistors after wire to 2 pin?

Due to some weird electronic properties, the state of the input to the Arduino is "undefined" when there is nothing connected. When the button isn't pressed down, it is neither connected to 5V or GND; it is left floating. When floating, the input isn't reliable.

To make sure that the input always has some sort of signal, we connect it to ground. However, there is a problem with directly connecting the input to ground. When you would push the button, you would create a short circuit by allowing current to flow directly from 5V to GND without any current limiting.

The solution is to add a resistor to limit the current between 5V and GND. When the button isn't pushed, the input is grounded to allow it to read LOW. When the button is pushed, the 5V rushes in and, since the 5V doesn't use a resistor, "the 5V is stronger," making the input HIGH.

  Why we need to add resistors after LED?

An overly simplified explanation: A LED will theoretically pull infinite power (as current) from your power source without a resistor. With too much power, the LED will be destroyed from heat.

Because the LED has some resistance, it will pull up to a finite amount of power, but that usually is much more than the LED can handle (and sometimes what the power supply can supply). We need a resistor there to ensure that the LED can only draw as much power as it can handle.

  And why 3, 5, 6, 9, 10, 11 pins with "wave" symbol?

If you look at an Arduino board, it will say DIGITAL (PWM~). That (PWM~) means that any pins with the "~" symbol are PWM pins... pins that can turn on and off their output very fast, in this case to create an illusion that the LED is dimming because the state changes faster than the human eye can detect.

  http://arduino.cc/en/uploads/Main/ArduinoUnoFront240.jpg

More explanation for PWM here: Arduino docs, an answer [of mine]


As the OP suggested, I'm posting a summing up of the comments under his question since the answer was found.

In order to make a common define for those parameters in different source files, the easiest solution is to make a shared header. To do this, just create a new file called FastLedInclude.h and, inside of that, write

#include <FastLED.h>
#define NUM_LEDS 60
#define DATA_PIN 6

Then in every source file you will just have to #include "FastLedInclude.h" to be able to use that library.

The FastLED library also requires the programmer to create a struct. Now, placing the definition of the struct (i.e. struct CRGB leds[NUM_LEDS];) into the header file leads to compilation errors, since the compiler writes the code to allocate it once for every object file.

The correct way to share this among different object files is to declare it extern in the header, then define it just once in one of the cpp or ino files:

// into FastLedInclude.h
extern struct CRGB leds[];

// into any cpp or ino file (but just once)
struct CRGB leds[NUM_LEDS];

This can also be done in the main ino sketch file, but personally I prefer to define it into another one (it depends, however, on how you choose to divide the program).

If you want to create a library, some other problems arise. The easiest solution is to ask the user to manually modify the header file which will be in the library folder. This solution is a bit uncomfortable, but it is the safest one.

Another solution is to force the user to create a header file into the sketch folder. Then the library should know the sketch folder path to back-include it. But.. This is a very discouraged option, since it will require the library to know the sketch location, thus violating the consistency principle at the base of a library-based approach.

The third solution is to modify the approach, from a compile-time static definition to a dynamic one. In order to do this, instead of defining NUM_LEDS and DATA_PIN at compile time you save them as variables in the library class.

For instance, in your library class definition you have

class yourclass
{
    public:
        yourclass(uint8_t data_pin, uint8_t num_leds);
        ~yourclass();
    private:
        uint8_t _data_pin;
        uint8_t _num_leds;
        struct CRGB *leds = NULL;
};

And the implementation can be

yourclass::yourclass(uint8_t data_pin, uint8_t num_leds)
{
    _data_pin = data_pin;
    _num_leds = num_leds;

    // Dynamic allocation of the array
    leds = (struct CRGB *) malloc(num_leds * sizeof(struct CRGB));
}

yourclass::~yourclass()
{
    // you should free the leds array when done
    free(leds);
}

Then the user can write

yourclass *obj = new yourclass(6, 60);

// or, if he wants to define,
#define NUM_LEDS 60
#define DATA_PIN 6
...
yourclass *obj = new yourclass(DATA_PIN, NUM_LEDS);

or, in the case of a statically allocated object,

yourclass obj(6, 60);

// or, if he wants to define,
#define NUM_LEDS 60
#define DATA_PIN 6
...
yourclass obj(DATA_PIN, NUM_LEDS);


ILI9341 backlight flickers when using USB power from Laptop

That happens because not all USB ports can supply more than 500mA of current.
When you use a charger's USB port, it is designed to provide more than 500mA of current(ex. 1-2amps in most chargers). Try using a USB port that can provide more than 500mA of current. Most PCs and Laptops will only supply 500mA at maximum unless specified so.

More information regarding USB power can be read here on Wikipedia.

Cheers!


What is the use of 1k resistor shown in the picture and why it is used? Please check Arduino Uno Schematics for more info

Its a pulldown resistor!

Comment there says "USB Boot Enable" so safe assumption that it's an digital pin.

They're handy because they mean if there is no input to whether that pin is headed, the voltage at the pin will be 0 instead of floating.

The value doesn't matter too much, "When in doubt 10k it out" is a pretty well known saying around electronics people, meaning just use a 10k Ohm resistor and you'll be fine.


A capacitor is a device that can store (and release) charge. It is made up of 2 metallic electrodes (or plates) that are separated by a thin dielectric material.

  When you apply a voltage over the two plates, an electric field is created. Positive charge will collect on one plate and negative charge on the other. - build-electronic-circuits.com

In short, a capacitor lets the AC component through and blocks the DC component.

Capacitors can be used in the following ways:

Decoupling Capacitors

(Also called Bypass capacitors)

  A decoupling capacitor’s job is to supress high-frequency noise in power supply signals. They take tiny voltage ripples, which could otherwise be harmful to delicate ICs, out of the voltage supply.

Image reference http://www.seattlerobotics.org/encoder/jun97/basics.html

  In a way, decoupling capacitors act as a very small, local power supply for ICs (almost like an uninterupptable power supply is to computers). If the power supply very temporarily drops its voltage (which is actually pretty common, especially when the circuit it’s powering is constantly switching its load requirements), a decoupling capacitor can briefly supply power at the correct voltage. This is why these capacitors are also called bypass caps; they can temporarily act as a power source, bypassing the power supply.

  Decoupling capacitors connect between the power source (5V, 3.3V, etc.) and ground. It’s not uncommon to use two or more different-valued, even different types of capacitors to bypass the power supply, because some capacitor values will be better than others at filtering out certain frequencies of noise.
  - sparkfun.com

Power Supply Filtering

DC power supplies can be quite noisy on their own. Take the output of a bridge rectifier for example, there is a lot of ripple on the output. Capacitors are a perfect solution for reducing the ripple/noise of power supplies.

Image Reference: http://www.electronics-tutorials.ws/diode/diode_6.html

  Capacitors are stubborn components, they’ll always try to resist sudden changes in voltage. The filter capacitor will charge up as the rectified voltage increases. When the rectified voltage coming into the cap starts its rapid decline, the capacitor will access its bank of stored energy, and it’ll discharge very slowly, supplying energy to the load. The capacitor shouldn’t fully discharge before the input rectified signal starts to increase again, recharging the cap. This dance plays out many times a second, over-and-over as long as the power supply is in use.

Also see Keelan's answer over at electronics stack exchange.

Signal Filtering

  You can also combine capacitors and resistors to form filters that target specific frequencies. - build-electronic-circuits.com

  They can block out low-frequency or DC signal-components while allowing higher frequencies to pass right through. They’re like a bouncer at a very exclusive club for high frequencies only. - sparkfun.com

  For example in an audio system you can target the high frequencies to remove them (e.g. in a sub-woofer). This is called a low-pass filter.  - build-electronic-circuits.com

Image Reference: Wikipedia

Back to your application.

Motors are notoriously noisy. Your mentor has recommended a capacitor to decouple the noise of the motors and protect the IC from voltage drops/spikes.

Side note: D1 in your schematic is a power indication LED. It needs a current limiting resistor in series with the LED to limit the current and prevent the LED from burning out.

Resources:

https://learn.sparkfun.com/tutorials/capacitors
https://www.build-electronic-circuits.com/how-does-a-capacitor-work/
Basic Circuits - Bypass Capacitors
wikipedia.org/wiki/Capacitor
wikipedia.org/wiki/Decoupling_capacitor
Youtube - How a Capacitor Works - by Dr. Oliver Winn
explainthatstuff.com/capacitors


Send text according to an ultrasonic measurement, on battery

First of all: what is the intention of your setup? What are you trying to measure, what do you want to do with the data? Where is the bucket located, in your backyard or miles away in a forest?

I foresee some problems with your current setup.

First of all, you need a enclosure that keeps your 'duino and other components dry and at a comfortable temperature. I don't know how severe the weather conditions are, but stuff can get unreliable when used close to the min/max operating temperatures. Can you find an enclosure that can protect your electronics against the elements?

My advice: think of a good enclosure.

Second, do you really think PING))) is the best sensor? Have you already tested how it behaves around water? Are the measurements correct?
Another option would be an array of metal strips, one connected to +V or GND, the others to separate ports on your Arduino. Space them evenly from the bottom of your bucket to your maximum water level (drill a hole in the bucket to prevent overflowing or drowning your duino). Poll the pins at a predefined interval (not too short, keeping battery life in mind) to see which ones make contact with the water (allowing current to flow from/to the pins from/to +V/GND)

My advice: do some research on sensors, or try to make your own

The best way to communicate with your 'server' (what are you going to use?) totally depends on how far it is from the bucket. GSM shields are quite pricey, other alternatives may be preferable (and do not have additional phone costs).
Is your server on the other site of the window? Bluetooth? Somewhere in your backyard? Zigbee. Across the street? High-power Zigbee (if allowed by local authorities). Far away but with WIFI access? Zigbee, posting data to an online place. In the middle of nowhere but with great cell phone reception? GSM.

My advice: check out wireless communication possibilities. There's a ton of them, each with pros and cons.

Last hurdle, energy. Your battery setup will most definitely NOT be able to provide enough energy for a whole year. There's just too little juice in them.

Arduino and standalone AVRs often have a sleep mode, in which power consumption can be very very low. Google is your friend on this one. Still, that won't let your setup last a year.

Unless there was a gigantic glowing ball of plasma hanging around some 8 lightminutes from here and we could harness its incredible power with the use of photovoltaic elements... Wait, we totally can! Using (a) solar panel(s) and some simple circuitry you can recharge your batteries, and depending on the weather conditions this could keep your project up and running for a year.

My advice: get down and dirty with small solar panels.

I really appreciate your ambition. If done right, this could be quite the project for a beginner! Just make sure you thoroughly research every part of the system, on itself and as a whole. This could prevent a lot of disappointment and unnecessary costs, while only expanding your knowledge.

Good luck!


Try Arduino mega. It has more memory 8 KB RAM, 256 KB flash memory.


Using an external pull-up resistor vs INPUT_PULLUP

There is no OUTPUT_PULLUP that I am aware of. Use INPUT_PULLUP for most things.

Add 3.3K (3.3V) or 4.7K (5V) external pullups for I2C. If you saw a 'scope trace with 10K I2C pullup on 5V system and even short wiring, the rise time is really slow. 4.7K is much quicker.

10K for external pullup works well for slow things, like buttons, switches.  If the wire lengths are longer, then 4.7K could be used as well, maybe even 1K if the wires are long.  If running on battery power, 10K is better as there is less current flow when the input is low.


5V power supply negative terminal connection

The Arduino common, normally referred to as ground, although it is usually only accidentally grounded through external connection. In general ALL connections should have a common "ground".

You can not measure voltage across the LED given the circuit you have listed. (You could read the voltage at both ends and subtract.)

If you swap the LED and resistor you can get an approximation of the LED voltage (actually LED + Arduino pin) from the junction of LED and resistor.


How can measure the 3-axis accelerations?

There is no difference between gravity and other kinds acceleration. Gravity is the constant downward acceleration of ≈9.81 m/s². You cannot feel any difference between the force of gravity and the force you would experience on a surface without gravity that's accelerating upwards at 9.81 m/s².

You can use the gyroscope to keep track of the orientation of the sensor, so you know the downward direction of gravity, and can correct your accelerometer measurements for it.

The problem is that gyroscope orientation measurements are subject to drift. To correct the orientation for drift, the accelerometer is used (because it can measure the direction of gravity, so you know what the downward direction is). The accelerometer only measures the exact acceleration due to gravity if the sensor is not accelerating, of course, but that's most likely not the setup you're going to use an accelerometer in.

As you can see, this is kind of a chicken and egg problem.
Luckily, there are advanced sensor fusion algorithms and complementary filters available that combine the accelerometer and gyroscope measurements, and give you a pretty good approximation for both.
I've successfully used Madgwick's algorithm for a quadcopter.
Depending on your use case, you'll have to tweak some coefficients to indicate if you rely mostly on the gyro or the accelerometer data. The MPU6050 has a DMP that can run sensor fusion algorithms on the chip itself, so the Arduino doesn't have to deal with that.


Do external battery packs need to connect to ground on the arduino?

Ground is merely a label. It is a logical point in the circuit relative to which you measure all other voltages against.

For instance the 5V pin on the Arduino is actually 5V relative to the ground pin.

A 12V battery's + terminal is 12V relative to the - terminal. In this situation the - pin can be labelled Ground.

Electricity only ever flows when there is a circuit.  That is, current can only flow when it has some way of flowing back to where it came from.

A battery with an LED and resistor attached has a circuit: Battery -> LED -> Resistor -> Battery.  An Arduino itself is a circuit: Power -> Arduino -> Internal Gubbins -> Power

By the rule above, electricity can only ever flow out of an I/O pin if it has some way of getting back to where it came from. That route back is the Ground pin of the Arduino.  Interfacing some external device with the Arduino, whether it has its own power supply or not, requires that connection back to the Arduino's ground in order for the signal you send from the Arduino to have a complete circuit.


Without any further configuration, the ADC (Analog Digital Converter) of the Atmega328P (which is build onto the Arduino Uno) uses Vcc as voltage reference (meaning 5V in the case of the Arduino Uno). A voltage of 5V will result in the maximal value (which is 1023, since this is a 10bit ADC). So the voltage range in this case is 0 to 5V.

The Arduino Uno has an extra pin, where you can supply an own reference voltage. But it's limit is tied to the ADCs supply voltage AVcc, which is 5V for the Arduino Uno rev3 (as shown in the schematics of the Uno). The reference voltage should then be in the range of 1V to AVcc. So this still gives you only a range of 0V to 5V or smaller.

When you use a standalone Atmega328P, you can make AVcc a bit higher than the chips supply voltage Vcc, but at maximum Vcc + 0.3V.

You can check all these numbers by looking into the datasheet of the Atmega328P, chapter 28.9 (Electrical Characteristics --> ADC Characteristics).

How to increase this range depends greatly on your requirements. If you simply need a constant higher range, you can simply put a voltage divider in front of the analog input. Or you can use a more complex circuit involving an op-amp (amplifier ciruit, here with amplification factor below 1). You can even build this to be variable.

Should it be, that your wanted voltage range exceeds the 5V greatly, for example, if you want to measure mains voltage (230V for most europe, 110V in USA), you should definitely take great care and never connect this directly to electronic like the Arduino. High voltages (especially at high possible currents) should always be handled with great care.


RFID RC522 reads the previous tag serial with different tag

One rule for writing safety code is :

The return value of non-void functions must be checked by each calling function, and the validity of parameters must be checked inside each function.

You forgot to check if the tag has been readed i.e the return value of PICC_ReadCardSerial. If it fails the value is not updated, that is the reason why the value is still the old one.

Using the following code (from the ReadNUID example of the MFRC522 library https://github.com/miguelbalboa/rfid/blob/master/examples/ReadNUID/ReadNUID.ino)

// Init array that will store new NUID
byte nuidPICC[4];

void loop() {

  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    Serial.println(F("NUID has NOT been readed."));

  if (rfid.uid.uidByte[0] != nuidPICC[0] ||
    rfid.uid.uidByte[1] != nuidPICC[1] ||
    rfid.uid.uidByte[2] != nuidPICC[2] ||
    rfid.uid.uidByte[3] != nuidPICC[3] ) {
    Serial.println(F("A new card has been detected."));

    // Store NUID into nuidPICC array
    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }

    Serial.println(F("The NUID tag is:"));
    printHex(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
  }
  else Serial.println(F("Card read previously."));

  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}

void printHex(byte *buffer, byte bufferSize) {
      for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
  }
}

the result is

  A new card has been detected.
  The NUID tag is:
  97 C6 6E 09
  NUID has NOT been readed.
  Card read previously.
  A new card has been detected.
  The NUID tag is:
  CC 16 5D 83
  A new card has been detected.
  The NUID tag is:
  97 C6 6E 09
  NUID has NOT been readed.
  Card read previously.
  A new card has been detected.
  The NUID tag is:
  CC 16 5D 83

Sometimes when the second tag is used the tag is not read and the uid remains the same.


A standard PIR motion sensor will work fine.  It can monitor motion in a very room.  You just need to make sure the PIR sensor is far enough away.

Here is one article that states it should work up to 10 meters away.

https://www.mobotix.com/eng_US/Support/FAQ/Configuration2/What-is-the-range-of-the-PIR-Passive-Infrared-motion-detector

Note that the device that the PIR sensor is mounted on must be stationary.  It will not work on a robot of anything that is moving.