text:
I can't make more than one arduino gas sensor work at the same time
I'm doing a school project in which I need to track different kinds of gases, the problem is I can't read more than one sensor at the same time, I'm using four sensors (mq5, mq7, mq8 and mq135) and the code I'm using was one that I merged using four different codes that I found on github (https://github.com/mdsiraj1992/Gassensors). When I'm only one sensor it works normally, but when I use the code I merged the values are totally off. So basically I'm doing something wrong, but I don't know what. Please help me, I have to deliver the code this week.
#include <Adafruit_Sensor.h>

#include <Adafruit_Sensor.h>

#include <DHT.h>
#include <DHT_U.h>

#include <DHT.h>
#include <DHT_U.h>

/***Hardware Related Macros***/

#define         MQ5PIN                       (2)
#define         RL_VALUE_MQ5                 (1)
#define         RO_CLEAN_AIR_FACTOR_MQ5      (6.455)

#define         MQ7PIN                       (3)
#define         RL_VALUE_MQ7                 (1)
#define         RO_CLEAN_AIR_FACTOR_MQ7      (26.09)

#define         MQ8PIN                       (1)
#define         RL_VALUE_MQ8                 (1)
#define         RO_CLEAN_AIR_FACTOR_MQ8      (1)

#define         MQ135PIN                     (5)
#define         RL_VALUE_MQ135               (1)
#define         RO_CLEAN_AIR_FACTOR_MQ135    (3.59)

/***Software Related Macros***/

#define         CALIBARAION_SAMPLE_TIMES     (50)
#define         CALIBRATION_SAMPLE_INTERVAL  (500)
#define         READ_SAMPLE_INTERVAL         (50)
#define         READ_SAMPLE_TIMES            (5)

/***Application Related Macros***/

#define         GAS_LPG                      (1)
#define         accuracy                     (0)
#define         GAS_CARBON_MONOXIDE          (3)
#define         GAS_HYDROGEN                 (0)
#define         GAS_METHANE                  (2)
#define         GAS_CARBON_DIOXIDE           (9)
#define         GAS_AMMONIUM                 (10)

/***Globals***/
float           Ro = 10;

void setup() {
  Serial.begin(9600);
  Serial.print("Calibrating...\n");

  Ro = MQCalibration(MQ5PIN);
  Serial.print("Calibration is done...\n");
  Serial.print("Ro5=");
  Serial.print(Ro);
  Serial.print("kohm");
  Serial.print("\n");

  Ro = MQCalibration(MQ7PIN);
  Serial.print("Calibration is done...\n");
  Serial.print("Ro7=");
  Serial.print(Ro);
  Serial.print("kohm");
  Serial.print("\n");

  Ro = MQCalibration(MQ8PIN);
  Serial.print("Calibration is done...\n");
  Serial.print("Ro8=");
  Serial.print(Ro);
  Serial.print("kohm");
  Serial.print("\n");

  Ro = MQCalibration(MQ135PIN);
  Serial.print("Calibration is done...\n");
  Serial.print("Ro135=");
  Serial.print(Ro);
  Serial.print("kohm");
  Serial.print("\n");
}

void loop() {

  Serial.print("METHANE:");
  Serial.print(MQGetGasPercentage(MQRead(MQ8PIN) / Ro, GAS_METHANE) );
  Serial.print( "ppm" );
  Serial.print("    ");
  Serial.print("HYDROGEN:");
  Serial.print(MQGetGasPercentage(MQRead(MQ8PIN) / Ro, GAS_HYDROGEN) );
  Serial.print( "ppm" );
  Serial.print("    ");
  Serial.print("GLP:");
  Serial.print(MQGetGasPercentage(MQRead(MQ5PIN) / Ro, GAS_LPG) );
  Serial.print( "ppm" );
  Serial.print("    ");
  Serial.print("CARBON_MONOXIDE:");
  Serial.print(MQGetGasPercentage(MQRead(MQ7PIN) / Ro, GAS_CARBON_MONOXIDE)
              );

  Serial.print( "ppm" );
  Serial.print("    ");
  Serial.print("CARBON_DIOXIDE:");
  Serial.print(MQGetGasPercentage(MQRead(MQ135PIN) / Ro, GAS_CARBON_DIOXIDE)
              );
  Serial.print( "ppm" );
  Serial.print("    ");
  Serial.print("AMMONIUM:");
  Serial.print(MQGetGasPercentage(MQRead(MQ135PIN) / Ro, GAS_AMMONIUM) );
  Serial.print( "ppm" );
  Serial.print("\n");
  delay(200);
}

/***MQResistanceCalculation*****************************************
  Input:   raw_adc - raw value read from adc, which represents the
  voltage
  Output:  the calculated sensor resistance
  Remarks: The sensor and the load resistor forms a voltage divider.
  Given the voltage
  across the load resistor and its resistance, the resistance of the
  sensor
  could be derived.

*******************************************************************/
float MQResistanceCalculation(int raw_adc)
{
  return ( ((float)RL_VALUE_MQ5 * (1023 - raw_adc) / raw_adc));
  return ( ((float)RL_VALUE_MQ7 * (1023 - raw_adc) / raw_adc));
  return ( ((float)RL_VALUE_MQ8 * (1023 - raw_adc) / raw_adc));
  return ( ((float)RL_VALUE_MQ135 * (1023 - raw_adc) / raw_adc));
}

/*** MQCalibration*******************************************************
  Input:   mq_pin - analog channel
  Output:  Ro of the sensor
  Remarks: This function assumes that the sensor is in clean air. It use
  MQResistanceCalculation to calculates the sensor resistance in clean
  air
  and then divides it with RO_CLEAN_AIR_FACTOR. RO_CLEAN_AIR_FACTOR is
  about
  10, which differs slightly between different sensors.
****************************************************************/
float MQCalibration(int mq_pin)
{
  int i;
  float RS_AIR_val = 0, r0;

  for (i = 0; i < CALIBARAION_SAMPLE_TIMES; i++) {
    RS_AIR_val += MQResistanceCalculation(analogRead(mq_pin));
    delay(CALIBRATION_SAMPLE_INTERVAL);
  }
  RS_AIR_val = RS_AIR_val / CALIBARAION_SAMPLE_TIMES;
  r0 = RS_AIR_val / RO_CLEAN_AIR_FACTOR_MQ5;

  return r0;

  for (i = 0; i < CALIBARAION_SAMPLE_TIMES; i++) {
    RS_AIR_val += MQResistanceCalculation(analogRead(mq_pin));
    delay(CALIBRATION_SAMPLE_INTERVAL);
  }
  RS_AIR_val = RS_AIR_val / CALIBARAION_SAMPLE_TIMES;
  r0 = RS_AIR_val / RO_CLEAN_AIR_FACTOR_MQ7;

  return r0;

  for (i = 0; i < CALIBARAION_SAMPLE_TIMES; i++) {
    RS_AIR_val += MQResistanceCalculation(analogRead(mq_pin));
    delay(CALIBRATION_SAMPLE_INTERVAL);
  }
  RS_AIR_val = RS_AIR_val / CALIBARAION_SAMPLE_TIMES;
  r0 = RS_AIR_val / RO_CLEAN_AIR_FACTOR_MQ8;

  return r0;

  for (i = 0; i < CALIBARAION_SAMPLE_TIMES; i++) {
    RS_AIR_val += MQResistanceCalculation(analogRead(mq_pin));
    delay(CALIBRATION_SAMPLE_INTERVAL);
  }
  RS_AIR_val = RS_AIR_val / CALIBARAION_SAMPLE_TIMES;
  r0 = RS_AIR_val / RO_CLEAN_AIR_FACTOR_MQ135;

  return r0;
}
/*****************  MQRead *********************************
  Input:   mq_pin - analog channel
  Output:  Rs of the sensor
  Remarks: This function use MQResistanceCalculation to caculate the
  sensor resistenc (Rs).
  The Rs changes as the sensor is in the different consentration of the
  target
  gas. The sample times and the time interval between samples could be
  configured
  by changing the definition of the macros.
********************************************************/
float MQRead(int mq_pin)
{
  int i;
  float rs = 0;

  for (i = 0; i < READ_SAMPLE_TIMES; i++) {
    rs += MQResistanceCalculation(analogRead(mq_pin));
    delay(READ_SAMPLE_INTERVAL);
  }

  rs = rs / READ_SAMPLE_TIMES;

  return rs;
}

/***********************  MQGetGasPercentage ****************************
  Input:   rs_ro_ratio - Rs divided by Ro
  gas_id      - target gas type
  Output:  ppm of the target gas
  Remarks: This function uses different equations representing curves of
  each gas to
  calculate the ppm (parts per million) of the target gas.
******************************************************************/
int MQGetGasPercentage(float rs_ro_ratio, int gas_id)
{
  if ( accuracy == 0 ) {

  }
  if ( gas_id == GAS_LPG ) {
    return (pow(10, ((-2.513 * (log10(rs_ro_ratio))) + 1.878)));
  }
  else if ( gas_id == GAS_CARBON_MONOXIDE ) {
    return (pow(10, ((-1.525 * (log10(rs_ro_ratio))) + 1.994)));
  }
  else if ( gas_id == GAS_HYDROGEN ) {
    return (pow(10, ((-2.568 * (log10(rs_ro_ratio))) + 0.360)));
  }
  else if ( gas_id == GAS_METHANE ) {
    return (pow(10, ((-16.16 * (log10(rs_ro_ratio))) + 1.093)));
  }
  else if ( gas_id == GAS_CARBON_DIOXIDE ) {
    return (pow(10, ((-2.890 * (log10(rs_ro_ratio))) + 2.055)));
  }
  else if ( gas_id == GAS_AMMONIUM ) {
    return (pow(10, ((-2.469 * (log10(rs_ro_ratio))) + 2.005)));

  }
  else if ( accuracy == 1 ) {
  }
  else if ( gas_id == GAS_LPG ) {
    return (pow(10, ((-2.513 * (log10(rs_ro_ratio))) + 1.878)));
  }
  else if ( gas_id == GAS_CARBON_MONOXIDE ) {
    return (pow(10, ((-1.525 * (log10(rs_ro_ratio))) + 1.994)));
  }
  else if ( gas_id == GAS_HYDROGEN ) {
    return (pow(10, ((-2.568 * (log10(rs_ro_ratio))) + 0.360)));
  }
  else if ( gas_id == GAS_METHANE ) {
    return (pow(10, (-281.3 * pow((log10(rs_ro_ratio)), 3) - 12.26 *
                     pow((log10(rs_ro_ratio)), 2) - 7.925 * (log10(rs_ro_ratio)) + 1.668)));
  }
  else if ( gas_id == GAS_CARBON_DIOXIDE ) {
    return (pow(10, ((-2.890 * (log10(rs_ro_ratio))) + 2.055)));
  }
  else if ( gas_id == GAS_AMMONIUM ) {
    return (pow(10, ((-2.469 * (log10(rs_ro_ratio))) + 2.005)));
  }
}

Using your merged code, but commenting out the calls to all but one sensor (at a time), will each of them run correctly?

First of all you only need to include once. Including anything more than once is pointless and could be bad, if the header doesn't have include guards (yours do, but still it just makes the code harder to read).
Let's take a look at the MQResistanceCalculation function, well... It's simply broken.
float MQResistanceCalculation(int raw_adc)
{
  return ( ((float)RL_VALUE_MQ5 * (1023 - raw_adc) / raw_adc));
  return ( ((float)RL_VALUE_MQ7 * (1023 - raw_adc) / raw_adc));
  return ( ((float)RL_VALUE_MQ8 * (1023 - raw_adc) / raw_adc));
  return ( ((float)RL_VALUE_MQ135 * (1023 - raw_adc) / raw_adc));
}

I'm not sure what you expect to happen, but as soon as you reach a return statement that block of code stops and the result is returned, so basically that function executes the first return and then stops. You probably want to pass a sensor type and then use a switch to make it return for either the MQ5, MQ7, MQ8 or MQ135, because right now it only returns the MQ5 value.
Then let's take a look at the MQCalibration function. So same thing as above applies, as long as you reach a return the function stops. Your MQCalibration function currently only does:
float MQCalibration(int mq_pin)
{
  int i;
  float RS_AIR_val = 0, r0;

  for (i = 0; i < CALIBARAION_SAMPLE_TIMES; i++) {
    RS_AIR_val += MQResistanceCalculation(analogRead(mq_pin));
    delay(CALIBRATION_SAMPLE_INTERVAL);
  }
  RS_AIR_val = RS_AIR_val / CALIBARAION_SAMPLE_TIMES;
  r0 = RS_AIR_val / RO_CLEAN_AIR_FACTOR_MQ5;

  return r0;
}

And then the MQGetGasPercentage function can be re-written with switch statements to be way easier to read and understand. Oh and also that accuracy == 0 check is also pointless it has nothing in it.
From reading this I see you've just copied code you don't understand and hoped it'll work, but as expected it didn't. And well copying code without atleast having an idea about what it does is stupid. So just read it, understand it and write it again, but by yourself. Your code has many pointless variable declarations and it just isn't well "written"(or copy-pasted should I say).
Also I've never worked with that sensor myself, so I was looking at the code aspect mostly, just so you know.

I understand now and I will try to make a new code by myself, I had to copy paste it because of my lack of knowledge in Arduino and I didn't have much time to research, thanks for the help, I'll make sure to do it right next time.


text:
Optocoupler on Tinkercad acting weird
So, maybe it's my understanding that is at fault or maybe it's tinkercad. It's probably the former. But anyway here's my problem
I've connected it according to picture
https://i.stack.imgur.com/SJ88F.jpg
There is no power going through the anode. The cathode is going to ground.
On the upper side 5v is going to base and the emitter sends signals to an input on pin 12.
If i digitalRead pin 12 and Serial.write it. it says 1. which is weird, least for my understanding.
As i understood there needs to be power going through the anode which lights up the diode inside the optocoupler. however there is no power going through the anode yet the emitter gives off a signal.
Anyone mind helping me out in understanding why this is?
Please ignore the resistors on the image

fixed it, or least a link to the picture

You connected 5V to the base of the transistor inside, so the transistor is turned on all the time.
Move the 5v pin one to the right (middle pin on the 4N35, i.e. the collector), and it should work.

https://imgur.com/a/Yv6UiZx do you mean like this? now the base is collected to ground, the collector to 5v, the emitter to the input pin.
on the other side 5v is connected to the anode and cathode is to the ground. Yet this produces the input pin to return only zeroes. this time it should be only ones

No, leave the base unconnected like this: https://imgur.com/a/uaUCqsC

Ok that actually works great, i'm a bit confused however. does giving power to the base just ignore the what i understand "main" function of the octocoupler?

Every transistor is light sensitive. That is why transistors are in black plastic instead of transparent plastic. The output of the optocoupler is a transistor and it can use the light (often a led or ir led) turned on by the input, but also the base pin can be used (for something, I don't know who uses that). Some optocouplers don't even have that base pin.

ah so you could say that the base pin is just extra functionally and not part of the main function of the octocoupler?

@magicmike992 Yes, it is extra. The base pin is used here to filter spikes: https://www.electronics-tutorials.ws/blog/optocoupler.html so it seems to be used, but a spike can be filtered at the input or output as well.

The light from the led "activates" the base. So you don't need to connect it to anything, to have it function.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Anomalous behaviour of ADC, digitalWrite and floating point operations
I'm trying to analyse mic (A0) input, calculate certain spectral lines with Goertzel algorithm to detect a number encoded by DTFM and display it with 8x8 matrix display (max7219 driver).
The code works perfectly fine without a display sending the result to serial, however when I added a display, strange things started to happen.

if goertzel(..) is called before displayDigit the display doesn't show anything
if displayDigit is called first the output of goertzel(..) is a complete mess
if I comment out 1 line in goertzel(..) which is amp = sqrt(re * re + im * im); // [1] the display works (but it doesn't make sense)

I'm using Arduino UNO, ADC in free-run mode.
The code below:
/**
 * 8x8 LED matrix display with MAX7219 driver
 * +5V, GND, CLK (8 pin), CS (9 pin), DIN (10 pin)
 */
#include <binary.h>
#include <LedControl.h>

#include "font8x8.h"

#define N           256
#define IX_LEN      8
#define THRESHOLD   20

/* Display PINs */
#define CLK     13//8
#define CS      12 //9
#define DIN     8 //10

LedControl matrix = LedControl(DIN, CLK, CS, 1);
int8_t lastDetectedDigit = -1;
int8_t currentDigit = -1;
uint32_t lastDetectedMillis = 0;

const int adc_channel = 0;

volatile uint16_t samples[N];
volatile uint16_t samplePos = 0;

float spectrum[IX_LEN] = {0,0,0,0,0,0,0,0};

// Frequences [697.0, 770.0, 852.0, 941.0, 1209.0, 1336.0, 1477.0, 1633.0]
// Corresponding spectrum indexes [18, 20, 22, 25, 32, 35, 39, 43]

// Calculated for 9615Hz 256 samples
const float cos_t[IX_LEN] = {
  0.9039892931234433, 0.881921264348355, 0.8577286100002721, 0.8175848131515837,
  0.7071067811865476, 0.6531728429537769, 0.5758081914178454, 0.49289819222978415
  };

const float sin_t[IX_LEN] = {
  0.4275550934302821, 0.47139673682599764, 0.5141027441932217, 0.5758081914178453,
  0.7071067811865475, 0.7572088465064845, 0.8175848131515837, 0.8700869911087113
  };

const char table[4][4] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

const uint8_t char_indexes[4][4] = {
  {0, 1, 2, 12},
  {3, 4, 5, 13},
  {6, 7, 8, 14},
  {10, 9, 11, 15}
};

void initADC() {
  // Init ADC; f = ( 16MHz/prescaler ) / 13 cycles/conversion
  ADMUX  = adc_channel; // Channel sel, right-adj, use AREF pin
  ADCSRA = _BV(ADEN)  | // ADC enable
           _BV(ADSC)  | // ADC start
           _BV(ADATE) | // Auto trigger
           _BV(ADIE)  | // Interrupt enable
           _BV(ADPS2) | _BV(ADPS1) | _BV(ADPS0); // 128:1 / 13 = 9615 Hz
//  ADCSRB = _BV(ADTS2) | _BV(ADTS0);              // Timer/Counter1 Compare Match B
  ADCSRB = 0; // Free-run mode
  DIDR0  = _BV(adc_channel); // Turn off digital input for ADC pin
}

void goertzel(volatile uint16_t *samples, float *spectrum) {
  float v[N + 2];
  float re, im, amp;

  for (uint8_t k = 0; k < IX_LEN; k++) {
    float a = 2. * cos_t[k];
    v[0] = v[1] = .0;
    for (uint16_t i = 2; i < N + 2; i++) {
      v[i] = float(samples[i - 2]) + a * v[i - 1] - v[i - 2];
    }
    re = cos_t[k] * v[N + 1] - v[N];
    im = sin_t[k] * v[N + 1];
    amp = sqrt(re * re + im * im); // [1]
    spectrum[k] = amp;
  }
}

float avg(float *a, uint16_t len) {
  float result = .0;
  for (uint16_t i = 0; i < len; i++) {
    result += a[i];
  }
  return result / len;
}

int8_t get_single_index_above_threshold(float *a, uint16_t len, float threshold) {

  if (threshold < THRESHOLD) {
    return -1;
  }

  int8_t ix = -1;
  for (uint16_t i = 0; i < len; i++) {
    if (a[i] > threshold) {
      if (ix == -1) {
        ix = i;
      } else {
        return -1;
      }
    }
  }
  return ix;
}

char detect_digit(float *spectrum) {
  float avg_row = avg(spectrum, 4);
  float avg_col = avg(&spectrum[4], 4);
  int8_t row = get_single_index_above_threshold(spectrum, 4, avg_row);
  int8_t col = get_single_index_above_threshold(&spectrum[4], 4, avg_col);

  if (row != -1 && col != -1) {
    return table[row][col];
  } else {
    return 0;
  }
}

void displayDigit(uint8_t c) {
  if (currentDigit == c) {
    return;
  }

  for (uint8_t i = 0; i < 8; i++) {
    matrix.setColumn(0, 7 - i, IMAGES[c][i]);
  }
  currentDigit = c;
}

void setup() {
  cli();
  initADC();
  sei();

  matrix.shutdown(0, false);
  matrix.setIntensity(0, 2);

  Serial.begin(115200);

}

unsigned long z = 0;

void loop() {
  while(ADCSRA & _BV(ADIE)); // Wait for audio sampling to finish

  goertzel(samples, spectrum);
  samplePos = 0;

//  if (z % 25 == 0) {
    displayDigit(2);

    for (int i = 0; i < IX_LEN; i++) {
      Serial.print(spectrum[i]);
      Serial.print("\t");
    }
    Serial.println();
    char digit = detect_digit(spectrum);
    Serial.println(digit);
//  }
  z++;

  ADCSRA |= _BV(ADIE);       // Resume sampling interrupt
}

ISR(ADC_vect) {
  uint16_t sample = ADC;

  samples[samplePos++] = sample;

  if(samplePos >= N) {
    ADCSRA &= ~_BV(ADIE); // Buffer full, interrupt off
  }
}

font8x8.h:
const byte IMAGES[16][8] = {
{
  B00001000,
  B00011000,
  B00001000,
  B00001000,
  B00001000,
  B00001000,
  B00001000,
  B00011100
},{
  B00111100,
  B01000010,
  B01000010,
  B00000100,
  B00011000,
  B00100000,
  B01000000,
  B01111110
},{
  B00111100,
  B01000010,
  B00000010,
  B00000100,
  B00000100,
  B01000010,
  B01000010,
  B00111100
},{
  B00010100,
  B00100100,
  B00100100,
  B01000100,
  B01111110,
  B00000100,
  B00000100,
  B00000100
},{
  B00111110,
  B01000000,
  B01000000,
  B01111100,
  B00000010,
  B00000010,
  B01000010,
  B00111100
},{
  B00111100,
  B01000010,
  B01000000,
  B01111100,
  B01000010,
  B01000010,
  B01000010,
  B00111100
},{
  B00111110,
  B01000010,
  B00000100,
  B00000100,
  B00001000,
  B00001000,
  B00010000,
  B00010000
},{
  B00111100,
  B01000010,
  B01000010,
  B00111100,
  B01000010,
  B01000010,
  B01000010,
  B00111100
},{
  B00111100,
  B01000010,
  B01000010,
  B01000010,
  B00111110,
  B00000010,
  B01000010,
  B00111100
},{
  B00111100,
  B01000110,
  B01001010,
  B01010010,
  B01010010,
  B01010010,
  B01100010,
  B00111100
},{
  B00000000,
  B01010100,
  B00111000,
  B01111100,
  B00111000,
  B01010100,
  B00000000,
  B00000000
},{
  B00101000,
  B00101000,
  B11111110,
  B00101000,
  B11111110,
  B00101000,
  B00101000,
  B00000000
},{
  B00011100,
  B00100010,
  B00100010,
  B01000010,
  B01111110,
  B01000010,
  B01000010,
  B01000010
},{
  B01111100,
  B01000010,
  B01000010,
  B01111100,
  B01000010,
  B01000010,
  B01000010,
  B01111100
},{
  B00111100,
  B01000010,
  B01000000,
  B01000000,
  B01000000,
  B01000000,
  B01000010,
  B00111100
},{
  B01111000,
  B01000100,
  B01000110,
  B01000010,
  B01000010,
  B01000010,
  B01000010,
  B01111100
}};

I use LedControl.h library but inside is uses only digitalWrite, no timing, interrupts.
Can somebody explain what is the problem?
UPD
This is what IDE tells me about the sizes:
Sketch uses 5602 bytes (17%) of program storage space. Maximum is 32256 bytes.
Global variables use 1048 bytes (51%) of dynamic memory, leaving 1000 bytes for local variables. Maximum is 2048 bytes.

This is LedControl library I'm using

Please update your question with more information. Can you give a link to the LedControl library and tell us what the compiler says about flash and ram usage. Start looking for an other arduino board, for example an arduino mkr or a arduino compatible board with a esp8266 or esp32.

How much static RAM does your program use, according to the compiler? Seems to me that should be close to 1 K, leaving little more than 1 K for the stack. Your goertzel() function alone uses more than 1 K of stack, so you could well be smashing the stack against the BSS.

Thx, @EdgarBonet I haven't even though about these constraints. I'll try to move constants to flash memory and replace floats to fixed point.

From your recent edit:

Global variables use 1048 bytes (51%) of dynamic memory, leaving 1000
  bytes for local variables. Maximum is 2048 bytes.

Your goertzel() function defines this
float v[N + 2];

where N is 256. This alone takes 258×4 = 1032 bytes of
stack and you only have 1000 bytes available. Then, as I suspected,
you are smashing the stack against the .bss section, effectively
overwriting some of your global variables with the local ones.
It is hard to predict what can happen in such circumstances. The program
is corrupting its memory: you can only expect it to act erratically.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How would I go about powering addressable RGB LED light strip? [Arduino Nano]
The addressable RGB LED I have is WS2812B. I plan on controlling the LEDs via an Arduino nano. I have a total of 188 LEDs to supply power to.
Would I require anything between the addressable RGB LED strip and the 12v power supply?
Would I require a 1000uF capacitor?

Would I require anything between the addressable RGB LED strip and the 12v power supply?

A suitable 5V regulator (assuming 5V LED strip)

Would I require a 1000uF capacitor?

For what? A suitable 5V regulator won't need one. An unsuitable one would be improved by it, but still be unsuitable.

Regarding the 1000uF capacitor - I was just guessing from looking a diagrams which included what I would be using.

Electronics is not about guesswork. It's about hard and fast rules and formulae.


text:
How are errors (not related to syntax) managed in arduino and in the AVR architecture in general?
I was just curious about how the AVR architecture manages errors that would cause a regular desktop program to crash. I'm talking about logical errors for example math problems that are undefined. Such as division by 0 and getting a square root of a negative number. At first I was expecting that by giving an error to the AVR chip it will just return 0. But I ran this program:
void setup() {
Serial.begin(9600);
}
void loop(){
int x = 0;
int p = 50;
int result;
result = p/x;
Serial.println(result);
result = sqrt(-10);
delay(1000);
Serial.println(result);
delay(10000);
}

and got this output:
4294967295
0

After this I got really confused. Why would the result variable take the maximum value of an unsigned long? Since I declared an int the micro controller must have dedicated 2 bytes of dynamic memory to this variable but apparently it somehow managed to get additional 2 bytes to store the data. Could this mean that the AVR chip can corrupt data in other memory locations while allocating new data for the variable that just was fed a undefined in to it? Okay maybe the AVR chip just sets any mathematical nonsense to 4294967295. But no in the example of getting the square root of -10 we see that the value became 0. Although this is probably a function processed by some library so maybe there is some kind of protection against these errors. Also, I tried to run the program above but with a byte variable for the result instead of int.
void setup() {
Serial.begin(9600);
}
void loop(){
int x = 0;
int p = 50;
int result;
result = p/x;
Serial.println(result);
result = sqrt(-10);
delay(1000);
Serial.println(result);
delay(10000);
}

And the result was the same. So, is there some kind of documentation about error management in AVR since this is important to know while development.
P.S. Everything was run on a real Atmega 328p chip on an arduino nano.

I think the standard is that it is undefined for integer math. The floating point is according to the IEEE standard and returns a nan, but no exception. Catching an exeption in the Arduino is not possible (I think) : https://stackoverflow.com/questions/10095591/enable-exceptions-in-the-arduino-environment When you find strange things with a byte, please give a full sketch that we can try and tell us which arduino board you use.

@Jot This is an interesting point but why would a nan be replaced with 4294967295. Apparently they don't have the same binary value. Why did Atmel not include a nan value (that maybe could be disabled through fuses) in their processor architecture. This is a useful troubleshooting feature that is heavily used in all major programming languages.

@Jot I used an Arduino nano with an Atmega 328p on board.

An integer can not be a 'nan', that is specified for floating point. Please update your question with board and microcontroller, and perhaps a full sketch.

I tried to make a sketch myself, and I have different results. Please show your sketch and tell us the results of the sketch that you show. Are you running this in a simulator?

@Jot No, everything is being run on a real arduino.

Thank you for the full sketch. I have added an answer. You have run into a very weird compiler bug that causes the 4294967295. Now I understand why my code did not show that number and your code does.

The simple answer is: they are not handled at all.
According to the C and C++ standards, what you are invoking is called
undefined behavior, meaning anything can happen. In practical
terms, it means that the compiler can do its optimizations assuming
you will never invoke undefined behavior, and completely disregard what
could happen if the assumption does not hold. The generated code could
be completely broken, it won't be the compiler's fault.
The AVR architecture cannot do divisions, nor floating point math. Thus
all the errors you have here happen at the software level. Note that
sqrt(-10) is not an error (it's NaN, which is correctly handled by
the avr-libc), but converting that to an int (which you do when you
assign it to result) is an error.
If you really want to know the details of what happens with each of
these errors, there is only one option: you have to disassemble the
executable program and read the assembly listing.

"... undefined behavior, meaning anything can happen." - It's worth emphasizing that this is completely a C/C++ thing, unrelated to the AVR chips. The exact same warning applies to code running on, say, an Intel i5.

Also worth noting that while the C++ standard states that the compiler can do anything, C++ compilers typically define additional behavior beyond the C++ specification.  For example, Visual Studio's compiler defines the behavior of x/0 which was undefined in the C++ spec, based on what it knows about the architecture.  This is really useful when you want to do something the spec forbids, but your particular compiler permits, like gcc extensions.

About the number 4294967295
To my surprise, the sketch produces indeed the number 4294967295. That is not okay.
It turns out that the compiler knows the numbers and tries to do the math itself (instead of runtime).
At runtime, the 50 / 0 results into a signed integer of -1.
When a byte is used, the 50 / 0 results into 255.
The result of that calculation is a variable with only 1's. That is 0xFFFF for a 16-bits variable. That results into 65535 for a unsigned integer and -1 for a signed integer and 255 for a unsigned byte.
So far, that is okay. It makes sense.
However, when the compiler tries to do the math itself with 50 / 0, it turns the result into a 32-bit variable of 0xFFFFFFFF. The compiler does not put the math into the binary result, but calls the Serial.println() directly with a 32-bit unsigned long of 0xFFFFFFFF, which is 4294967295.
The reason is not the variable type of the variable 'result', but the division with 'p/x'. The compiler thinks it is better to make a 32-bit integer when the math is done with two 16-bit integers.
I think that when the compiler optimizes, the result should be same as a runtime calculation.
There is an interesting discussion below this answer. @EdgarBonet calls the compiler behaviour weird but not a bug.
Below is a test sketch that produces 4294967295 with Arduino 1.8.7 for an Arduino Uno:
void setup() {
Serial.begin(9600);
}

void loop(){
  int x = 0;
  int p = 50;
  int result;
  result = p/x;
  Serial.println(result);
  delay(5000);
}

The code outputs normal results when 'x' or 'p' is calculated, for example the result from a function, or when one of the three variables is made volatile.

The handling of undefined behavior by the compiler is never a bug because, by definition, whatever the compiler does is acceptable per the language standard.

@EdgarBonet I think it should do whatever in the same way. In your opinion the compiler can insert code to whistle a tune when dividing by zero? I don't think so. Changing an int to unsigned long is too weird in my opinion.

Although the compiler may not deliberately do silly things, strange things do happen when you invoke undefined behavior. See for example the beginning of this blog post (the whole post series is a must-read for any C or C++ programmer). Weird? Yes. Bug? No.

@EdgarBonet, thanks, interesting to read that. The things they mention are straightforward. What happens here is that runtime a certain function is called, and when the compiler optimizes it, a different (overloaded) function is called. That is one step further into weirdness.

"In your opinion the compiler can insert code to whistle a tune when dividing by zero? I don't think so." - When you invoke Undefined Behaviour, everything goes, including unexpectedly large variables, tune whistling, or formatting your hard drive. Welcome to the wonderful world of C and C++. It would be interesting though to see if the same "variable promotion" occurs without UB.

It only happens when x is zero and p is non-zero. When the 4294967295 is printed, the sizeof(result) is still 2.


text:
Wemos D1 mini fatal exception
I'm trying to flash a Wemos D1 mini ESP8266 board with the blink sketch, but get an error. The built in LED turns off when flashing starts.
Sketch uses 247872 bytes (23%) of program storage space. Maximum is 1044464 bytes.
Global variables use 28000 bytes (34%) of dynamic memory, leaving 53920 bytes for local variables. Maximum is 81920 bytes.
warning: serialport_set_baudrate: baud rate 921600 may not work
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I tried changing the programming speed to most of the other options.
If I open the serial monitor and set the baud rate to 74880, I get the following message repeatedly.
Fatal exception (0):
epc1=0x400cd530, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000

Is the board dead, or is there a way of reflashing it without using the serial port?

How are you powering the board?

warning: serialport_set_baudrate: baud rate 921600 may not work try a lower baudrate (115200 is safe) because your code isn't uploading error: espcomm_upload_mem failed - perhaps you got a partial upload at some time which is causing the fatal exception on boot -

Flashing with the serial port is the only practical option. The flash chip can be removed, and it can be flashed off board, but that isn't practical.
Has the board ever worked? Have you used other RSP8266 boards before or is this the first you have? Do you have a different USB cable you can try? Marginal power can cause unpredictable operation.


text:
compilation error when changing variable from char to String
I have a code with these two lines:
  char handshakecode = "S"; // Capital S
  char receive;

The lines of code are placed in a separate void, and not setup or loop.
When i change the two variables from char to String i get a error(complete error at bottom) when compiling to the arduino or verifying the code.
  String handshakecode = "S"; // Capital S
  String receive;

When i snippes out partial code for just that particular void, it compiles fine, so it must be in combination with the rest of the code, which i have left out from this post at the moment.
Is this a known error or am I doing something wrong?

In function 'global constructors keyed to 65535_0_WFS_v0.3.ino.cpp.o':
lto1.exe: internal compiler error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See http://gcc.gnu.org/bugs.html for instructions.
lto-wrapper.exe: fatal error: C:\Program
  Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc
  returned 1 exit status
compilation terminated.
c:/program
  files/windowsapps/arduinollc.arduinoide_1.8.15.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe:
  error: lto-wrapper failed
collect2.exe: error: ld returned 1 exit status
exit status 1 Error compiling for board Arduino/Genuino Mega or Mega
  2560.

that does not look like a compilation error ... that looks like a compiler program failure .... try reinstalling the Arduino IDE

This is a known error with the windows store version of the IDE. Delete it and download it from Arduino.

@Majenko it happens with the regular version of the Arduino IDE also.

Interesting. It used to just be the app version. I guess they messed up the real version. Another reason to switch to UECIDE I guess :)

I encountered the bug using the standard Arduino IDE back when the new toolchain was still in beta testing, as well as with the production release. I'm normally all about using the latest versions of everything but I'm stuck with Arduino AVR Boards 1.6.21 until this gets fixed.

I just did a review of all occurrences of the bug and 22 were using the Windows App version of the Arduino IDE, 17 were using the regular Arduino IDE, 3 did not show which version they were using. In all cases, the OS was Windows. So this is good evidence that it's completely unrelated to which IDE version is used.

This bug is specific to the 5.4.0-atmel3.6.1-arduino2 version of avr-gcc used by Arduino AVR Boards 1.6.22 and newer. It has been reported here:
https://github.com/arduino/Arduino/issues/7949
Here's the workaround:

Tools > Board > Boards Manager
Wait for downloads to finish.
When you move the mouse pointer over "Arduino AVR Boards", you will see a "Select version" dropdown menu appear. Select "1.6.21".
Click "Install".
Wait for installation to finish.
Click "Close".

Due to a bug, this workaround doesn't work with Arduino IDE 1.8.6, but it will work with any other version of the Arduino IDE.
If you have File > Preferences > Check for updates on startup checked, the Arduino IDE may occasionally notify you that a new version of Arduino AVR Boards is available, you'll need to refrain from updating back to the new Arduino AVR Boards version, otherwise you'll be back to seeing the segmentation fault error again.


text:
Creation of multiple power cells to be controlled by Arduino
I'm fairly new to the Arduino world, but have a history of good working knowledge of computers and software (I'm a software engineer), but I've only had the opportunity so far to create a few simple successful play-around projects.
I've decided to embark on a fairly ambitious project to build my son a ride on battery powered car for Christmas and trying to put all the pieces together.
An integral part of this plan is to develop what I call a couple of 'Power cells', which is simply a battery enclosure that has:
Updated:

An input from the Arduino to control the motor speed/voltage.
An input from either the Arduino or forward reverse switch to control the direction of polarity (make motor spin forwards or backwards)
Has a output to power the motor: 20V, drawing about 1-1.5 Amps
Has a output to power the 9x 12V LED lights on it, about upto 50W total (the LED lights will be controlled by the Arduino outside of the power bank, seeing there are a few of them).

I've drawn up a schematic that works with the components I've bought to help put the system together and was wondering if I am missing anything, critical or not?
Info about the battery I'm using can be found here: Aldi Xfinity 20V Li-Ion Battery teardown.
More Specifically:

Are there any errors with the cabling, I'm assuming no additional earth is required in a DC Circuit.
What size cables will i need to adequately service my power requirements?
Would I be able to control the reverse polarity switch directly from the Arduino? As I would like to also trigger a beeper when it is switched in reverse mode. Keep in mind the arduino would need to control 2-4 power cells.
I assume the controlling the potentiometer from the arduino I would need to use junction boxes between the arduino and the power cells to distribute the signal across each power cell, would this be the best way to do this?
The Li-Ion Battery also seems to have T output pin, i assume this is temperature monitoring, is there a way to utilize this input into the arduino for safety monitoring?
I was thinking of splitting the lighting power load between 2 power banks, would this be recommended / possible? (left power cell would power left side leds and right power bank would power right cell leds, with the exception of them both powering the center led).
Are there any additional safety precautions I should be following, especially working with a Li-Ion battery, ie. Fuse etc ?

