text:
Unable to replicate Arduino code into ATmega8 code
I am trying to replicate an LTC Audio Decoder code from Arduino Uno into AVR ATmega8 which I got from here.
My Arduino Uno code is working great. Here is my Arduino Uno code:
#define one_time_max          588 // these values are setup for NTSC video
#define one_time_min          422 // PAL would be around 1000 for 0 and 500 for 1
#define zero_time_max          1080 // 80bits times 29.97 frames per sec
#define zero_time_min          922 // equals 833 (divide by 8 clock pulses)

#define icpPin 8        // ICP input pin on arduino
#define end_data_position      63
#define end_sync_position      77
#define end_smpte_position     80

volatile unsigned int bit_time;
volatile boolean valid_tc_word;
volatile boolean ones_bit_count;
volatile boolean tc_sync;
volatile boolean write_tc_out;
volatile boolean drop_frame_flag;

volatile byte total_bits;
volatile byte current_bit;
volatile byte sync_count;

volatile byte tc[8];
volatile char timeCode[11];

/* ICR interrupt vector */
ISR(TIMER1_CAPT_vect)
{
 //toggleCaptureEdge
 TCCR1B ^= _BV(ICES1);
  //Serial.println("Inter");
 bit_time = ICR1;

 //resetTimer1
 TCNT1 = 0;

if ((bit_time < one_time_min) || (bit_time > zero_time_max)) // get rid of anything way outside the norm
 {
   //Serial.println(bit_time, DEC);
   total_bits = 0;
 }
 else
 {
   if (ones_bit_count == true) // only count the second ones pluse
     ones_bit_count = false;
   else
   {
     if (bit_time > zero_time_min)
     {
       current_bit = 0;
       sync_count = 0;
     }
     else //if (bit_time < one_time_max)
     {
       ones_bit_count = true;
       current_bit = 1;
       sync_count++;
       if (sync_count == 12) // part of the last two bytes of a timecode word
       {
         sync_count = 0;
         tc_sync = true;
         total_bits = end_sync_position;
       }
     }

     if (total_bits <= end_data_position) // timecode runs least to most so we need
     {                                    // to shift things around
       tc[0] = tc[0] >> 1;

       for(int n=1;n<8;n++)
       {
         if(tc[n] & 1)
           tc[n-1] |= 0x80;

         tc[n] = tc[n] >> 1;
       }

       if(current_bit == 1)
         tc[7] |= 0x80;
     }
     total_bits++;
   }

   if (total_bits == end_smpte_position) // we have the 80th bit
   {
     total_bits = 0;
     if (tc_sync)
     {
       tc_sync = false;
       valid_tc_word = true;
     }
   }

   if (valid_tc_word)
   {
     valid_tc_word = false;

     timeCode[11]= '\0';
     timeCode[10] = (tc[0]&0x0F)+0x30;      // frames
     timeCode[9] = (tc[1]&0x03)+0x30;      // 10's of frames
     timeCode[8] =  '-';
     timeCode[7] = (tc[2]&0x0F)+0x30;      // seconds
     timeCode[6] = (tc[3]&0x07)+0x30;      // 10's of seconds
     timeCode[5] =  '-';
     timeCode[4] = (tc[4]&0x0F)+0x30;      // minutes
     timeCode[3] = (tc[5]&0x07)+0x30;      // 10's of minutes
     timeCode[2] = '-';
     timeCode[1] = (tc[6]&0x0F)+0x30;      // hours
     timeCode[0] = (tc[7]&0x03)+0x30;      // 10's of hours

       drop_frame_flag = bit_is_set(tc[1], 2);

     write_tc_out = true;
   }
 }
}

void setup()
{
 Serial.begin(9600);
 pinMode(8, INPUT);                  // ICP pin (digital pin 8 on arduino) as input

 bit_time = 0;
 valid_tc_word = false;
 ones_bit_count = false;
 tc_sync = false;
 write_tc_out = false;
 drop_frame_flag = false;
 total_bits =  0;
 current_bit =  0;
 sync_count =  0;

 Serial.println("Finished setup ");
 delay (1000);

 TCCR1A = B00000000; // clear all
 TCCR1B = B11000010; // ICNC1 noise reduction + ICES1 start on rising edge + CS11 divide by 8
 TCCR1C = B00000000; // clear all
 TIMSK1 = B00100000; // ICIE1 enable the icp

 TCNT1 = 0; // clear timer1
}

void loop()
{
  if (write_tc_out)
   {
     write_tc_out = false;
     //if (drop_frame_flag)
       //Serial.print("TC-[df] ");
     //else
       //Serial.print("TC-[nd] ");
     Serial.println((char*)timeCode);
   //  Serial.print("  ");
     //Serial.print("\r");
   }
}

Now to replicate this code for AVR ATmega8, I just copy this code in AVR studio and make small changes like initializing UART, initializing Input Capture Mode etc. Here is my AVR ATmega8 code:
#define F_CPU 16000000UL

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <avr/sfr_defs.h>

#define one_time_max          588 // these values are setup for NTSC video
#define one_time_min          422 // PAL would be around 1000 for 0 and 500 for 1
#define zero_time_max          1080 // 80bits times 29.97 frames per sec
#define zero_time_min          922 // equals 833 (divide by 8 clock pulses)

#define icpPin 8        // ICP input pin on arduino
#define end_data_position      63
#define end_sync_position      77
#define end_smpte_position     80

volatile unsigned int bit_time;
volatile char valid_tc_word;
volatile char ones_bit_count;
volatile char tc_sync;
volatile char write_tc_out;
volatile char drop_frame_flag;

volatile unsigned char total_bits;
volatile unsigned char current_bit;
volatile unsigned char sync_count;

volatile unsigned char tc[8];
volatile char timeCode[11];

