text:
ADXL345 Arduino UNO Activity Inactivity interrupt
I have DATA_READY, Activity and Inactivity interrupts mapped from INT1 to INT0 on the arduino. DATA_READY works fine, the problem is Activity and Inactivity are always set to 0 in the INT_SOURCE register. I have set up the threshold for activity and inactivity and the time of inactivity. I would like the algorithm to run when DATA_READY and Activity interrupts are 1 and do nothing when Inactivity is 1 (activity is 0). When Activity is 0 the accelerometer should go automatically in sleep mode and wakes up if activity is detected.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
#include <avr/io.h>
#include <avr/power.h>

#define F_CPU 16000000UL

int state=0; //0--active detecting; 1--sleeping
int state_count=0; //sleeping trigger between 2 states
double mag[40];
int i=0;
double acc_rate[39];
int hunt_sub=0;
int exit_marker=-10,trough_marker=-30,peak_marker=-10;
volatile int sensor_update=0, active_mode=0;//active_mode=0, inactive; 1--active;      sensor_update=0, no new data; 1--new data comes
byte buff[1] ;

volatile unsigned long time=0, time0=0,time_dis=0,time_array[40]={0};

//----------------------------------------------------------------------------------------------

//Read ADXL345 registers
void readFrom(int device, byte address, int num, byte buff[]) {
Wire.beginTransmission(device); //start transmission to device
Wire.write(address);        //sends address to read from
Wire.endTransmission(); //end transmission

Wire.beginTransmission(device); //start transmission to device (initiate again)
Wire.requestFrom(device, num);    // request 1 byte from device

int i = 0;
while(Wire.available())    //device may send less than requested (abnormal)
{
buff[i] = Wire.read(); // receive a byte
i++;
}
Wire.endTransmission(); //end transmission
}

//Write to ADXL345 registers
void writeTo(int device, byte address, byte val) {
Wire.beginTransmission(device); //start transmission to device
Wire.write(address);        // send register address
Wire.write(val);        // send value to write
Wire.endTransmission(); //end transmission
}

//----------------------------------------------------------------------------------------------

/////////////////////////////////////////////////////////////////////////////////////////////

//ISR function

void interrupt(void){

readFrom(0x53, 0x30, 1, buff);

if(buff & 0b00010000){
  active_mode=1;//active state
}
if(buff & 0b00001000){
  active_mode=0;//inactivity state
}

if(buff & 0b10000000){
sensor_update=1;//DATA_READY each 10ms
}

}

/* Assign a unique ID to this sensor at the same time */
Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12345);

void setup(void)
{
if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
Serial.begin(9600);
//Serial.println("Accelerometer Test"); Serial.println("");

pinMode(4, OUTPUT);// buzzer output pin
pinMode(2, INPUT);

/* Initialise the sensor */
if(!accel.begin())
{
/* There was a problem detecting the ADXL345 ... check your connections */
//Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
while(1);
}

/* Set the range to whatever is appropriate for your project */
accel.setRange(ADXL345_RANGE_8_G);
accel.setDataRate(ADXL345_DATARATE_100_HZ);
// displaySetRange(ADXL345_RANGE_8_G);
// displaySetRange(ADXL345_RANGE_4_G);
// displaySetRange(ADXL345_RANGE_2_G);

/* Display some basic information on this sensor */
//displaySensorDetails();

/* Display additional settings (outside the scope of sensor_t) */
//displayDataRate();
//displayRange();
//Serial.println("");

//Create an interrupt that will trigger when a tap is detected.

writeTo(0x53, 0x2D, 59);//POWER_CTL  auto sleep, link, 1hz rate
writeTo(0x53, 0x2C, 10);//BW_RATE low power mode off rate 100Hz
writeTo(0x53, 0x2E, 0);// disable interrupt

attachInterrupt(0, interrupt, RISING);

writeTo(0x53, 0x2F, 0); //map to to INT1
writeTo(0x53, 0x2E, 152); //enable data_ready, activity, inactivity
writeTo(0x53, 0x25, 18); //THRESH_INACT  ((11/9.8)*1000)/62.5
writeTo(0x53, 0x26, 60); //TIME_INACT    one minute
writeTo(0x53, 0x24, 21); //THRESH_ACT    ((13/9.8)*1000)/62.5
writeTo(0x53, 0x27, 0); //ACT_INACT_CTL   dc coupled, use only magnitude.

}

void loop(void)
{

readFrom(0x53, 0x30, 1, buff);
Serial.print("buff: "); Serial.print(buff); Serial.print("  ");

sensors_event_t event;
do{ //clear DATA_READY
accel.getEvent(&event);
readFrom(0x53, 0x30, 1, buff);
}while(buff & 0b10000000);

if(sensor_update==1 && active_mode==1){
//When sensor_update is set to 1 in the ISR,the algorithm process the data from the accelerometer being updated every 10ms(100Hz)
//rest of algorithm is here
 sensor_update=0;//reset

}

}

Edit:
I have modified the program to check in the loop whether the different flags are set and only the DATA_READY is. Activity and Inactivity are never set.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
#include <avr/io.h>
#include <avr/power.h>

#define F_CPU 16000000UL

int state=0; //0--active detecting; 1--sleeping
int state_count=0; //sleeping trigger between 2 states
double mag[40];
int i=0;
double acc_rate[39];
int hunt_sub=0;
int exit_marker=-10,trough_marker=-30,peak_marker=-10;
volatile int sensor_update=0, active_mode=0;//active_mode=0, inactive; 1--active;     sensor_update=0, no new data; 1--new data comes
byte buff[1] ;

volatile unsigned long time=0, time0=0,time_dis=0,time_array[40]={0};

//----------------------------------------------------------------------------------------------

//Read ADXL345 registers
void readFrom(int device, byte address, int num, byte buff[]) {
Wire.beginTransmission(device); //start transmission to device
Wire.write(address);        //sends address to read from
Wire.endTransmission(); //end transmission

Wire.beginTransmission(device); //start transmission to device (initiate again)
Wire.requestFrom(device, num);    // request 1 byte from device

int i = 0;
while(Wire.available())    //device may send less than requested (abnormal)
{
buff[i] = Wire.read(); // receive a byte
i++;
}
Wire.endTransmission(); //end transmission
}

//Write to ADXL345 registers
void writeTo(int device, byte address, byte val) {
Wire.beginTransmission(device); //start transmission to device
Wire.write(address);        // send register address
Wire.write(val);        // send value to write
Wire.endTransmission(); //end transmission
}

//----------------------------------------------------------------------------------------------

/////////////////////////////////////////////////////////////////////////////////////////////

//ISR function

void interrupt(void){

//
//    if(buff & 0b00010000){
//      active_mode=1;//active state
//    }
//    if(buff & 0b00001000){
//      active_mode=0;//inactivity state
//    }
//
//    if(buff & 0b10000000){
//    sensor_update=1;//DATA_READY each 10ms
//    }

}

/* Assign a unique ID to this sensor at the same time */
Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12345);

void setup(void)
{
if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
Serial.begin(9600);
//Serial.println("Accelerometer Test"); Serial.println("");

pinMode(4, OUTPUT);// buzzer output pin
pinMode(2, INPUT);

/* Initialise the sensor */
if(!accel.begin())
{
/* There was a problem detecting the ADXL345 ... check your connections */
//Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
while(1);
}

/* Set the range to whatever is appropriate for your project */
accel.setRange(ADXL345_RANGE_8_G);
accel.setDataRate(ADXL345_DATARATE_100_HZ);

//Create an interrupt that will trigger when a tap is detected.

  writeTo(0x53, 0x2D, 59);//POWER_CTL  auto sleep, link, 1hz rate
  writeTo(0x53, 0x2C, 10);//BW_RATE low power mode off rate 100Hz
  writeTo(0x53, 0x2E, 0);// disable interrupt

  attachInterrupt(0, interrupt, RISING);

  writeTo(0x53, 0x2F, 0); //map to to INT1
  writeTo(0x53, 0x2E, 152); //enable data_ready, activity, inactivity
  // writeTo(0x53, 0x25, 18); //THRESH_INACT  ((11/9.8)*1000)/62.5
  writeTo(0x53, 0x27, 119); //ACT_INACT_CTL   dc coupled, use only magnitude.
  writeTo(0x53, 0x25, 5); //THRESH_INACT  ((3.0625/9.8)*1000)/62.5
  writeTo(0x53, 0x26, 1); //TIME_INACT    one minute
  writeTo(0x53, 0x24, 21); //THRESH_ACT    ((12.8625/9.8)*1000)/62.5

  }

  void loop(void)
  {

  if(digitalRead(2)) {

  readFrom(0x53, 0x30, 1, buff);

  //Serial.print("### ");

  //Serial.println(interruptSource, BIN);

  if(buff[0] & 0b10000000) {

  Serial.println("### DATA_READY");

  }

  if(buff[0] & 0b00001000) {

  Serial.println("### Inacitivity");

  }

  if(buff[0] & 0b00010000) {

  Serial.println("### activity");

  // we don't need to put the device in sleep because we set the AUTO_SLEEP bit to 1 in R_POWER_CTL

  // set the LOW_POWER bit to 1 in R_BW_RATE: with this we get worst measurements but we save power

}

delay(150);

}

sensors_event_t event;
do{ //clear DATA_READY
accel.getEvent(&event);
readFrom(0x53, 0x30, 1, buff);
}while(buff & 0b10000000);

if(sensor_update==1 && active_mode==1){
//When sensor_update is set to 1 in the ISR,the algorithm process the data from the accelerometer being updated every 10ms(100Hz)
//rest of algorithm is here
 sensor_update=0;//reset

}

}