I'm planning to make 2x of these Power cells to put in the car (each powers its own motor) (with the ability to add another 2 down the track).
Would really appreciate your feedback (please let me know if this is not the right place to ask this sort of question).

I don't understand what you are trying to show with the wires. You have = and - lines merging. What is this supposed to mean? And this question will probably get flagged as not being a "Arduino" question since it is about stuff not directly about the Arduino boards or code that is running on them. I think a more electrical engineering forum is where they want questions like this. But while it is here I will try and give you an answer. One thing, there are no protection diode for the mosfet. I think you need to draw the negative paths for the circuit. It really doesn't make sense.

Each controller / regulator board has a + and a - input, the merging is simply the way in which visio represents it, they never merge except on the boards.

You show them merging and then connected to a mosfet. And that is meaningless. If you want to know if anything is wrong you need to clearly show how the circuit is connected. I design electronics for a living. 30+ year. What you have shown is nothing anyone can work with.

Maybe start with the boards. Then draw wires that show the connections to the terminal blocks/connectors on those boards. Use one color for + and one for -. (red and black are my favorites)

I've updated the schematic image, I hope this is more understandable. Red is positive, black is negative (ground) and the blue one is a data wire from the controller. Does this make sense ?

Do you have specific question, so that this would fit into the Q&A style of this site?