void USARTInit(uint16_t ubrr_value)
{

    UBRRL = ubrr_value;
    UBRRH = (ubrr_value>>8);
    UCSRC|=(1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
    UCSRB=(1<<RXCIE)|(1<<RXEN)|(1<<TXEN);

}

unsigned char USARTReadChar()
{

    while(!(UCSRA & (1<<RXC)));
    return UDR;
}

void USARTWriteChar(char data)
{

    while(!(UCSRA & (1<<UDRE)));
    UDR=data;
}

void send_string(char s[])
{
    int i =0;

    while (s[i] != 0x00)
    {
        USARTWriteChar(s[i]);
        i++;
    }
}

int main(void)
{

    USARTInit(103);
    DDRB=0;
     bit_time = 0;
     valid_tc_word = 0;
     ones_bit_count = 0;
     tc_sync = 0;
     write_tc_out = 0;
     drop_frame_flag = 0;
     total_bits =  0;
     current_bit =  0;
     sync_count =  0;

    send_string("FINISHED SETUP");
    _delay_ms(1000);

    TCCR1A = 0;
    TCCR1B = (1<<ICNC1)|(1<<ICES1)|(1<<CS11);
    TIMSK = (1<<TICIE1);
    TCNT1 = 0;
    sei();
    while(1)
    {

        if (write_tc_out==1)
        {
            write_tc_out = 0;
            send_string((char*)timeCode);
        }
}

}

ISR(TIMER1_CAPT_vect)
{

 //toggleCaptureEdge
 TCCR1B ^= _BV(ICES1);
  //Serial.println("Inter");
 bit_time = ICR1;

 //resetTimer1
 TCNT1 = 0;

if ((bit_time < one_time_min) || (bit_time > zero_time_max)) // get rid of anything way outside the norm
 {
   //Serial.println(bit_time, DEC);
   total_bits = 0;
 }
 else
 {
   if (ones_bit_count == 1) // only count the second ones pluse
     ones_bit_count = 0;
   else
   {
     if (bit_time > zero_time_min)
     {
       current_bit = 0;
       sync_count = 0;
     }
     else //if (bit_time < one_time_max)
     {
       ones_bit_count = 1;
       current_bit = 1;
       sync_count++;
       if (sync_count == 12) // part of the last two bytes of a timecode word
       {
         sync_count = 0;
         tc_sync = 1;
         total_bits = end_sync_position;
       }
     }

     if (total_bits <= end_data_position) // timecode runs least to most so we need
     {
               // to shift things around
       tc[0] = tc[0] >> 1;

       for(int n=1;n<8;n++)
       {
         if(tc[n] & 1)
           tc[n-1] |= 0x80;

         tc[n] = tc[n] >> 1;
       }

       if(current_bit == 1)
         tc[7] |= 0x80;
     }
     total_bits++;
   }

   if (total_bits == end_smpte_position) // we have the 80th bit
   {
     total_bits = 0;
     if (tc_sync)
     {
       tc_sync = 0;
       valid_tc_word = 1;
     }
   }

  if (valid_tc_word==1)
   {

     valid_tc_word = 0;

     timeCode[11]= '\0';
     timeCode[10] = (tc[0]&0x0F)+0x30;      // frames
     timeCode[9] = (tc[1]&0x03)+0x30;      // 10's of frames
     timeCode[8] =  '-';
     timeCode[7] = (tc[2]&0x0F)+0x30;      // seconds
     timeCode[6] = (tc[3]&0x07)+0x30;      // 10's of seconds
     timeCode[5] =  '-';
     timeCode[4] = (tc[4]&0x0F)+0x30;      // minutes
     timeCode[3] = (tc[5]&0x07)+0x30;      // 10's of minutes
     timeCode[2] = '-';
     timeCode[1] = (tc[6]&0x0F)+0x30;      // hours
     timeCode[0] = (tc[7]&0x03)+0x30;      // 10's of hours

       drop_frame_flag = bit_is_set(tc[1], 2);

     write_tc_out = 1;
   }

 }
}

Now when I run this code, I don't get any time stamps. I have gone through this code many times but I am unable to figure out the mistake in my code. Can any one help me figure out the issue?

I figure out the issue , I just add a small delay in ISR and my code is running fine now. I don't know reason behind it but anyway my code is running now. Here is my new code:-
#define F_CPU 16000000UL

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <avr/sfr_defs.h>

#define one_time_max          588 // these values are setup for NTSC video
#define one_time_min          422 // PAL would be around 1000 for 0 and 500 for 1
#define zero_time_max          1080 // 80bits times 29.97 frames per sec
#define zero_time_min          922 // equals 833 (divide by 8 clock pulses)

#define icpPin 8        // ICP input pin on arduino
#define end_data_position      63
#define end_sync_position      77
#define end_smpte_position     80

volatile unsigned int bit_time;
volatile char valid_tc_word;
volatile char ones_bit_count;
volatile char tc_sync;
volatile char write_tc_out;
volatile char drop_frame_flag;

volatile unsigned char total_bits;
volatile unsigned char current_bit;
volatile unsigned char sync_count;

volatile unsigned char tc[8];
volatile char timeCode[11];

void USARTInit(uint16_t ubrr_value)
{

    UBRRL = ubrr_value;
    UBRRH = (ubrr_value>>8);
    UCSRC|=(1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
    UCSRB=(1<<RXCIE)|(1<<RXEN)|(1<<TXEN);

}

unsigned char USARTReadChar()
{

    while(!(UCSRA & (1<<RXC)));
    return UDR;
}

void USARTWriteChar(char data)
{

    while(!(UCSRA & (1<<UDRE)));
    UDR=data;
}

void send_string(char s[])
{
    int i =0;

    while (s[i] != 0x00)
    {
        USARTWriteChar(s[i]);
        i++;
    }
    USARTWriteChar('\n');
}

int main(void)
{

    USARTInit(103);
    DDRB=0;
    bit_time = 0;
    valid_tc_word = 0;
    ones_bit_count = 0;
    tc_sync = 0;
    write_tc_out = 0;
    drop_frame_flag = 0;
    total_bits =  0;
    current_bit =  0;
    sync_count =  0;

    send_string("FINISHED SETUP");
    _delay_ms(1000);

    TCCR1A = 0;
    TCCR1B = (1<<ICNC1)|(1<<ICES1)|(1<<CS11);
    TIMSK = (1<<TICIE1);
    TCNT1 = 0;
    sei();
    while(1)
    {

        if (write_tc_out==1)
        {
            write_tc_out = 0;
            send_string((char*)timeCode);
        }
    }

}

ISR(TIMER1_CAPT_vect)
{

    //toggleCaptureEdge
    TCCR1B ^= _BV(ICES1);
    //Serial.println("Inter");
    bit_time = ICR1;

    //resetTimer1
    TCNT1 = 0;
_delay_us(13);

    if ((bit_time < one_time_min) || (bit_time > zero_time_max)) // get rid of anything way outside the norm
    {
        //Serial.println(bit_time, DEC);
        total_bits = 0;
    }
    else
    {
        if (ones_bit_count == 1) // only count the second ones pluse
        ones_bit_count = 0;
        else
        {
            if (bit_time > zero_time_min)
            {
                current_bit = 0;
                sync_count = 0;
            }
            else //if (bit_time < one_time_max)
            {
                ones_bit_count = 1;
                current_bit = 1;
                sync_count++;
                if (sync_count == 12) // part of the last two bytes of a timecode word
                {
                    sync_count = 0;
                    tc_sync = 1;
                    total_bits = end_sync_position;
                }
            }

            if (total_bits <= end_data_position) // timecode runs least to most so we need
            {
                // to shift things around
                tc[0] = tc[0] >> 1;

                for(int n=1;n<8;n++)
                {
                    if(tc[n] & 1)
                    tc[n-1] |= 0x80;

                    tc[n] = tc[n] >> 1;
                }

                if(current_bit == 1)
                tc[7] |= 0x80;
            }
            total_bits++;
        }

        if (total_bits == end_smpte_position) // we have the 80th bit
        {
            total_bits = 0;
            if (tc_sync)
            {
                tc_sync = 0;
                valid_tc_word = 1;
            }
        }

        if (valid_tc_word==1)
        {

            valid_tc_word = 0;

            timeCode[11]= '\0';
            timeCode[10] = (tc[0]&0x0F)+0x30;      // frames
            timeCode[9] = (tc[1]&0x03)+0x30;      // 10's of frames
            timeCode[8] =  '-';
            timeCode[7] = (tc[2]&0x0F)+0x30;      // seconds
            timeCode[6] = (tc[3]&0x07)+0x30;      // 10's of seconds
            timeCode[5] =  '-';
            timeCode[4] = (tc[4]&0x0F)+0x30;      // minutes
            timeCode[3] = (tc[5]&0x07)+0x30;      // 10's of minutes
            timeCode[2] = '-';
            timeCode[1] = (tc[6]&0x0F)+0x30;      // hours
            timeCode[0] = (tc[7]&0x03)+0x30;      // 10's of hours

            drop_frame_flag = bit_is_set(tc[1], 2);

            write_tc_out = 1;
        }

    }
}


text:
Linker error when trying to use functions in separate header and source files
It is my first day of working with Arduino (it is a Due). I want to read from TMP102 through I2C. I wrote some code and it works just fine. But now I want to separate the TMP102 code from the main source code. But I get linker error:

sketch_jun15a.ino.cpp.o: In function setup':
  C:\Users\Saeid\Desktop\sketch_jun15a/sketch_jun15a.ino:62: undefined
  reference totmp102_allocate(int)' collect2.exe: error: ld returned 1
  exit status

My code is at the moment consist of 3 files:
tmp102.h
#ifndef TMP102_H
#define TMP102_H

//TP102 sensor struct
typedef struct TMP102 {
  int   address;
  float celsius;
  float fahrenheit;
} tmp102_t;

tmp102_t* tmp102_allocate(int address);

void tmp102_init_struct(tmp102_t * t, int address);

#endif

tmp102.c
#include "tmp102.h"

tmp102_t* tmp102_allocate(int address) {
  tmp102_t* t = (tmp102_t*) malloc(sizeof(tmp102_t));
  if(t) { //allocation success
    tmp102_init_struct(t, address);
    return t;
  } else {
    return 0; //null pointer
  }
}

void tmp102_init_struct(tmp102_t* t, int address) {
  t->address = address;
  t->celsius = 0.0;
  t->fahrenheit = 0.0;
}

and here is the setup function of the sketch:
#include "tmp102.h"
void setup(){

  //setup TP102 sensors
  tp_1 = tmp102_allocate(72); //error is here
  tempSensors[0] = tp_1;

  //rest of stuff...

}

I think there is no mistake in the code. There is also no option in the Arduino IDE so that I can meddle with the compiler/linker options.
All the files are inside the sketch folder. I created these files using the drop down button in the IDE...

are you including tmp102.h in the sketch, before the setup?

@Talk2 Yes of course!

Why are you not declaring the
tmp102_t* tmp102_allocate(int address) in the tmp102.h?

@Talk2 Oh sorry I have it in my code, I accidentaly removed it when pasitng the code in the question. That is not the problem :(

The reason you are getting the undefined reference to  `tmp102_allocate(int)' is because your c source file is being converted to a cpp file and the function name is being mangled to support overloading etc etc. You need to flag that the functions are c code with  extern "C" blocks. If you change your header file to  the following it should compile. Alternatively, if you change the extension of your source file to .cpp you won't have any issues with name mangling but your code will probably not work (malloc). Note that by checking if __cplusplus is defined you can use this header in both cpp and c projects.
tmp102.h
#ifndef TMP102_H
#define TMP102_H

#ifdef __cplusplus
  extern "C" {
#endif

//TP102 sensor struct
typedef struct TMP102 {
  int   address;
  float celsius;
  float fahrenheit;
} tmp102_t;

 tmp102_t* tmp102_allocate(int address);

void tmp102_init_struct(tmp102_t * t, int address);

#ifdef __cplusplus
  }
#endif

#endif

Thanks a lot. I was thinking that it will be compiled by a C compiler not a C++. I just enabled the compile output and I see that it is indeed using arm-none-eabi-g++ to compile my code!

Actually you are almost there. The c file is compiled as c but the header is being included in a c++ file. It is the reference to the external c function that is being mangled not the named in the c file, which is where the mismatch occurs. The solution given here is still the correct one though. This method tells the compiler that the functions referenced are in a c file not a c++ file and disables the name mangling for them.

I gave extern "C" to the header and it does not help. it says multiple definitions found. even it does not matter if I name the file c or cpp

It compiles fine for me. Suggest you copy past the header file. Maybe your #defines arent right. And your souurce file is still .c, correct?

This is talked about here.  Evidently, the C++ compiler changes names of *.c files when compiling.  Try changing the names of your files from *.c to *.cpp so that the C++ compiler does not change the names. Then recompile.

source: Stack Exchange

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

sort: votes


text:
Use LDR with 220 ohm resistor
I have read many tutorials on LDR(Light dependent resistor) with Arduino which includes a 10 kilo ohm resistor but can i use it with 220 ohm resistor or even without resistor.

Do the math. If you know what you're doing, sure. However, the fact that you're asking suggests that you're not quite sure what you're doing, so if you try, you'll likely have problems making it work, or even damage your micro.

You can use it with no external resistor: connect it between an analog input and GDN, then activate the internal pullup resistor. This pullup has a value somewhere between 10 and 50 kΩ, typically around 30 kΩ. The large uncertainty in the pullup value means you will not be able to compute the resistance of the LDR but, given some calibration, it should be OK for telling light and shadows apart.

can you post an answer with example

It can't hurt to use the 220Ohm. Though with most typical LDRs you won't get the range of different values. I.e. the values get from analogRead in the light, and in the dark will be closer to each other. Giving you a worst "resolution".

Unless properly filtered, an LDR has a spectral sensitivity very
different from the human eye, which makes it unsuitable for any kind of
photometric measurement. It is also typically very loosely specified,
so you won't know the illuminance it receives better than a factor two
even if you measure its resistance very accurately. Thus, if you really
need accurate illuminance measurements like, e.g., for complying with
legal requirements, then forget the LDR and get a real luxmeter with a
calibration traceable to the SI lux standard.
Now, if you only want to tell apart substantially different illuminance
levels, like sunny and cloudy, then the LDR is fine. And don't let
Majenko scare you into believing you really need to know the resistance
of your pullup: it doesn't really matter.
That being said, you will get the best sensitivity if your pullup has a
resistance in the same range as the resistance of the LDR in the typical
conditions you will use it. Thus, if your LDR is nominally 10 kΩ, I
would avoid pulling up with 220 Ω, as the sensitivity would be very
poor. A 10 kΩ pullup resistor would be ideal, but the internal
pullup of the I/O pin (20 – 50 kΩ, 30 kΩ typical) should
be fine.
Many tutorials on LDRs use the ADC reading to compute a resistance, for
which you need to know the resistance of the pullup. If you want to
follow this path, just assume a 30 kΩ pullup. All your numbers will
be somewhat off, but that makes absolutely no difference, because you
don't know how to relate the resistance to the illuminance anyway.
I would suggest you forget about computing the resistance. Just look at
the raw ADC readings instead. Take some test readings in the typical
conditions that are of interest to you: now you have a baseline to which
you can compare further readings against. Keep in mind, though, that the
ADC readings get lower as the illuminance gets higher. And beware
that the resistance of the pullup, and probably that of the LDR also,
can be sensitive to temperature variations. You may do a hairdryer test
to check whether it gets really bad.
Example code? This one is pretty trivial:
/* Connect an LDR between A0 and GND. */

void setup() {
    pinMode(A0, INPUT_PULLUP);  // enable pullup for the LDR
    Serial.begin(9600);
}

void loop() {
    Serial.println(analogRead(A0));  // print out a reading
    delay(1000);                     // delay for one second
}

Thank you The code worked with LDR. But as you said that it does not fit the legal requirements what specefic luxmeter shall i buy

Would BH1759 be fine?

@Yash: That's another question, and one I do not have the answer to.

The simple fact is: you need a resistor with it. There's no getting away from that fact (short of building and using a constant-current source, but that's beyond the scope of this answer).
What value should the resistor be? Well, that depends on how sensitive or insensitive you want the LDR to be.
Yes, it will work with 220Ω, but will it give suitable results? Probably not. Ideally you want the resistor to be somewhere in the vicinity of the nominal resistance of the LDR - and that usually means 10s of KΩ.
As Edgar has mentioned, you can, at a pinch, use the internal pullup resistor of an IO pin instead of an external one (pinMode(A0, INPUT_PULLUP)), but the variability in the possible resistances that it might be make it pretty useless for anything more than "is it light or dark".
So you are best off getting a 10KΩ resistor where you then know that it is 10KΩ (or within a small percentage) and can calculate the LDR's resistance properly.

The variability in the possible resistances may not be an issue if he is only building one single setup.

@EdgarBonet Yes, but without knowing what the pullup resistor value is, even on just a single setup, the returned ADC values are pretty meaningless, other than "light" and "dark". Yes, you could experimentally work out the resistance of the pullup if you really wanted, but the simple fact that the OP has had to ask this question means that such experimentation will be beyond him.

Typical LDRs are so loosely specified that, even with a 10.000 kΩ pullup, the ADC values are meaningless without prior experimentation.

@EdgarBonet At least with a known pullup you only have one unknown. That then allows you to calculate the actual LDR resistance. With two unknowns you have no hope at all.

@EdgarBonet Anyway, they're illegal in most civilised countries due to the use of cadmium.

Why would you want to ever calculate the LDR resistance? That is completely useless without a precisely know illuminance–resistance function. Instead, just compare the raw ADC readings with previously taken test readings.

@EdgarBonet I wouldn't. But then I wouldn't use an LDR full-stop. My latest project used the Lite-On LTR-329ALS-01 which gives you the actual Lux value of both visible and IR illumination over I2C. And it's in a 2mm² surface mount package.

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


text:
How to simply close a tab?
How can one close a tab in the Arduino IDE? There is a Tab button (little triangle) with the Option "Delete"(kind of misleading term). There is no "Close" option. And the "Delete" option doesnt do the job for me either, because the tabs are write-protected, and I just get a prompt.

I don't think you can. The IDE just opens all c/cpp/ino files inside the sketch's folder.

You cannot close a tab in the Arduino IDE.  If a file exists in the sketch then it is there with a tab. Deleting a tab deletes the file.
In the Arduino IDE a tab is a file and a file is a tab. You can't remove one without removing the other.
You might like to check out my IDE, UECIDE, which deals with tabs in a more traditional manner.


text:
Selection of presence sensor
For one of my university projects I need to detect the presence of a person in the shower. In order to do that what I have in mind is use a proximity sensor. If the target is in a distance range (let's say 20 to 50 cm) It will assume that the person is in the shower when the distance measure is no longer in this range then it will mean that the person left the shower. I need to detect all the time of the person in the shower (meaning when he/she gets in and then out). I have read a lot of info and forums to properly choose the type of sensor. However I still don't have a clear answer. About the Ultrasonic proximity sensors I know that they are cheap and more accurate by it can be affected by Temperature, humidity and some ambient noise, all of them which happen in a shower. The other option an Infrared one gets affected by lightning conditions and the surface of the target. The last option I checked is a PIR sensor I know it senses Temperature of the target, but I don't know if it will be affected by the running hot water and also is more expensive. In general, I don't know how the running hot water will affect the detection of the person in shower. Also,so again I don't know how this will work. Sorry for the huge amount of  questions, I am a little bit confuse with all the factors to have in mind. I am hoping someone out there can help a lost newbie like me and give me a suggestion. Thanks a lot :)

There is no one sensor that is perfect, but some are more reliable than others.
Yes, the temperature and humidity can play an important role in your sensing, and has to be taken into account. That's not to say that things like Ultrasound don't have a place in the scheme of things.
There's one word you need to think about here: Correlation.
If one single sensor isn't completely reliable then add a second that works in a different way. If both of them agree that there is someone in the shower (i.e., the sensors correlate) then the probability that there is actually someone in the shower is considerably higher.
The great thing about a shower is you are working in a defined enclosed space. That makes it much easier and there are plenty of sensors which, when combined with others, would be quite good at reliably sensing the presence of someone in that enclosed space.
Some ideas:
Ultrasound above the person's head

Pros:

Simple to arrange.
Safe.

Cons:

Can be fooled by the water from the shower head.
Steam isn't good for them.

Infra-red distance

Pros:

Accurate
Can be sealed

Cons:

Expensive
Harder to work with
Can be blocked by steam

Horizontal infra-red beam

Pros:

Can be positioned outside the shower glass with a reflector inside
Safe

Cons:

Small sensing area
Can be blocked by steam

Pressure sensor

Pros:

People weigh more than water so is very reliable
Simple to interface

Cons:

Hard to install safely
Needs to be completely waterproof and sealed.
Could be a shock hazard if not waterproof

You notice I haven't mentioned PIR. I'm not a fan of PIR for sensing the presence of humans. They work by detecting moving heat sources. If the person is moving (entering an area, walking round a room, etc) then they get detected. If the person stands still (as is often the case in a shower) it "forgets" they are there.
Of the choices above (and I am sure someone would come up with others) I would probably opt for the infra-red beam. Maybe split it into a V shape to cover more area - that is, the beam enters the side of the shower at an angle, strikes a reflector on the shower wall, and is reflected back at another angle. The detector is then placed away from the emitter. You could also have a second set to give better coverage.
Infra-red distance measuring in/on the ceiling could be used to improve correlation and thus the probability that there is actually someone there.
I'd stay away from pressure sensing unless you can get hold of a proper waterproof pressure sensing mat designed for in-shower use. Don't try and make one yourself, waterproofing isn't an easy task, especially when people stand on it all the time.

There is always pressure sensitive mats that are used outside in front of doors etc.


text:
Changing the tick time in FreeRTOS
I am trying to use FreeRTOS's vTaskDelay() function in order to periodically execute tasks.  The latest version of FreeRTOS came with the "tick" time set to 15 ms. Therefore, the smallest resolution I can delay for is 15 ms. I would like to lower this resolution to at least 1 ms.  Is it possible to configure FreeRTOS in this way?  I found this answer online : http://www.freertos.org/FreeRTOS_Support_Forum_Archive/November_2012/freertos_Problem_changing_Tick_time_from_1ms_to_10ms_6231539.html.
But for me, the configTICK_RATE_HZ is not defined and it seems to be using a watchdog timer to enforce the 15 ms resolution. I think the forums are referring to an earlier version.

see also this FreeRTOS port with F_CPU

See the configTICK_RATE_HZ configuration option.
Also note it is better to specify times in milliseconds, rather than ticks, so you can change the tick frequency without effecting the timing (other than the resolution of the time).
The pdMS_TO_TICKS() macro can be used for that purpose, for example to create a delay of 100ms.
const TickType_t xBlockTime = pdMS_TO_TICKS( 100 );
vTaskDelay( xBlockTime );

authors: Андрей Тернити


text:
How do I communicate with a sensor via an Arduino's RX/TX ports?
I have a sensor that communicates via serial communication. CTi Sensors TILT-05. It transmits an ASCII string with data separated by commas. I want to be able to read the incoming ASCII data in the Arduino IDE's Serial Monitor in real time (the device is an accelerometer).
I am struggling to convey this in the code. Currently, I have the sensor's RX connected to an Arduino Uno's TX port (digital 1) and sensor TX-> Arduino RX (digital 0). The sensor is powered and grounded via the Arduino.
I have searched for serial communication methods but can't find any that seem to work. How can I receive and interpret the incoming data from the sensor?

You don't mention the sensor brand or a datasheet so this will be a very general answer to the problem.
Firstly, how you have the sensor connected now should just spool info into the Serial monitor of the Arduino IDE without any code on the Arduino.
What are the data speed and the exact way the Serial comes out from the sensor?
If you want to interpret the data as it is coming through you should use Software Serial as you can't relay info to the PC with an Arduino's RX TX lines connected to something else.
What you can do is below(Untested):
#include <SoftwareSerial.h>

SoftwareSerial mySer(3, 4); //RX TX

//these are char areay because its from Serial
char accel[3] = {'0'};
uint8_t place = 0;

// array to print in sync with the accelerometer values array
const char* SerialText[3] = {
   "\nX Axis: ",
   "\nY Axis: ",
   "\nZ Axis: ",
};

char inData = '0';
char separator = ','; // separator you described

void setup(){
//set to the normal baud, mines for the example
     Serial.begin(9600);

     mySer.begin(9600);

}//~ end setup

void loop(){

    if(mySer.available()){

     inData = mySer.read(); // get the value at the instance of the serial data being there

        if(inData != separator){
          accel[place] = inData;
          Serial.print(SerialText[place]); // print the current values identifier
          Serial.print(accel[place]); // print value
          place++; // increment for the next time
     }
   }

if(place >= 3) place = 0;
}//~ end loop

The above gives this output at the moment, with an input of $CSACC,-0156.4,-0226.3,+0981.2*49
X Axis: $
Y Axis: C
Z Axis: S
X Axis: A
Y Axis: C
Z Axis: C
X Axis:
Y Axis: -
Z Axis:
X Axis: 0
Y Axis: 1
Z Axis: 5
X Axis: 6
Y Axis: .
Z Axis: 4
X Axis:
Y Axis: -
Z Axis:
X Axis: 0
Y Axis: 2
Z Axis: 2
X Axis: 6
Y Axis: .
Z Axis: 3
X Axis: +
Y Axis: 0
Z Axis: 9
X Axis: 8
Y Axis: 1
Z Axis: .
X Axis: 2
Y Axis: *
Z Axis: 4
X Axis: 9
Y Axis:
Z Axis:
X Axis:

The code doesn't filter this the way it should but is a stepping stone. I will update it to do it properly when I have a chance.

There are other ways, but I will add some info later if needed or after clarification from the OP.

Hi there, thank you so much for trying to help. For clarification, this is the sensor I'm trying to use: http://ctisensors.com/wp-content/uploads/2016/03/TILT-05-Datasheet-01b.pdf. It transmits an ASCII string at a baud rate of 115200. I've tried your code but have encountered a few errors, primarily: error: array must be initialized with a brace-enclosed initializer
char accel[3] = 0;

@FYoung        thanks for the sensor info, i will amend my answer to that and also to fix the error of the code.

As a side note, as the device uses NMEA 0183, here is a link to way to split it nicely

With RSM's help I've managed to get the sensor reading into the serial monitor semi-reliably. I have yet to solder the headers onto the sensor yet and am just doing prototyping (basically just me pushing a wire against the sensor output hole) which is unreliable. I believe once I get some headers soldered on the output will be much more reliable. For those searching, this code worked for me.
Digital pins 3/4 function as your RX/TX pins respectively. Connect the TX of your sensor to the RX (3) of the Arduino and likewise for the TX. I used a baud rate of 115200 but you can change it to whatever works in the code. This is simply a simplification of RSM's code in his previous answer and all credit/kudos goes to him.
#include <SoftwareSerial.h>

SoftwareSerial mySer(3, 4);

char inData = '0';

void setup(){
     Serial.begin(115200);
      mySer.begin(115200);
}

void loop(){
    if(mySer.available()){
     inData = mySer.read();
     Serial.print(inData);
  }
}


text:
Can I connect and control 12 Arduino's over USB/serial to my laptop?
I have 12 arduinos, each of them controlling some simple hardware peripherals. I want to interact with all of them over 1 USB connection to my laptop, where I have a python program communicating over serial.
The following seems like it could work: https://www.amazon.ca/Satechi-Power-Adapter-Control-Switches/dp/B0051PGX2I
Are there any electrical/other considerations to take into account for why this would/wouldn't work?

You want one program to handle 12 serial connections at the same time, as if it was one?

From a technical standpoint, USB can host up to 127 devices, so 12 Arduino boards is certainly not pushing the limit. Having 12 serial ports shouldn't be an issue in either Linux or Windows.
From a practical standpoint, you will have to find a powered USB hub which can support that many devices, or plug multiple hubs together. I'll leave that up to you as shopping recommendations are off topic.
In terms of the hub you use, you need to make sure you don't exceed its maximum current rating. The Arduino boards draw typically around 60-100mA alone. 12 of those and you will need at least 1.2A rating. The hub you mentioned says that it cannot exceed 2A. Depending on what other circuitry you attach to your Arduino boards you may need an external power supply for the boards.


text:
How accurate is arduino time keeping?
I want to use my arduino to turn a light off for 16 hours and on for 8 hours. I know the general code, just using delays and the relay shield code as well. I want to know how accurate this will be? ( I tagged uno and leonardo, as I have access to both)

Arduino delay() is not really meant for timekeeping.  In single uses at moderate duration it might in the best case approach the accuracy of the clock, but using it repetitively to add up to a longer period of time is a mistake as the start/end error and granularity will accumulate.  Instead, you should use something that looks at the cumulative number of clock ticks that have elapsed over the entire interval of interest.

There are multiple versions and "clones" of the Arduino, and each one will probably use different components. The time you refer, in this case "millis()" I believe, is maintained from a timer interrupt, which is derived from the main clock (normally 16Mhz).
The main clock on your board might be generated by a ceramic resonator, which is not very accurate: around 0.5%-1% error. It also might be from good quartz crystal, with up to 0.001% accuracy. Those variations on the frequency source will produce some drift over time... Like your watch needs to be readjusted from time to time.
Another factor that affects accuracy, including for RTCs using a 32.768KHz crystal, is the temperature. Here an Application Note on this: http://www.st.com/content/ccc/resource/technical/document/application_note/55/e2/3d/2a/87/ab/4d/e1/CD00232494.pdf/files/CD00232494.pdf/jcr:content/translations/en.CD00232494.pdf
Your application might not require too much precision, and you could simply write a sketch to print the time every second on the serial... let it run from one hour, one day, and check how much drift you're getting. After that will be easy to estimate how much drift you'll have a after a month.

“you still have some losses for the little overhead of your software to increment millis()”. No, you don't. The hardware timer driving millis() does not stop counting while the software increments timer0_millis. Unless you do something very wrong, like blocking interrupts for more than 1 ms, you will not loose a single tick of the crystal/resonator.

Yep, you're right, the little overhead to increment the millis won't be cumulative.

By definition, the Arduino is as accurate as it's crystal clock/resonator.
This clock runs at approximately 16mhz for an Uno.
The Arduino's internal time is just a count of how many times this crystal has vibrated.
READ THIS! - these next two paragraph are apparently incorrect. See Nick Gammon's comment below.

The crystal in question is approximately like this one: https://www.sparkfun.com/products/536 - this one from SparkFun is accurate to 50 ppm - that's parts per million. So, if your Arduino has that EXACT crystal, it may lose or gain 50 parts per million - in a million seconds, it would count somewhere between 999,950 and 1,000,050 seconds. This would mean you gain/lose less than 4.3 seconds per day, or 2 minutes per month.
  If you find the crystal on your board, google the code (probably something like 16.000N, for the Sparkfun one), which should tell you exactly what the accuracy is for that chip. Note that, if you can find the datasheet, it should tell you the accuracy, at particular temperatures - as the temperature goes up and down, the error will change too.

Remember also that an Arduino's clock is in volatile memory - that is, if you power down the Arduino, and power it back up, it has no idea what time it is - you would need to set the clock again, either by connecting it to a PC, network, or via buttons/display on your project.
There are a number of alternatives, depending on your need, to work around this: you can get the data from LAN or WIFI, if your project has that, or you can use a RTC module - you need to set this to the correct time once, then it will remember after that.
Alternatively, you can use a light-dependent resistor (aka photoresistor), and trigger automatically when it gets dark. This may trigger when it gets dark for some other reason, e.g. a storm, which may or may not be an advantage.

The Uno has a resonator connected to the Atmega328P, not a crystal. The crystal you see on the board is connected to the Atmega16U2 (the USB interface) because that needs more accurate timing. A resonator is not as accurate as a crystal, generally speaking.

H'm, if there is an accurate crystal for the USB, would it not have made design sense to push the output of that to the AtMega328P? I know the AtMega328P has a clock-out, I assume the 16U2 has a clock out too? The AtMega328P definitely has a clock in....

Interesting question. They could have saved a cent or two by doing that. There must be some reason, if only the desire to keep high frequency signals from going from one side of the board to the other.

Would that be an issue? The signal delay would not - the two chips aren't synchronized, and nothing assumes that they are (obviously, otherwise separate clocks wouldn't work). The clock-out is generated by the first chip, so I would expect it to be a strong clear signal - surely 16mhz over a few cm wouldn't be an issue? It would also save a pin (as the crystal requires two pins).

True. And the two chips are quite close together too. I don't know why. Maybe by the time it occurred to them it was too late because of the way the other traces on the board ran.

the below information is incorrect... i'm not sure why you say it is incorrect. I would argue that you are largely accurate in that with good coding, the long-term accuracy of arduino, or any other mcu, is only a function of the oscillator. the fact that the oscillator is a crystal, or a txco, or an internal oscillator, etc., doesn't fundamentally change that fact.

@dannyf - edited post to mark just a single paragraph as "inaccurate", not the entire post. I've been unable to identify a part number, so cannot say how accurate it is.

I made a temperature and humidity sensor in August 2013. It uses a RTC chip (DS1307) which you can buy on eBay for $1 if not less. It has a battery backup (lithium cell).
I don't recall ever resetting the clock on it. It is now about 3 years later, and it is running about 11 minutes slow. This would be an acceptable error for something like turning garden lights on and off. Even for taking the temperature, a few minutes out when logging a reading is probably not going to matter.
Using the internal clock probably won't be as accurate, but could be OK in this case. I suggest you follow Chris Stratton's suggestion and code so that errors are not cumulative. For example, if you delay for an hour, and then do something, make sure that the "do something" isn't added to the next delay time.
If you want super accuracy (sounds like you don't) then connecting up a GPS module lets you query the exact time from the satellite, which could cut the error down to negligible amounts. Those GPS modules however aren't cheap.

Something to consider if you try to make do with the internal clock is: what happens if the power goes off? Then it loses track of when to turn the lights on and off. A clock chip however (usually) has a battery backup, and will "know the time" once the power comes back on.

If you go to eBay, to buy and RTC, just spend an extra buck and get a DS3231 instead of a DS1307. This one has a temperature compensated oscillator, resulting in even better accuracy. 2 minutes off per year, maximum. I have mine running for 2 year, and it is still correct to the minute (i.e. less than 60 seconds off).

Sounds like very good advice. :)

I think that RTC modules and real time clock chips have some sort of "mistake" said that, it CAN max. delay for fast forward for max. 6 seconds per month. Something as this, I've read year or so ago, when I was dealing with some sort of doors locking mechanism.
But for app. 8 hours, there's an arduino RTC module more than enough, I'd say. I assume, that seconds doesn't matter.

Just because it's always an option...  I'm usually connecting my Arduinos to the Internet one way or another, so I just get the time from NTP servers once every day or so using UDP to keep the clock accurate, or accurate enough.
The advantage is that, even if power is lost, it's relatively easy to ask Arduino to get the time while booting up.  Then it always knows, and is always on time.
Happy to share fave code, but I found mine in UDP library examples and have adapted it to my own needs.

Not very.
For that kind of period of timing you are far better off using a Real Time Clock (RTC) module.

How long off will I end up being? It doesn't need to be super accurate

The longer it is running for the longer it will drift. The oscillator (ceramic) on the Arduino Uno is very poor. It's better on the Leonardo since it has to drive USB, but the whole delay() / millis() thing is inaccurate at best.

Alright, I may just use a phone and another shield to interface with it and get the time. Thank you very much :)

That sounds massively more complex and expensive than using an RTC...

You may think, but I have all the materials and an old ipod that just begs to be used for this :)

I want to know how accurate this will be?

accuracy is a function of coding and hardware. with good coding, you can make it as accurate as your hardware is capable of.
I experimented with a tco-919 high accuracy oscillator (19.2Mhz), in an unairconditioned environment, no meaningful timing drift after a month.
So if you really want accuracy, go with a good oscillator.
if you just care about reasonable accuracy (1%?), the internal oscillator will do.


text:
Saving library example sketch getting error "you cannot save a sketch into a folder inside itself.."
I'm writing a library, and that library .cpp/.h code is in devel/arduino/libraries/LightBrightLib/.  I have test code that calls that library, and an example program using the library.  Right now they're in /devel/arduino/lightbright/LightBrightMain/ and /devel/arduino/lightbright/LightBrightLibTest/.
I see most libraries have an examples directory inside the library, so I tried moving mine to /devel/arduino/libraries/LightBrightLib/examples/LightBrightMain/ and /devel/arduino/libraries/LightBrightLib/examples/LightBrightLibTest/
When I do that, and try to save my LightBrightMain.ino file into /devel/arduino/libraries/LightBrightLib/examples/LightBrightMain/, it says "You cannot save a sketch into a folder inside itself. This would go on forever.".  And of course it won't let me select the examples directory or any other directory above it.
How do other library makers do this?  Maybe they don't use the IDE, or they copy it in outside the IDE, or use symlinks?
What does the IDE think it's doing and why is it fighting putting the file where it already is?
NOTE: This is not a file permission problem as I own all files

What I normally do is make the examples in their own folders (ie. inside the sketchbook folder). Then when they are tested I just use the file system to move the folders into the "examples" folder under the library.

When I do that, and try to save my LightBrightMain.ino file into /devel/arduino/libraries/LightBrightLib/examples/LightBrightMain/,

The IDE makes the folder, so you would (if this works at all) save LightBrightMain into the examples folder. Don't make a folder of the same name as the sketch. The IDE does that.

I removed the directories under examples and tried that, and it worked. However...  when I modify it and try to save it, it says 'Some files are "read-only", so you'll need to re-save the sketch to another location'. Of course the files are NOT read only.

It always does that when you open an example file from the IDE. The idea is to stop you corrupting the example. Open them with an external editor if you want to tweak them, or move them somewhere else as required.

But this is MY example. OK I guess I need to give up. It's not possible using the IDE. Thanks


text:
Arduino Robot. a function-definition is not allowed here before '{' token
The code is very messy. We have an L293D circuit which has two enable pins always on. We also have an LDR light sensor with two light resistors, one on the left and one on the right.
We are trying to make a line following robot
We are ambitious high school students.
// Use this code to test your motor with the Arduino board:

// if you need PWM, just use the PWM outputs on the Arduino
// and instead of digitalWrite, you should use the digitalWrite command

// --------------------------------------------------------------------------- Setup
void setup() {
{Serial.begin(9600);

// --------------------------------------------------------------------------- Motors
int motor_left[] = {2, 7};
int motor_right[] = {10, 15};
int LDR = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDRValue = 0;      //that’s a variable to store LDR values
int light_sensitivity = 500;    //This is the approx value of light surrounding your LDR
int LDR2 = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDR2Value = 0;      //that’s a variable to store LDR values
int light_sensitivity2 = 500;    //This is the approx value of light surrounding your LDR
int i;
for(i = 0; i < 2; i++){
pinMode(motor_left[i], OUTPUT);
pinMode(motor_right[i], OUTPUT);
LDRValue = analogRead(LDR);
    Serial.println(LDRValue);

    if (LDRValue < light_sensitivity);
    Serial.println("wat");

}
// --------------------------------------------------------------------------- Loop

// --------------------------------------------------------------------------- Drive

void motor_stop(){
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], LOW);

digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], LOW);
delay(25);
}

void drive_forward(){
digitalWrite(motor_left[0], HIGH);
digitalWrite(motor_left[1], LOW);

digitalWrite(motor_right[0], HIGH);
digitalWrite(motor_right[1], LOW);
}

void drive_backward(){
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], HIGH);

digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], HIGH);
}

void turn_left(){
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], HIGH);

digitalWrite(motor_right[0], HIGH);
digitalWrite(motor_right[1], LOW);
}

void turn_right(){
digitalWrite(motor_left[0], HIGH);
digitalWrite(motor_left[1], LOW);

digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], HIGH);
}
void loop() {
drive_forward();
delay(1000);
motor_stop();
Serial.println("1");

drive_backward();
delay(1000);
motor_stop();
Serial.println("2");

turn_left();
delay(1000);
motor_stop();
Serial.println("3");

turn_right();
delay(1000);
motor_stop();
Serial.println("4");

motor_stop();
delay(1000);
motor_stop();
Serial.println("5");
}

I copied your code into the question, to save everyone having to go to Pastebin to get it. Please copy and paste the actual error message. Inside it is a line number which will tell us which line it is failing at.

You need to look more closely at your braces. Use the auto-format tool (Ctrl+T) to help you. For example:
void setup() {
{Serial.begin(9600);

// --------------------------------------------------------------------------- Motors
int motor_left[] = {2, 7};
int motor_right[] = {10, 15};
int LDR = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDRValue = 0;      //that’s a variable to store LDR values
int light_sensitivity = 500;    //This is the approx value of light surrounding your LDR
int LDR2 = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDR2Value = 0;      //that’s a variable to store LDR values
int light_sensitivity2 = 500;    //This is the approx value of light surrounding your LDR
int i;
for(i = 0; i < 2; i++){
pinMode(motor_left[i], OUTPUT);
pinMode(motor_right[i], OUTPUT);
LDRValue = analogRead(LDR);
    Serial.println(LDRValue);

    if (LDRValue < light_sensitivity);
    Serial.println("wat");

}   // <------------------------------------ HERE

// --------------------------------------------------------------------------- Loop

// --------------------------------------------------------------------------- Drive

void motor_stop(){

Where I marked "HERE" you are closing the for loop but you should also be closing setup.
You also have two opening braces here:
void setup() {
{Serial.begin(9600);

Proper indentation is very helpful for sorting out these sorts of issues.

authors: ประสิทธิ์ เกิดนอก


text:
Clearing EEPROM
I'm trying to clear my EEPROM and am using this code:
#include <EEPROM.h>
void setup()
{
// write a 0 to all 4096 bytes of the EEPROM
for (int i = 0; i < 4096; i++)
EEPROM.write(i, 0);

delay(9999999);
}

void loop()
{
}

I don't see a problem with it but it is ineffective.  Am I missing something?

from memory, you need EEPROM.commit(); or maybe EEPROM.end(); after writing

Aaaaaah! Of course! Thank you.  Stupid stuff like this drives me crazy.

Although, that MAY just be on the ESP8266 judging from the sample sketches

What do you mean "ineffective"? The EEPROM is not cleared? Or only some is? If so, how do you know? Which Arduino do you have?

Ineffective in thwt the eeprom was not erased.  Nothing changed after I ran this sketch.  I saved "TEST01" to eeprom and it was still there after I tried to erase it.

Note that empty EEPROM is all 1s, not all 0s. Write -1 instead.

I am nitpicking but... when you EEPROM.write(), you are actually erasing an EEPROM cell, then writing a new value into it. This takes 3.4 ms, irrespective of the value written. You could do an erase-only operation, which takes only 1.8 ms. It looks, though, like this cannot be done with the Arduino EEPROM library, and not even with <avr/eeprom.h> from avr-libc. You would have to access the EEPROM address and control registers directly, as documented in the datasheet of the MCU.

Thankyou for this sketch , It works perfectly for me. I added a two lines to turn on LED after the sketch completed.

The tutorial here is very clear about how to clear the contents of the Atmel's EEPROM.  I only see 2 major difference.  The tutorial finds the size of the EEPROM through a function call.  Probably much safer.  And there is no call to a delay() function.
The tutorial does include lighting up an LED when finished.  And @Edgar Bonet is correct that erasing an EEPROM (altering each floating gate with in the chip) does take time.  And you have no way to known when the EEPROM clearing is finished in your code.
It is possible you are forcing your code to stop before it is finished.  In which case it would appear the EEPROM is not completely cleared.

Thank you all for helping me out.  This is what I ended up using (ESP8266 1.0 12E with Arduino IDE):
#include <EEPROM.h>
#include <ESP8266WiFi.h>

void setup()
{
  Serial.begin(115200);
  EEPROM.begin(512);
  delay(5000);
  Serial.println("clearing EEPROM...");
  // write a 0 to first 1000 bytes of the EEPROM
  for (int i = 0; i < 1000; ++i) {
    EEPROM.write(i, -1);
 }
  EEPROM.commit();
  delay(5000);
  Serial.println("Reading EEPROM ssid");
  String esid;
  for (int i = 0; i < 64; ++i)
  {
    esid += char(EEPROM.read(i));
  }
  Serial.print("SSID: ");
  Serial.println(esid);
  Serial.println("Reading EEPROM pass");
  String epass = "";
  for (int i = 64; i < 128; ++i)
  {
    epass += char(EEPROM.read(i));
  }
  Serial.print("PASS: ");
  Serial.println(epass);
}

void loop()
{
}

It's probably longer than it has to be but I pulled stuff from other sketches I've worked on and prioritize function over form.  This writes a "-1" to the first 1000 bytes and then prints the first 128 bytes.  Since I am only concerned about the first 50 bytes or so this was sufficient for my needs.


text:
Wire.h not found!
Here's the code that's making this error:
#include "Wire.h"

Here's the error:
fatal error: Wire.h: No such file or directory
 #include "Wire.h"
                  ^
compilation terminated.
Error compiling.

I also can't include any file from my Arduino\libraries folder. I tried to reinstall the IDE several times in different places and nothing happened. Why is this happening?
EDIT: after some time I discovered that this error occurs in header files only, not in sketches!

Could you clarify a little more on your setup of the IDE and the full paths to those libraries and if you have any duplicates. Also what is the settings you chose in the Boards menu.

D:\Arduino\hardware\arduino\avr\libraries\Wire\Wire.h And I chose the Arduino Uno COM3

Is the library there header there(I know its an obvious ques). That is where the arduino system should be looking when UNO is chosen

yes it is there

try hard linking it to the exacr path in the #include macro. Also what version of the IDE are you using?

my version is 1.6.3

Change it from #include "Wire.h" to #include <Wire.h>

I still get the same error

Delete your IDE. Delete your preferences.txt file. Download and install 1.6.9

Use #include <Wire.h>
Including files in double quotes (") will point to headers in current working directory first.
Edit: ... and there is nothing wrong with copying headers to CWD if you are modifying them, but that's probably not what you want.

First go to your library folder and check whether u included that Wire.h header file or not.If not then first include that file then problem will get solved automatically.

The line that is causing the problem in the include statement, the one you think will fix it. If that's not what you mean please can you clarify your answer?

I had a similar issue and found this question. However, the solution for me is different.
I already had #include <Wire.h>, nevertheless the compiler told me it's missing. It turned out, I had selected a wrong board from a previous project. Needed to change to "Arduino Uno".

I copy here the answer from https://forum.arduino.cc/t/wire-h-no-such-file-or-directory-solved/297761, cause it worked for me:

It's not enough to put "#include <Wire.h>" in the source file you are using the library in. It seems you must also put "#include <Wire.h>" in the main *.ino file for the sketch as well, before it can be used in any other source code files.

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


text:
Arduino 4G LTE Shield
Is there by any chance a shield that can take an 4G LTE compatible SIM card activated by a carrier and establish a connection?

Googling "4g shield arduino" gave this. It will need a 4G LTE capable SIM, but I guess "it depends" if any 4G LTE SIM will work..

This is a really old post but I also found this LTE shield which is much cheaper than the cooking hacks one.
Be carefully; this module is a dual band only (900/1800 MHz); no 850 or 1900 MHz.

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


text:
Arduino and a Web Server
I'm here because I couldn't find any answer anywhere and the problem seems pretty easy and hard in a same time.
I have a website, for exemple : My_website.host.fr
I have arduino's sensors at home, for exemple temperature sensor in my garage, servomotor in shutter, etc... with Wifi-module.
I want to, as a User, access the website, update some information on the website, for exemple : I want the shutter down, so I put it to 0 on the website, and the arduino will, for exemple each X seconds check if the value has changed, if it does then it updates itself and so lower the shutter.
So, by this, i'll never have to connect directly through an @ip to my arduino, without hosting a server at home which could be hacked or anything, the arduino update itself with the infos that are on the website,
So from my arduino I must ? I have no idea, get the source code of the web page and search for some value, or, from the web page, update a file with PHP variables and retrieve that file with my arduino then read it for the values ?
I don't know if it's clear tho and I have no idea how to manage it.
Sorry about the bad english sentence or words, not main language;
Thank for the help i'm kind of lost.

You will have to make a web API. Make it as simple as possible. E.g. "GET /shutter" would return just 0 or 1.

MQTT might be a good solution for this...

You're in luck! A lot of people are doing, or trying to do similar things. One way of doing it is using a provider like adafruit.io. I imagine there are many other providers out there. Or will be.

Could you please provide more information about the server? Is this a website you own? If so, does your hosting provider allow you to put scripts? If so, in what language(s)? You mentioned PHP, is it supported by your provider? If so, do you know some PHP? I'm asking all this because your discussion with st2000 is revolving around scrapping data from HTML, which would be a very bad idea if you can easily have the server deliver text/plain.

I believe the term you want to search on is "web scraping".  Assuming you are fine with people knowing the state of "things" in your home, you can simply leave the states up on your public web page.  That is, you click on a button on your web page and change the text from "shutter up" to "shutter down".  Mean while, your Arduino is "web scraping" the same page looking for "shutter" and acting on the next word "up" or "down".
In this blog, someone has posted his Arduino "web scrapping" code.  I have not tried it, so do some research before considering this particular solution.

Indeed it's web scraping !
Well, public people can access the states of my arduino's sensors right, first they have to know the site used to, the reals pages used to it (according on the fact that the website will be a food website fake pages). Just thinking that it gives so much more security isn't ? Connecting to your home @IP seems so unsafe, that anyone can access and even open doors...

Web scraping is for the case when you do not control the server, and have to extract the desired information from unstructured HTML. In this instance the OP controls the server. He can return the needed data in whatever format is easiest to digest for the Arduino. It would be silly to embed that data into an HTML document, only to have the Arduino remove all that crap through pattern matching.

Agreed, but web scraping is an easy concept.  And he may not have access to features like CGI scripts and scripting languages like PERL, ect on the web server computer.  Also, he may not have a dedicated home IP address.  So the web server (assumed located else where) may not be able to send information home (yes, there are dns look up services he could subscribe to to get around this).  He can look into all these things and more if he needs to.  But for getting started, I still think scraping is the easiest concept to grasp.

So, If I understand well and to sum up all this, I must, with my arduino, get the SOURCE CODE of the page (can it be in php :V and so it retrieves the html output from server ?), then look for datas to seek and update itself considering the values of the datas ?
You saying, that the easiest to control things in my home, would be to ssh the main that control the nodes ? Despite all the weakness it can has about security this is the easiest way ?
Tho my apologies again about my bad spelling, and thank you for your help

I understood you wanted to control things in your home with an Arduino using a web page far removed from your home.  I suggested you write a web page of which had text that changed through button presses.  Then to have your Arduino periodically read the web page using HTTP.  I did not say anything about a Secure SHell layer (SSH).  After all, what's to keep secret?  Anybody can view this web page.  Keep in mind there are many ways to do this.  And if you are that interested in security, you may find an Arduino insufficient.

Well, If someone wants to know if the cat still have food or if it's hotter than 25° inside he could do such gr8 things... wait..
Why do you say text change w/ button ? Mean button with sql request and text in php ?
Talking about SSH to know if, FOR YOU, It was the easiest way to finally do this ... Coz nothing seems to exist about web scrapping arduino or w/e, knowing the fact I suck at arduino I won't be able to do it on my own and CREATE it ^^

I'm sorry, I though you only wanted to control things in your house. If you want to send information from your house ... maybe you could use tftp and copy a small file of data from your arduino to the web server. Then serve up that data by reading that file on the web server and rendering a web page. But this requires you to store a password on the arduino which is a security risk which was something I was trying to avoid.

Evertime you give a way to solve my question about 'how to control sensor at home and know what  their values are' you just put another problem in, security tho both time, I said it, and say it again : I just want the easiest way for a newbie to set up this : Control sensor at home and know their states / values from far (through internet).
Thank you :D

Another option is Blynk who offer a server, a smartphone app, and a set of libraries and example sketches for Arduino. Also an active and helpful online user community, where the developers participate.
The server does not make view-able web pages; its job is to enable the Arduino and the app to communicate with each other.
The app lets the user quickly and easily configure a custom control panel which can communicate both ways with your Arduino.
The Arduino Blynk libraries can be installed and an example program compiled and uploaded a few minutes, with support for I/O port reading and writing already built-in. Online documentation describes how to expand the example code to do more specific things. Blynk is still under active development, meaning the documentation isn't always as detailed as one might like, that bugs are being fixed and occasional new ones appear, and new features are being developed.
I use it myself and teach other people how to, and I find it a really quick and easy to use platform for interactive remote control of my Arduino-based gadgets.
For example, I am using it right now to develop a ventilation controller for room- and window-fans. It will mix the room air in winter when the heat rises to the ceiling, and ventilate or just mix the room in summer depending on the floor, ceiling, and outdoor temperatures. It will report back to the smartphone which fans are on and off; allow me to turn any of them on or off; and display a history of the temperatures and fan states.

From your comment of Jul 1st, I understand that you can program your
server in PHP. Then, and to expand on my own comments, I am only
recommending that, whatever Web API you design, you keep it as simple as
possible. For example, for telling the Arduino whether it should keep
the shutter open or closed, you could write something like this in PHP:
header('Content-Type: text/plain');

if (user_wants_shutter_open())
    echo "open";
else
    echo "close";

In particular, it makes absolutely no sense to write a PHP program that
generates an HTML document. Consider that the Arduino is a very low
powered platform: there is no point in having it process more than a
handful of bytes when you only want to communicate a single bit of
information. And you should know that there is really nothing wrong with
using HTTP to transport plain text (but you should use the header
Content-Type: text/plain). If you want to send a more complex set of
data, you could use something like text/tab-separated-values, or maybe
even application/json.
Concerning web scrapping, it is a solution to a specific problem, the
problem being that the server returns the information in a format that
is not very well suited for machine consumption. You do not have this
problem. Obviously, you could create the problem by having your PHP
return an HTML document, and then you could apply the solution. My point
is that it is better to avoid creating the problem in the first place:
just return the information in a format that is as easy to parse as
possible.


text:
Sketch behaves differently when motor driver is added
I have written a simple sketch that takes values via serial communication through a Python script.
Here's the code-
#define LEDPin 13

void setup() {
Serial.begin(9600);
pinMode(LEDPin, OUTPUT);
Serial.println("Ready");
}

void loop() {
char inByte = ' ';
if(Serial.available()){
 inByte = Serial.read();
}
if (inByte == 'L')
 digitalWrite(LEDPin, HIGH);
if (inByte == 'R')
 digitalWrite(LEDPin, HIGH);
if (inByte == 'S')
 digitalWrite(LEDPin, LOW);
}

Now this code runs perfectly fine with my python script. No problems at all. But When I add code for my L293D motor driver module, like this -
int E1 = 6;
int Left= 5;
int Right = 4;
char data = ' ';

void setup()
{
  pinMode(E1, OUTPUT);
  pinMode(Left, OUTPUT);
  pinMode(Right, OUTPUT);
  pinMode(13, OUTPUT);
  Serial.begin(9600);

  }

  void loop(){
    if (Serial.available()>0){
      data = Serial.read();
    }
    if (data =='L'){
      digitalWrite(E1, HIGH);
      digitalWrite(Left, HIGH);
      delay(2000);
      digitalWrite(Left, LOW);
      digitalWrite(E1, LOW);
      digitalWrite(13, HIGH);
    }
     if (data == 'R') {
      digitalWrite(E1, HIGH);
      digitalWrite(Right, HIGH);
      delay(2000);
      digitalWrite(Right, LOW);
      digitalWrite(E1, LOW);
      digitalWrite(13, HIGH);
    }
     if(data == 'S'){
      digitalWrite(E1,LOW);
      digitalWrite(Right, LOW);
      digitalWrite(Left, LOW);
      digitalWrite(13, LOW);
    }

     }

With this code added, the sketch, takes the first value it recieves, for example L, and then would go on executing the if block for that particular value ONLY. Even if the valueschange, still the same code block gets repeated. If I reset the Arduino, using the reset button, again the first value it recieves it starts executing the conditions of the same value and not the rest of the sketch.
P.S- I have attached the capacitor between the pins 5v and RESET.
EDIT
I put ser.readline() in my python script and found that no matter what the script only sends S to the Arduino. Even if the other two conditions are being satisfied, only S is send, and then suddenly, either L or R will be sent and then thats it. No more sending from the script.
Here's my script-
import numpy as np
import cv2
import serial
ser = serial.Serial('COM3',9600,writeTimeout = 0)
def f(x): return
cv2.namedWindow('Thresholding Control')

# create trackbars for color change
cv2.createTrackbar('High H','Thresholding Control',179,179, f)
cv2.createTrackbar('Low H','Thresholding Control',0,179, f)
cv2.createTrackbar('High S','Thresholding Control',255,255, f)
cv2.createTrackbar('Low S','Thresholding Control',0,255, f)
cv2.createTrackbar('High V','Thresholding Control',255,255, f)
cv2.createTrackbar('Low V','Thresholding Control',0,255, f)
cv2.createTrackbar('Guassian Blur','Thresholding Control',0,99, f)

cap = cv2.VideoCapture(0)
while(True):
  ret, image = cap.read()
  HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  # Getting trackbar values
  highH = cv2.getTrackbarPos('High H','Thresholding Control')
  lowH = cv2.getTrackbarPos('Low H','Thresholding Control')
  highS = cv2.getTrackbarPos('High S','Thresholding Control')
  lowS = cv2.getTrackbarPos('Low S','Thresholding Control')
  highV = cv2.getTrackbarPos('High V','Thresholding Control')
  lowV = cv2.getTrackbarPos('Low V','Thresholding Control')
  # Thresholding the image.
  thresh = cv2.inRange( HSV, (lowH, lowS, lowV), (highH, highS, highV))
  blurVal = cv2.getTrackbarPos('Guassian Blur','Thresholding Control')
  if(blurVal%2==0):
      blurVal=blurVal+1
  thresh_smooth = cv2.GaussianBlur(thresh, (blurVal, blurVal), 0)
  #Defining the kernel to be used for Morphological ops.
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
  # Applying Opening and Closing.
  thresh_smooth = cv2.morphologyEx(thresh_smooth,cv2.MORPH_OPEN,kernel)
  thresh_smooth = cv2.morphologyEx(thresh_smooth, cv2.MORPH_CLOSE, kernel)

  #(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(thresh_smooth)
  eleR = np.count_nonzero(thresh_smooth[0:480, 320:550])
  eleL = np.count_nonzero(thresh_smooth[0:480, 0:320])
  eleO = np.count_nonzero(thresh_smooth[0:480, 550:640])
  if (eleL>eleR and eleL>eleO and eleL!= (eleR+eleO)):
     cv2.putText(image,"Left Turn", (320,240), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
     print ('L')
  elif (eleO>eleR and eleO>eleL):
     cv2.putText(image,"Right Turn", (240,320), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
     print ('R')
  else:
     cv2.putText(image,"Straight", (240,320), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
     print ('S')
  cv2.imshow("BGR", image)
  cv2.imshow("Thresholded", thresh_smooth)
  print ser.readline();
  if cv2.waitKey(1) & 0xFF == ord('q'):
        break
#cv2.imwrite('ImG.png', thresh_smooth)
cap.release()
cv2.destroyAllWindows()

One uses inByte and the other uses data? Also; are there any motors attached? Motors use a lot of current and can create a lot on electrical noise, which could make the Arduino freeze or reset.

@Gerben oh that's my fault, actually they are two different sketches I wrote, they are mostly identical except for variable names. Anyways, no there's only one motor attached.

Please post the actual entire sketch that you are having problems with.

How exactly are you updating the value received through serial? Also is the code exactly the same between Arduino sketches as I see you use a different variable to compare for the motor driver.

@Majenko post updated.

@RSM please see the entire code. Yes the sketches are different but very much identical except for variable names and a few things

Are you just being impatient and not waiting for the 2 second delays to expire before expecting it to look to see if there is an updated value? delay() is never a good idea.

@Majenko I wait. I mean once it receives its first value, it just keeps on iterating that code block. Even after quite sometime after the variable changes.

Have you tried adding some debugging (Serial.println()) to get some visual feedback about how your program flow is working?

@Majenko I removed the delay and the sketch responded. I got the motor to turn (L), stop(S) and run backwards (R) but it got stuck on R. Moreover I only got L as print output. Doing the same from the Serial Monitor works just fine.

Ok, then it's your python program that is at fault. Maybe you should show as that as well?

I don't suspect the python program. It runs the first script just fine.

@YaddyVirus    possibly post a link to the python code or put it here? Then people could possibly test it if need be.

@Majenko yes you were right... Most probably my python script is at fault. Posting it now

Okay I figured it out. Putting what I did here, for people who are curious and for those who need help.
It was probably the Arduino, autoresetoverserialcomm, for some reason the Arduino auto-resets whenever you send a value over the serial comm to the Arduino from a computer, not from the Serial port (obviously). I knew of this earlier, and another one of my script which also sends data to the Arduino was working fine with this setup.
What I did? I just put a 10µ capacitor between the RESET and the GND pins. That didn't work initially, but I tried putting the +ve of the capacitor in the GND pin and -ve in the RESET pin and voila! The script started working just fine.
I guess this wasn't a programming issue at all, but an issue of the Arduino and the script not being able to contact each other.
I still am not sure as to what was causing the problem or whether what I have done is a permanent fix, or even a fix at all, but my problem seems to have been solved. I'll keep updating the post.
Suggestions and discussions are always welcome!

You have got quite a bit of difference between the two codes.
In your first code you declare char inByte = ' '; at the beginning of void loop. This means that each time you run through the loop it clears the value which you assign the Serial value to.
In the second code you declare data as a global variable outside of loop.
What that means is that you first code basically allows a one-shot reaction to a Serial value because it clears the value at the beginning of loop. Thus it only goes into an if() statement once.
Whereas your second code will retain the value that it received at Serial.read() the first time. Thus it will continue to run the matching if statement.
What you could do is after each matched if() statement you do data = ' '; or at the beginning of loop you can clear it.
Also you might be missing the updates from your python script because of the delays during motor control. Also Gerben is correct about there possibly being issues with the motor drivers affecting the Arduino.

I tried putting the data = ' ' statement in all the possible places. Wherever I place it, the sketch stops working

3 things:
1: your delay statement is worrying, I'd highly recommend parallel coding in this case.
2: you don't have a "data = ' ';" statement in your loop function of the second code, but you do in the first. Is this intentional?
3: if your arduino receives Serial while executing Delay, you mustn't pour in more than the buffer.

I've removed the delay but that didn't help


text:
How can I use wifi to wirelessly communicate (and wirelessly code if possible) between multiple arduinos?
I am using arduino as the base for an accelerometer project - the end goal is to have multiple arduinos with accelerometer chips that can wirelessly start and stop collecting data and wirelessly send this data back to the "base" arduino (which will be connected to a computer).  Currently we have only two arduinos communicating to test a lot of this, and currently are using a bluetooth node to wirelessly code the accelerometer arduino and Rf nodes to wirelessly send the data back to the arduino connected to a computer which then prints the data it is collecting.  How could we replace this with a wifi network?

https://www.arduino.cc/en/Main/ArduinoBoardYun and https://www.arduino.cc/en/Tutorial/ArduinoISP

Sending data to a computer using WiFi is simple enough and there are plenty of examples. The simplest way is to set up a web server on the computer and use HTTP POST to send the data. There are "lighter" ways but entail more coding.
You won't do OTA updates on a normal Arduino. Yes, you could use a Yún, but they aren't always the best choice - the Linux side of things does make it a very "heavyweight* board.
You may be better off using an ESP8266 based system (not wired to an Arduino, but standalone) and programming it direct. Maybe a NodeMCU or something similar.  The Arduino core for ESP8266 supports OTA programming direct from the Arduino IDE.


text:
SoftwareSerial error:
Please help me with this library "Softwareserial". The basic sketch does not work. Please look the errors:
    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:128:2: error: #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors

 #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors

  ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'bool SoftwareSerial::listen()':

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:184:23: error: 'SREG' was not declared in this scope

     uint8_t oldSREG = SREG;

                       ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:185:9: error: 'cli' was not declared in this scope

     cli();

         ^

In file included from C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\cores\arduino/delay.h:27:0,

                 from C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\cores\arduino/Arduino.h:76,

                 from C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:43:

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'void SoftwareSerial::setTX(uint8_t)':

C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\variants\arduino_zero/variant.h:62:82: error: invalid conversion from 'PortGroup*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( &(PORT->Group[g_APinDescription[P].ulPort]) )

                                                                                ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:360:18: note: in expansion of macro 'digitalPinToPort'

   uint8_t port = digitalPinToPort(tx);

                  ^

C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\variants\arduino_zero/variant.h:65:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->OUT.reg) )

                                            ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:361:27: note: in expansion of macro 'portOutputRegister'

   _transmitPortRegister = portOutputRegister(port);

                           ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'void SoftwareSerial::setRX(uint8_t)':

C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\variants\arduino_zero/variant.h:62:82: error: invalid conversion from 'PortGroup*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( &(PORT->Group[g_APinDescription[P].ulPort]) )

                                                                                ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:371:18: note: in expansion of macro 'digitalPinToPort'

   uint8_t port = digitalPinToPort(rx);

                  ^

C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\variants\arduino_zero/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portInputRegister(port)    ( &(port->IN.reg) )

                                            ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:372:26: note: in expansion of macro 'portInputRegister'

   _receivePortRegister = portInputRegister(port);

                          ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'void SoftwareSerial::begin(long int)':

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:383:31: error: 'table' was not declared in this scope

   for (unsigned i=0; i<sizeof(table)/sizeof(table[0]); ++i)

                               ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:399:38: error: 'digitalPinToPCICR' was not declared in this scope

     if (digitalPinToPCICR(_receivePin))

                                      ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:401:78: error: 'digitalPinToPCICRbit' was not declared in this scope

       *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));

                                                                              ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:401:79: error: '_BV' was not declared in this scope

       *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));

                                                                               ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:402:37: error: 'digitalPinToPCMSK' was not declared in this scope

       *digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));

                                     ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:402:78: error: 'digitalPinToPCMSKbit' was not declared in this scope

       *digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));

                                                                              ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'void SoftwareSerial::end()':

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:417:36: error: 'digitalPinToPCMSK' was not declared in this scope

   if (digitalPinToPCMSK(_receivePin))

                                    ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:418:77: error: 'digitalPinToPCMSKbit' was not declared in this scope

     *digitalPinToPCMSK(_receivePin) &= ~_BV(digitalPinToPCMSKbit(_receivePin));

                                                                             ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:418:78: error: '_BV' was not declared in this scope

     *digitalPinToPCMSK(_receivePin) &= ~_BV(digitalPinToPCMSKbit(_receivePin));

                                                                              ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'virtual size_t SoftwareSerial::write(uint8_t)':

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:453:21: error: 'SREG' was not declared in this scope

   uint8_t oldSREG = SREG;

                     ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:454:7: error: 'cli' was not declared in this scope

   cli();  // turn off interrupts for a clean txmit

       ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:458:26: error: 'XMIT_START_ADJUSTMENT' was not declared in this scope

   tunedDelay(_tx_delay + XMIT_START_ADJUSTMENT);

                          ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'virtual void SoftwareSerial::flush()':

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:501:21: error: 'SREG' was not declared in this scope

   uint8_t oldSREG = SREG;

                     ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:502:7: error: 'cli' was not declared in this scope

   cli();

       ^
PLEASE HELP ME!

Welcome. This is a Q&A system and not a dump and answer forum. Also if you provide more info and about the board used and also bother formatting the code. The answer will be as simple as you have probably tried to use the library with a board that is no compatible.

This is impossible to answer without your code, and without knowing what board you are compiling for. Please read How do I ask a good question?.

You're trying to use the AVR SoftwareSerial library with an ARM based board. It won't work. Ever.
There should be no need to use SoftwareSerial - the SAMD chips have multiple UART channels - just use one of those.

Thanks, I understand what you mean. BTW one more question. What about Bluetooth which connecting to Arduino board.
I have this line in my code:
SoftwareSerial bluetooth(1,0); In this case, i use the softwareserial library, how then to be?


text:
Arduino for Weather and Air Monitoring: Casing and Power Source
I am intended to use Arduino to measure Temperature and Humidity (DTH11) and Gases Grove Sensor (Multichannel). Due to weather conditions in UK, I would to get your advice how to shield all of them in water proof box? Do you believe that using Polystyrene is useful?
Any recommended power source?

As this stands it is pretty opinion based and possibly broad. Aside, I wouldn't go with styrene stuff. Trying looking for weather station sensor enclosures(DIY route if need be)

The phrase you are looking for is "louvre box"

http://www.metoffice.gov.uk/guide/weather/observations-guide/how-we-measure-temperature

I'd say, use a IP-54 protection plastic case. The IP is a standard, that tells you, how big particles can(not) come into the case.
About powering, depends, how often can you go and switch batteries.
If you can, you can plug the cable in the case - drill the hole through and use watertight silicone plug to ensure, it is water resistant.
In case of batteries - use some LiPo batteries with DC-DC converter to minimum voltage.
Maybe you could even add a solar panel or two for addional life extension of batteries.


text:
Communication between two Arduinos over RF module
I want to communicate Arduino A to Arduino B by using RF module. But my RF module (Tx- XLPCF20, Rx- XY-R01A) only consist of 4 pins of data pin where it can send 4 bits of data only. So, I want to develop a new encoding to send data by using 4 bits of data. How should i do for the coding since I don't want to use serial write for coding. Any suggestion? Help me please. If u can give me the coding, I'm beyond thankful.

You have 4 channels of raw HIGH/LOW communication.  How you use them is up to you.
The simplest method is to use an asynchronous serial protocol:

Use Serial: Connect the TX of one Arduino to channel 1 at the TX, and RX channel 1 to RX on the other Arduino
Use SoftwareSerial: The same as above but you choose the pins
Use VirtualWire: very similar to SoftwareSerial

For higher speeds, since you have 4 channels, you could use a synchronous serial communication protocol. It should be perfectly possible to connect three of the channels to SPI and communicate as if it were talking directly to an SPI device - one channel to SCK, one to MOSI and one to SS. The other end has SCK, MOSI and SS but running in slave mode.
No need to "invent" a 4-bit protocol, it's too much work.


text:
Passing pointers between setup and loop
I'm new to the Arduino world. The last time i was programming microprocessors, was back with the Z80 in assembly language.
I am also teaching myself C++ and seems to be going quite well.
I have decided to write my own 'library' for driving 7 segment LED's. The reason for writing my own, rather then using an existing one is to aid with the learning process. I'm quite pleased to say it works ( it may not be the most efficient code)
The books I have on C++ are great, but i do find sometimes the explanation of concepts seem to get lost.
what I would like to know, how do you go about initialising an object class in setup() and using it in loop()? I have this sneaky suspicion that it involves creating the object on the heap, and passing a pointer to the object over somehow.
I could just initialise it once in loop(), and make my own continuous loop afterwards, but there are other things done between the and of a loop() and the beginning of the next loop() (things like timer interrupts).
I will post the code im using, but not the library unless asked to, as it is quite a few lines.
# include "Leddisplay.h"
void setup() {

    byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };

    Leddisplay *pRightDigit = new Leddisplay(Digit);

}

void loop() {

    pRightDigit->setDigit(5);
    pRightDigit->displayDigit();

}

^^  Obviously this does not compile  ^^
# include "Leddisplay.h"
void setup() {

}

void loop() {

    byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
    Leddisplay *pRightDigit = new Leddisplay(Digit);

    pRightDigit->setDigit(5);
    pRightDigit->displayDigit();

    for (;;);   // or do.. while within which has other code to repeat
                // but wont allow anything to be executed between loop() iterations

}

^^  This does, and runs fine, but may not achieve what I want  ^^
I'm not sure if I have used the right wording, or even asked the right question.
Thank you for any help in advance.
Dave

Declare the Leddisplay *pRightDigit variable outside of the scope of these functions and in the global space.

I know that's a scope question. But remember that setup(){} and loop(){} are an Arduino thing. You could do is leave setup(){} empty and do:
setup(){}  loop(){  int a = 0;  while(1)  {    a++;  } }

Timer interrupts aren't handled after the loop! The will interrupt the current loop code, wherever it currently is, run the ISR, and then return back to where it was in the loop. The only thing that is handled after the loop is, the arduino code check is there is any serial data available, and calls the function serialEvent if it is defined. If you aren't using this function (which is kind of silly anyways), you can use a for(;;;) or while(1) without any problems.

What you have to understand is the concept of scope.
Everything (well, almost everything) in C and C++ is enclosed in { and }. Those define a scope, and everything defined within that scope is available to any other scopes defined within that scope.
You can also assume that the whole sketch is surrounded by { and }. This scope is called the global scope.  Anything defined within it is available anywhere in your sketch.
So by defining the object in the global scope it is available everywhere:
# include "Leddisplay.h"

Leddisplay *pRightDigit;

void setup() {
    byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
    pRightDigit = new Leddisplay(Digit);
}

void loop() {
    pRightDigit->setDigit(5);
    pRightDigit->displayDigit();
}

However the use of new etc is discouraged in low-memory systems. Better is to statically define the object:
# include "Leddisplay.h"

const byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
Leddisplay pRightDigit(Digit);

void setup() {
}

void loop() {
    pRightDigit.setDigit(5);
    pRightDigit.displayDigit();
}

Note that, when statically defined like this, things in the constructor aren't guaranteed to be run at the right time. They should be moved into a .begin() function that you then call from setup():
# include "Leddisplay.h"

const byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
Leddisplay rightDigit(Digit);

void setup() {
    rightDigit.begin();
}

void loop() {
    rightDigit.setDigit(5);
    rightDigit.displayDigit();
}

The Library I have written can (and does) drive multiple led displays.
I also understand then when programming for ucontrollers, you use as little ram as possible.
Also, you usually know at compile time, what hardware is available,
However, say you only know how many displays there are at runtime. This is why I have created the LED display instance on the heap (I assume on the Arduino, thats RAM, not flash)
Let us say at runtime the program would ask you how many displays are connected via the serial terminal, then they will be activated, and a recompile is not an option.
Regards,
Dave

... how do you go about initialising an object class in setup() and using it in loop()?

You declare it in a global context so that it's accessible by both.
But that's not quite what you want here:
#include "Leddisplay.h"

byte Digit[] = {...};
Leddisplay RightDigit(Digit);

void setup() {
}

void loop() {
    RightDigit.setDigit(5);
    RightDigit.displayDigit();
}

Sorry, I cannot comment as I do not yet have enough rep.
This is in response to @Dave Dunnes comment

The Library I have written can (and does) drive multiple led displays.
  I also understand then when programming for ucontrollers, you use as
  little ram as possible. Also, you usually know at compile time, what
  hardware is available, However, say you only know how many displays
  there are at runtime. This is why I have created the LED display
  instance on the heap (I assume on the Arduino, thats RAM, not flash)
  Let us say at runtime the program would ask you how many displays are
  connected via the serial terminal, then they will be activated, and a
  recompile is not an option. Regards, Dave – Dave Dunne 9 hours ago

If you do not know the exact number of segments (or any element really) at build time then you could implement a linked list and dynamically allocate new  Leddisplay objects at run time or build the list in to your class. Alternatively you can try try using std::list with the AVR port of the STL (I have not personally tried this).