updated code ..

from the datasheet apparently reading the INT_SOURCE registers clears the Activity and Inactivity flags, in that case it would be normal to read o for them. As an alternative, I mapped the activity interrupt from INT2 of ADXL to INT1 of the arduino. active_mode=1 inside the second interrupt function, the first is for data_ready where sensor_update is set to 1. Even with this sensor_update and active_mode always reads 0. Confusing!


text:
Which sensor to detect light?
I have a kit of 37 sensors as described here:

http://www.instructables.com/id/Arduino-37-in-1-Sensors-Kit-Explained/?ALLSTEPS
https://tkkrlab.nl/wiki/Arduino_37_sensors

I want to create a simple circuit:

if the light is detected - flash LED
if there is no light - do nothing

Among 37 sensors I don't seem to find anything related to light / brightness / lumens...
Can you please advise me which sensor to get?

Shall I get a photocell  (Light Dependent Resistor) as described here: https://learn.adafruit.com/adafruit-arduino-lesson-9-sensing-light/parts ?

You are after the "KY-018 Photo resistor module". It is number #23 "Photoresistor" on the instructables.com webpage.

The module contains a Light Dependant Resistor (LDR).
More information on the module can be found at https://tkkrlab.nl/wiki/Arduino_KY-018_Photo_resistor_module.

Number 23 in the list says photoresistor, corresponding to module KY-018 in your kit, which is what you called photocell (a photocell is another type of sensor to my knowledge).
As the name states, a photoresistor is a device changing it's resistance depending on the amount of light it detects/receive.
A photoresistor usually looks like:

In order to get a meaningful reading from an LDR you need to convert the resistance into a voltage which the Arduino's ADC can read. The simplest method is to use a voltage divider: the junction between the LDR (photoresistor) and R1 is the node to connect your analog pin to get your readings, which will be a voltage that is a proportion of the supply voltage (5V) defined by the ratio of the two resistances.
The KY-018 module mentioned above already provides all the necessary and provides you 3 pins: 5V, ANALOG and GND.

simulate this circuit – Schematic created using CircuitLab

Your last paragraph is complete nonsense.

Why do you say so @Majenko? If he connects the LDR directly to 5V and GND and he moves the rig under a 50W lamp he will create a short, with the LDR resistance quickly becoming negligible under strong light.

If he connects the LDR directly to 5V and GND how on earth is he going to get any readings at all from it?

@Majenko where on earth did I mention getting a reading? And anyway, does my last paragraph make sense now? Also, will he be able to get a reading out of its rig by using a voltage divider? Not to mention how many times I've seen beginners getting surprised they were constantly getting a 1023 or 0 out of their analog readings just because they had connected their pin to the 5V or GND lines. Anyway, I'm going to update that paragraph, but relax!

No, that is not much better at all. It has absolutely nothing whatsoever to do with sinking or sourcing too much current and everything to do with the fact that the Arduino ADC reads a voltage and a voltage divider is the easiest way to get a variable voltage from a variable resistance.

I edited my answer once again to remove the absolutely nothing whatsoever infringing part you seem to care so much, but I believe it is still a valid general advice. Nonetheless you have no reason to be that aggressive to me, I am trying to help people here and my advice was not like stick your fatty fingers in the mains socket, so cool down and be more kind to your fellow contributors! I appreciate the comments and corrections, that doesn't justify an aggressive wording though.

Let us continue this discussion in chat.

Use a photoresistor aka photocell. They are variable resistors that change there values depending on the intensity of the light source.
It is sensor KY-018 : KY-018 Photo resistor module.
Here is a helpful code:
const int sensor = A0; //declare photocell pin
const int led = 13;

void setup()
{
  pinMode(sensor, INPUT);
  pinMode(led, OUTPUT);
}

void loop()
{
  int val = analogRead(sensor);
  if(val > 512)
  {
    digitalWrite(led, HIGH);
    delay(500);
    digitalWrite(led, LOW);
    delay(500);
  }
}

No,  I would suggest you not bother with photocell, phototransisters nor light-dependent resistors.
Better answer is the 1750 light-detection and measurement module.

It connects by I2C and reads out a numeric value corresponding to the amount of light (Lux) it senses.
Very easy to set up.
I use one to measure the light of the sky so I can compare it to the output of my solar cells.
Here is a cool light meter project (complete with hookup instructions and code) that uses one to sense light and displays the results on a 7-segment display:
BUILDING A SIMPLE DIGITAL LIGHT METER USING ARDUINO AND BH1750FVI SENSOR

The OP already owns a light-detecting sensor. Unless you are selling those, it makes very little sense to advice the OP to buy yet another module.

source: Stack Exchange

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

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

sort: votes


text:
Error: Expected primary-expression before void
We have been working on this "disaster bot" code for days and hours. AFter all of our hard work, Arduino gives us this error code: expected primary-expression before void. Please please please assist we are so desperate to get this to work. Here is our code below. Please.
// HEARTBEAT SENSOR (displays heart rate on LCD screen)
int sensorPin = A0; // This is the analog sensor pin the backwards S pin is connected to
                           // you can use any of the analog pins, but would need to change this to match
double alpha = 0.75; // This code uses a rather cool way of averaging the values, using 75% of the
                               // average of the previous values and 25% of the current value.
int period = 20; // This is how long the code delays in milliseconds between readings (20 mSec)
int in = 8;
int Reset=6;
int start=7;
int count=0,i=0,k=0,rate=0;

// LCD SCREEN
#include<LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// BIG SOUND SENSOR
int soundDetectedPin = 10;
int soundDetectedVal = HIGH;
boolean bAlarm = false;

unsigned long lastSoundDetectTime;

int soundAlarmTime = 500;

// PUSH BUTTON AND BUZZER
int buzzer = 3;
int ledPin = 13;
int inPin = 7;
int val = 0;

#define sing

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978

#define melodyPin 3
//Hotline Bling Melody
int hotlineb_melody[] = {
  0, NOTE_D5, NOTE_D5, NOTE_D5,
  NOTE_F5, NOTE_E5, NOTE_D5, NOTE_C5,
  NOTE_E5, NOTE_C5, 0,  NOTE_F5,
  NOTE_E5, NOTE_D5, NOTE_C5, NOTE_E5,

  NOTE_C5, NOTE_A4, NOTE_F5, NOTE_E5,
  NOTE_D5, NOTE_C5, NOTE_E5, NOTE_C5,
  0, NOTE_F5, NOTE_E5, NOTE_D5,
  NOTE_C5, NOTE_E5, NOTE_C5, NOTE_A4,

  NOTE_F5, NOTE_C6, NOTE_C6,
  NOTE_C6, NOTE_A5, NOTE_C6, NOTE_C6,
  NOTE_D6, 0, NOTE_F5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,

  NOTE_A5, 0, NOTE_C6, NOTE_C6,
  NOTE_C6, NOTE_A5, NOTE_C6, NOTE_C6,
  NOTE_D6, 0, NOTE_F5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,

  NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,
  NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,
  NOTE_A5, NOTE_D6, NOTE_A5, NOTE_A5,
  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,

  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
  NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5,
  NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5,
  NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5,

  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
  NOTE_F5, NOTE_C6, NOTE_A5, NOTE_C6,
  NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,

  NOTE_A5, NOTE_D6, NOTE_A5, NOTE_A5,
  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
  NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5,

  NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5,
  NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5,
  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_G5
};