The connections for the regulator input (upper right) is reversed, just a drawing error, I'm sure you connect it right. It all looks OK but I would like a link to the PWM board. I don't know what the terminal block on the left is. Currently unused. IN, Out, but for what I don't know.

I've updated the question and schematic with more detail and specific questions. Feel free to post an answer :)

OK. Looks much better now. And I see one problem. It seems that the normal way to do the speed control is with a pot. A variable voltage at the input depending on the rotation. The Arduino low end designs have an analog out capability but it really is not analog. It is a pulse width variable signal that produces an on percentage between 0 volts and the CPU positive supply voltage. The boards do not have a real digital to analog converter. (maybe some higher end boards but not boards based on the Uno CPU.
It may still work but you need to integrate the pulse output and produce a real analog output voltage. A resistor on the output connected to a capacitor to ground will do the integration and filter out the pulses.

See http://www.ontrak.net/pwm.htm for more details.

The problem you might encounter is to much loading on the capacitor by the pot input circuit. Without more details about the module I couldn't say. The signal can be buffered with an amplifier but that adds to the complexity. Still would be doable though.
Or you can add a real digital to analog converter to the Arduino board. That would be my preference rather than having to add a buffer amplifier if a simple RC circuit wasn't good enough.
Do you have a link for that board?
From the picture of the linked speed module. It uses a LM324 opamp to generate the PWM signal. I did a quick look and found a typical circuit.

http://www.pcsilencioso.com/cpemma/graphics/erg_pwm_sch.gif
Typical but not the exact one. It is much as I expected. And if you did the RC only filtering then it may just work. The opamp input would not be too much loading on the capacitor. The concern that I have is that the 5 volt maximum from the Arduino may not be high enough to turn the motor on at its maximum value.

DC Motor Controller: https://www.banggood.com/PWM-DC-Motor-Speed-Switch-Controller-Control-Reversible-Regulator-p-912617.html?rmmds=search&cur_warehouse=CN

Voltage Regulator: https://www.banggood.com/LM2596-DC-DC-Voltage-Regulator-Adjustable-Step-Down-Power-Supply-Module-With-Display-p-1005123.html?rmmds=search&cur_warehouse=CN

I updated the answer.


text:
Connect Arduino Uno to server using oneM2M platform
I have an Arduino Uno that doesn't have any Wi-Fi. After putting the sensor there, I've found out that it is quiet impossible to connect to localhost for oneM2M platform.
Is there any possibility that I can connect to localhost using just the blue cable below which will also being used for uploading the code? Any help will be much appreciated!

there was an attempt to make TCP over Serial. I don't know if it works. https://playground.arduino.cc/Code/SerialIP

You can not do it without a special software running on the computer. I mean special as in someone will need to write it since there likely isn't something available that you can find.
The most practical solution is to either use an ethernet shield on the Uno. Or use a board like the Wemos D1 Mini (an ESP8266 based board) that can do Wifi. It can run under the Arduino platform. And they are dirt cheap.
https://wiki.wemos.cc/products:d1:d1_mini
https://wiki.wemos.cc/doku.php
https://wiki.wemos.cc/products:d1_mini_shields:dht_shield

So what you mean here is it is impossible to connect to server without the wifi thingy (ESP8266) ?

Wifi or ethernet. Ethernet is a wired connection, it would go into a router. I prefer WiFi as it is more convenient. And not all that hard to do. There are a lot of examples that can be the foundation for what you want to access.


text:
How to build a wireless pump controller using arduino and esps?
I want to have automatic control for my pump, wirelessly.
A transmitter unit fitted in the water tank would sense the water level and transmit the data to a receiver unit attached to the pump starter to turn it off/on.
Also an override unit would allow me to turn the pump on/off according to my will and will also display the water level.
How do I write the code for the wireless transmission part ?

this question has been asked almost exactly same way before .... is this a school assignment?

which of the transmitters are you asking about?

Since it was closed I decided to post a new one with more specific on point questions as directed.

I want to know about how to code the wireless transmission-receiving part of the system.
For the sensor an ultrasonic sensor can be used to output the water levels.
so, the code goes like this :
if(waterlevel <= minimum )
turn pump on;
if(waterlevel = maximum)
turn pump off;
I now want to know how to send the instruction from the transmitter module (that will be attached with the tank) to the receiver module (that will be attached to the pump switch) wirelessly over my home network.

First of all I would recommend to play around with Web Server example to understand how the server hosting works. Also, the ip adders is assigned randomly to the ESP so you definitely need to write a rule in your WiFi router in order to assign a static ip to the ESP. But you can try to use mDNS to assign a name to your esp. For example http://pump.local/path. You can find some instructions here. If you are looking for simplicity you can use Blynk. It is a fully automated and free service that allows you to control you ESP from anywhere where there is a internet connection. And it also can display different variables such as the water level in your case.


text:
Triggering a soft reset (Arduino Leonardo)
I want to trigger a soft reset on my Arduino Leonardo, and after some searching settled on using the watchdog timer, as it seemed to be the easiest and cleanest way to do it.
However, I don't think it works as it should. It seems to work fine on the following example:
#include <avr/wdt.h>

int outputPin = LED_BUILTIN;

void setup() {
  MCUSR = 0;
  wdt_disable();
  pinMode(outputPin, OUTPUT);
  digitalWrite(outputPin, HIGH);
  delay(500);
  digitalWrite(outputPin, LOW);
  delay(500);
  digitalWrite(outputPin, HIGH);
  delay(500);
  digitalWrite(outputPin, LOW);
  delay(1000);
}

void loop() {
  wdt_enable(WDTO_15MS);
  while (true) {}
}

The LED blinks continuously,.
But for the following example:
#include <avr/wdt.h>

void setup() {
  MCUSR = 0;
  wdt_disable();
  Serial.begin(9600);
  while (!Serial);
  Serial.println("Hello");
}

void loop() {
  wdt_enable(WDTO_15MS);
  while (true) {}
}

"Hello" only gets printed once (where I would expect it to arrive continuously).
I tried increasing the watchdog timeout to 2 seconds, but that didn't solve the issue.

try for a test a longer time, for example WDTO_2S. some bootloaders don't reset the wdt flag and then the next reset is triggered before the chip enters your setup().

@Juraj changing WDTO_15MS to WDTO_2S in the above example only causes the final state (L on, RX blinking) to set in 2 seconds later, unfortunately it didn't solve the problem.

you test with a sketch without Serial like the sketch in the Question?

Hint: You could define a function to the reset-vector, e.g. void (*RESET)() = NULL; and then call the function when wanted, e.g. RESET();. Please note that all hardware registers are not reset. The sketch setup should not assume a hardware register state.

@Juraj I edited the question. I have since discovered that I was missing pinMode from my original example, and that solved that specific issue. However, for the (now added) Serial example it still doesn't work.

@MikaelPatel do you mean something like this? https://pastebin.com/raw/0UNf3mik This still only prints "Hello" once.

Try the blink led instead. Set registers correctly in the setup.

Oh hold on, I think the problem might just be that after every reset the serial monitor disconnects (even though it doesn't get greyed out), and that's why I can't see the following "Hello"s. I'll investigate a bit further.

Serial (USB) will disconnect and the USB connection to the host is dropped. You will need a much more advanced detect and reconnect on the host :)

Yeah, it looks like that was the only issue. Thanks for the help MikaelPatel and Juraj!

one more thing: the  while (!Serial); stops the sketch if USB connection is not open

So it turns out my code was working correctly, the watchdog performed the reset as it should, the problem was only that I needed to relaunch the serial monitor after each reset.


text:
expected unqualified id before token
here is the code.
PROBLEM:- if I use for the loop the error comes "expected unqualified-id before for .......but if I use the void loop instead of for loop...the code is run without any error. Meanwhile, I needed for loop .
long int Distance = 0;  // Record the number of steps we've taken
//LOW LOGIC MOVEMENT BACKWARD and GEARS MOVE clocwise
// PIN 18 FOR DIRECTIRON
// PIN 19 FOR STEP  INPUT
int y= 10^-6;
long int k;
long int h= 1600;
void setup() {
Serial.begin(9600);
  pinMode(18, OUTPUT);
  pinMode(19, OUTPUT);
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  digitalWrite(18,LOW);
  digitalWrite(19, LOW);
 digitalWrite(14, LOW);
 digitalWrite(15, LOW);
}
for ( k=0; k<=h; k++)
{
  //if we are at the end of our move
  digitalWrite(19, HIGH);
  delayMicroseconds(100);
  digitalWrite(19, LOW);
  delayMicroseconds(100);
  Distance = Distance + 1;   // record this step
  //k=Distance;
//   Check to see
  if (Distance ==h)
 {
   // We are! Reverse direction (invert DIR signal)
   if (digitalRead(18) == LOW)
    {
     digitalWrite(18, HIGH);
   }
   else
   {
     digitalWrite(18, LOW);
   }
//    Reset our distance back to zero since we're
 //   starting a new move
   Distance = 0;
  //   Now pause for half a second
    delay(1000);
  }
  }
}

It looks like you intended the for-loop to run to completion once. If that is correct, just include it and its entire block of code within and at the end of the setup() function. You will still need to provide a loop() function but it can be empty:
void loop(){
   ;
}

If, instead, you wanted the for() loop to be run repeatedly, enclose it in the loop() function:
void loop(){
   for ( k=0; k<=h; k++ )
   {
   ...
   }
}

The setup() function runs once after a power up or reset. The loop function then gets called repeatedly, forever. Put your functional code in whichever one fits your purpose.
The reason for the error message is that, as you've written the for-loop, it is outside of a function, but executable code (as opposed to defining global variables) is only valid within a function.

You need the void loop() function on your sketch. This function gets called directly after the setup. If it's not there, then the program cannot compile. You cannot put any execution code (means code other than declarations and such) outside of a function.
Depending on what exactly you want to achieve, you have 2 options:

If you want the program to only run once and then stop until the next reset, you can put your code inside the setup() function and leave the void loop() function empty ( with this: void loop(){ } ).
If you want the program to repeat itself indefinitely after the for loop, you can put the code inside the void loop() function.

Whatever you choose, you need the void loop() function.
Note: The void loop() function is part of the Arduino world. In general all programs for microcontroller in C/C++ have a function called main(). It is the function, that starts the execution of the program. Without it no program would actually run. The Arduino framework wraps this main() function up and gives you directly one function to execute the initialization code (void setup()) and one function, that runs after that and loops indefinitely (void loop()). This infinite loop is an important thing, because the microcontroller has no OS or such that he can return to. If you don't have an infinite loop there, the execution can go on to the next address in the program, where you don't know what it contains.

Also the line int y= 10^-6; does not, what you might think it does. In C/C++ the ^ is not the power function, but will do a bitwise OR operation. You will have to use a function for this, for example the pow(value1, value2) function. You can use google to find one of the many examples, how to use it.
And in the same line, (I assume as above) you want to tell Arduino to put a value much smaller than 1 (a value between 0 and 1) into an integer variable. It will contain 0. int means integer and cannot hold decimal numbers (number with something after the decimal point). It can hold numbers like -1,0,1,2,3 in the range from -32768 to 32767 (because it is 16 bits wide on the Arduino UNO and Mega). You will have to use the float type for this.

“10^-6” should be written 1e-6 rather than pow(10, -6).


text:
How to package a 16 bit integer to send it with serial.write?
I am trying to display the values i get from reading a potentiometer (0-1023) in the program called 'processing'.
when I just use Serial.write(integer) and display the value on a line graph in 'processing' the line will max out at 256 and loop back around to 0 as i vary the potentiometer.
I understand that this is because the serial.write can only write in bytes(8 bits) so I would need to package the 16 bit integer into 2 bytes.
i was considering using a union but as you can probably guess i am very new to arduino so i haven't been able to make that work.
here is the code i have tried:
union Data{  uint16_t now; } data;

void setup() {   // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(A1, INPUT);

}

void loop() {   // put your main code here, to run repeatedly:
    uint16_t sensorVal = analogRead(A1);
     union Data data;

    data.now = sensorVal;

    Serial.println(data.now);

    //Serial.write(sensorVal);
    delay(10); }

why do you prinln() the union, but write() the int? does Processing expect the number as text or as byte values? perhaps you need Serial.print(sensorVal) to send the value as text. btw: union with only one member is not an union. You can write int as write(&sensorValue, sizeof(int)), but I doubt that Processing will understand that