//HotlineBLING tempo
  int hotlineb_tempo[] = {
  12, 12, 12, 12,
  12, 12, 12, 12,
  6, 2, 3, 12,
  12, 12, 12, 3,

  3, 3, 12, 12,
  12, 12, 6, 2,
  3, 12, 12, 12,
  12, 3, 3, 4,

  12, 12, 12,
  12, 12, 12, 12,
  2, 3, 12, 12,
  12, 12, 12, 12,

  2, 3, 12, 12,
  12, 12, 12, 12,
  3, 3, 12, 12,
  12, 12, 12, 12,

  2, 12, 12, 12,
  12, 12, 12, 12,
  12, 1.5, 12, 12,
  12, 12, 12, 12,

  12, 12, 6, 2,
  12, 12, 12, 12,
  12, 12, 12, 12,
  6, 2, 12, 12,

  12, 12, 12, 12,
  12, 12, 6, 2.4,
  12, 12, 12, 12,
  12, 12, 12, 12,

  12, 1.5, 12, 12,
  12, 12, 12, 12,
  12, 12, 6, 2,
  12, 12, 12, 12,

  12, 12, 12, 12,
  6, 2, 12, 12,
  12, 12, 12, 12,
  12, 12, 8, 24, 2
};

void setup() {

{
  //lcd.createChar(1, heart);
  lcd.begin(16,2);

  lcd.print("Heart Beat");
  lcd.write(1);
  lcd.setCursor(0,1);
  lcd.print("Monitering");
  pinMode(in, INPUT);
  pinMode(Reset, INPUT);
  pinMode(start, INPUT);
  digitalWrite(Reset, HIGH);
  digitalWrite(start, HIGH);
  delay(1000);

  lcd.begin(16,2);
  lcd.print("need to talk?");
  delay(1000);

  lcd.begin(16,2);
  lcd.print("not yet satisfied with care?");
  delay(1000);
}
// This code runs on startup, it sets ledPin to output so it can blink the LED that is built into the
// Arduino (but then never does), and sets the serial port up for fast 115,200 baud communication
// of the values (make sure you change your serial monitor to match).

  Serial.begin (115200); // the baud rate of the serial data
  {
    Serial.begin(115200);
    pinMode (soundDetectedPin, INPUT);
  }
  //PUSH BUTTON AND BUZZER
  {
    pinMode(buzzer, OUTPUT);
    pinMode(13, OUTPUT);
    pinMode(inPin, INPUT);
    }
}

void loop() {
  // HEARTBEAT SENSOR
    static double oldValue = 0; // used for averaging.
    static double oldChange = 0; // not currently used
    int rawValue = analogRead (sensorPin); // This reads in the value from the analog pin.
                                                              // this is a 10 bit number, and will be between 0 and 1023
                                                              // If this value doesn't change, you've connected up
                                                              // something wrong

  unsigned long time2,time1;
  unsigned long time;

    double value = alpha * oldValue + (1 - alpha) * rawValue; // Calculate an average using 75% of the
                                                                                // previous value and 25% of the new

    Serial.print (rawValue); // Send out serially the value read in
    Serial.print (",");          // Send a comma
    Serial.println (value);   // Send out the average value and a new line
    oldValue = value;        // Save the average for next iteration
    delay (period);            // Wait 20 mSec

  if((digitalRead(start)))
  {
    k=0;
    lcd.clear();
    lcd.print("Please wait.......");
    while(k<5)
    {
     if(digitalRead(in))
     {
      if(k==0)
      time1=millis();
      k++;
      while(digitalRead(in));
     }
    }
      time2=millis();
      rate=time2-time1;
      rate=rate/5;
      rate=60000/rate;
      lcd.clear();
      lcd.print("Heart Beat Rate:");
      lcd.setCursor(0,1);
      lcd.print(rate);
      lcd.print(" ");
      lcd.write(1);
      k=0;
      rate=0;
    }

  if(!digitalRead(Reset))
  {

      rate=0;
      lcd.clear();
      lcd.print("Heart Beat Rate:");
      lcd.setCursor(0,1);
      lcd.write(1);
      lcd.print(rate);
      k=0;
  }
  // LCD SCREEN (helpful hotlines message)
  {
    lcd.setCursor(0,1);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("1-800-273-8255");
    delay(1000);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("1-877-726-4727");
    delay(1000);
  }
  // BIG SOUND SENSOR
  {
    soundDetectedVal = digitalRead(soundDetectedPin);

    if (soundDetectedVal == LOW)
    {
      lastSoundDetectTime = millis();
      if (!bAlarm){
        Serial.println("you're doing great :)");
        bAlarm = true;
      }
    }
    else
    {
      if( (millis()-lastSoundDetectTime) > soundAlarmTime && bAlarm) {
        Serial.println("keep breathing");
        bAlarm = false;
      }
    }
  }
  // LCD SCREEN (are feeling better/listen to these sick tunes buddy message)
  {
    lcd.setCursor(0,1);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("if still need comfort");
    delay(500);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("hold button");
    delay(1000);
    }
    //PUSH BUTTON AND BUZZER
    {
      val = digitalRead(inPin);
      if (val == HIGH) {
        digitalWrite(buzzer, LOW);
      } else {
        digitalWrite(buzzer, HIGH);
      }
      }
// BUZZER
{{
  sing(1);
  sing(1);
  sing(2);
  }
  int song = 0;
   void sing(int s) {
    song = s;
    if (song == 1) {
      Serial.println("recognize this?");
      int size = sizeof(hotlineb_melody) / sizeof(int);
      for (int thisNote = 0; thisNote < size; thisNote++) {
        int noteDuration = 1000 / hotlineb_tempo[thisNote];

        buzz(melodyPin, hotlineb_melody[thisNote], noteDuration);

        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);

        buzz(melodyPin, 0, noteDuration);
      }
    }
  }
  {
    void buzz(int targetPin, long frequency, long length) {
      digitalWrite(13, HIGH);
      long delayValue = 1000000 / frequency / 2;
      long numCycles = frequency * length / 1000;
      for (long i - 0; i < numCycles; i++) {
        digitalWrite(targetPin, HIGH);
        delayMicroseconds(delayValue);
        digitalWrite(targetPin, LOW);
        delayMicroseconds(delayValue);
      }
      digitalWrite(13, LOW);
          }
        }
      }
    }
  }
}

You could probably use a rest ... My first year university programming I spent the whole day from 6 am to midnight trying to solve this one little impossible task, at the end I just gave up and went to bed. The next morning I woke up at 9:00 and solved it by 9:05

Try properly indenting your code. The error will then become perfectly obvious.

`void setup() {
{?? There are 2 more }than{`.

One of the most effective techniques for dealing with compilation errors is to read the error message, then read the code near the line referred to.  If the message is obscure, google it.

Auto-format is your friend. Use it.

HEARTBEAT SENSOR (displays heart rate on LCD screen), you mean play Hot Line Bling with a piezo buzzer?? :)

@DatHa Yes! We actually spent a whole day coding the hotline bling! These codes work by themselves, just when we compile them into a master code, this error shows up.

@Majenko We auto-formated; how do we proceed after?

@EdgarBonet do you mean auto-format? We still don't understand, more help please? Thank you!

@ИвоНедев Lol! That's really funny, however, we are actually very incompetent so we still have no idea what to do for this :(

Just read the formatted code. The error should be absolutely obvious now.

@EdgarBonet I'm sorry, we have no idea what's going on right now. If you think the error is actually obvious right now, we would appreciate if you would tell us what is going on. Thank you very much.

Here are the problems I found while trying to make your code compile:
Opening and closing braces should match
Trying to autoformat your code gave me the error:

Auto Format Canceled: Too many right curly braces.

I had to remove the last two braces for Auto Format to succeed.
Functions cannot be nested
You should move the declarations of sing() and buzz() out of
loop(). You can call them from loop() though.
Other random errors

#define sing is defining sing as an empty string, and you cannot
give a function an empty name
the variable song should be either global or local to sing(), not
local to loop()
to declare and initialize a variable to zero you should write
int i = 0, not int i - 0
soundAlarmTime should be unsigned
oldChange and time should be removed (they are not used)

Thank you so much for your assistance! This project was made so much easier, and we appreciate your efforts and time! Thanks again :)

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


text:
Code conversion
Following is the zabbix documentation with the query header format.
Document Zabbix
I have difficulty implementing this header in C ++ (Arduino),
I saw an implementation of what I need in this forum here , however it is in Russian and is implemented in C #, I tried to translate it but to no avail.
So I need someone to help me write the function of the header examples in C ++ (Arduino).
Follows full Arduino code after @EdgarBonet change suggestion
#include <ArduinoJson.h>
#include <SPI.h>
#include <Ethernet.h>

// Config IP
IPAddress ip(192, 168, 0, 130);
IPAddress gw(192, 168, 0, 1);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
float contador = 0;

EthernetClient client;

//Config Server address
const char* server = "192.168.0.135";
int porta = 10051;

void setup() {
    Serial.begin(9600);
    Ethernet.begin(mac, ip);
}

void loop() {
    // Begin Json
    const size_t capacity = JSON_ARRAY_SIZE(1)
                          + JSON_OBJECT_SIZE(2)
                          + JSON_OBJECT_SIZE(3);
    DynamicJsonBuffer jsonBuffer(capacity);

    JsonObject& root = jsonBuffer.createObject();
    root["request"] = "sender data";

    JsonArray& data = root.createNestedArray("data");

    JsonObject& data_0 = data.createNestedObject();
    data_0["host"] = "ethernet";
    data_0["key"] = "variavel1";
    data_0["value"] = contador;

    String json = "";
    root.printTo(json);

    const uint8_t *dataSend = (const uint8_t *) json.c_str();
    uint64_t data_length = json.length();
    uint8_t packet[13 + data_length];  // 13-byte header + payload

    // Write the 5-byte signature.
    memcpy(packet, "ZBXD\1", 5);

    // Add the 8-byte packet length, LSB first.
    for (int i = 0; i < 8; i++) {
        packet[5+i] = data_length >> 8*i;
    }

    // Add the payload.
    memcpy(packet + 13, dataSend, data_length);
    if (client.connect(server, porta)) {
        Serial.println("Enviando ao servidor");
        delay(1000);
        // Send the packet.
        client.write(packet, sizeof packet);
        delay(1000);
        contador ++;
    }
}

Following server response:
2034:20191003:101411.196 Message size 2066888786 from 192.168.0.130 exceeds the maximum size 1073741824 bytes. Message ignored.

The problem is quite explicit in the error message:

expected 808529969 bytes

You told the server that you were going to give it 808529969 bytes, yet
you provided much less. Why did you tell it you were going to send so
much data? Maybe we can get a clue by rewriting this number in
hexadecimal:
808529969 = 0x30313031
Breaking this into individual bytes, LSB first (as this is how the
server expects it), you have
0x31 0x30 0x31 0x30
These are the bytes you sent to the server, and they all happen to be
ASCII codes for digits, which make up the string "1010". I don't know
how you came up with this, as the code you posted is not the one you
tested (the posted code does not even compile!). But it seems at one
point you tried to convert something to ASCII binary, and indeed
String(10, BIN) produces exactly the string above.
The server expects the data length to be provided as binary bytes,
not as an ASCII string. I personally try to avoid the String
class, which can create memory issues. In this situation I would just
work with an array of bytes, typed as uint8_t (the same as the Arduino
byte type, only more standard). In the code below, I assume for
simplicity that you keep a String for building the payload, but then I
switch to a raw byte array:
const uint8_t *data = (const uint8_t *) json.c_str();
uint64_t data_length = json.length();
uint8_t packet[13 + data_length];  // 13-byte header + payload

// Write the 5-byte signature.
memcpy(packet, "ZBXD\1", 5);

// Add the 8-byte packet length, LSB first.
for (int i = 0; i < 8; i++) {
    packet[5+i] = data_length >> 8*i;
}

// Add the payload.
memcpy(packet + 13, data, data_length);

// Send the packet.
client.write(packet, sizeof packet);

Note that when working with binary, rather than text data, you have to
use memcpy() instead of strcpy(), and client.write() instead of
client.print().