Send the 16-bit value as two 8-bit values (with a start byte as per JRobert's answer):
Serial.write(0xCC); // Send the start byte
Serial.write((sensorVal >> 8) & 0xFF); // Send the upper byte first
Serial.write((sensorVal & 0xFF); // Send the lower byte

You need to send the uint16_t as the two the individual bytes it is composed of, one at a time, in whatever order your Arduino code and the code on the PC agree on: (MSB first, aka, big-endian; or LSB first, aka little-endian).
Since it would be possible for the two devices to get out of sync, you may also want to package up the two bytes with a third, or "start-byte". Pick some fixed value (such as 0xCC) that has a couple of its MSbits set, then the MSB, then the LSB. Your receiver can know to look for that fixed value, then the MSB (which it knows can't have those high bits set because the analog data is only 10-bits), then the LSB (which could have any value).
The PC should only accept a three-byte packet when it has received one that fits that scheme. Otherwise it waits for another 0xCC (or whatever value you choose), collects two more bytes, and tries again.

This may help
Transmisor
int valor;
byte val;

void setup() {

Serial.begin(9600);
}

void loop() {

valor=analogRead(A0);
val=map(valor,0,1023,0,179);
Serial.println(val);
Serial.write(val);
delay(100);
}

Receptor
byte mensaje;
int valor;
void setup() {

Serial.begin(9600);
}

void loop() {

if (Serial.available()){
  mensaje=Serial.read();
  valor=mensaje;
  Serial.print(valor);
  Serial.println(" ");
}
}

Sometimes mapping values 0 .. 1023  to a range 0 .. 179 is nice. Sometimes it's easier, to map them to 0 .. 255 (By a division/4 or a right shift by 2 bits from 10 bit ADC to an 8 bit value).

I was checking out the documentation for Serial.write()
You can sent out an array of 2 8Bits in the form of Serial.write(buf, len)
Simply create an int buffer, and then use your original integer and do bit shifting. Notice the & 255 used to make sure there are no values beyond 8 bits.
int data = 1000;
short int buf[2];
buf[0] = data & 255;
buf[1] = (data >> 8)  & 255;
Serial.write(buf, 4);

Also, in C, the name of an array is used as the pointer for the first element. So if you look at the documentation for Serial.write(buf,len) again, you will find that you can probably get the pointer for your int value, and write 2 bytes itself!
Serial.write(*data, 2);

or Serial.write(&data, 2)


text:
Sanity check for dual IR LED circuit
If the intent is to drive the two LED's with 200-400mA (using PWM @ 38Hz), is there anything wrong with this solution?

Perhaps this is a better solution, as it ensures the current is exactly the same for the two LED's (so that they are not out of phase with each other):

I would use a single transistor rated at minimum 1A continuous (a MOSFET by choice), and have both LEDs switched in parallel with their own resistor.  By having them in series as in your second schematic you are limiting the input voltage to a minimum of 2×Vf which could be as high as 5.2V, and thus more than your power source can provide.

simulate this circuit – Schematic created using CircuitLab
This gives the same result as your first circuit, but only uses one transistor for the switching. You can add more LED+Resistor pairs in parallel as you like as long as the total current is below that which the chosen MOSFET can handle.
You should rate the MOSFET to handle the maximum continuous current, not the pulse current, in case the output of the Arduino should be set continuously HIGH instead of sending PWM.
You should also note that the pulse current of an LED is usually rated at 1% duty cycle.
Also note that as the voltage of your power source drops, so will the voltage across the resistors, and thus the current flowing through them (and your LEDs) making the LEDs dim.  It may be beneficial to first pass your battery power through a high-efficiency 3.3V switch-mode regulator to keep the voltage stable whilst wasting the minimum amount of power in the regulation.

Thanks @Majenko.  I read about using MOSFET's vs BJT's and came across one statement that asserted that BJT's can switch faster, which I thought would be relevant in my case since I'm pulsing at 38KHz...but perhaps the MOSFET's are plenty fast enough so it's not a concern.  I have already ordered some 30A/60V NPN MOSFET's...are those a good choice in your opinion?  Thanks again.

Yes, BJTs switch faster. But by faster we're talking high MHz and GHz not just a few kHz.  The critical parameter for a MOSFET is the threshold voltage. You need it to be fully turned on at a voltage below he output of your Arduino.  Aim for <3V threshold voltage. Check the graphs in the datasheet.

Also you should realise that the output of the Arduino is MOSFETs anyway, so they must be able to switch fast enough. In fact the entirety of the Arduino internals are MOSFETs. And that can run at up to 20MHz.  38kHz is nothing to a MOSFET...  I regularly work with MCUs at 200MHz. Still 100% MOSFETs internally...  Even your swanky 3.8HGz computer is MOSFETs...  Teeny tiny MOSFETs...

Gate threshold is 1-2V, if I'm reading the datasheet correctly.  (It has 1 in the Min column and 2 in the Max column, but nothing in the Typical column.)  Thanks for the tip about Arduino's internal MOSFET's!  Very cool to know...

There should be a graph of gate voltage vs drain-source current. Shaped like a curve. Find 5V on the gate voltage axis and see what the current flow is. It should be on the almost vertical section of the graph.

However 1 min and 2 max sounds good to me.

I wanted to paste the chart in the comments, but I'm thinking that's not possible.  Link to datasheet below if you'd like to take a look.
I can't interpret that chart and any way I try it seems to indicate that if the transistor is fully saturated (at 4.2-5V) then a large amount of current will be going through my circuit.
I must not be reading it right.
https://www.sparkfun.com/datasheets/Components/General/RFP30N06LE.pdf

At 5V gate voltage the MOSFET has 0.047Ω resistance ("Drain to Source On Resistance" in the table). If you put 15V directly across it (Vdd annotation on the graph) you would see about 80A flow through it (assuming your voltage source could provide it of course).  It's just a representation of the resistance of the MOSFET (R_DSON as it's called) as profiled using their test conditions.


text:
Controlling LED and Button with single pin
I am trying to use an ATTINY85/Ardunio Uno to turn an LED on and listen to a button input. I don't mind if the LED turns on when the button is used.
I am have found this thread from a couple of years ago however it doesn't seem to work at low voltage (3V) due ending up with floating pins due to the forward voltage of the LED. I was wondering if anyone had a soltion or if they could check to see if my solution would be suitable.
Many Thanks

simulate this circuit – Schematic created using CircuitLab

I think this is what you want...

simulate this circuit – Schematic created using CircuitLab
To check for button, set pin to INPUT and enable pullup. If pin is LOW, then the button is pushed.
To light LED, set pin to OUTPUT and LOW.

Ah this is the one I tried to link, OP has been updated. The issue I am having with this one is the drop in voltage of the LED is 1.6V so it's causing it to float and go in-between input states.

@Archie why is it "floating in-between input states"? if you enable the pull-up, either the button is not pressed (and so the pin floats to 3.3V, even if the LED is not conducting anymore, since there is a pull-up) or it is pressed (and so it is capable of pulling low both the pull-up and the LED, and it goes to GND). Please note that the LED is put not in the same position as your circuit, but it is in the upper part, while the button is in the low part

Ahh the internal pull ups were not enabled. Thank you very much.


text:
How to avoid Multiple definition of 'Blynk' error?
By including
 #include <BlynkSimpleEsp8266.h>

Blynk library (https://github.com/blynkkk/blynk-library) from more than 1 module/cpp file, "Multiple definition of `Blynk’" error is thrown at compile time. The header file contains following:
static WiFiClient _blynkWifiClient;
static BlynkArduinoClient _blynkTransport(_blynkWifiClient);
BlynkWifi Blynk(_blynkTransport);

How can I get the Blynk declarations into a second or third module, without multiple definitions error? Editing the header/library file/s is not an option!
By the question in How to create global variables/includes/functions for use in multiple source files it is still not clear what a working solution is...

Possible duplicate of How to create global variables/includes/functions for use in multiple source files

Like that answer already says:>  If you include BlynkSimpleEsp8266.h in one cpp file only, you will get only one instance of Blynk.

Whole magic of "possible duplicate" is the extern keyword in header file and instance must be defined in .cpp file (without extern). The extern means this variable is placed somewhere else.

Please read my question - I need to include the lib in multiple modules/cpp files! And editing header file is out of scope...

You want to include header, that CAN NOT be included in more than one cpp file, in more than one cpp file without any change in that header file. You may think we don't read your question, but it's just because there is no other way than fix to the library using extern.

The Blynk "simple" header files are not ready to be included into multiple cpp files. They are meant to be included only in the main ino file. The reason is that the variable allocations are in headers file, which is bad practice for  C and C++. The h files should contain only declarations. The right way would have
extern BlynkWifi Blynk;

and the lines which are now in the h file should go in a cpp file. Then every cpp file that includes the .h will know about the variables but the variables would be allocated only once.
The fix is to change the library or to copy the BlynkSimpleEsp8266.h include to your project as for example MyBlynk.h and change the Blynk variable in MyBlynk.h to extern and add a MyBlynk.cpp file with variables allocation
#include "MyBlynk.h"

WiFiClient _blynkWifiClient;
BlynkArduinoClient _blynkTransport(_blynkWifiClient);
BlynkWifi Blynk(_blynkTransport);

As good as Blynk is - and it is; I use it for many of my projects - and even though it is actively being maintained and improved, this issue has remained uncorrected. It is one of the few blemishes in an otherwise incredibly useful project.

it is a compromise. that is why it is called "simple". they can't create cpp for this, because the builder would try to compile all the cpp for different networking libraries and board architectures. they could make ifdefs for architectures but not for libraries


text:
Why do I get “ stray '#' in program ” error?
I am making an Arduino program with SIM800L module and would like to check credit status of the SIM card.
When I manually enter the command: AT+CUSD=1,"*123#" into Serial Monitor, it works fine.
But in the Arduino (1.8.7) I am receiving an error
      stray  "#" in program
when compiling this line of sketch:
      SIM800.print("AT+CUSD=1,"*123#"\r");
I am not experienced enough to fix this problem.
Could somebody help me, please?
Thank you.
Marko

I think something else is stray. Why are there three double quotes in "*123#"\r". A backslash is a normal part of a string, why did you put it outside the string?

There are four quotes in the command ("AT+CUSD=1,"*123#"\r"). When I manually enter this command into Serial Monitor, I type  AT+CUSD=1,"*123#" .

Sorry, there are four indeed. A double quote " in a string closes the string. You need the escape backslash and use " in the same way as the escape is used for \r. https://en.cppreference.com/w/cpp/language/escape

I understand that  *123#  is a string for provider to perform this function (return a info of my SIM credit). When I make a phone call from my mobitel, I just enter *123# and receive an answer with this info.

It is interesting that a similar command:    SIM800.print("ATD*123#\r");   works fine ( return OK) and without any compiler comment.

Use the escape backslash to get a double quote in a text. See: https://en.cppreference.com/w/cpp/language/escape
Is the *123$ between double quotes?
Serial.println("Hello");
Serial.println("I said: Hello to you");
Serial.println("I said: \"Hello\" to you");
Serial.println("AT+CUSD=1,\"*123#\"\r");
Serial.println("AT+CUSD=1,\"*123#\"");

I think the carriage return \r at the end is not needed when the println is used. The println adds a linefeed \n by the way.

The last suggested command   SIM800.println("AT+CUSD=1,"*123#"");  is accepted by compiler but returns only "OK" - the same answer as basic command  SIM800.println("AT+CUSD=1"); . It looks like as the parameter "*123#\  is not forwarded to SIM800?

.....or the provider does not recognise this parameter "*123#\  ?

You could try to send the ASCII code of these characters with Serial.write(). In that way you don't have to bother about escaping and the compiler doesn't see the # anymore.

The command "*123#" is translated by the compiler into "*123#" including the two double quotes. I don't know if that is recognized, I see examples that have a comma and a number after it.

Thank you all for the good will and your efforts to help me. Jot, can you please clarify what is meant by "... have a comma and a number after it."

For example AT+CUSD=1,"*123#",15 You should use the sim800 commands. On Github are arduino libraries for the sim800 that you can use (or use as an example).


text:
Make a float using integers
I want to make a floating point number that has only one decimal point.
I have separate integers for both side.
Ex:
int n1 = 8;
int n2 = 2;
I want to make 8.2 as float value using separate integers.
Please give me a solution.

Seems too simple:
float x = n1 + n2 * 0.1;

Is there a trick?
Edit: The method proposed by Michel Keijzers, namely
float x = n1 + n2 / 10.0;

(I removed the redundant casts) can be slightly more accurate, but takes
longer to compute, because division is significantly slower than
multiplication on the Uno. Computing n2/10.0 always yields the
correctly rounded result, namely the float that best approximates the
exact mathematical result. On the other hand, n2*0.1 involves two
rounding operations: one at compile time, in the representation of 0.1
(which is not an exact float), another at run time, which rounds the
result of the multiplication. If n2 is between 0 and 8, you end up
getting the correctly rounded result anyway, just as with n2/10.0.
However, if n2 is 9, then

n2*0.1 yields 0.900000035762786865234375 (error ≈ 3.6e-8)
n2/10.0 yields 0.89999997615814208984375 (error ≈ -2.4e-8)

The former carries a rounding error 1.5 larger than the latter.

float x = (float) n1 + (float) (n2 / 10.0);

This works only if the value of n2 has 1 digit. Otherwise the following make it smaller until n2 gets below 1.0:
float x = (float) n1;

float f2 = (float) n2;
while (f2 >= 1.0)
{
   f2 /= 10.0;
}
x = n1 + f2;


text:
Getting incorrect output from ADC over SPI in Arduino Uno
I am trying to read data from an ADC ADCS7476 (datasheet) using SPI on Arduino Uno. I am using the following code to read the data from the ADC and printing it on serial monitor. However, the code is always printing 0. I never used SPI before and I am not able to debug the issue, does anyone know where I am going wrong.
I am using the following connections:

ADC's SCLK to Pin 13 on Ardunio
ADC's SDATA to Pin 12 on Arduino
ADC's CS to Pin 10 on Arduino

Code:
#include <SPI.h>
#define cs 10

SPISettings settingsA(250000, MSBFIRST, SPI_MODE0);
byte highbyte,lowbyte;
unsigned int data;

void setup() {
  Serial.begin(9600);
  pinMode(cs, OUTPUT);
  digitalWrite(cs, HIGH);
  delay(1000);
  SPI.begin();
}

void loop() {
  SPI.beginTransaction(settingsA);
  digitalWrite(cs, LOW);
  delayMicroseconds(1);
  highbyte = SPI.transfer(0xFF);
  lowbyte = SPI.transfer(0xFF);
  digitalWrite(cs, HIGH);
  delayMicroseconds(1);
  SPI.endTransaction();
  data= ((unsigned int)highbyte << 8 ) + lowbyte;
  Serial.println(data);
  delay(100);
}

apart from the #include and #define having a space (but since the compiler does not complain I think it is just a wrong copy-paste), I can't see anything obviously wrong. So, just for the most basic questions, 1) is the circuit powered? 2) does the ADC have its own power supply or you are powering it from the arduino 5V? 3) if the former, did you connect th two grounds? 4) is the adc powered at 5V? 5) Can you attach an oscilloscope to the data and clock lines to see what is on the bus?

see the BarometricPressureSensor example of the SPI library

You can't delay this little  delayMicroseconds(1);  Minimum workable value is 3 or 4 per the Arduino Reference section.

You also don't need this line at all  SPISettings settingsA(250000, MSBFIRST, SPI_MODE0);  The default settings use 4 MHz, clock, MSBFIRST, SPI Mode 0. The part works with up to 20 MHz clock, so 4 would be fine.  At 16 MHz, 1 uS is 16 clocks, so digitalWrite or two to another pin after taking CS low would give a short delay for the conversion to get started.

@frarugi87 The circuit is powered from the arduino 5v and the two grounds are connected. I will attach the oscilloscope screenshots by tonight or tomorrow.

@CrossRoads Should I have to increase the delay?

delayMicroseconds(1) I think results in 0 delay.  Change to 3 or 4, that will be the lowest usable value.

I am leaving this answer in case anyone stumbles across this question in the future
In a super frustrating, anti-climactic end, it turns out that the ADC chip itself was not working properly. I tested the (faulty) chip using the code above and observed the output of data pin on the oscilloscope and the output was the same square wave irrespective of the input. I managed to find a new ADC and I tested it and it was working correctly. But this raises a new issue for me, this is the third ADC chip I tested that was working correctly, the first two were faulty. It is very unlikely that it is a manufacturing issue and I used the same connections and the same code to test all three of them. Maybe it has to something to do with soldering, because AFAIK that's the only thing that's different.  If anyone knows anything else that might have gone wrong, I'm all ears.


text:
How to retain the on state of the LED and buzzer if the sensor is triggered?
I'm working on a project which is likely an earthquake alarm. The sketch that I got from the internet does not retain the "on" state of the indicators(LED and buzzer)when it is triggered. I want to modify the sketch that it makes the LED and buzzer retains their "on" state when the sensor(accelerometer) is triggered. Could someone help me ?
Here is the code:
#include <Wire.h>
#include <MPU6050.h>

#define minval -5
#define maxval 3

MPU6050 mpu;

void setup()
{
  Serial.begin(115200);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);

  delay (2000);

  // Initialize MPU6050
  Serial.println("Initialize MPU6050");

  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  mpu.setThreshold(3);
  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.println();
  Serial.print(" * Sleep Mode:        ");
  Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
  Serial.print(" * Clock Source:      ");
  switch(mpu.getClockSource())
  {
    case MPU6050_CLOCK_KEEP_RESET:
      Serial.println("Stops the clock and keeps the timing generator in reset");
      break;
    case MPU6050_CLOCK_EXTERNAL_19MHZ:
      Serial.println("PLL with external 19.2MHz reference");
      break;
    case MPU6050_CLOCK_EXTERNAL_32KHZ:
      Serial.println("PLL with external 32.768kHz reference");
      break;
    case MPU6050_CLOCK_PLL_ZGYRO:
      Serial.println("PLL with Z axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_YGYRO:
      Serial.println("PLL with Y axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_XGYRO:
      Serial.println("PLL with X axis gyroscope reference");
      break;
    case MPU6050_CLOCK_INTERNAL_8MHZ:
      Serial.println("Internal 8MHz oscillator");
      break;
  }

  Serial.print(" * Gyroscope:         ");
  switch(mpu.getScale())
  {
    case MPU6050_SCALE_2000DPS:
      Serial.println("2000 dps");
      break;
    case MPU6050_SCALE_1000DPS:
      Serial.println("1000 dps");
      break;
    case MPU6050_SCALE_500DPS:
       Serial.println("500 dps");
       break;
    case MPU6050_SCALE_250DPS:
       Serial.println("250 dps");
       break;
  }

  Serial.print(" * Gyroscope offsets: ");
  Serial.print(mpu.getGyroOffsetX());
  Serial.print(" / ");
  Serial.print(mpu.getGyroOffsetY());
  Serial.print(" / ");
  Serial.println(mpu.getGyroOffsetZ());
  Serial.println();
}

void loop()
{
  Vector rawGyro = mpu.readRawGyro();
  Vector normGyro = mpu.readNormalizeGyro();
  Serial.print(" Xraw = ");
  Serial.print(rawGyro.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(rawGyro.YAxis);
  Serial.print(" Zraw = ");
  Serial.println(rawGyro.ZAxis);

  if (normGyro.XAxis > maxval ||
      normGyro.XAxis < minval &&
      normGyro.YAxis > maxval ||
      normGyro.YAxis  < minval &&
      normGyro.ZAxis > maxval ||
      normGyro.ZAxis  < minval)
  {
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    delay (1000);
  }
  else
  {
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
  }
  Serial.print(" Xnorm = ");
  Serial.print(normGyro.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(normGyro.YAxis);
  Serial.print(" Znorm = ");
  Serial.println(normGyro.ZAxis);
  delay(10);
}

i've seen your code before ..... you had someone delete all the LCD code from a sketch that you copied from the web ..... that resulted in a bunch of useless and redundant code being left behind .... one of the useless commands is obvious even for a beginner, i think.... it appears that you have not even bothered to read through the code because you have not deleted the redundant code or at least questioned why it is there ..... how do you expect to learn any programming if you always ask someone else to do it for you

Sorry dude, but I'm just afraid that I will mess up the code. I've been thinking that if i could remove the local variables inside the " void checkseetings; ", coz i think they are related to the LCD code. Could you help me ?

Define a (boolean: bool) variable, set it to false initially.
When the sensor is activated, set the variable to true.
Define something that should be able to disactivate the buzzer/LEDs. And if that happens, set the variable to FALSE. Maybe this is a reset button ?
Than based on this variable set the buzzer and LEDs on or off.

So you get something like a global variable
bool alarmTriggered;

In setup:
alarmTriggered = false;

In loop:
if (AreSensorsTriggered(...)) // Create your own function
{
   alarmTriggered = true;
}
else if (IsResetButtonPressed(...)) // Create your own function
{
   alarmTriggered = false;
}

SetBuzzer(alarmTriggered); // Create a function that enables/disables buzzer
SetLEDs(alarmTriggered); // Create a function that enabled/disables LEDs

Sorry dude, I'm newbie when it comes to programming, could you modify it for me?

How can I say this, but I can't apply it in the sketch, do i just copy/paste in the sketch ? sorry for the trouble dude .

First you need to think how to switch off the LEDs/buzzer.

The leds/buzzer will only turn off when i reset the arduino

That's why you need to think of a trigger also to switch it off (to set the boolean back to false). I cannot invent it, maybe after some time, or a 'reset alarm' button?

I'm okay with the 'reset alarm button'

Ok, than when that button is pressed, set the boolean to False.


text:
How to manage variable I2C read lengths requiring address incrementation (Wire/I2C/EEPROM IC emulation)
The question is about how to have information/control of a variable length read for an Arduino acting as a slave device.
The concrete context is that I want to emulate an EEPROM IC.
A byte write to the EEPROM's address sets the internal EEPROM address to start reading from.
The subsequent read from the EEPROM's address, will start returning bytes from that internal address which is incremented for each byte read.
"Wire.onRequest(requestEvent);" allows us to set up a handler, but it seems to be called only once on the start of the read.
In the handler it is possible to provide a reply of multiple bytes.
However I did not find the documentation allowing to know how many bytes were effectively sent to the master.
I got the initial code from the arduino forum .  I've adapted it to this:
#include <Wire.h>
//#define DEBUG
byte XEEPROM[256] = {
  0x5D, 0x26, 0x31, 0x91, 0x3e, 0x12, 0x8e, 0x70, 0xa5, 0x57, 0x3d, 0xed, 0x91, 0x99, 0xb4, 0x11,
  0x38, 0xde, 0x1b, 0xd6, 0x4c, 0xd9, 0xf5, 0x13, 0x23, 0x94, 0xb8, 0x3d, 0x9c, 0xb0, 0xc4, 0x54,
  0xf0, 0x69, 0xca, 0xb3, 0x28, 0x84, 0xa5, 0xc1, 0x80, 0x53, 0x69, 0x0c, 0x38, 0x4f, 0x0c, 0x74,
  0xa1, 0x5b, 0x8c, 0x71, 0x34, 0x30, 0x38, 0x30, 0x30, 0x38, 0x31, 0x35, 0x33, 0x31, 0x30, 0x35,
  0x00, 0x12, 0x5a, 0x1e, 0xbd, 0x9e, 0x00, 0x00, 0x02, 0x82, 0x30, 0xaa, 0x10, 0xb7, 0x7f, 0x8d,
  0x0a, 0xcb, 0x2e, 0xc1, 0xeb, 0x52, 0x20, 0xdc, 0x00, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x97, 0x55, 0x57, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x47, 0x4d, 0x54, 0x00, 0x42, 0x53, 0x54, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x05, 0x00, 0x02, 0x03, 0x05, 0x00, 0x01,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc4, 0xff, 0xff, 0xff,
  0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
  0x68, 0xaa, 0xdd, 0x02, 0x46, 0x45, 0x8f, 0x8f, 0x78, 0x56, 0xbb, 0x69, 0x01, 0x04, 0x46, 0x45,
  0x8f, 0x8f, 0x78, 0x56, 0xbb, 0x69, 0x01, 0x04, 0x46, 0x45, 0x8f, 0x8f, 0x78, 0x56, 0xbb, 0x69,
  0x12, 0x03, 0x46, 0x45, 0x8f, 0x8f, 0x78, 0x56, 0xbb, 0x69, 0x02, 0x02, 0x46, 0x45, 0x8f, 0x8f,
  0x78, 0x56, 0xbb, 0x69, 0x12, 0x02, 0x84, 0x79, 0x80, 0x00, 0x00, 0x00, 0x16, 0x01, 0x00, 0x00
};
static volatile byte rQ;

void setup()
{
 Wire.begin(0x50);
 Wire.onReceive(receiveEvent);
 Wire.onRequest(requestEvent);
 Serial.begin(115200);
 Serial.println("I2C EEPROM EMULATION\n");
}

void loop()
{
}

void requestEvent(){
  //Wire.write(XEEPROM[rQ]); // Just 1
  Wire.write(XEEPROM+rQ,6); /// More than 1
  #ifdef DEBUG
  Serial.print("ADR:");
  Serial.print(rQ,HEX);
  Serial.print("R:");
  Serial.print(XEEPROM[rQ],HEX);  // print the character
  Serial.println();
  #endif
  rQ++; // Increment should depend on number of reads - not sure how to detect that.
}

void receiveEvent(int iData){
    rQ = Wire.read();
    Serial.print("ADR:");
    Serial.print(rQ,HEX);
    bool dwHeader=false;
    // loop through all but the last
    while(1 < Wire.available())
    {
      if(!dwHeader) {
          dwHeader=true;
          Serial.print("DATAW:");
      }
      XEEPROM[rQ]=Wire.read();;
      Serial.print(XEEPROM[rQ],HEX);  // print the character
    }
    Serial.println(); // new line
}

The question is about requestEvent and specifically:
void requestEvent(){
  //Wire.write(XEEPROM[rQ]); // Just 1
  Wire.write(XEEPROM+rQ,6); /// More than 1
  rQ++; // Increment should depend on number of reads - not sure how to
}

I would like to send one at a time, or at least be able to increment rQ according to the number of bytes effectively sent.
If you want to look at a datasheet, you can look at the AT24C02 datasheet.
With regards to the incrementing internal EEPROM address, the EEPROM specification says:

CURRENT ADDRESS READ: The internal data word address counter maintains
  the last address accessed during the last read or write operation,
  incremented by one. This address stays valid between operations as
  long as the chip power is maintained. The address “roll over” during
  read is from the last byte of the last memory page to the first byte
  of the first page. The address “roll over” during write is from the
  last byte of the current page to the first byte of the same page.

This is why the Arduino code emulating the EEPROM should know exactly how many bytes were read.
Thanks.

Please add more information to your question. Is the master device also an arduino board? If not, you are in trouble because the arduino as a slave is not the same as a eeprom. Which arduino board do you use for the slave and the master? The "loop through all but the last" is not normal, it is from an example but that is a bad example. If you use arduino unos, then the i2c buffer size is 32, and you may do a Wire.write with 32 bytes. When using the arduino wire libray, the slave does not know how many bytes will be read or are read by the master device.

The master is also an Arduino for the test, but normally it isn't and that does not matter. * I agree that there are some other bugs, I just wanted a quick start * I am using Arduino Nanos * The Arduino should act as an EEPROM - this avoids getting one for the test, but I am surprised that there is no way to know how many bytes are sent at the end of the I2C Transaction * I looked at Wire.cpp and twi.c just now * The only way to know how many bytes are sent would be to fill the buffer completely, and then fill it constantly (in the loop) using twi_transmit() and count one when it returns 0.

It matters a lot if the master is a arduino or not. The arduino as a slave uses clock pulse stretching and an eeprom does not. It is therefor impossible to act in the same way as an eeprom. Can you find an example of the arduino that simulates an eeprom in exactly the same way? That is not possible. For the software it is possible to change the library or use a library that generates interrupts for every single byte (I forgot the name of that library). The master often writes the register address before reading the data, then it is no problem to fill up the buffer with 32 bytes.

Ok, I understand that it can not be perfect.  An EEPROM does not do clock stretching because it is fast enough at the maximum I2C frequency.  The Arduino emulating the EEPROM could still be functionnaly equivalent which is enough.

Note, that I haven't tested the code below, since I currently don't have enough time for it. But it may help you to get, what you want to do.
The way the I2C interface works is, that after each byte read from the slave, the master will answer with ACK or NACK, depending on if he wants to read more data or not. So the slave doesn't know beforehand, how many bytes the master wants to read.
But you can change the Wire library, to call the onRequest callback for every single byte, instead of every request. The important code lies in the path of your Arduino installation at hardware/arduino/avr/libraries/Wire/src/utility/twi.c at line 575 (I refer to my installation of version 1.8.5; might be slightly different for you):
case TW_ST_SLA_ACK:          // addressed, returned ack
case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
      // enter slave transmitter mode
      twi_state = TWI_STX;
      // ready the tx buffer index for iteration
      twi_txBufferIndex = 0;
      // set tx buffer length to be zero, to verify if user changes it
      twi_txBufferLength = 0;
      // request for txBuffer to be filled and length to be set
      // note: user must call twi_transmit(bytes, length) to do this
      twi_onSlaveTransmit();
      // if they didn't change buffer & length, initialize it
      if(0 == twi_txBufferLength){
        twi_txBufferLength = 1;
        twi_txBuffer[0] = 0x00;
      }
      // transmit first byte from buffer, fall
case TW_ST_DATA_ACK: // byte sent, ack returned
      // copy data to output register
      TWDR = twi_txBuffer[twi_txBufferIndex++];
      // if there is more to send, ack, otherwise nack
      if(twi_txBufferIndex < twi_txBufferLength){
        twi_reply(1);
      }else{
        twi_reply(0);
      }
      break;

When receiving a request with correct address, the first case will be executed (of course after other stuff with receiving address and sending ACK). The twi_onSlaveTransmit() function will execute the onRequest callback. When that is done, the code falls directly into the next case statement, which sends the first byte. When the slave receives an ACK after that byte, it should come back to this case and send another byte.
We can now put the buffer filling code into the second case statement, so that the callback will be executed for every requested byte. In this case we also need to change the if statement after that, so that it only triggers and sends NACK, if the user didn't write a byte in the callback. The original library seems to write at minimum 1 byte (even it nothing is in the buffer; it is set to zero). So we will also do this by setting a flag in the first case statement. The code now looks like this:
case TW_ST_SLA_ACK:          // addressed, returned ack
case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
      // enter slave transmitter mode
      twi_state = TWI_STX;
      twi_slave_transmit_first_byte = 1;
      // transmit first byte from buffer, fall
case TW_ST_DATA_ACK: // byte sent, ack returned
      // ready the tx buffer index for iteration
      twi_txBufferIndex = 0;
      // set tx buffer length to be zero, to verify if user changes it
      twi_txBufferLength = 0;
      // request for txBuffer to be filled and length to be set
      // note: user must call twi_transmit(bytes, length) to do this
      twi_onSlaveTransmit();
      if(twi_slave_transmit_first_byte == 1){
          twi_slave_transmit_first_byte = 0;
          // if they didn't change buffer & length, initialize it
          if(0 == twi_txBufferLength){
            twi_txBufferLength = 1;
            twi_txBuffer[0] = 0x00;
          }
      }
      // copy data to output register
      TWDR = twi_txBuffer[twi_txBufferIndex++];
      // if there is more to send, ack, otherwise nack
      if(twi_txBufferIndex < twi_txBufferLength){
        twi_reply(1);
      }else{
        twi_reply(0);
      }
      break;

And we have to add the flag declaration at the top of the file (where all the other static volatile variables are defined) as static volatile:
static volatile uint8_t twi_slave_transmit_first_byte = 0;

In the onRequest callback you can now write a single byte to the buffer and incrementing your counter.

I think, that should work. If someone knows better, please correct me.

Hi, changing the Wire library is one way to go about it - for portability this would have to be added as a new Wire library, possibly just extending the standard library.  I'll try to check this out.

This is exactly what I stumbled upon when trying to create a I2C slave with a memory-based interface.
You are right, the requestEvent callback is called only once. So you have to prepare it beforehand. What is positive, however, is that the write function will discard all the unused bytes.
So, what can you do? Well, first of all a sum up of the I2C "messages". You, as a master, can

Send a "write" command, with a payload
Send a "read" command, with no payload, and the slave will reply with bytes as long as you continue to send ACKs

In my mind there were two different approaches:

The "write" command should contain the initial register and the number of registers to read; this approach, however, complicates distinguishing between a "read from EEPROM" and "write to EEPROM" commands
The write command should send only the initial register for reading from EEPROM, and the initial register + content to be written for writing to EEPROM.

In my project I chose the second approach. For this reason, when the master writes something on the I2C bus, the first byte of the payload is the register number, and then if there is no other data the slave prepares for sending the contents of the register and the next ones, while if there is any data this is treated as a write command.
The only problem with this approach is that the slave has to prepare a buffer, and the buffer size limits the maximum number of registers returned. I set this limit to 8 in my code; if the master asks for more than only 0s are returned.
Here is the library I wrote for this project.
File I2CInterface.h:
#ifndef I2CINTERFACE_H
#define I2CINTERFACE_H

#include <stdint.h>

class I2CInterface
{
  public:
    static I2CInterface instance;

  public:
    void start();

  private:
    I2CInterface();

    static void requestEvent();
    static void receiveEvent(int howMany);
    void resetSendingBuffer();

  private:
    static const uint8_t Address = 0x46;

    static const uint8_t MaxBufferLength = 8; // (max) 8 byte
    uint8_t sendingBuffer[MaxBufferLength];
};

#endif // I2CINTERFACE_H

File I2CInterface.cpp
#include <Arduino.h>
#include <Wire.h>
#include "I2CInterface.h"

I2CInterface I2CInterface::instance;

I2CInterface::I2CInterface()
{

}

void I2CInterface::start()
{
  Wire.begin(Address);
  Wire.onRequest(requestEvent);
  Wire.onReceive(receiveEvent);
  resetSendingBuffer();
}

void I2CInterface::requestEvent()
{
  Wire.write(instance.sendingBuffer, MaxBufferLength);
  instance.resetSendingBuffer();
}

void I2CInterface::receiveEvent(int howMany)
{
  if (howMany <= 0)
    return;
  else if (howMany == 1)
  { // Reading request
    uint8_t regist = Wire.read();
    for (uint8_t i = 0; i < MaxBufferLength; i++)
      instance.sendingBuffer[i] = Configuration.getRegister(regist++);
  }
  else
  { // Writing request
    uint8_t regist = Wire.read();
    while (Wire.available())
    {
      Configuration.setRegister(regist++, Wire.read());
    }
    instance.resetSendingBuffer();
  }
}

void I2CInterface::resetSendingBuffer()
{
  for (uint8_t i = 0; i < MaxBufferLength; i++)
    sendingBuffer[i] = 0x00;
}

Please note that the Configuration.getRegister and Configuration.setRegister are the functions I used to get and set some registers; you can substitute them with a direct EEPROM access or your own functions.
You just need to add, in your main file,
#include "I2CInterface.h"
...

void setup()
{
  ...
  I2CInterface::instance.start();
  ...
}

Thank you for your reply.  This is more or less what I do with "Wire.write(XEEPROM+rQ,6);", where 6 is currently increased to 16 which is all that I need in my setup. *  However, the address counter does not get correctly updated on reads, so while 16 or more bytes may be prepared for sending to the master, I would have to know how many have been actually sent...  Either during or after the transfer.
Most importantly, you confirm that requestEvent is called only once for the read from the master.

@le_top Well, in my case the new request (which is a write with one single byte) will have a new start address, so you should not increment rQ. The sequence to read, for instance, 20 bytes from byte 5 in your master should be: write address 5; read 6 bytes; write address 11; read 6 bytes; write address 17; read 4 bytes. It is the master who keeps track of the increment, not the slave. As for the only once, I detected it experimenting (I did not go deep in the Wire library to confirm this)

By changing the protocol, the Slave will no longer behave as the EEPROM.   I add an extract of the EEPROM specification to the question.

@le_top sorry, I've always used the EEPROMs this way (by always asking for a particular address every read operation rather than relying on the internal counter), so I totally forgot the usage of that feature. If you want this feature, I think the library should be modified (I think like chrisl suggests), since the number of written bytes information is not available AFAIK

I understand.  For safety it is best to always send the address first.  However, when emulating exactly the behavior, one woul hve to follow the specification.
My main question is related to the right method to find how many bytes were replied or how to reply byte by byte - this is what basically triggered the question.
The EEPROM example is the concrete application.
As the core question seemed to be new, I decided to open this topic.


text:
How to define and use a list/array of chars using `Serial.print`
I wish to define a list of months names and access it when printing a report.
Array was defined as follows:
const char months []=
{'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'};
for (int i=0; i<=11; i++) {

                                 Serial.print(months[i]);
                        }

Tries:
I was looking for help under Arrays in Arduino documentation didn't give, as far as I found, any explanation for such case, but arrays of int
Appreciate any help.

I just want to point out that Arduino uses C++. Straightforward questions like this, about how to create and access arrays can be answered by doing a C++ tutorial. There is nothing particularly special about the fact that the code is running on an Arduino.

@NickGammon - thank you for your answer. I'm aware of that, but still I did not find any explanation for such case.

Very good. I try to define and access this list without any success - I suggest for future questions you are more explicit about the problem. I see that I can actually define the array the way you did it without error, but I can see that you would have problems printing it because you used single quotes rather than double quotes. It helps to explain what "without success" actually means. If I said "I tried to bake a cake, without success" how would you advise me? A different recipe? A different technique? A better oven? Better ingredients?

I'll rewrite it.

@NickGammon - question is now re-written. Hope it is more undrestandable and not "off-topic"

Very good. I see that there are vote(s) to re-open the question. Most of the moderation here is done by community members, so we'll see what happens to it.

You are almost there:

Use a char* instead of char, a char can only contain one character
Use " instead of ' (Thanks Juraj)

Then you get:
const char* months[] =
 {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

Just fixed :-), found this computer has Arduino installed

The timelib uses progmem and a single string for short names and multiplies the index with 3: https://github.com/PaulStoffregen/Time/blob/master/DateStrings.cpp

@Jot that's also possible, than you just need a function to retrieve the three characters; btw, I didn't see any different in using PROGMEM in my code, maybe it helps if it is just one string (would save 48 bytes).

const char* regards[] ={"Thank", "you","very","much!!"};

@Guy.D You're welcome


text:
LED intensity on digital pins
I am using an Arduino UNO.
On any digital/analog pin, if an LED (with resistor) is connected and we use digitalWrite(pin,HIGH) the LED lights up rather dimly.
On the other hand, if we use pinMode(pin,OUTPUT) and then use digitalWrite, the LED lights up to maximum intensity.
I checked that in both cases, the voltage on the pin is 5V. Any explanation for this ? Thanks.

This is not a duplicate question. I am specifically asking the effect of declaring a pin as OUTPUT versus direct use of digitalWrite on the pin.

This is due to a specific feature of the AVR microcontrollers, where the
same register (PORTB, PORTC or PORTD) is used for controlling both
the output value of the pin and its optional internal pullup resistor.
The command digitalWrite(pin,HIGH) sets to 1 the bit of this register
corresponding to the selected pin.

If the pin is set to INPUT (which is the default), the effect of
digitalWrite(pin,HIGH) is to turn on the internal pullup.
If the pin is set to OUTPUT, the same command sets the output to
HIGH.

The internal pullup is about 30 kΩ, which lets flow a very small
current through the LED. You may notice that the voltage at the pin is
5 V if nothing is connected to it, but significantly less when the
LED is connected. Notice also that the preferred way of enabling the
pullup is pinMode(pin,INPUT_PULLUP).