Hello Mr @EdgarBonet, first I want to thank you for the help, finally I put your code inside my project, but the server is reporting another error, now says that the message is still too big, according to the documentation, this message may have in 128MB maximum, and according to the error code code Message size 2066888786 from 192.168.0.130 exceeds the maximum size 1073741824 bytes. Message ignored. is exceeding this limit, as I don`t have enough reputation to answer here in the forum I forwarded my entire code to link[/link]. Thank

@VeniciusBack: You probably have enough reputation to edit your question. And you wouldn't want to answer anyway... unless you do have an answer!

@VeniciusBack: Also, when you provide your code and report an error message, make double sure that the error message your report is generated by the exact same version of the code you are showing. Otherwise you are wasting everyone's time. I am pretty sure the error message and the code your are showing do not match.

I edited the post, with the full code of the arduino I am sending and the response of that code provided by the zabbix server.
Thanks!

@VeniciusBack: Do not edit your answer, which was deleted by VE7JRO for a very good reason (it's not really an answer). Edit your question.

Mr @EdgarBonet, I want to thank you for all the help, finally the code worked correctly, I made the change to ArduinoJson 6, thank you for all the patience you had with me, you did a great job, thank you very much! How do I credit you or close this topic? Thank you one more time! Strong hug!

@VeniciusBack: The way to credit is to “accept” an answer.

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


text:
ultrasonic sencor give wrong distances
. I used      the inbuilt basic example of measuring the distance to test my ultrasonic sensor. the object is kept at 10 - 15 cm. form the ultrasonic sensor but still the readings show 135 cm only
#include <Ultrasonic.h>
int trigPin = 5;
int echoPin = 6;
#include <Servo.h>   //servo library
Servo servo;
int servoPin = 7;
long duration, dist, average;
long aver[3];   //array for average

void setup() {
    Serial.begin(9600);
    servo.attach(servoPin);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    servo.write(0);         //close cap on power on
    delay(100);
    servo.detach();
}

void measure() {
 digitalWrite(100,HIGH);
digitalWrite(trigPin, LOW);
delayMicroseconds(100);
digitalWrite(trigPin, HIGH);
delayMicroseconds(150);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
dist = (duration/2.0) / 29.1;    //obtain distance
}
void loop() {
  for (int i=0;i<=2;i++) {   //average distance
    measure();
   aver[i]=dist;
    delay(100);              //delay between measurements
  }
 dist=(aver[0]+aver[1]+aver[2])/3;

if ( dist<15 ) {
//Change distance as per your need
 servo.attach(servoPin);
  delay(1);
 servo.write(0);
 delay(2500);
 servo.write(100);
 delay(500);
 servo.detach();
}
Serial.print(dist);
}

#include <Ultrasonic.h>
int trigPin = 5;
int echoPin = 6;
#include <Servo.h>   //servo library
Servo servo;
int servoPin = 7;
long duration, dist, average;
long aver[3];   //array for average

void setup() {
    Serial.begin(9600);
    servo.attach(servoPin);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    servo.write(0);         //close cap on power on
    delay(100);
    servo.detach();
}

void measure() {
    digitalWrite(100,HIGH);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(100);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(150);
    digitalWrite(trigPin, LOW);
    pinMode(echoPin, INPUT);
    duration = pulseIn(echoPin, HIGH);
    dist = (duration/2.0) / 29.1;    //obtain distance
}

void loop() {
  for (int i=0;i<=2;i++) {   //average distance
    measure();
   aver[i]=dist;
    delay(100);              //delay between measurements
  }
  dist=(aver[0]+aver[1]+aver[2])/3;

  if ( dist<15 ) {
    //Change distance as per your need
    servo.attach(servoPin);
    delay(1);
    servo.write(0);
    delay(2500);
    servo.write(100);
    delay(500);
    servo.detach();
  }
  Serial.print(dist);
}

No, we are not able to, because you didn't give us enough information. You should edit your question to include your complete code (format it correctly please) and your wiring. Also you should explain, how you are testing the project. An ultrasonic sensor needs a rather hard surface in front of it, so that the ultrasonic waves get reflected enough. Soft materials like fabric, or surfaces, that are not parallel to the sensor, will make the measurement more difficult/less accurate.

i have sent my code

To provide additional information, please always edit your question. There is an edit button for this. Your code is not the answer for your question, thus it should not be posted as answer. As you are a new contributor (welcome!), you might find the Tour rather helpful. High quality question have way more probability to get good answers.

I edited your question for you

Re “digitalWrite(100, HIGH);”: There is no pin 100 on the Uno.

Why did you added your code a second time to your question? I don't see a difference. Also you should really write more text and explain something. I asked more question in my first comment and you still didn't answer them

You have a lot of redundant code:

include Ultrasonic.h is unnecessary.
servo.attach and servo.detach without reusing pin is unnecessary
The ultrasonic code is not correct.
It should be:

    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    // measure duration of pulse from ECHO pin
    duration_us = pulseIn(echoPin, HIGH);

    // calculate the distance
    distance_cm = 0.017 * duration_us;

Refer to the Ultrasonic sensor tutorial and Servo motor tutorial


text:
FIXING BUG when Using Wire library to obtain compass heading
I am using the HMC-5983 magnetometer module to obtain the compass heading of a autonomous car I am building using the arduino platform.I'musing the
Z axis and X axis to obtain the heading.
However when the headingFiltered variable is at 359 and the car turns to Zero,the headingFiltered becomes to 0 via all the values between 0 and 360 rather than just becoming 0.This causes my car be constantly steering side to side when heading in this relevant direction.
Also if there is anyway that this function could be improved,I'm open to suggestions.
The function I'm using  is as follows.
void chead() {

  //---- X-Axis
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mX1);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mX0 = Wire.read();
  }
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mX0);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mX1 = Wire.read();
  }

  //---- Y-Axis
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mY1);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mY0 = Wire.read();
  }
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mY0);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mY1 = Wire.read();
  }

  //---- Z-Axis
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mZ1);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mZ0 = Wire.read();
  }
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mZ0);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mZ1 = Wire.read();
  }

  //---- X-Axis
  mX1=mX1<<8;
  mX_out =mX0+mX1; // Raw data
  // From the datasheet: 0.92 mG/digit
  Xm = mX_out*0.00092; // Gauss unit
  //* Earth magnetic field ranges from 0.25 to 0.65 Gauss, so these are the values that we need to get approximately.

  //---- Y-Axis
  mY1=mY1<<8;
  mY_out =mY0+mY1;
  Ym = mY_out*0.00092;

  //---- Z-Axis
  mZ1=mZ1<<8;
  mZ_out =mZ0+mZ1;
  Zm = mZ_out*0.00092;
  // ==============================
  //Calculating Heading
  heading = atan2(Zm, Xm);// arc tangent of z/x

  // Correcting the heading with the declination angle depending on your location
  declination = 0.03717551307 ;
  heading += declination;

  // Correcting when signs are reveresed
  if(heading <0) heading += 2*PI;
  // Correcting due to the addition of the declination angle
  if(heading > 2*PI)heading -= 2*PI;
  headingDegrees = heading * 180/PI; // The heading in Degrees unit
  // Smoothing the output angle / Low pass filter
  headingFiltered = headingFiltered*0.85 + headingDegrees*0.15;
  //Sending the heading value through the Serial Port to Processing IDE

  //this was done to fix an error.which was when the compass was made to turn by 180° the reading obtained did not change by 180°.
  if(headingFiltered >= 0 && headingFiltered <= 89){
    c_head=map(headingFiltered,0,90,270,359);
  }
  if(headingFiltered > 89 && headingFiltered <= 204){
    c_head=map(headingFiltered,90,204,0,90);
  }
  if(headingFiltered > 204 && headingFiltered <= 290){
    c_head=map(headingFiltered,205,290,91,180);
  }
  if(headingFiltered > 290){
    c_head=map(headingFiltered,291,359,181,269);
  }

  //Further calibration
  if(c_head>=0 && c_head<8){
    c_head=352+c_head;
  }
  if(c_head>=8){
    c_head=c_head-8;
  }

  // Serial.print("Degrees - ");
  // Serial.println(c_head);

  float teta1 = radians(clatval);
  float teta2 = radians(dlatval);
  float delta1 = radians(dlatval-clatval);
  float delta2 = radians(dlongval-clongval); //==================Heading Formula Calculation================//

  float y = sin(delta2) * cos(teta2);
  float x = cos(teta1)*sin(teta2) - sin(teta1)*cos(teta2)*cos(delta2);
  float brng = atan2(y,x);
  degris = degrees(brng);// radians to degrees
  degris = ( ((int)degris + 360) % 360 );

  dif_h=c_head - degris;
  abs_dif_h=abs(dif_h);
}

The problem comes from the low-pass filter you are using:
// Smoothing the output angle / Low pass filter
headingFiltered = headingFiltered*0.85 + headingDegrees*0.15;

This filter is designed to smooth out rapid variations of the measured
heading. If the heading suddenly jumps from 359° to 0°, the filter will
replace that jump by a continuous change that goes through the
intermediate values.
I can think of three different options for solving this problem.
Option 1: filter the Cartesian coordinates
Unlike the heading, the in-plane components of the magnetic field vary
smoothly as the vehicle rotates. You can filter these components before
computing the heading as follows:
const float filter_constant = 0.15;

float filtered_angle(float y, float x)
{
    static float x_f, y_f;  // filtered components
    x_f += filter_constant * (x - x_f);
    y_f += filter_constant * (y - y_f);
    return atan2(y, x);
}

Then you would replace
heading = atan2(Zm, Xm);

by
heading = filtered_angle(Zm, Xm);

Option 2: filter the unwrapped heading
Another possible approach is to unwrap the heading before
filtering it. This is similar to phase unwrapping: instead of
requiring the heading to be limited to the interval [−π, π] (or
[0, 360°) if you work with degrees), you let it take arbitrary
values. Each time your vehicle does a full turn, the unwrapped heading
varies by ±360°. Here is a simple unwrapping filter:
// Unwrap an angle in radians.
float unwrap(float angle)
{
    static int revolutions;
    static float previous_angle;
    float delta = angle - previous_angle;
    previous_angle = angle;
    if (delta >= M_PI)
        revolutions--;
    else if (delta < -M_PI)
        revolutions++;
    return 2*M_PI*revolutions + angle;
}

The unwrapped heading is continuous, and can be safely low-pass filtered
without creating the kind of issue you have now. After the low-pass
filter, you can wrap it again with fmod() if you wish.
Option 3: wrap the heading differences within the filter
The previous idea can be applied backwards: instead of unwrapping the
heading, you can wrap the heading differences within the low-pass
filter, in order to keep them within [−π, +π) (i.e.
[−180°, +180°)). Then, if the filtered heading is 359° and you get
a new raw heading of 0°, the difference is −359°, but you wrap
it to +1°. This will cause the filtered output to just slightly increase
to 359.15°, given your chosen filter constant of 0.15.
Here is a low-pass filter based on this idea, that is aware of how
angles are supposed to wrap:
const float filter_constant = 0.15;

// Wrap an angle to [-pi, pi).
float wrap(float angle)
{
    while (angle < -M_PI) angle += 2*M_PI;
    while (angle >= M_PI) angle -= 2*M_PI;
    return angle;
}

// Low-pass filter an angle.
float filter_angle(float angle)
{
    static float filtered_angle;
    filtered_angle += filter_constant * wrap(angle - filtered_angle);
    filtered_angle = wrap(filtered_angle);
    return filtered_angle;
}

I think I like this option better that the other two because it does its
arithmetics in a way that is consistent with how angles are supposed to
wrap, and also because it
keeps less state (only one static variable). Also, you have
implemented something very similar to the wrap() function above, in
order to wrap the heading to [0, 2π). You could instead reuse
wrap() as:
// Wrap to [0, 2 pi).
heading = wrap(heading - M_PI) + M_PI;

Edit: There is a recently published Arduino library that implements
this third option. It “provides a class, runningAngle, that computes
an exponentially weighted running average of a series of angles, such as
compass readings. It is aware of how angles wrap modulo 360°.” The
library is called runningAngle and is available through the library
manager of the Arduino IDE.


text:
Matching incoming data with a variable
I have a system where an RFID tag can be checked and Its individual 4byte UID will be printed. My task is to check if subsequent tags have the same UID and if not, print “access denied”. I'm assuming i need to use const char but I'm not sure. I get an error at if (myrfid.serNum[i] == ID) saying comparison between pointers and integers are forbidden.
Any sort of clarity would be appreciated, thanks!
(Code is only a section from the for loop)
void loop()
{
    int i;
    const char ID[] = "111 11 11 11";

    cardpresent = myrfid.isCard();

    if (cardpresent && ! lastcardpresent)
    {
        if (myrfid.readCardSerial())
        {
            for (i = 0; i < 4; i++)
            {
                if (myrfid.serNum[i] == ID)
                {
                    Serial.print("Acess granted ");
                }
                else
                {
                    Serial.print("Acess not granted ");
                }
            }
        }
        Serial.printf("%3d ", myrfid.serNum[i]);
    }
    Serial.print("\n");

    // ...
}

The accepted way to initialize an array in C follows this example:
const char ID [] = {111, 11, 11, 11};

You can read more about it here.
You later use an array name ("ID") with no index ("ID[0]").  The C compiler assumes the programmer who uses an array name with no index is interested in the memory address of the first element of the array.  But you wanted the value in that memory location.  So you should use the array name with the appropriate index.  Guessing, it would appear you intended to use "ID[i]" in the above code fragment.

Ah, i see. Thanks for the explanation, fixed the major issues i had!

Good.  If you understood that - welcome to C Programming with pointers.  Pointers are very useful.  And, honestly, you have a leg up on a lot of C programming beginners if you understand the difference between the address of a variable verses the value of the variable.


text:
How do I use this sound sensor?
I bought one of these:

There are 3 pins on it:

5V
GND
OUT

My guess is that OUT is an analogue signal that I can measure with my Arduino, am I right?
I am using the "Analogue Output" example code but I just get 5V all the time, it does not seems to change with the sound levels.
Am I doing something wrong? What am I adjusting with the blue square on the board? Should I maybe do that?

Output should be +5V with no sound and 0V with sound. The AnalogInOutSerial example should display on your monitor wit values close to mx for no speech and close to ground for speech present.

The wording on this particular eBay item is pretty poor but there are plenty of similar products with better descriptions that are photographically identical... example that make a little bit more sense.
Anyway, I don't think this gives an analog value output, the LM393 is a comparator, so I think the blue dial sets the 'threshold level' and any sounds over that level cause a logic low. i.e. it compares the audio level and the dial and when one exceeds the other it gives a signal.
The features also say "The output effective signal is low level" which is probably Chinglish for the signal is a logic low, i.e. when the sound is heard it goes to 0V rather than 5V which is what I think you were expecting.
In summary: This device is is more like a Clapper, it detects a loud noise and sends a digital low signal.
Try making a loud noise with the same setup you already have, and if not try adjusting the potentiometer by turning it, but not too far! It probably only turns 180-270º.

Sound good, I will try to change potentiometer and check the output. Is it easy to turn it too far?


text:
Error running FirebaseDemo on nodeMCU
So I followed the guide on GitHub to run this demo which compiles and runs. It does warn of some deprecations and such in the firebase libraries :

In member function 'const String& FirebaseArduino::error()'  warning:
  returning reference to temporary [-Wreturn-local-addr]
       return error_.message().c_str();

It is failing to update my firebase database and the firebase error message is not being displayed, seems to be because of the above error. But this does make it complicated to debug...
Can someone please help me get around this?
Appreciate any feedback or pro tips :)
UPDATE
So found an issue on GitHub that solved connecting to the database. Fingerprint update apparently... https://github.com/FirebaseExtended/firebase-arduino/issues/369 but still would like to solve the firebase library error so that everyone can get legible error messages back when using it.

It does warn of some deprecations and such in the firebase libraries :
In member function 'const String& FirebaseArduino::error()' warning: returning reference to temporary [-Wreturn-local-addr] return error_.message().c_str();

i also get some depreciation like
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'bool FirebaseObject::isNullString(const String&) const':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:67:57: warning: 'const char* ArduinoJson::Internals::JsonVariantCasts<TImpl>::asString() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:28): use as<char*>() instead [-Wdeprecated-declarations]
   return variant.is<const char *>() && variant.asString() == NULL;
                                                         ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'ArduinoJson::JsonVariant FirebaseObject::getJsonVariant(const String&) const':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:87:26: warning: 'ArduinoJson::JsonObject& ArduinoJson::Internals::JsonVariantCasts<TImpl>::asObject() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:23): use as<JsonObject>() instead [-Wdeprecated-declarations]
     json = json.asObject().get<JsonVariant>(start);
                          ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/throw_out_of_range.cpp:6:28: warning: unused parameter 'str' [-Wunused-parameter]
 void __attribute__((weak)) __throw_out_of_range(const char* str) {
                            ^
In file included from /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:1:0:
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.h:82:79: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
   const void AddToJson(const FirebaseCloudMessage& message, JsonObject& json) const;
                                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:80:60: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
     const FirebaseCloudMessage& message, JsonObject& json) const {
                                                            ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'int FirebaseRequest::sendRequest(const string&, const string&, char*, const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:76:1: warning: no return statement in function returning non-void [-Wreturn-type]
 }
 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'void FirebaseStream::startStreaming(const string&, const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:89:48: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   analyzeError("STREAM", status, path_with_auth);
                                                ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'String FirebaseArduino::push(const String&, const ArduinoJson::JsonVariant&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:79: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
                                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:7: warning: unused variable 'status' [-Wunused-variable]
   int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
       ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::set(const String&, const ArduinoJson::JsonVariant&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:94:65: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "PUT", path.c_str(), buf);
                                                                 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::getRequest(const String&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:101:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "GET", path.c_str());
                                                            ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual void FirebaseArduino::remove(const String&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:147:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "DELETE", path.c_str());
                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual const String& FirebaseArduino::error()':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:201:33: warning: returning reference to temporary [-Wreturn-local-addr]
   return error_.message().c_str();
                                 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:47:50: warning: 'bool HTTPClient::begin(String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:156) [-Wdeprecated-declarations]
     http_.begin(url.c_str(), kFirebaseFingerprint);
                                                  ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:51:80: warning: 'bool HTTPClient::begin(String, uint16_t, String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:157) [-Wdeprecated-declarations]
     http_.begin(host.c_str(), kFirebasePort, path.c_str(), kFirebaseFingerprint);
                                                                                ^
Compiling library "ESP8266HTTPClient"

to fixed that, go to Preferences in Compiler Warnings choose as Default. it ignored all warning in depreciation, don't forget to update your library to get Firebase Fingerprint has changed on 2 Aug 2018.
Uploaded your sketch again, your should be get data like

the compiler warning settings is only about reporting them to console

@Juraj it's up to the OP, he needs it or not, the most important thing he need the latest Firebase Fingerprint has changed to 2 Aug 2018

It is quite right to tell you that.  The offending code is here:
const String& FirebaseArduino::error() {
  return error_.message().c_str();
}

In that, it calls the message() function on the error_ object to get a std::string object, which it then gets the C string data from with c_str().  It then creates (due to the return type) a temporary String object and copies the C string data into it.
A reference to that temporary String object is then returned and the String is then destroyed immediately.  That's bad. The returned reference now points to nothing in particular.
It wouldn't surprise me if there were other places where that kind of thing happens. Which would explain why things aren't necessarily working right.
You should raise an issue on the Github issues page for that project with the author.

Thanks Majenko, will try and make a strong reference updated with the temporary one and return that rather?

@AMAN77 That will fix that one issue - but as I say in my answer if that one exists chances are there are other hidden, insidious, problems of a similar nature.


text:
Want to play short voice recordings, with fast switching between them
I want to output a chosen sound (e.g a singer singing a D, or E, or F note) which I have recorded.  I can change the filetype to whatever is neccessary, e.g mp3 or whatever.  The recording could be 10ms, or longer if that helps.
I want to be able to switch between notes quickly (ideally 1ms delay), is this possible?  I read about using a WTV020-SD Mini but this has a gap of 20ms between tunes sadly.
At the very least I don't want a 20ms noiseless 'gap' as it switches between one note to the next.  If it plays the old noise that would be ok, but ideally i'd like it to be able to switch between the notes in a millisecond or so.
What is the best way to accomplish this?
Ideally, the solution would be narrow, to fit in a 10mm radius cylinder, up to 100mm in length, although ideally smaller.

You're never going to fit an Arduino into those dimensions. Consider using a bare MCU instead.

The audio files can be on whatever - i'd only have about 10 of them - so not sure if they'd fit on 32KB arduino memory, or could use a microsd or anything else that would help.

The dimensions are not a huge importance if it doesn't fit, it's fine, just would be ideal if it did.  What is an MCU?  Google didn't help.  Apologies for typo - meant radius not diametre.

It's the fourth link. And fifth. And sixth.

OK thanks for that.  Do you have any information on the main topic, i.e not about the size of it?

Store the sounds interleaved in a SPI flash. Change the index of the byte you output. Since all three sounds are loaded at the same time, there will be only a few microseconds delay maximum.

Agree on the SPI flash, but no need for interleaved.  An ATtiny25/45/85 is probably sufficient, and has better PWM than an ATmega anyway.


text:
Simulink with arduino : data acquisition
I'm working on data acquisition from a sensor attached to the Arduino : MPU6050 using a model in Ssimulink. I have installed the hardware support in Simulink but I don't know how to start building the model. The model must read the data from the Arduino by deploying it into the Arduino.
My connection Arduino <=> MPU6050 is :
Arduino    MPU 9150
3.3V       VCC
GND        GND
A5         SCL
A4         SDA
DIGITAL 2  INT
GND        AD0

update : i have use a s-function but I get the following error:
_The call to realtime_make_rtw_hook, during the after_make hook generated the following error: Could not download the model to the target hardware. Verify the connection between the computer and target hardware.
The build process will terminate as a result.
Caused by: Could not download the model to the target hardware. Verify the connection between the computer and target hardware._
But the target is definitely connected, and downloading others module (like led blinking ) with simulink is working fine. I've also tested this on a different PC with Windows 8 (64bits) with the same result. Can anyone give me a hint please?

I just made my GY-521(MPU6050) work with Simulink using s-function.
I wish this would be helpful for you.
I am using an Arduino MEGA 2650 board. The sensor data is read in in real time.
Note that currently only Arduino MEGA 2650, Arduino MEGA 2650 ADK, and Arduino DUE support the real time windows target.
If you are using other types of board, this answer may not applied.
Your hardware connection looks correct. But if you have some troubles you can refer to mine for checking:
5v VCC
GND GND
SCL SCL(check the register map of your board)
SDA SDA(check the register map of your board)

Above four connections are adequate if you just read raw sensor data.
INT is needed if you are going to read fused data. But I did not try that.
Next you may write a small program in Arduino IDE to ensure everything works.
You can refer to the Arduino MPU6050 examples.
The code written here will be used to construct your Simulink s-function later.
Now you can start to build your Simulink block using s-function builder.
If you did not do this before, here is a good tutorial:
https://m.youtube.com/watch?v=_OLctOFjjYQ
In our case, you need to copy Wire.h, twi.h and their .c counterparts in your current working directory where your s-function resides.
And do not forget to rename generated .c file to .cpp, and add external "C" declaration. All of these are illustrated in above video tutorial.
After all of above are done, you turn your simulation mode to external, and run.
You can view your sensor data in scope if everything goes right.

Source code and configuration used in my function:
I include all headers in the Libraries panel of S-Function Builder,
#ifndef MATLAB_MEX_FILE
#define ARDUINO 100
#include <Arduino.h>
#include <Wire.h>
#include <Wire.cpp>
#include <twi.h>
#include <twi.c>
#define MPU 0x68
#endif

Wire.* and twi.* files are copied from Arduino IDE's directory. I put these files along with my S-Function block file.
The address of I2C is 0x68 here.
Next, the code for sensor outputs are placed in Outputs panel. And do not forget to add ports in Data Properties panel.
#ifndef MATLAB_MEX_FILE
Wire.beginTransmission(MPU);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU, 14, true);

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

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

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

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

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

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

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

Finally, initialization and configuration are done in Discrete Update panel.
#ifndef MATLAB_MEX_FILE
if (xD[0] != 1) {
    Wire.begin();

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

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

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

    xD[0] = 1;
}
#endif

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

Thanks a lot :) , i'm actually using an ARDUINO uno but it give an error when i try to deploy the s-function i will try with an ARDUINO MEGA but please can you send me the s-function that you have built to chfakht@gmail.com , it will be very helpful ;)

@user3530803 Does that error look like "you should enable external mode in parameter configuration"? I had this kind of error before and went to MEGA then. You can supply your error message to your question, maybe someone can help you solve that using just UNO. I am on vacation these days, about 5 days later I will share the detail source code in my answer.

Thanks , i have update the post : you can see the error in the now , have a good vacation i will be waiting you

@user3530803 I just updated my answer with source code of s-function.

thanks a lot , i have just done it with the s-function but this time with an ARDUINO MEGA ... please can you tell me for what kind of project you have used the s-function ... here is my email for further contact : chfakht@gmail.com

Not working, whatever I try, it keeps giving this error. "Error(s) encountered while building "I2C_reading_test":
Failed to generate all binary outputs.
Component:Simulink | Category:Modelerror
"
Any idea from what it comes?

@Andrei you may search this error on google. I do not have a simulink to check your code currently. Sorry


text:
Programming ATtiny85 with Arduino-IDE and an 8MHz external oscillator
I have a digispark ATtiny85 development board and I am using the Arduino IDE to program it along with the Arduino UNO as my hardware programmer.
I have successfully burned the fuses for both the internal 1 and 8 MHz RC oscillators using the original Arduino as ISP sketch (you'll understand why I said original in a moment), but as my application needs precise timing, I would like to use an external oscillator, however, every time I tried to burn/program the bootloader/fuses using the Arduino IDE and using the original Arduino as ISP, the avrdude spits the infamous (Yikes).
I searched online and found an updated version of the Arduino as ISP sketch, which is supposed to an updated version, it has only one downside, which is, it can't do anything other than burn/program the bootloader/fuses, meaning that it can't be used to program the ATtiny85 like the original Arduino as ISP could do.
So without hesitating, I tested it to burn/program the bootloader/fuses for the internal 1 and 8 MHz RC oscillators, and it worked perfectly, and as expected, it fails to upload the code.
But the original Arduino as ISP successfully uploaded the code.
When I tried to burn/program the bootloader/fuses for the external 8MHz crystal oscillator using the updated Arduino as ISP, it worked flawlessly... until I noticed that the ordinary Arduino as ISP can not upload the code anymore and I am presented with the infamous (Yikes!) error.
Let me elaborate the difference in the connections between the two sketches.
The updated Arduino as ISP generates a clock signal on pin #9, which connects to the CLKI of the ATtiny85 (AKA Pin #2 "PB3"), while the original Arduino as ISP does not utilize this pin at all.
I found the updated Arduino as ISP on the electronics stack exchange forum, but unfortunately I lost the link to the question which contained why is this updated Arduino as ISP is better.
I can provide both codes though if someone needs them.
I have my crystal connected in both cases, burning/programming the bootloader/fuses and while trying to upload my code.
This is the infamous (Yikes!) error which I was talking about.

This is my current wiring.

Please note that I connect pin #9 to the CLKI of the ATtiny85 (AKA Pin #2 "PB3"), only when I am using the updated Arduino as ISP.
This is the actual wiring.

My two questions are:

How could I burn/program the bootloader/fuses of the ATtiny85 to use an external oscillator of 8MHz or 16 MHz?
How could I upload my application code after burning/programming the bootloader/fuses?

I hope the answers elaborate how the connections would differ, if it would.
Thank a lot in advance.

It may just be because I'm tired, but: You programmed the fuses for use with a crystal.  Did you not attach a crystal?

@timemage, good comment, I forgot to mention that I have my crystal connected in both cases, burning/programming the bootloader/fuses and while trying to upload my code.

Can you show how this is wired?

@timemage, yes, allow me 5 minutes to upload a proper image please.

@timemage, post edited.

I was sort of looking for a picture of the actual wiring.  But, your diagram does raise the question: Do you not have any load capacitors?

@timemage, no problem I can upload a picture of the actual wiring, sorry for the misunderstanding.
But to answer your question, if by load capacitors you mean the capacitors connected between the crystal pins and ground, no I have both of them disconnected.
But if you mean the decoupling capacitors connected between VCC and GND, yes I do have these connected, one 0.1uF to be exact.

Let us continue this discussion in chat.

@jsotola, I am sorry, I only wanted to reach more people in different fields.
That post is now deleted.

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

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

Thank you, I am glad you asked for actual wiring.
Can I "in theory" remove the resistors R1 and R2 so I can test this out?
The end-user project will not be using a digispark, but a bare-metal ATtiny85 on a PCB.

Yes, that should allow you to use an external crystal.  Although it will no longer bit-bang USB, but I suspect you understand that.

Yes, I do understand, thank you very much for your time.
I will try what I have said and get back to you if you please.
Thank you.

It may be a number of hours before I see any update or respond to it.

No problem at all, take your time.

It worked, thanks a lot.
Words can't express it really.

It might have been easier to use a bare ATTiny85 DIL package and a 5V linear voltage regulator, you don't seem to be using much else on the Digispark. The old "Arduino as ISP" sketch supported three diagnostic LEDs which were useful. AVR programmers can be quite inexpensive - e.g. I like the Pololu USB AVR programmer (another)


text:
Passing variables for a PID in an interrupt
I'm needing to pass variables from my timerIsr() function to my loop() function. I have little experience with the Arduino language, I'm mostly familiar with Python so this has been quite difficult for me.
Essentially I'm creating a PID controller to maintain RPM of a fan motor if friction is applied to it. I'm implementing the PID control in the loop() function but I need the rotation variable information from my timerIsr() function. I've tried to return the variable info but it doesn't match up to the actual fan speed. I think it has something to do with difference delay/timer times operating at different instances but I'm unsure.
Here's what I have so far
#include "TimerOne.h"
#include <PID_v1.h>

int counter=0;

const int IN1 = 11;
const int IN2 = 10;
volatile float pot=0;
const int POT = 0;
const int ENA = 6;

double Setpoint, Input, Output;
double Kp=2, Ki=5, Kd=1;

PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

void docount()  // counts from the speed sensor
{
  counter++;  // increase +1 the counter value
}

void timerIsr()
{
  Timer1.detachInterrupt();  //stop the timer
  Serial.print("Motor Speed: ");
  int rotation = (counter / 30);  // divide by number of holes in Disc
  Serial.print(rotation,DEC);
  Serial.println(" Rotation per second");
  counter=0;  //  reset counter to zero
  Timer1.attachInterrupt( timerIsr );  //enable the timer
  Serial.print("pot = ");
  Serial.print(pot);
  Serial.print("\n");

  //return rotation;
}

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

  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);

  Timer1.initialize(1000000); // set timer for 1sec
  attachInterrupt(0, docount, FALLING);  // increase counter when speed sensor pin goes High
  Timer1.attachInterrupt( timerIsr ); // enable the timer

  myPID.SetMode(AUTOMATIC);
}

void loop()
{
  //Input = timerIsr();
  pot=analogRead(POT)/4.01569;
  //Setpoint = sp;

  //Serial.print(Input);

  analogWrite(ENA, pot);
  digitalWrite(10, HIGH);  // set rotation of motor to Clockwise
  digitalWrite(11, LOW);

  delay (250);
}

As you can see I've commented some stuff out that's related to the PID library. Right now I'm just trying to pass the rotation variable to the loop() function.
Is it possible to update global variables at different times so any function can access them?

Short answer: Yes, it is possible to update global variables from interrupt routines, but it comes also with problems.
Long answer:
First you have to understand, how interrupts work. You are using a timer interrupt and an external (pin) interrupt. The compiled program lies in the flash of the chip. At the start there are some special addresses for the different interrupts. If the hardware then registers a condition for an interrupt, it will stop the execution of the main code (the code, that was executed, when the interrupt condition occured), saving the current state and jumping to the corresponding address, where it get's send to the ISR (interrupt service routine), that you defined (in your case the function docount()). After the execution of this program the microcontroller will return to the execution of the main code (by restoring the previously saved state and jumping there). An ISR can only have a return type of void (no return value), because when it returns, there is no special code to receive and use this value. The interrupt may occur at different times every time.
Instead it is common to write global variables in the ISR. For this you have to consider some points:

Global variables, that may be changed during an ISR, has to be declared (additionally to the type) as volatile. This means, that the compiler cannot optimize this variable (for example to a local variable) and has to consider, that it may change anytime, so that he cannot use a cached value.
The usage of the variable in the main code has to be atomic or secured against changing of the variable. If you use a variable in a calculation, it may take many cycles for it (especially if you have a big datatype or some expensive calculations as with float). If the interrupt occures in this time, the value might be changed in the middle of calculation, making the result a bunch of garbage. If the calculation only takes 1 statement cycle, is cannot be interrupted and is called atomic. Since this is rarely possible, you can enclose the corresponding code into securing code. For the Arduino platform, you can use the noInterrupts() and interrupts() functions, to turn off all interrupts, do the calculation and turning the interrupts on again. Be sure do turn the interrupts off only for a short time, so that you don't miss interrupts. Often this is only used to copy the variables value into a local variable (local working copy), which then can safely used for calculations, while the global variable may still change.

Besides that, you also have to think about, what code you write into an ISR. An ISR cannot be interrupted by another interrupt. So functions, that depend on interrupts to work, will not behave like intended. The delay() function for example will simply block all code execution, since the return of the millis() function will not change (it depends on the timer0 interrupt). In your Timer1 ISR, you use Serial.print(). This function can be used, but only until the Serial libraries buffer is filled. The actual communication will take place, after the ISR returns, because it also depends on interrupts. When you try to send more, than fits in the buffer (64 bytes), you will loose data. Currently you should be below that, but you should have this in mind, when coding.

I don't think, that you really need a timer interrupt for calculating and outputting the data every second. Here I would use a non-blocking coding style in the loop() function, like you can see in the BlinkWithoutDelay example, that comes with the Arduino IDE. This is better than using delay(), which is just busy waiting. You save a timestamp with the millis() function and check the time difference. That saves Timer1 for other purposes and also refactors your main code for being extendable and non-blocking, if you want to add more functions.

As I read from this example from the PID library, you need to call myPID.Compute() once in a while to do the PID calculations with the new values. Since these only change every second, you should call this function directly after the calculation of Input.

All in all you need something like this (I didn't include all the code, just the important part, so that you should be able to understand the principle):
unsigned long timestamp;
#define INTERVAL 1000

void loop(){
    if(millis() - timestamp >= INTERVAL){
        timestamp += INTERVAL;
        noInterrupts();
        int counter_copy = counter;
        interrupts();
        // Do the calculations with counter_copy and same the result to `Input`
        // You can put the code from your timerisr here (without the Timer1 code)
        myPID.Compute();
    }
}

Your pot code then should also be enclosed in such an if statement, to prevent, that the PWM get's restarted again and again very fast. If a reaction time of 1s is ok for you, you can put this code in the if statement above. If you want faster reaction times, you can add a second if statement like this to the loop() function (including it's own global timestamp variable and interval value).
The digitalWrite() calls for the direction can be put into the setup, since they don't ever change in your code.

You mean if (millis() - timestamp >= INTERVAL).

Oh, yes, you are right. I corrected that. Thank you.

So what you're saying is I can pretty much condense all of my interrupts down to this loop by just using timestamps? I'm trying to digest all of this information and apply it, sorry.

No, not all. You still have the external interrupt, which you attach with attachInterrupt() and the docount() function. This makes sense, because you don't want to miss any of the pulses. I left that out from my code, since it is exactly the same, as in your code. I ditched only the Timer1 interrupt. I think the accuracy of the 1s interval is not that important, that you really need an own hardware timer for it. If you use non-blocking code the loop() run very fast, so that should be sufficient.


text:
nRF24L01 6TXA_1RXA network + 6TXB_1RXB network with arduino

How to build nRF24L01 network shown above with arduino ?
SPI pins are shared between RXA,RXB and separate pins for both CE, CSN, IRQ.
Which nRF24L01 library supports my requirements ?

You can share the SPI (MISO, MOSI and SCK) pins but need separate pins for IRQ, CE, CSN.

@Kwasmich This is all the information that the OP requires, but please write an answer too.

@MichaelT My comment was meant to be an obvious generality to let zastereo improve on his/her question. I don't think the raw pin connection is what was asked about. So I hope for more details on the actual problem.

@Kwasmich Off-course I need separate pins for IRQ, CE, CSN

Answer below is definitely correct, but just to be sure: are you aware you probably don’t actually NEED two masters? The 6 peers limitation of the nRF24 doesn’t apply unless you are using databurst protocol

You can use the RF24 library that you can install right away from the Arduino IDE. It provides you all you need. Just use two instances of RF24 with different CSN and CE pins assigned to get started.
RF24 radioA(7, 8); // CE, CSN
RF24 radioB(5, 6); // CE, CSN

Use the simple ping sketch as a starting point and add a second radio to it.


text:
Arduino Uno - Stepper motor not working with button
I am completely new to Arduino, and all sorts of hardware and software. I have a stepper motor, which I want to rotate by a number of rotations when I press a button, and then go backwards by a number of rotations when pressed again. I'm not getting any errors with the code, but it does not seem to do what I want. Before adding the button, the stepper motor worked fine, so I don't think it's malfunctioning. When the button is pressed, the LEDs on the H-bridge flicker, but there's no response at all from the motor. I don't know if it's a problem with the code or the set up.
#include <Stepper.h>
const float STEPS_PER_REVOLUTION = 4096;
const float GEAR_REDUCTION = 4;
const float TOTAL_STEPS = STEPS_PER_REVOLUTION * GEAR_REDUCTION
int StepsRequired = 16384;
int switchPin = 7;
boolean current = LOW;
boolean last = LOW;
boolean isOpen = LOW;
Stepper steppermotor (STEPS_PER_REVOLUTION, 8, 10, 9, 11);

void setup() {
  pinMode(switchPin, INPUT);
}

boolean debounce(boolean inLast) {
  boolean inCurrent = digitalRead(switchPin);
  if(inLast != current) {
    delay(5);
    inCurrent = digitalRead(switchPin);
    }
  return inCurrent;
}

void garageAction(float factor){
  StepsRequired = TOTAL_STEPS*factor;
  steppermotor.setSpeed(1000);
  steppermotor.step(StepsRequired);
  if (isOpen == LOW) {
    delay(3000);
  } else if (isOpen == HIGH) {
    delay(5);
  }
}

void loop() {
  current = debounce(last);

  if (current == HIGH && last == LOW && isOpen == LOW) {
    garageAction(2);
    isOpen = !isOpen;
  }

  if(current == HIGH && last == LOW && isOpen == HIGH) {
    garageAction(-2);
    isOpen = !isOpen;
  }
}

I would really appreciate any help with this - as mentioned, I'm completely new to any sort of hardware and software, and I'm also under time pressure to get this done, so I'd really appreciate any help in getting this solved. I could just be missing something really silly, but I'm completely lost.
Thanks in advance

all this program will do is constantly alternate isOpen and call garageAction. This will happen so fast that nothing will actually happen in the real world.Now that I've reformatted your code, perhaps you can reconsider the other two clauses in your if statements relating to current and last. That is untile the debounce function sets current to be low - after that nothing will happen until current is reset to HIGH.