text:
Pass class's public function as an argument to external command
I am trying to write a library for encoders.
main.ino:
#include <./Encoders.h>

Encoders encoders();

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

void loop(){
    Serial.print("");
}

Encoders.h:
#ifndef Encoders_h
#define Encoders_h

#include "Arduino.h"

class Encoders{
    public:
        Encoders();
        void EncodersSetup();
        long RightCount;
        long LeftCount;
        void R_A_RISE();
        void R_A_FALL();
        void R_B_RISE();
        void R_B_FALL();
        void L_A_RISE();
        void L_A_FALL();
        void L_B_RISE();
        void L_B_FALL();
    private:
        short R_A_SIG, R_B_SIG, L_A_SIG, L_B_SIG;
};

#endif

Encoders.cpp
#include "Arduino.h"
#include "Encoders.h"

long RightCount;
long LeftCount;
long R_A_SIG, R_B_SIG, L_A_SIG, L_B_SIG;

Encoders::Encoders(){
    attachInterrupt(0, R_A_RISE, RISING);
    attachInterrupt(1, R_B_RISE, RISING);
    attachInterrupt(2, L_A_RISE, RISING);
    attachInterrupt(3, L_B_RISE, RISING);
    R_A_RISE();
}

void Encoders::R_A_RISE(){
    detachInterrupt(0);
    R_A_SIG = 1;
    if(R_B_SIG == 0){
        RightCount++;
    }
    if(R_B_SIG == 1){
        RightCount--;
    }
    attachInterrupt(0, R_A_FALL, FALLING);
}
void Encoders::R_A_FALL(){
    detachInterrupt(0);
    R_A_SIG = 0;
    if(R_B_SIG == 1){
        RightCount++;
    }
    if(R_B_SIG == 0){
        RightCount--;
    }
    attachInterrupt(0, R_A_RISE, RISING);
}
void Encoders::R_B_RISE(){
    detachInterrupt(1);
    R_B_SIG = 1;
    if(R_A_SIG == 1){
        RightCount++;
    }
    if(R_A_SIG == 0){
        RightCount--;
    }
    attachInterrupt(1, R_B_FALL, FALLING);
}
void Encoders::R_B_FALL(){
    detachInterrupt(1);
    R_B_SIG = 0;
    if(R_A_SIG == 0){
        RightCount++;
    }
    if(R_A_SIG == 1){
        RightCount--;
    }
    attachInterrupt(1, R_B_RISE, RISING);
}
void Encoders::L_A_RISE(){
    detachInterrupt(2);
    L_A_SIG = 1;
    if(L_B_SIG == 0){
        LeftCount++;
    }
    if(L_B_SIG == 1){
        LeftCount--;
    }
    attachInterrupt(2, L_A_FALL, FALLING);
}
void Encoders::L_A_FALL(){
    detachInterrupt(2);
    L_A_SIG = 0;
    if(L_B_SIG == 1){
        LeftCount++;
        }
    if(L_B_SIG == 0){
        LeftCount--;
        }
    attachInterrupt(2, L_A_RISE, RISING);
}
void Encoders::L_B_RISE(){
    detachInterrupt(3);
    L_B_SIG = 1;
    if(L_A_SIG == 1){
        LeftCount++;
    }
    if(L_A_SIG == 0){
        LeftCount--;
    }
    attachInterrupt(3, L_B_FALL, FALLING);
}
void Encoders::L_B_FALL(){
    detachInterrupt(3);
    L_B_SIG = 0;
    if(L_A_SIG == 0){
        LeftCount++;
    }
    if(L_A_SIG == 1){
        LeftCount--;
    }
    attachInterrupt(3, L_B_RISE, RISING);
}

When I try to compile this, I get errors like this:
C:/Users/marcel/Documents/dev/Arduino/encodeurs/Encoders.cpp:10:38: error: cannot convert 'Encoders::R_B_RISE' from type 'void (Encoders::)()' to type 'void (*)()'

I tried answers on other threads. Most said to make the functions passed to attachInterrupt() static. That threw different errors:
C:/Users/marcel/Documents/dev/Arduino/encodeurs/Encoders.cpp:16:33: error: cannot declare member function 'void Encoders::R_A_RISE()' to have static linkage [-fpermissive]

I also tried this:
attachInterrupt(0, &Encoders::R_A_RISE, this, RISING);

with no success.
The Arduino in question is a Mega but I doubt that matters.
Edit: Per Nick Gammon's answer, I now have this.
MotorEncoderMaster.ino
#include </home/marcel/dev/Arduino/encoders/MotorEncoderMaster/Encoders.h>
Encoders * Encoders::instances [2] = { NULL, NULL };

// instances of our class
Encoders right;
Encoders left;

void setup (){
    right.begin (2);   // pin D2
    left.begin (3);   // pin D3
}  // end of setup

void loop (){
    // whatever
}  // end of loop

Encoders.h:
class Encoders{
    volatile bool switchChanged;

    static Encoders * instances [2];

    static void switchPressedExt0(){
        if(Encoders::instances [0] != NULL){
            Encoders::instances [0]->switchPressed();
        }
    }

    static void switchPressedExt1 (){
        if (Encoders::instances [1] != NULL){
            Encoders::instances [1]->switchPressed();
        }
    }

    public:
        void begin (const int whichPin){
            pinMode (whichPin, INPUT_PULLUP);
            switch (whichPin){
                case 2:
                    attachInterrupt(0, switchPressedExt0, CHANGE);
                    instances [0] = this;
                    break;

                case 3:
                    attachInterrupt(1, switchPressedExt1, CHANGE);
                    instances [1] = this;
                    break;

            }
        }

        void switchPressed(){
            switchChanged = true;
        }

};

When I try to compile this, I get :
In file included from MotorEncoderMaster.ino:1:0:
/home/marcel/dev/Arduino/encoders/Encoders.h: In static member function ‘static void Encoders::switchPressedExt0()’:
/home/marcel/dev/Arduino/encoders/Encoders.h:7:34: error: ‘NULL’ was not declared in this scope
    if(Encoders::instances [0] != NULL){
                                  ^
/home/marcel/dev/Arduino/encoders/Encoders.h: In static member function ‘static void Encoders::switchPressedExt1()’:
/home/marcel/dev/Arduino/encoders/Encoders.h:13:35: error: ‘NULL’ was not declared in this scope
    if (Encoders::instances [1] != NULL){
                                   ^
/home/marcel/dev/Arduino/encoders/Encoders.h: In member function ‘void Encoders::begin(int)’:
/home/marcel/dev/Arduino/encoders/Encoders.h:21:24: error: ‘INPUT_PULLUP’ was not declared in this scope
     pinMode (whichPin, INPUT_PULLUP);
                        ^
/home/marcel/dev/Arduino/encoders/Encoders.h:21:36: error: ‘pinMode’ was not declared in this scope
     pinMode (whichPin, INPUT_PULLUP);
                                    ^
/home/marcel/dev/Arduino/encoders/Encoders.h:24:45: error: ‘CHANGE’ was not declared in this scope
       attachInterrupt(0, switchPressedExt0, CHANGE);
                                             ^
/home/marcel/dev/Arduino/encoders/Encoders.h:24:51: error: ‘attachInterrupt’ was not declared in this scope
       attachInterrupt(0, switchPressedExt0, CHANGE);
                                                   ^

Interrupt Service Routine (ISR) outside a class
Let's consider a simple use of interrupts:
volatile bool switchChanged;

void switchPressed ()
  {
  switchChanged = true;
  }  // end of switchPressed

void setup ()
  {
  pinMode (2, INPUT_PULLUP);
  attachInterrupt (0, switchPressed, CHANGE);
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

That compiles fine.

ISR inside a class as a class function (method)
Now let's imagine we want to put the interrupt handling into a class for our convenience.
class myClass
  {
  volatile bool switchChanged;

  public:

  void begin ()
    {
    pinMode (2, INPUT_PULLUP);
    attachInterrupt (0, switchPressed, CHANGE);   // <--- line 10
    }  // end of myClass::begin

  void switchPressed ()
    {
    switchChanged = true;
    }  // end of myClass::switchPressed

  };  // end of class myClass

myClass foo;  // make an instance of myClass

void setup ()
  {
  foo.begin ();
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

That does not compile:
ISR_in_class_test.ino: In member function ‘void myClass::begin()’:
ISR_in_class_test:10: error: argument of type ‘void (myClass::)()’ does not match ‘void (*)()’

What is going on here?
ISRs have to be static functions, taking no arguments. However (non-static) class functions have an implied this-> pointer which points to the particular instance of the class.
For example, if we have two instances:
myClass foo;
myClass bar;

If we call foo.begin() then this-> points to "foo", and if we call bar.begin then this-> points to "bar".
However an ISR, when fired by the processor, cannot know whether this-> is "foo" or "bar" or something else. Thus the compiler cannot compile that line.

ISR inside a class as a static class function
We can try to work around this by making the class function static. Doing that means that the function is not tied to any particular instance, and thus the attachInterrupt line will compile.
class myClass
  {
  volatile bool switchChanged;   // <--- line 3

  public:

  void begin ()
    {
    pinMode (2, INPUT_PULLUP);
    attachInterrupt (0, switchPressed, CHANGE);
    }  // end of myClass::begin

  static void switchPressed ()
    {
    switchChanged = true;   // <--- line 15
    }  // end of myClass::switchPressed

  };  // end of class myClass

myClass foo;  // make an instance of myClass

void setup ()
  {
  foo.begin ();
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

However now we have a different problem:
ISR_in_class_test.ino: In static member function ‘static void myClass::switchPressed()’:
ISR_in_class_test:3: error: invalid use of member ‘myClass::switchChanged’ in static member function
ISR_in_class_test:15: error: from this location

A non-static class variable cannot be called from a static class function. Why? Because the compiler doesn't know which variable you want. Is it foo.switchChanged or bar.switchChanged?

ISR inside a class as a static class function with static variables
To make the static function work, it can only access static variables. So we can make switchChanged static. Plus we need to define an instance of this static variable.
class myClass
  {
  static volatile bool switchChanged;  // declare

  public:

  void begin ()
    {
    pinMode (2, INPUT_PULLUP);
    attachInterrupt (0, switchPressed, CHANGE);
    }  // end of myClass::begin

  static void switchPressed ()
    {
    switchChanged = true;
    }  // end of myClass::switchPressed

  };  // end of class myClass

volatile bool myClass::switchChanged;  // define

myClass foo;  // make an instance of myClass

void setup ()
  {
  foo.begin ();
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

Now the class compiles. However we have thrown away most of the advantages of having a class in the first place, as we are forced to use a static function, and that static function can only access static variables.

Glue routines
To work around this problem we can write short "glue" routines. These are functions that interface between an ISR and an instance of a class.
class myClass
  {
  volatile bool switchChanged;

  static myClass * instances [2];

  static void switchPressedExt0 ()
    {
    if (myClass::instances [0] != NULL)
      myClass::instances [0]->switchPressed ();
    }  // end of myClass::switchPressedExt0

  static void switchPressedExt1 ()
    {
    if (myClass::instances [1] != NULL)
      myClass::instances [1]->switchPressed ();
    }  // end of myClass::switchPressedExt1

  public:

  void begin (const byte whichPin)
    {
    pinMode (whichPin, INPUT_PULLUP);
    switch (whichPin)
      {
      case 2:
        attachInterrupt (0, switchPressedExt0, CHANGE);
        instances [0] = this;
        break;

      case 3:
        attachInterrupt (1, switchPressedExt1, CHANGE);
        instances [1] = this;
        break;

      } // end of switch
    }  // end of myClass::begin

  void switchPressed ()
    {
    switchChanged = true;
    }

  };  // end of class myClass

myClass * myClass::instances [2] = { NULL, NULL };

// instances of our class
myClass foo;
myClass bar;

void setup ()
  {
  foo.begin (2);   // pin D2
  bar.begin (3);   // pin D3
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

This is a bit fiddly, however what it is doing is remembering in an array which instance of the class is associated with which interrupt. The "glue" routines switchPressedExt0 and switchPressedExt1 call the appropriate instance of the switchPressed function by using the remembered class pointer.
Now the non-static function switchPressed can access non-static class variables.

Adapted from my web page Calling an ISR from a class

The whole point of this was to break my code into multiple files. When I put the class declaration in a different file and #include it, I get this error: http://pastebin.com/TkBCG74G. Is there a way to declare the class in another file and not break everything?

Of course. However not seeing your code it is hard to advise.

Code: https://bitbucket.org/MarcelRobitaille/encoders/

See my reply here Classes and objects: how many and which file types do I actually need to use them? - you don't need to include .ino files - the IDE does that for you (if they are in the same folder). Also don't call your files "main.xxx".

Rename your file Encoders.ino to be Encoders.h and include that into your main file. Rename your main file to be something other than main.ino. Then it compiles.

Still not compiling: http://pastebin.com/g2c5NQ6S

What is still not compiling? We seem to be jumping from error messages, to code. The fact is, that I got it to compile. Therefore you are doing something different from me.

Could you send me your files so I know if it's my code or my compiler? Thanks.

Rather than having me send you files (which other readers won't see) please amend your original question to show what your code is now, exactly, including file names. Then post the error message underneath, rather than having it in Pastebin somewhere.

Is that what you meant or should I remove what I used to have?

That's fine - I wasn't sure whether to suggest editing the original or not. It would have been in the edit history. Anyway, give me a minute to look at it.

Why don't you have #include "Encoders.h" - instead of that huge include statement? - Is that not in the same folder?

I changed that include line to what I suggested: #include "Encoders.h" and it compiled fine under IDE 1.6.7. Just those two files.

what do you know. It worked in 1.6.7. I had to use my windows laptop. Unfortunately I can't easily get 1.6.7 on my main pc because the linux package repo is behind. Anyway I am rambling. Thanks for all your help!

I just download the Linux package onto my Ubuntu and run from that (my test was on Ubuntu). You don't need to wait for the package to be updated.

@NickGammon: why don't you use as ISR a friend function, paired to a reference to the class instance? The reference can be a static field in the class itself. I would find it much more expressive.

@IgorStoppa - can you give an example somewhere? There are probably other ways of achieving this, but the method I showed was integrated into the class. I don't see how using a friend gets around needing to know which instance of the class the interrupt is for.

@NickGammon: I meant that the class does have a static pointer to an instance of itself. This cannot be avoided. But the friend function could be the ISR itself. It would get away with one level of indirection (you called it "the glue"). If it's not clear what I mean, where could i put a snippet of code?

Er, yes but the ISR won't know which class instance to call? You can make your own answer with your alternative example. :)

Isn't this solution the equivalent of using named static functions for every possible pin?

Yes, effectively. There is no easy workaround, except to make static functions for each pin, one way or the other.


text:
Raspberry Pi Arduino Installer broken
I am tring to use ShorTie8's new arduino ARM installer on my RPI B+ by copying this into my terminal:

cd
sudo apt-get update -y && sudo apt-get dist-upgrade -y
wget https://raw.githubusercontent.com/ShorTie8/Arduino_IDE/master/Arduino_IDE_builder.bash
chmod +x Arduino_IDE_builder.bash
sudo ./Arduino_IDE_builder.bash
sudo Arduino/build/linux/work/./arduino
sudo Arduino/build/linux/work/./install.sh
sudo apt-get install -y mercurial subversion build-essential gperf bison ant texinfo zip automake flex libusb-dev libusb-1.0-0-dev libtinfo-dev pkg-config libwxbase3.0-dev libtools

But Getting The following Error at sudo ./Arduino_IDE_builder.bash

echo -e '\n\nConfiguration values\n\n'

Configuration values

Stable=1.6.7
Update_me=yes
Silence_is_Golden=yes
echo -e '\n\nSystem check\n\n'

System check
++ date
  + start_time='Sat 13 Feb 11:12:37 GMT 2016'
  ++ pwd
  + Start_Directory=/home/pi
  ++ pwd
  + Working_Directory=/home/pi/Arduino/build
  + echo -e '\n\nChecking for root .. \n'
Checking for root ..
++ id -u
  + '[' 0 '!=' 0 ']'
  + echo 'Yuppers .. :)~'
  Yuppers .. :)~
  + [[ yes == \y\e\s ]]
  + echo -e '\n\nChecking to see if I'\''m update\n'
Checking to see if I'm update

git remote update
  fatal: Not a git repository (or any of the parent directories): .git

Instead of manually downloading a file from the github repository, check out the repository properly with git clone 《repository》

It is a bash script. How can I edit it without messing up?

Pardon? Who said anything about editing anything? Just clone the github repository like you would with any other github repository. Delete your current bash script, you don't want it.

source: Stack Exchange

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

sort: votes


text:
Arduino and hard drive
So in a laptop you have a CPU and a hard drive. The hard drive feeds data to the CPU and the CPU executes it. In Arduino you flash the CPU and the "hard drive" is built into it. Is it possible to have a hard drive or SD card feed data into the Arduino to be executed and then feed more data in and so on? If it is possible how is it done?

Is it possible to have a harddrive or sd card feed data into the Arduino to be executed and then feed more data in and so on. If it is possible how is it done?

A harddrive would be difficult to connect, but an SD card will work just fine.
You can write a sketch that reads data from an SD card. There is library support for both SD and FAT16/32 file systems.
Another interpretation of your question is; is it possible to load a sketch from an SD card. The answer is yes; there are a number of projects that have done that.
Cheers!

will loading sketches take long and will it reduce the lifespan of the chip?

Depends on how often you want to update the sketch? It is not a very good idea to load the sketch from SD every time. There should be some logic to when the sketch is updated and should be loaded.

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


text:
Dimmer on Due: digitalWrite on one pin affects digital value of another
I'm trying to make dimmer for heater using Arduino Due. I'm using a variant of this very common scheme:
My scheme has MOC3043 with zero-crossing detection.
I use two pins to control the dimmer: detectorPin to analyse input voltage wave and controlPin to drive optocoupler. The program is very simple thanks to zero-crossing MOC.
I attached an interrupt to the input detectorPin on CHANGE event. And controlPin is used as digital output. When I test detection with controlPin unplugged everything works fine. But when controlPin is connected, value which is read inside the interrupt becomes wrong! So my dimmer cannot detect any half-wave and reports errors. This happens at the moment when controlPin value is set to HIGH with help of digitalWrite() func. After nearly 40-50 milliseconds detected values go back to normal, so most of time my dimmer work as expected.
I measured current on the controlPin, it's only 3.2mA, which is lower than maximum possible current for Arduino Due.
I tested this with detectorPin = 51, and different controlPins: 52, 36, 31.
So, how do you think, what is the problem? Is my Arduino broken?

What happens if you remove the traic (T1)? Do you still get the error?

What is the mode of the control pin ? INPUT or INPUT_PULLUP? And the I/O circuits have common ground with your Due, right?

@Gerben, I don't know, I will check.

@JanHus, mode is INPUT, there is external 10k pullup. Yes, right, circuits are attached to one of GND pins on Arduino.

The problem with wrong input was caused by floating base of optocoupler:

100k pull-down will fix it.

There are a few issues with your circuit.
First, you need to add a diode to your 4N25 circuit. See EDIT below.     You should still put a diode across your 4N25 LED.  Right now, your 4N25 diode (LED) gets a high voltage across it 1/2 of the time.  Because you have 60K (30K+30K) in the circuit, the LED is likely not damaged, however the LED isn't really designed to handle reverse voltage more than 6 volts. Depending upon the reverse characteristics of the Bridge diodes (leakage current), your 4N25 LED could be experiencing greater than 6 volts.  Using devices beyond their "maximum specification" can produce unusual side effects.
Place the new diode (1N4007 is good, almost any diode will work) across the LED on your 4N25. Wire the new diode with new diode anode to the LEd cathode. Now, the LED will turn on during 1/2 cycle of the AC,  and be protected against overvoltage during the other half of the cycle.
Second,  rearrange your circuit for the Triac.  The data sheet for your MOC3043 triac driver shows a typical schematic.

Notice the 39 ohm resistor and the 0.01 uf capacitor in the circuit.  This is called a snubber and will reduce interference and voltage spikes. This type of interference is famous for disrupting low voltage circuits such as micro-controllers.
Without seeing your code, I can't say much on that.  However, I presume that you are trying to detect the zero cross, and then waiting a certain amount of time AFTER the zero cross to turn on the Triac.

I measured current on the controlPin, it's only 3.2mA

Your 3.2mA may not be enough to drive the LED in your dimmer circuit. You will likely need 10mA to assure proper operation.  You can reduce the resistor to achieve higher current to the MOC3043.
EDIT  :  I just realized that your bridge rectifier protects the LED (4N25) from reverse voltage.

Hi, thanks! First of all, this is not my scheme, I have different resistors and bridge, this is just example image from the internet. Second – all your notes are not concerned with problem in question. And I know that current is too low, I write this information to emphasize that there is no overcurrent through the pin.


text:
Timer/Counter programming Arduino
I'm trying to blink an LED on an ATMega328P (same MCU as Arduino I think..) using the internal timer but I'm stuck since it doesn't seem to light the LED at all....
#include <avr/io.h>
//#include <avr/delay.h>

void delay(void);

void delay_long(void);

int main(void) {

  DDRB = 0xFF;                   // port B is configured as output   DDRB : 0b11111111
  DDRB &= ~(1<<PB1);             // pin 1 of port B is configured as input  DDRB : 0b11111101
  PORTB = 0x00;                  // pins of port B are low (output) and with no pull-up resistor (input)
  PORTB |= (1<<PB0)|(1<<PB1);    // pin 0 is high (output) and pin 1 is pulled high (input)    PORTB : 0b00000011

  while(1) {
    PORTB &= ~(1<<PB0);
    delay();
    PORTB |= 1<<PB0;
    delay();
    PORTB = ~(1<<PB0);
    delay_long();
    PORTB = 1<<PB0;
    delay_long();
  }

  return 1;

}

void delay(void) {
  TCNT0 = 0x00;
  TCCR0B = 0x05;
  while ( (TIFR0 & TOV0) == 0 )
    ;
  TCCR0B = 0x00;
  TIFR0 |= 1<<TOV0;
}

void delay_long(void) {
  TCNT0 = 0x00;
  TCCR0B = 0x05;
  while ( (TIFR0 & TOV0) == 0 )
    ;
  TCCR0B = 0x00;
  TIFR0 |= 1<<TOV0;
  TCCR0B = 0x05;
  while ( (TIFR0 & TOV0) == 0 )
    ;
  TCCR0B = 0x00;
  TIFR0 |= 1<<TOV0;
}

if I remove the body of the event loop it lights up... so I think I must be missing something in the delay functions...

This looks like an AVR question. You are not using the Arduino core functions (that actually abstract what you are trying to do). In any case you are missing some of the timer configuration.

It seems that the offending line is:
while ( (TIFR0 & TOV0) == 0 )

TOV0 by itself equals 0, so the above loop will never end.
You should use:
 while ( (TIFR0 & (1<<TOV0)) == 0 )

instead.


text:
Is the Uno Vin pin protected by the voltage regulator?
I guess it's all in the title. When using Vin as input, does it go through voltage regulator, or must I feed it precisely 5V?

If you look at the schematic you'll see Vin is connected to the input of the voltage regulator. Just like the barrel-jack (except for the diode).
So the same input-voltage of    7-12V applies to Vin.

Actually because of the lack of the diode the lower bound for the input voltage is slightly lower. I am not sure on the specs of the diode they use, but it could be as low as 6.3v.

@Majenko the limit is 6-20V (according to the website), so it could be even lower.

when you connect you regulated 5V at Vin port your 5V output will be lower than 5V as it have to pass through the 5V regulator. The input voltage should range from 7-12V.


text:
Error uploading to ATtiny
I followed Great Scott's video on YouTube for uploading to an ATtiny85. When I tried I got the following error messages:

Arduino: 1.6.7 (Windows Vista), Board: "ATtiny85 (internal 8 MHz clock)"
Board attiny-master:attiny:attiny85-20 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY85-20
Board attiny-master:attiny:attiny45-8 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY45-8
Board attiny-master:attiny:attiny85-8 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY85-8
Board attiny-master:attiny:attiny44 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY44

etc. etc. ...

exec: "-w": executable file not found in %PATH%
Error compiling.`
This report would have more information with
"Show verbose output during compilation"
enabled in File > Preferences.

When I unplug  my ATtiny85 and restart Arduino, I have no problems uploading, though I get about 8 error messages saying something like:

Board attiny-master:attiny:attiny84 doesn't define a 'build.board' preference. Auto-set to: ATTINY_ATTINY84

Please edit question and add a link to whatever video you mean, and a link to the file you downloaded to set up boards.txt for those processors.

It's likely that a compiler's file name is missing from a command line the IDE is trying to execute.  To find out more about what the command looks like (which will let you figure out what name is missing), turn on verbose output during compilation.  That is, click File, Preferences in the IDE, then click the box in front of “compilation”.  After you find out what's missing, you can then turn off verbose output and fix platform.txt, which is the file the IDE looks at to find out what commands to execute when compiling sketches.
To get rid of the warnings about undefined build.board values, add lines like the following to the boards.txt file in the tiny/avr/ directory (or whereever you installed it).  (Your 1.6 IDE wants build.board definitions, which IIRC weren't needed by 1.5 and earlier IDEs.)
attiny85-20.build.board=ATTINY_ATTINY85-20

Each of the lines you add will contain the Auto-set value, prefaced by a string made up of a board-type and .build.board= concatenated together.  Add each line just before or after other .build.-containing lines.


text:
BLE Python with GUI on OSX
Has anyone connected BLE devices with Python + GUI on OSX? I've looked into a few libraries (most are old), but one that has the most success if Adafruit's BlueFruit library. However, this library works poorly with GUI's since it requires use of the main event loop (which GUI's usually use). After doing a bunch of Google searches, I couldn't find any good examples of using a GUI with Python + BLE. There seems to be no good BLE libraries for Python either.
Specifically looking for help integrating BLE with Kivy, but other GUI toolkit examples should be fine.
Also trying to gauge interest in this to see if I can do development to solve this (if it really is a problem).

I'm voting to close this question as off-topic because it is not about Arduino but rather desktop GUI software for OSX.  Perhaps you can solve your difficulty using multiple threads (or programs) and pipes or mailboxes between.

If you are still searching for a lib check out:
https://github.com/adafruit/Adafruit_Python_BluefruitLE
Its specifically made for BLE communication on OS X or Linux by wrapping the corebluetooth and its Linux equivalent bluez in a python lib. Windows is not supported at this moment.
Unfortunately there is no documentation to it. You will have to read the examples and search for specific functions in the lib manually.


text:
Convert UNIX Timestamp
I have an UNIX Timestamp in my Arduino Sketch and would like to get the day of the week of this timestamp (1-7).
How can I convert the timestamp to get the day of the week?

Do you mean, your program will be given a UNIX Timestamp number as data and should produce a day-of-the-week number?  Or that you have a timestamp number and want to know its day-of-the-week number?  If the latter, the Unix date command can tell you, via format code +%u.  Eg, if date +%s says 1455407637 (for Sat Feb 13 16:53:57 MST 2016), date -d@1455407637 +%u says 6.

The simplest solution to that problem is to download the Time library and use the weekday() function:
int weekday(time_t t); // the weekday for the given time

Cheers!

One caveat, the breakTime() code at line 168 of Time.cpp computes Wday = (t/(60*60*24) + 4) % 7) + 1, ie, it apparently ignores leap seconds [26 in number since 1972] so for 26 seconds before every midnight the day-of-the-week calc will be off by 1.

Ignore previous comment.  As noted in wikipedia's Unix time article, Unix timestamps don't count leap seconds, so they are locally correct and calculations near midnight will be ok, except during a leap second itself.  Also see Eric Raymond's Time, Clock, and Calendar Programming In C article, and the article Unix leap seconds.

UNIX timestamps are also kept in GMT/UTC time.  So you may run into problems with it being some hours out.  If so look to the functions gmtime() Vs locatime().  You may need to set your time-zone.  Oh and watch out for daylight savings time if it matters for your project.


text:
Distance sensor
I am adding a distance sensor to existing project that uses Arduino due, do I connect the trigger pin and the echo pin of the HC-SR04 ultrasonic sensor directly to  Arduino due which uses 3.3V   while HC-SR04 ultrasonic sensor uses 5V or do I need to use a voltage divider?

Could you tell us a bit more about the thickness sensor?

Reading the datasheet for the sensor will get you the output voltage range of the sensor.

@user17339 Thank you for adding information about what sensor you were writing about.

@Avamander I was just advising OP to read the sensor datasheet.

@ChetanBhargava I mixed up the @.

As suggested in previous answers, you can directly use a Due output to drive the HC-SR04's Trig pin; according to the HC-SR04 spec sheet, that pin operates at TTL levels.  It will see 0 V as a 0-input and will see 3.3 V as a 1-input since it exceeds 2.4 V.  Also see  3.3v input to Arduino digital pin in electronics.stackexchange.
However, the Due's inputs are not 5 V tolerant, so you will need to use a voltage divider between the Echo pin and a Due input.  See second paragraph of arduino.cc's ArduinoBoardDue article:

Warning: Unlike most Arduino boards, the Arduino Due board runs at 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. Applying voltages higher than 3.3V to any I/O pin could damage the board.

Well, it depends on the sensor itself. Some sensors run on both 5V and 3.3V. There's a similar question here on StackExchange: How to connect 5V sensors to 3.3V digital input (Due)?
But, in short, if the sensor can't operate in 3.3V, you'll need a level converter /shifter.

The trigger pin is an input, so you can connect that directly to the Due.
The echo pin will however output 5v. You could use a voltage divider to bring that down to 3.3v or a bit lower.


text:
Is it possible to upload previously compiled binary?
I have a number of sketches that I keep wanting to load into the Arduino but I don't necessarily need to recompile them because I haven't changed anything since the last compile. Since the compile takes a minute or 2 each time, this would save me some waiting.
I can see that the IDE has the option to "Export Compiled Binary", but doesn't seem to have the converse option of Uploading a previously compiled binary. Is there any way to do this?

Arduino 1.8.10 is using upload.py

@FallenDragon. it is not. only the esp8266 arduino boards package has upload.py

Yes!
Its possible that you can upload a previously complied binary, using
AVRDUDE - a command line utility which is actually used to upload binaries, behind the arduino IDE.
You can find AVRDUDE in
Arduino folder > hardware  > tools > avr > bin
This some documentation for AVRDUDE
http://www.nongnu.org/avrdude/user-manual/avrdude.html
else simplest thing you can do is turn on verbose output during upload and watch for a command in the end with AVRDUDE in it along with the path of hex file, just copy paste &  run the same command in CommandLine; your task is accomplished.

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


text:
Why need a delay between readings?
When I learn the tutorial in

Analog Read Serial
Digital Read Serial

both of the code examples have a line of code of delay(1) and I cannot understand the comments clearly:
 delay(1);        // delay in between reads for stability

The stability for/of what?

Cross-posted to Arduino Forum.

yes,  i was afraid that no one will answer  my question, since i think there is no much active user as much as Stack Exchange.
Sorry!

You can't have been too afraid, as you posted the questions within an hour of each other. Maybe cross-post if a day or two elapsed with no answers. The Arduino Forum has quite a fast response to questions. You got a response there 8 minutes after posting. And another one 5 minutes later. So I don't quite believe this "fear" of yours.

sorry，it is my fault， i wont do it again

Those delays are nonsense. They don't add to the stability of anything. The best you could say is that they stop you spamming your serial port. (However 1 ms is not very long).
Sometimes people throw in a delay because "it seems to work better" without examining the underlying cause. I would speculate that in this case the author may have been using delays to improve receiving serial data, and got the idea into their head that the occasional delay now and then "improves stability".

Analog Stability
From the Datasheet of ATMEGA328 Page 240:
When the bandgap reference voltage is used as input to the ADC, it will take a certain time for the voltage to stabilize. If not stabilized, the first value read after the first conversion may be wrong.
So if you are doing multiple reads, you need to wait a few cycles.
Delays are not required when using auto-triggering:
When Auto Triggering is used, the prescaler is reset when the trigger event occurs. This assures a fixed delay from the trigger event to the start of conversion. In this mode, the sample-and-hold takes place two ADC clock cycles after the rising edge on the trigger source signal. Three additional CPU clock cycles are used for synchronization logic.
Also if reading different channels of the same ADC module, you need to provide a delay between the reads so that the analog MUX is positioned and the S&H capacitor is charged.
This information is from hardware perspective and I'm not sure if Arduino internal ADC routines compensate for those delays.
Digital Stability
From the digital read tutorial schmatic:

In the schematic, the push button is not electrically de-bounced. A delay in reading states would help de-bounce it in software.
As Nick Gammon suggested, they also improve serial flooding.


text:
Arduino how to get amount of elements in an array?
Hello  have an array of strings that loads strings from a txt file on an sd card.
The txt file on the SD card can change from time to time(not while the Arduino is running).I want to be able to get the amount of elements in the array after the txt file has been loaded into the array. The txt file has lines of txt in it. Each line in the file is put into a string in the array. I want to be able to get the amount of elements in the array how can I do this?

This is your third post on basically the same subject. If I attempt to "read-between-the-lines" you are trying to implement a simple shell. You need to rethink how command lines are entered. It is not a very good idea to read the whole file into a vector of strings. Even worse is using the String class. Cheers!

You can't. That concept does not exist in C.
An array has a fixed size - as such you know how many elements are in it, since that is the number of elements you created it with.
String myStrings[4];

That is an array of 4 String objects. It has 4 elements. It will always have 4 elements.

so could I set the array size to say 400 and only load 100  lines of text?

If you have the memory to store that kind of thing.

numElements = (sizeof(array) / sizeof(array[0]));

This is not working for String array.

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


text:
Writing not permitted on genuino 101 Built in Bluetooth LE (phonegap)
I have a Genuino 101 which has a built in Bluetooth LE module. I have been trying to connect this to my phone using phonegap. I have been using cordova-plugin-bluetootle and with it I have been able to receive data from the arduino and display that data on the phone.
I tired adapting it so that I could send data from the phone to the arduino. I noticed in the CurieBle examples there was a project called "Callback LED" but when I connected to the Arduino from the Phone gap app I noticed in the debug message about characteristics it said "properties":{"notify": true, "read": true} but nothing about write. I tried writing "Hello world" (converted into bytes then encoded string) I got an error similar to (I couldn't copy it exactly as it was an alert on the phone): "error": "write", "message": "Error Domain=CBATTErrorDomain Code = 3 \"Writing is not permitted.\" ..."...There is more detail to the error message that is not at all relevant and is slightly repetitive.
Here is the arduino code (which is almost straight from the example):
#include <CurieBle.h>

const int ledPin = 13; // set ledPin to use on-board LED
BLEPeripheral blePeripheral; // create peripheral instance

BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // create service

// create switch characteristic and allow remote device to read and write
BLECharCharacteristic switchChar("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT); // use the LED on pin 13 as an output
  digitalWrite(ledPin, HIGH);
  while(!Serial);
  digitalWrite(ledPin, LOW);
  // set the local name peripheral advertises
  blePeripheral.setLocalName("LEDCB");
  // set the UUID for the service this peripheral advertises
  blePeripheral.setAdvertisedServiceUuid(ledService.uuid());

  // add service and characteristic
  blePeripheral.addAttribute(ledService);
  blePeripheral.addAttribute(switchChar);

  // assign event handlers for connected, disconnected to peripheral
  blePeripheral.setEventHandler(BLEConnected, blePeripheralConnectHandler);
  blePeripheral.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);

  // assign event handlers for characteristic
  switchChar.setEventHandler(BLEWritten, switchCharacteristicWritten);
// set an initial value for the characteristic
  switchChar.setValue(0);

  // advertise the service
  blePeripheral.begin();
  Serial.println(("Bluetooth device active, waiting for connections..."));
}

void loop() {
  // poll peripheral
  blePeripheral.poll();
}

void blePeripheralConnectHandler(BLECentral& central) {
  // central connected event handler
  Serial.print("Connected event, central: ");
  Serial.println(central.address());
}

void blePeripheralDisconnectHandler(BLECentral& central) {
  // central disconnected event handler
  Serial.print("Disconnected event, central: ");
  Serial.println(central.address());
}

void switchCharacteristicWritten(BLECentral& central, BLECharacteristic& characteristic) {
  // central wrote new value to characteristic, update LED
  Serial.print("Characteristic event, written: ");

  if (switchChar.value()) {
    Serial.println("LED on");
    digitalWrite(ledPin, HIGH);
  } else {
    Serial.println("LED off");
    digitalWrite(ledPin, LOW);
  }
}

Here is the write function (phonegap) which is where the error is being produced from :
var string = "Hello World";
var bytes = bluetoothle.stringToBytes(string);
var encodedString = _arrayBufferToBase64(bytes);
alert("Service : " + connection.service + "  char : " + connection.char + " Address: " + address);
var params = {"value":encodedString,"service":connection.service,"characteristic":connection.char,"address":address};
alert("params : " + JSON.stringify(params));
bluetoothle.write(function(res) {
alert("Success writing : " + JSON.stringify(res));
}, function(err) {
alert("Error writing: " + JSON.stringify(err));
}, params);

I think the error lies in the fact that the Arduino appears not to be advertising the "write" characteristic.
BTW the phone tells me that the service was 180d and the characteristic was 2a37.

I finally figured it out thanks to finding this GitHub issue. It turns out to be an error with CurieBLE which manifests in a way that means that on IOS it reads the original characteristics and services so when I tried to write it was still thought that the characteristic was read-only. I had to restart my phone and it is working now.
There was another thing which is that I needed to send a shorter message, I think it was 20 bytes max per message although I'm not sure, but I sent "h" and the Arduino received it.

I can't for another two days :-( but I will...

Yes, iOS seems to cache a lot of things by peripheral hardware address and not notice that they have changed for quite some time.  If you change addresses it will think you are something new, or else you have to get iOS to flush its cache.


text:
Help with school project (Arduino GSM and Thermal printer)
I'm with some friends from my school and we have started to do a project where we send an SMS text message to our Arduino UNO (with GSM module), which then print the text message on a thermal printer(tx, rx). we've got huge problems, and now we can not figure it out anymore.
We started making a machine that will print out a message that is sent from any mobile.So I send an SMS message with my mobile to Arduino connected to a GSM shield (SIM800L). Then sends the Arduino the message to the thermal printer via TX RX, and then the message should be printed out.
We have spent two examples, GSM shield from Arduino itself, and thermal printer example from SparkFun.
These two files work fine separately, but when we try to merge them together, there is a compilation error.
The printer model from Sparkfun.

code:
#include <GSM.h>
#include <SoftwareSerial.h>

#define PINNUMBER ""

//Printer
SoftwareSerial Thermal(6, 7);
//GSM modul
//SoftwareSerial GSM(4, 5);

int heatTime = 10;
int heatInterval = 2;
char printDensity = 15;
char printBreakTime = 15;

// initialize the library instances

GSM_SMS sms;

// Array to hold the number a SMS is retreived from
char senderNumber[20];

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
  while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
  }
Serial.println("SMS Messages Receiver");

// connection state
boolean notConnected = true;

 Thermal.println("GSM initialized");
 Thermal.println("Waiting for messages");
 }
 /*{
 Thermal.begin(19200); // to write to our new printer
 initPrinter();
 }
 */
void initPrinter()
{
 //Modify the print speed and heat
 Thermal.write(27);
 Thermal.write(55);
 Thermal.write(7); //Default 64 dots = 8*('7'+1)
 Thermal.write(heatTime); //Default 80 or 800us
 Thermal.write(heatInterval); //Default 2 or 20us
 //Modify the print density and timeout
 Thermal.write(18);
 Thermal.write(35);
 int printSetting = (printDensity<<4) | printBreakTime;
 Thermal.write(printSetting); //Combination of printDensity and     printBreakTime

 }
 void loop() {
 char c;

 // If there are any SMSs available()
  if (sms.available()) {
  Thermal.println("Message received from:");

// Get remote number
sms.remoteNumber(senderNumber, 20);
Thermal.println(senderNumber);

// An example of message disposal
// Any messages starting with # should be discarded
if (sms.peek() == '#') {
  Thermal.println("Discarded SMS");
  sms.flush();
}

// Read message bytes and print them
while (c = sms.read()) {
  Thermal.print(c);
}

}

delay(1000);

}

And what actually are these "huge problems" that you have?

Had a look at that sketch - wont compile, basic stuff. Also, they are sending startup messages to the thermal printer that they should be sending to serial. The usual story - they are hacking up some sample code, and stopping in bewilderment at the very first problem they got. Or simply scrambling the sample code somehow and have no idea about C++ syntax.
Guys: get online and google "C++ tutorial".

Your sketch isn't that long. Please include it in the question using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you. Also copy and paste the error messages you get. we've got huge problems - we all have problems. Can you be more explicit? Please read How do I ask a good question?

I'm voting to close this question as off-topic because it's a pure programming question, abandoned, no answers.


text:
Arduino how to loop a method
Hello I have a method where when you press a button a string is compared with a substring to see if the string contains the substring. The problem is when I load in the string I call the check button press and substring comparing method. Which only ever happens once. I want to know how I can keep calling the method. It sounds simple but it isn't.
void loadPrograme(){
   file = SD.open("/classes/basic.txt", FILE_READ);
   Serial.print("Reading, Checking and Compiling \n\n\n");

   for (int i = 0; i < arraysize; i++) {
      while (file.available()) {
         character23 = file.read();
         if (character23 == '\n') break;
         if (character23 != '^') {
            content += character23;
         }
      }
      content.trim();
      if (content != "") {
         result[i] = content;
         content = "";
         delay(1000);
      }
   }
   for (int i = 0; i <arraysize; i++) {
      if(result[i].substring(0,5) == "print"){
         printlnMethod(result[i]);

      }else
         if(result[i].substring(0,5) == "delay"){
            delayMethod(result[i]);
         }else
            if(result[i].substring(0,11) == "buttonPress"){
               buttonMethod(result[i]);

            }

   }

   file.close();
}

void buttonMethod(String s){
   s = s.substring(s.indexOf('{') + 1);
   s = s.substring(0, s.lastIndexOf('}'));
   String btn =" ";
   String daction = " ";
   String indaction = " ";
   btn= s.substring(s.indexOf('"')+1 );
   btn= btn.substring(0, btn.lastIndexOf('"'));
   daction = s.substring(s.indexOf(',')+1);
   daction = daction.substring(0, daction.lastIndexOf('('));
   indaction = s.substring(s.indexOf('~')+1);
   indaction = indaction.substring(0, indaction.lastIndexOf('~'));
   int buttonpressed;
   if(btn == "BUTTON_PIN_ENTER"){
      buttonpressed = 2;
   }else if(btn == "BUTTON_PIN_LEFT"){
      buttonpressed = 3;
   }else if(btn == "BUTTON_PIN_RIGHT"){
      buttonpressed = 4;
   }else if(btn == "BUTTON_PIN_DOWN"){
      buttonpressed = 5;
   }else if(btn == "BUTTON_PIN_UP"){
      buttonpressed = 6;
   }else if(btn == "BUTTON_PIN_ACTION"){
      buttonpressed = 7;
   }

   int btncheck = digitalRead(buttonpressed);
   if(btncheck == LOW){
      if(daction.substring(0,5) == "print"){
         printlnMethod(indaction);

      }else if(daction.substring(0,5) == "delay"){
         delayMethod(indaction);
      }
   }
}

}

So basically it loads in the txt file into the string array and loops through it and reads each line. each line is executed. for example if it get the substring of buttonpressed it goes to the buttonmethod(). The problem is in the button method. I want to have the button method keep looping until the button is pressed but it only runs through that method once. How can I keep running threw this method until the button is pressed?

Fix code format.

Help us out by telling us about the syntax and semantics for the script language.

what do u mean?

Do you want to keep calling the buttonMethod() or keep calling the digitalRead portion of the buttonMethod()?

the buttonmethod

Please give examples of a script and what it means, what should be executed.

Testing for string equality with '==' is a mistake: https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c  The '==' operator on strings will compare the pointers to the strings rather than their content and likely always fail the if() tests.
To loop and block on the last bit, if that is what you mean, you might try:
   int btncheck;
   ...
   while(btncheck = digitalRead(buttonpressed)){ // wait for button
      if(strcmp(daction.substring(0,5),"delay")){
         delayMethod(indaction);
      }
   }  // blocked until btncheck == LOW
   if(strcmp(daction.substring(0,5), "print")){
         printlnMethod(indaction);
   }

This has the blocking on non-pressed button feature, but also has the same logic as the original.  If the string equality tests do not match, it appears you want to do nothing and quickly pass on.
To loop buttonMethod(), put it in a loop:
while(1)buttonMethod(string);

If you want to condition on getting the button press that corresponds with the string, I'd make buttonMethod return a value and loop conditionally on that:
int buttonMethod(...
    int retVal = 0;
    ...

  if(btncheck == LOW){
     retVal = 1;
     ...
  }
  return(retVal);
}

...
while(!buttonMethod(result[i]));  // wait for the button

Might need to debounce the button.


text:
Can we detect a magnet using Arduino? If so how?
If so, please tell me and also tell me if any interfacing of other microcontroller needed?

Please read How do I ask a good question?. More details give you a better answer. Is this something slow (eg. detecting a window opening) or something fast (eg. a magnet on a bicycle spoke)? What are you trying to achieve?

I can't comment yet but you probably are looking for a hall effect sensor.
Something like this is a simple version of the sensor. https://www.sparkfun.com/products/9312
You can then do a digitalRead on the DO pin to detect if a magnet is near the sensor.
You would connect the Vdd to 5v arduino supply and GND to the GND of the board.

Just note that there are different kind of hall-effect sensors. Some respond only to one polarity (i.e. only North or only South). Some will give a on-off value (i.e. magnet present/magnet not present), while others can give an analog value proportional to the magnetic field present. Choose the one most suitable to your project.

If you don't care about measuring the strength of the magnetic field, you can use a magnetic switch (sometimes called a reed switch). A magnetic switch closes when a magnet is put up to it and opens when there is not. The only problem with this is that the magnet has to be within about one inch from the switch. The magnetic switch works just like a normal switch and usually has two contacts. Here is an example.


text:
How to run 5 wires hibrid stepper motor with arduino uno?
I have a question. How to run stepper motor (Nema 17) that has 5 wires with arduino and stepper driver.
Here is the driver, stepper and Arduino when stepper has 4 wires.
http://jdreyer.com/projects/Arduino/ArduinoEasyDriverStepperMotorv1_Resize.png
I need help identifying the wires on my hibrid stepper motor. I will provide picture of dissasembled motor.
Questions are:

Wires identification?
How to connect it to ArduinoEasyDriver?
Code example desired.

UPDATE

I am now thinking of making it bipolar (4 wires), because now in 5
  wires configuration motor is unipolar. I did some research and this
  motor is HIBRID. It can be driven as unipolar or bipolar. I will try
  to troubleshoot the wiring and find the common wire. Ill keep you
  informed.

The stepper has 8 coils? So it already has "4 wires" and one for ground I guess. You shouldn't be all to distracted by the amount of wires, check it first (if one is ground).

It has 8 coils. I will check the wires.

Could you look at this page: http://ebldc.com/?p=253 and read "The Five Wire Stepper" section? If you can confirm your stepper motor is wired like the picture in the example, and none of the wires are connected to the stepper motor's metal case, then I can help you.

1) it is probably something like A1, A2, Common, B1, B2.  You could confirm this with an ohmmeter. Common to any of the others would be a certain resistance X, while between any of the others (A1-A2, B1-B2, A1-B1, A1-B2, B1 A2) would be 2X.
2) You can't.  It is a unipolar stepper.
The EasyDriver faq number 5.1 at http://www.schmalzhaus.com/EasyDriver/ says:  "... The only kind you can't use is 5-wire stepper motors. (They need uni-polar drivers.)"
The difficulty with the 5-wire steppers is that they short the middle of the two coils together, which makes it hard to drive the coils independently.
Since you have the motor open, you might be able to do some surgery and disconnect the centers of the coils from each other, but you'll probably be better off getting a 4, 6 or 8 wire stepper instead.

Im up for the surgery. Guide me in how. :)

One of the 5 beads should have 4 wires going to it.  You would need to unsolder them.  If you leave all four of them free, you have an 8-wire stepper.  If you hook the right pairs together you get a four wire stepper. If you put pigtails on the pairs, you would have a 6-wire stepper.   Guidance on the right pairing might be to connect the pair that are connected to the two left terminals as one the middle terminal, and then the pair that are connected to the right two terminals as the other middle.  Look at the 4,6,8 wire coils on https://www.pololu.com/product/1182/faqs .

I'd guess that it is the upper-left solder joint in your picture that needs to be separated.

Ok I will try something today. I will keep you informed.

Do be aware that the patient could die.  Good luck.

I have 3 of them. All patients volunteered for experiment. :D

On stepper motors there are a few types of wiring, but essentially there are two coils inside the stepper motor. To figure out where the wiring is you need a way to test if the coils are being connected. On your setup I would suggest to connect two of the wires together at a time and spin the shaft. If the shaft offers resistance then you have found the two wires for one coil.
For your stepper motor it looks like it may have three coils, but out of the 6 wires you may also only come up with 4 wires; which would equal 2 coils.
As far as connecting it to an easy driver, the easy driver only takes two coils. you would need to find a driver that can take three coils, or just connect two coils out of the three and hope for the best.

Finding the ground pin
We should start off by finding the Ground/GND pin.
Do you have an Ohm-meter? I believe one of the pins should be GND/ground, and should have low resistance when referenced to the other pins.
Wiring the stepper
Steppers have a coil and thus are an inductive load, you should really check your wiring with sources, to be sure they're valid.
(At this point I can't give you a 100% accurate wiring diagram, but it should be easy to find, as wiring steppers is quite common.)
You could use a pre-assembled stepper-driver. Having such a thing is usefull when you want to design the circuitry yourself.
Driving the steppers
You should generate a signal like this: https://en.wikipedia.org/wiki/Stepper_motor#Phase_current_waveforms
(The source/link describes the different forms of stepping. Like "Wave drive (one phase on)" in which each coil is activated/deactivated in a rotary fashion, making the core turn around.)
Extra
Adafruit always has extremely well documented tutorials for beginners:
https://learn.adafruit.com/all-about-stepper-motors/types-of-steppers
The wiki of RepRap should be a good source, since steppers are the hearth of 3D printers (RepRap is a 3D printer brand):
http://reprap.org/wiki/Stepper_wiring

I will try to find the ground with ohm-meter. Resistance should be different comparing to other combinations. Thank you for your suggestion. Ill keep you informed.

Instead of doing surgery on your unipolar stepper, you can use it like a unipolar stepper. Some transistors to hook the motor to power (just get a darlington array chip), and four output pins on the arduino. Works fine.

Can you provide some schematics? Or wiring?

@PaulMurrayCbr That's exactly what I'm using and it works great. Texas Instruments makes one: ULN2003A but I cheated and got a board from ebay: http://www.ebay.ca/itm/1PCS-ULN2003-Stepper-Motor-Driver-Board-for-Arduino-AVR-AR-M-/181586125620?hash=item2a47606334:g:gqUAAOSwMKpUZsTN


text:
Arduino loading from file
Hello I have a programme that loads a piece of text from a file. In this case it loads "drawrect(4,10,20,20);" from the txt file and stores it in a string. I then use substrings to change the string into just "4,10,20,20" which is good but I need to simplify it down even more to four strings each with one of those 4 numbers in it.
Currently I use:
void drawRectMethod(String s){
  String var1,var2,var3,var4;
  s = s.substring(s.indexOf('(') + 1);
  s = s.substring(0, s.lastIndexOf(')'));
  Serial.println(s);
}

to simplify the string down to "4,10,20,20" but this wont work to store each number in a separate string. How can I can I store each variable in a separate string. The numbers will be stored in var1 - var4.

This is not nearly related to Arduino at all?

ye it is an Arduino based project the string is loaded from an sd card that is attached to an arduino

Ah, okay, an Arduino is sending text over USB. But what is receiving it at the moment?

the sd card sends text to a string on the Arduino the Arduino then reads it and if it says drawrect(4,10,20,20) it will draw a rectangle on my nokia 5110 screen. I just cant figure out how to store each of the 4 numbers in a separate string hopefully using the substring method like I have been doing before

Why is the title: "Java loading from file"?

You meant that you're searching for the Arduino equivalent of the Java code above?

Want some help with this as well? Soon I will have written most of your sketch. No seriously I was hoping that the previous question-answer would help you understand how to parse strings.

oops it should be arduino

@MikaelPatel I have  written quite a lot of the sketch, there is just a few things I didn't understand and I am trying to learn like these things I've asked because this is all new to me but I want to understand it

Need some more help? As I previously wrote that snippet I might as well continue until you understand how to use indexOf() and substring().
  String s = "draw(10,20,30,40)";

  // Parse the argument list
  s = s.substring(s.indexOf('(') + 1);
  s = s.substring(0, s.lastIndexOf(')'));

  // Parse comma separated arguments
  String arg[4];
  for (int i = 0; i < 3; i++) {
    int ix = s.indexOf(',');
    arg[i] = s.substring(0, ix);
    s = s.substring(ix + 1);
    Serial.println(arg[i]);
  }
  arg[3] = s;
  Serial.println(arg[3]);

There is absolutely no error handling in this. You will have to add that. You can also improve the parse of the right parenthesis. That could be added last instead.
Later in the game we will come to why using String is a bad idea and why a character buffer and the standard library functions such as strtok() is a much better solution strategy both performance and memory footprint and especially heap.
  char* s = (char*) "draw(10,20,30,40)";
  s = strtok(s, "(),");
  Serial.println(s);
  while ((s = strtok(NULL, "(),")) != NULL)
    Serial.println(s);

Maybe the simplest solution is to use sscanf(). That will also do the conversion from text to binary.
  const char* s = "draw(10,20,30,40)";
  int x, y, w, h;
  int n = sscanf(s, "draw(%d,%d,%d,%d)", &x, &y, &w, &h);
  Serial.print(F("n="));
  Serial.println(n);
  Serial.print(F("x="));
  Serial.println(x);
  Serial.print(F("y="));
  Serial.println(y);
  Serial.print(F("w="));
  Serial.println(w);
  Serial.print(F("h="));
  Serial.println(h);

Cheers!


text:
Problem with inaccurate delays between sensor readings
During the last two months I have been working on a project that consists of using a Seeeduino Stalker V2.3, two AM2305 sensors, a TSL2561 sensor, an HC-05 XBee module, a 1,800 mAh 3.7V LiPo, a 7 cm x 7 cm 5V solar cell, and a waterproof suction box, to assemble a portable and waterproof environmental data logger that can be used to take samples on a continuous basis (1 sample every 30 minutes, 48 samples per day).
After struggling to make my logger work, I finally did it last week. It all runs fine, except that the intervals between readings are incorrect. When I program my board to store samples every 30 minutes (1,800,000), it takes them every 30 minutes and some extra seconds. When I try the same but with a rate of 1 sample every 10 seconds, my device logs data every 13 seconds more or less...
Here is the code I have been using:
#include "SPI.h"
#include "Wire.h"
#include "SD.h"
#include "DS3231.h"**

DS3231 clock;
RTCDateTime dt;

#include "DHT.h"

#define DHTPIN 8
#define DHTTYPE DHT21
DHT dht1(DHTPIN, DHTTYPE);
#define DHTPIN2 7
DHT dht2(DHTPIN2, DHTTYPE);
#include "TSL2561.h"
TSL2561 tsl(TSL2561_ADDR_FLOAT);

const int chipSelect = 10;
int XBEE = 5;
int FLASH = 4;

void setup() {
  pinMode(5, OUTPUT);
  digitalWrite(XBEE, HIGH);
  Serial.begin(9600);
  Wire.begin();
  clock.begin();
  analogReference(INTERNAL);
  pinMode(10, OUTPUT);
  pinMode(4, INPUT);
  SD.begin(10);
  dht1.begin();
  dht2.begin();
  Serial.println("EcoLOGGER DE PRUEBA PARA GENERACION DE DATOS ...");
  Serial.println(" ");
  delay(3000);
  Serial.println("RECUERDA QUE ESTE PROYECTO NO HUBIERA SIDO POSIBLE SIN LA AYUDA DE LA COMUNIDAD ARDUINO...");
  Serial.println(" ");
  delay(3000);
}

int counter = 0;

void loop() {
  float h = dht1.readHumidity();
  float t = dht1.readTemperature();
  float f = dht1.readTemperature(true);
  float h2 = dht2.readHumidity();
  float t2 = dht2.readTemperature();
  float f2 = dht2.readTemperature(true);
  dt = clock.getDateTime();
  if (tsl.begin()) {
  } else {
    while (1);
  }
  tsl.setGain(TSL2561_GAIN_0X);
  tsl.setTiming(TSL2561_INTEGRATIONTIME_402MS);
  uint16_t x = tsl.getLuminosity(TSL2561_FULLSPECTRUM);
  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;
  float vis = full-ir;
  Serial.print("Muestreo: ");
  Serial.println(counter);
  Serial.print("Fecha: ");
  Serial.print(dt.day);
  Serial.print('/');
  Serial.print(dt.month);
  Serial.print('/');
  Serial.println(dt.year);
  Serial.print("Hora: ");
  Serial.print(dt.hour);
  Serial.print(':');
  Serial.print(dt.minute);
  Serial.print(':');
  Serial.println(dt.second);
  Serial.print("Temperatura sistema: ");
  Serial.print(clock.readTemperature());
  Serial.println("*C ");
  Serial.print("Voltaje bateria: ");
  Serial.print(analogRead(A7) * (1.1 / 1024)* (10+2)/2);
  Serial.println(" V ");
  Serial.print("Carga bateria: ");
  Serial.print(-149.4 + 59.52 * (analogRead(A7) * (1.1 / 1024)* (10+2)/2));
  Serial.println("% ");
  Serial.print("Luz FULL: ");
  Serial.println(full);
  Serial.print("Temperatura ambiente: ");
  Serial.print(t);
  Serial.println(" *C ");
  Serial.print("Humedad relativa: ");
  Serial.print(h);
  Serial.println("%");
  Serial.print("Temperatura suelo: ");
  Serial.print(t2);
  Serial.println(" *C ");
  Serial.print("Humedad suelo: ");
  Serial.print(h2);
  Serial.println("%");
  Serial.println(" ");
  digitalWrite (FLASH, HIGH);
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.print(" Muestreo: ");
    dataFile.print(counter);
    dataFile.print(",");
    dataFile.print(" Fecha: ");
    dataFile.print(dt.day);
    dataFile.print('/');
    dataFile.print(dt.month);
    dataFile.print('/');
    dataFile.print(dt.year);
    dataFile.print(",");
    dataFile.print(" Hora: ");
    dataFile.print(dt.hour);
    dataFile.print(':');
    dataFile.print(dt.minute);
    dataFile.print(':');
    dataFile.print(dt.second);
    dataFile.print(",");
    dataFile.print(" Temperatura sistema: ");
    dataFile.print(clock.readTemperature());
    dataFile.print("*C ");
    dataFile.print(",");
    dataFile.print(" Voltaje bateria: ");
    dataFile.print(analogRead(A7) * (1.1 / 1024)* (10+2)/2);
    dataFile.print(" V ");
    dataFile.print(",");
    dataFile.print(" Porcentaje carga: ");
    dataFile.print(-149.4 + 59.52 * (analogRead(A7) * (1.1 / 1024)* (10+2)/2));
    dataFile.print("% ");
    dataFile.print(",");
    dataFile.print(" Luz FULL: ");
    dataFile.print(full);
    dataFile.print(",");
    dataFile.print(" Temperatura ambiente: ");
    dataFile.print(t);
    dataFile.print(" *C ");
    dataFile.print(",");
    dataFile.print(" Humedad relativa: ");
    dataFile.print(h);
    dataFile.print("%");
    dataFile.print(",");
    dataFile.print(" Temperatura suelo: ");
    dataFile.print(t2);
    dataFile.print(" *C ");
    dataFile.print(",");
    dataFile.print(" Humedad suelo: ");
    dataFile.print(h2);
    dataFile.print("%");
    dataFile.println("");
    dataFile.close();
    digitalWrite (FLASH, LOW);
  } else {
    Serial.println("");
    Serial.println("IMPOSIBLE GUARDAR DATOS");
    Serial.println("");
  }
  counter++;
  if (counter > 5) {
    delay (1000);
    digitalWrite (XBEE, LOW);
    delay (1799000);
  } else
    digitalWrite (XBEE, HIGH);
  delay (10000);
}

I have been trying to find possible solutions, but I am just lost. Do any of you have an idea of what could be going on?
Thank you in advance :)

How accurate do you think delay() is? And how much time does the sketch take when not in delay(). All this adds up. Check for instance how accurate the clock crystal/resonance is. Consider using an external RTC or try getting the Arduino Team to implement something that actually could work as a stable timer (< 1 second drift per month).

It might also matter that most Arduinos are slow, that means all data transfer and calculations take time.

Thank you @MikaelPatel, I now realize that delay() is good for learning arduino but not for implementing real world ideas... I will try to use the DS3231 RTC that comes on the Seeeduino stalker V2.3 to trigger my readings... I still have to think of a way of implementing this idea on code... Any advices?

The problem is that you are using delay().
delay() will wait, from the moment delay() is called, for the given number of milliseconds.
That is, in more structured terms:

Do something
Do something else
Do something more
Wait 30 minutes

That will only take precisely 30 minutes if steps 1 to 3 take absolutely no time at all.  And that will never be the case. Things take time. Reading from sensors, writing to SD cards, etc, all take time.
So waiting for 30 minutes between doing things means that every 30 minutes will be slightly later than the one before.
And as you saw the difference is more pronounced when you have 10 seconds instead - it ends up as 13 seconds.  So your other actions - reading from sensors, writing to SD card, etc, must be taking about 3 seconds each time.
So instead of "Stop everything for half an hour", you need to think slightly differently:

Look at the time.
Decide if 30 minutes have passed since the last time you ran the code
Remember the time so you can know when 30 minutes have elapsed next time
Do your sensor/SD actions.

Since you're now keying things happening on the difference between now and when you last started to do things you get a 30 minute total delay, rather than a 30 minute delay plus other bits.
For an example of how this is done programatically you can look at the BlinkWithoutDelay example in the Arduino IDE.

Thank you for your comment. I have been reading some info about your statements and it seems that there are several ways to get rid of delay() function... I think the "Millis()" function is a very straightforward technique, but if it depends on a clock that is prone to give outputs with only 90% of accuracy (on-board clock cycle, as mentioned by @PaulMurrayCbr) I don't think it is going to be useful for my porpues. So I'm thinking of "asking the time" to the Stalker's on-board DS3231 RTC, but I cannot think clearly of its implementation on code... I suppose I should use if, else...

Do you have any recomendations? Thank you again for your help :)

You can use an RTC in just the same way as millis(). Take a look at the Time.h library for help manipulating times.

The second problem is that delay() on the arduino uses the on-board clock cycle. This is powered by a resonator, which can be off by as much as 10%. If you need accurate timings and timestamps, you will want to use a Real-Time Clock (RTC) module.
Instead of using delay, the loop() asks the RTC what time it is, and uses that to determine if it's time to take another reading.
Another very common thing for this type of monitoring is for the arduino to go into sleep mode and be woken by a tick from the RTC every second (or longer), in order to extend the battery life.


text:
Change Servo Speed With RedBearLabs BLE Shield
I recently got the RedBearLabs BLE shield to use it to control two high spped continuous rotation servos. I have the BLE example sketch loaded and the ios controller app works. The problem is that the servos are too fast to control and I want to slow them down. I cannot use the app to slow them down. I was wondering how I could modify the example sketch or servo library to change the ax speed or something. Thanks in advance.
BLE Shield Homepage: http://redbearlab.com/bleshield/
BLE Libraries and Example Sketch: https://github.com/RedBearLab/nRF8001

Can you be more explicit in what you want to achieve.  What do you mean by "the servos are too fast to control" - do you mean the servos are repositioning too quickly?  Something else?  Also can you please post (or link to) the exact code you need help with - not a whole library of stuff.

The servos spin too fast to be able to control it very well. I want to slow those down.
https://codebender.cc/sketch:245943
This is the code

SnapDraggen, please edit the question to answer the items in Kingsley's comment.  Note, there are seven different examples at the github link, four of them having BLE in their names, so you should say which one you mean.  Also add a direct link to whatever iOS app you used.

This is the app: https://itunes.apple.com/us/app/ble-controller/id855062200?mt=8
The sketch is the one called BLEControllerSketch
I am using it to build a robot

I am building a robot with two servos as motors. I want to use the BLE Controller app(linked above) to drive it. I have already done this but it is very fast and hard to control. I want to somehow slow down how fast the servos spin. They are parallax high speed continuous rotation servos.

@SnapDraggen - please edit your question and copy the information in your comments into it. The question will then be more complete. Please read How do I ask a good question?

The bi-directional Parallax High Speed Continuous Rotation Servo responds to “simple pulse-width modulation”, according to its web page.  That is, pulse widths in the range from about 500 μs to 2500 μs will set the speed and direction, with some value near 1500 μs corresponding to zero RPM.
The code in the BLEControllerSketch uses the following bits of code, among others, to initialize servo-control data structures and to control them:
#include <Servo.h>
...
byte pin_servo[TOTAL_PINS];
Servo servos[MAX_SERVOS];
...
      case 'O': // set Servo
        {
          byte pin = ble_read();
          byte value = ble_read();

          if (IS_PIN_SERVO(pin))
            servos[PIN_TO_SERVO(pin)].write(value);
          pin_servo[pin] = value;
          reportPinServoData(pin);
        }
        break;

Thus, you will need to send an O message from your iOS app, together with servo pin number and control value, to set a servo's speed.
As noted on the ServoWrite page at arduino.cc, the parameter to Servo's .write() method is a number:

On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).

You can find out a little more by looking at Servo's .write() method in Servo.cpp:
void Servo::write(int value)
{
  if(value < MIN_PULSE_WIDTH)
  {  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
    if(value < 0) value = 0;
    if(value > 180) value = 180;
    value = map(value, 0, 180, SERVO_MIN(),  SERVO_MAX());
  }
  this->writeMicroseconds(value);
}

SERVO_MIN() and SERVO_MAX() are macros that access min and max fields in a Servo object and convert them to microsecond values.  Because the code in BLEControllerSketch.ino lets those fields default, the range evidently will be from 544 to 2400 μs (see the values given in Servo.h).
Note that you can get better resolution – hence, better speed control – by sending values in that range of microseconds to your servos, instead of trying to control it using values in degrees.  The .write() method will interpret such numbers as microseconds instead of as degrees.  Servo.cpp appears to use half-microsecond timer ticks; and each degree corresponds to about 10 μs of pulse width; so resolution using microsecond values should be about 10 times better than using degrees.
In short, it appears that you should do some experimenting with O messages that send values around 1500, to find the values that correspond to slowest forward and backward speeds.


text:
How to split a string received via a GSM module (message)
I am doing a motorcycle security system. In this system, I will receive a message from GSM in the form {password:operation (like start,stop,alarm):time}.
Example:(9990:start:30)
now i need to split  each term seperately (a=9990,b=start,c=30).help me to solve

You may need to say how you receive the message or how it's stored.   As is, the question is vague.  Also edit the question and add an explained example, like "{14:C:123}"

Simplest solution is to use sscanf().
  int password;
  char operation;
  int time;
  char* buf = "{14:C:123}";
  int n = sscanf(buf, "{%d:%c:%d}", &password, &operation, &time);
  Serial.print(F("n="));
  Serial.println(n);
  Serial.print(F("password="));
  Serial.println(password);
  Serial.print(F("operation="));
  Serial.println(operation);
  Serial.print(F("time="));
  Serial.println(time);


text:
Double clap sensor not working as intended
I have this double clap sensor code written, it seems it would work but it seems to trigger the double clap even on a single clap, any ideas?
int soundSensor = A1;
int relay = A2;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;
int claps = 0;
long detectionSpanInitial = 0;
long detectionSpan = 0;
boolean clapState = false;
int doubleClap = 0;

//Light sensor
int photocellPin = A0;     // the cell and 10K pulldown are connected to a0
int LEDbrightness;

//int delayValue = 100;
int photoSensor = 0;

// sound sample
const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;

//other
boolean isRelaysOn = false;
void setup() {
  pinMode(soundSensor, INPUT);
  pinMode(relay, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  turnRelayOff();
  Serial.begin(9600);
}

boolean state = false;
boolean lastState = true;
boolean lightTurnedItOff = false;
void loop() {

  /////////////
  // photo sensor
  ////////////////////

  photoSensor = analogRead(photocellPin) > 623;

  /////////////
  // clap sensor
  /////////////////////
  double sensorState = getSoundLevel();
  Serial.println(sensorState);
  double threshold = .2;

  if (sensorState > threshold)
  {
    if (claps == 0)
    {
      detectionSpanInitial = detectionSpan = millis();
      claps++;
    }
    else if (claps > 0 && millis()-detectionSpan >= 50)
    {
      detectionSpan = millis();
      claps++;
      Serial.println(" CLAP ADDED!!!!");
    }
  }

  if (millis()-detectionSpanInitial >= 400){

    if (claps == 2)
    {
      claps++;
      doubleClap = 1 - doubleClap;
      state = !state;
      Serial.println("TWO claps!");

      if(lastState == state ){
        relayControl(doubleClap);
        lastState = !lastState;
      }
    }
    claps = 0;
  }

  if(isRelaysOn == true && photoSensor == 1){
    turnRelayOff();
    lightTurnedItOff = true;
  }
  if(isRelaysOn == true && photoSensor == 0 && lightTurnedItOff == true){
    turnRelayOn();
    lightTurnedItOff = false;
  }

}

void relayControl(int doubleClap){
  /////////////
  // relay control
  /////////////////////

  if(doubleClap == 1){
    turnRelayOn();
    Serial.println("on");
    isRelaysOn = true;

  }
  else{
    turnRelayOff();
    Serial.println("off");
    isRelaysOn = false;
  };

}

void turnRelayOn(){
  int delayAmount = 100;
  digitalWrite(relay, LOW);
  delay(delayAmount);
  digitalWrite(relay2, LOW);
  delay(delayAmount);
  digitalWrite(relay3, LOW);
  delay(delayAmount);
  digitalWrite(relay4, LOW);
  delay(100);
  digitalWrite(relay4, HIGH);
  delay(100);
  digitalWrite(relay4, LOW);
}

void turnRelayOff(){
  digitalWrite(relay, HIGH);
  digitalWrite(relay2, HIGH);
  digitalWrite(relay3, HIGH);
  digitalWrite(relay4, HIGH);
}

double getSoundLevel(){

  unsigned long startMillis= millis();  // Start of sample window
  unsigned int peakToPeak = 0;   // peak-to-peak level

  unsigned int signalMax = 0;
  unsigned int signalMin = 1024;

  // collect data for 50 mS
  while (millis() - startMillis < sampleWindow)
  {
    sample = analogRead(soundSensor);
    if (sample < 1024)  // toss out spurious readings
    {
      if (sample > signalMax)
      {
        signalMax = sample;  // save just the max levels
      }
      else if (sample < signalMin){
        signalMin = sample;  // save just the min levels
      }
    }
  }
  peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
  double volts = (peakToPeak * 3.3) / 1024;  // convert to volts

  return volts;
}

Serial monitor:

0.02
  0.02
  0.02
  0.02
  0.01
  0.01
  2.20
  0.30  CLAP ADDED!!!!
  0.13
  0.09
  0.04
  0.02
  0.02
  0.01
  0.02 TWO claps! on
  1.11
  0.06
  0.05
  0.07
  0.15
  0.10
  0.03
  0.10
  0.06
  0.03
  0.04
  0.06

Other than this being a possible duplicate of your other question. Could you also give more info like a copy of the serial monitor for one loop when you have clapped. Also try moving else if (sample < signalMin){ signalMin = sample; } out of the if(sample <1024) as you will never enter that else if statement and peaktopeak will always be greater than your threshold.

It would help if you described your intended logic better.  There are a bunch of state variables (state, lastState, doubleClap) and several timeouts; deciphering your intent from code which doesn't accomplish that intent is extra work and error prone.

@RSM The else is not hard to enter; consider the first two samples 600, 500.  Both are < 1024.  The first will set signalMax=600, the second will set signalMin=500.  There is a different logic error however, which could be fixed by removing "else" so there are two if statements, one setting signalMax and one setting signalMin; the thing is, the first value should trigger both if statements.  Otherwise (with the else) consider what happens with samples 100,300,700,900 - each one sets signalMax, but signalMin is never set and retains the dummy 1024 value for a span of -124 instead of 800.

@RSM I added the serial monitor.

If your first clap rings for more than 50ms, the program counts it as a second clap.  After detecting a clap, you need to wait for the sound to die down before you start listening for a second clap.

What you probably want to track is something more like:

high sound period of highMin to highMax ms
low sound period of lowMin to lowMax ms
high sound period of highMin to highMax ms
low sound period of at least lowDone ms (no max needed)

Anything not meeting those time bounds is not two claps, reset state and timers.  If you get to the end of the fourth step, accept as two claps.
I have not tested timing of claps to estimate the periods needed; you need to tweak that with the hardware you are actually using; for example, different microphones may ring for different times after a sharp clap impulse.
States could be:

waiting for start of first clap (sample until > threshold)
waiting for end of first clap (sample until < threshold or timeout)
waiting for start of second clap (sample until > threshold or timeout)
waiting for end of second clap (sample until < threshold or timeout)
got second clap

I have noticed that you have used analogue inputs as your digital outputs by connecting relays to them.
I think this is wrong. You should connect your digital signals to the digital pins.

It really doesn't matter that much.


text:
Send AND Receive through i2c / set Arduino as master AND slave
For a project I'm using 2 Arduino Uno's, where Arduino#1 (master) sends raw data to Arduino#2 (slave). The slave should receive and encrypt the data and afterwards send the encrypted data back to the master. I'm building my project from the sketch found at arduino.cc.
How can I make the slave send back data, if he's the only one listening on incoming data, should both arduinos be listening to each other, and how to achieve this?

The I2C protocol is both read and write. Master/Slave depends on who initiates the communication. Typically the master will issue a read command to the slave to retrieve the results.
Cheers!

As the master I can use beginTransmission() and write() to send, and requestFrom() to receive, am I right? and on the slave side I use 2 eventhandlers for this, right?

Yes that is correct! All transmissions are initiated by the master with write() to send to the slave, and requestFrom() to read.

Thanks, that works now, only challenge now is to predict how long the return message is going to be. i.e. I use requestFrom(8,50) and the return message is 40 chars long instead of 50 then it gets filled with strange chars.

Typically you would have a number of "commands" or "registers" that you would issue or read from. One might be "Get buffer length" which returns the number of bytes in the "message" that are available for reading. Then you use that to get the right number of bytes.  So it's "Get Buffer Length => 40 => Get Buffer(40) => 40 chars"

I think the transmission size is limited to 32 bytes in the Arduino AVR Wire I2C driver implementation. Obviously there is no such limitation in Cosa :).


text:
how to solve Varing duty cycle value while using Pulsein()
Well im new to coding, but i do have the basic knowledge.
I'm using an UNO to measure a duty cycle.
The source of pulse is a Tektronic signal generator (Duty cycle set to 50.000 with frequency of 2khz).
my code is as follows,
byte PWM_PIN = 3;
float pwm_value_H;
float pwm_value_L;
float D;

void setup() {
    pinMode(PWM_PIN, INPUT);
    Serial.begin(115200);
}

void loop() {
    pwm_value_H = pulseIn(PWM_PIN, HIGH);
    Serial.println(pwm_value_H);
    pwm_value_L = pulseIn(PWM_PIN, LOW);
    Serial.println(pwm_value_L);
    D = ((pwm_value_H) / (pwm_value_H + pwm_value_L)) * 100.0;
    Serial.print("D=");
    Serial.println(D);
    Serial.print("D=%");
}

but the problem is that my output value of "D" keeps on varying between 49.71, 49.90, 50.00 and 50.7
Is this because of PULSEIN() function ineffiency?
or can anyone suggest a better way to measure the duty cycle with +/- 0.01 accuracy.
Regards,
Cj

I would start by removing Serial interrupts from the pulseIn period.
void loop() {
    pwm_value_H = pulseIn(PWM_PIN, HIGH);
    pwm_value_L = pulseIn(PWM_PIN, LOW);
    Serial.println(pwm_value_H);
    Serial.println(pwm_value_L);
    D = ((pwm_value_H) / (pwm_value_H + pwm_value_L)) * 100.0;
    Serial.print("D=");
    Serial.println(D);
    Serial.print("D=%");
    Serial.flush();
}

For higher accuracy I would then look to the Timer based Input Capture.
Cheers!

This seems logical. I'll give it a shot and check if the accuracy is meeting my requirements. And by the way, thanks a loads for the reply Mikael

There's two basic things wrong with what you are doing there:

pulseIn() isn't good for very accurate measurements
The signal is still happening while you're doing other things, such as printing the high/low times.

You're not actually measuring the duty cycle of one single cycle, but the HIGH time of one cycle followed by the low cycle of a later one. If you want to do it properly you will have to ditch pulseIn() and instead get your head around interrupts and timestamps.
The basic method is to present the signal to one of the INT pins, and attach an interrupt to that pin with the trigger set to CHANGE.  The interrupt routine you specify will then be triggered every time the signal changes from HIGH to LOW or from LOW to HIGH.
Then the interrupt routine does very little.  It basically records the time the interrupt happened (that must be the very first thing you do), then looks to see if it's a HIGH or a LOW signal on the pin.  You then use the previous timestamp from the last time the interrupt was triggered to work out how long the previous phase lasted and set either a HIGH or a LOW variable depending on the current level of the state (if it's low set a high variable since that was the previous phase level, and if it's high set a low variable) with the time that phase lasted.
Then in your main loop you interrogate those variables periodically to display the duty cycle.
If that still isn't accurate enough then you should look at the hardware Input Capture module built into the MCU. That uses a hardware timer in much the same way as the interrupt but is able to capture a much more accurate time stamp for you since the time stamp is grabbed the moment the signal changes, rather than after a short delay once the interrupt routine has been called.  Details can be found in the datasheet for the MCU on your Arduino.

As i said, im new to coding. I understood what you said, but it is going to take me some time to implement it. And by the way, thanks a loads for the reply Majenko!!


text:
At what level does low dynamic memory effect performance?
I have a few Arduino sketches that take 70-90% of dynamic memory. It seems that over 70%, the compiler gives the warning:
Low memory available, stability problems may occur.

but otherwise I wasn't noticing any problems.
Then I uploaded a sketch that took 89%, which logged String data to the serial port, and found that only newlines were being written out. When I commented out some global variables so that dynamic memory usage got to 88%, then it started printing out the data.
Is there any hard/fast rule on when this problem occurs? I was surprised by this problem, because the global variables I removed weren't even being used in the sketch, so I had thought the compiler would have removed or optimized them so they didn't waste any space. Are there any ways to automatically improve compilation efficiency and detect wasteful variables?

The typical build memory statistics is:
Global variables use XXX bytes (X%) of dynamic memory,
leaving YYY bytes for local variables.
Maximum is ZZZ bytes.

What is all this about? First, the maximum number of bytes SRAM depends on the MCU. Arduino Uno is ATmega328 based and has 2K byte SRAM. Arduino Mega2560 has 8K byte. "Dynamic memory" in the print out is SRAM. It is not the heap (malloc/free). To avoid confusion I will use "data memory" below.
The compiler allocates memory for all global variable (objects, struct, etc). It also allocates memory for literal strings (character vectors). These are copied from program memory to data memory at startup. All static variables in functions are also allocated. The sum of all these allocations are the "Global variables".
To execute the sketch data memory is used for the stack. It contains the function parameters, local variables in called functions (that are not allocated to registers), saved registers such as return address to the caller, etc. The size of the frame is known by the compiler and may be found in the assembly listing of a sketch. The maximum stack size required is tricky to calculate as it is the call chain with the largest frame size sum. This is not necessarily the deepest call chain. Also the compiler does to a fair amount of inlining.
The heap (malloc/free) is used by classes such as String. The heap starts directly after the global variables in data memory and grows towards the stack. The heap is blocks of memory allocated and deallocated during the execution of the sketch. This behavior may give heap fragmentation.
Interrupt Service Routines (ISR) need to be able to execute "on top of" any function call. The ISRs are typically called on hardware events such as USART data received. The compiler has to generate code that stores the machine state on stack to execute the ISR. Depending on how many registers the ISR needs more or less of the machine state (registers) need to be stored. The worst case is all 32 registers.
The warning at 30% of SRAM is at approx. 600 bytes left (Arduino Uno, 2K byte). That has to cover the stack and possible heap usage together with ISRs. With a stack heap limit of 32-128 byte, ISR frame of 32-64 byte, that actually leaves worst case approx. 400 bytes for local variables in functions and possible usage of the heap (such as String).
Cheers!

The problems occur when you run out of memory. That all depends on what you are doing with the memory that is available.
String objects are not good and are wasteful of memory. They really should be avoided, since they use dynamic memory allocation, which uses the "spare" memory that is what's left over from what the compiler says is used.
There is no rule, other than "don't run out of memory", and tracking dynamic usage can be very hard, so try to avoid using it if you can.


text:
Connection between Matlab and Arduino
I'm trying to connect Maltab and Arduino by this code:
arduino=serial('COM7','BaudRate',9600);
fopen(arduino);

But I get this message:

Open failed: Port: COM7 is not available. No ports are available. Use
  INSTRFIND to determine if other instrument objects are connected to
  the requested device.

What might be a proper reason?
I have another question which is; How can I save a text file (.txt) from Matlab to Arduino SD card .. ? Wether opening a .txt file in arduino or saving it from Matlab directly to Arduino SD card.

when you open it and after forget to close it (lets say your script crashes) and retry to reopen it will cause these errors. Try force a fclose on serial object.

I've done this and it still gives the same message.
Isn't there any other possible option maybe to add a text file to Arduino SD card or anything else?

If you use arduino IDE, does it open the port normally?

Hmmm I currently have no time to order one since I have to finish my project in only 3 days .. You see, I got the results of my algorithm from Matlab in a .txt file, and what's left is to add this .txt file in Arduino SD card in a way or another... my first option was to add it directly from Matlab but the connection seems not quite supportive.. so is there any way to put this text file from my pc to Arduino SD card? Thanks in advance! You'd save my life :)

Sorry but now you got me confused. You don't actually have an arduino (hardware)? When before I asked if the port opens correctly I was talking about arduino IDE (the software). I suppose a basic SD card reader connected to computer is out of question right?

Ahh apologies, Yes I have the Arduino hardware and the port works normally from what I see in IDE, however, in Matlab there seems to be a problem, I don't think it is the port neither the Arduino plug-ins in Matlab, this was actually the second option, my first option was to take the text file from my pc and save it in Arduino SD card but I don't think it is possible!

There is no 'Arduino SD card'. There are only SD cards and Arduino libraries that help you talk with the cards. Now, the text file you wish to write to an SD card, where exactly is it? Is it already on your PC? If so, then transferring it to the SD card using a standard card reader or adapter, like has been suggested already, is all you need to do. Unless there's some other reason why you need the Arduino...

@JackSparrow aparrently the problem is related to the fact the uno usesatmega16u2 as serial emulator. I managed to make it work in linux by following this link: (http://www.mathworks.com/matlabcentral/newsreader/view_thread/194071). However I do not have any windows pc to test similar approach as refered like here: http://www.mathworks.com/matlabcentral/answers/93708-is-it-possible-to-support-1024-serial-ports-in-win32-systems-in-matlab . Try to test it with your port

The first step in debugging this is to use the Device Manager (available in Computer Management) to see what ports the PC thinks are there.  It will confirm whether or not there is a COM7 at all.  Your error message seems to indicate the port does not exist.


text:
Cannot receive data from GPS SD Shield V2-B
I am attempting to receive GPS data from a GPS SD Shield V2-B purchased from maplin. I have attempted the very simple sketch they provide on their website linksprite.com.
I have also tried following a tutorial found here: http://tronixstuff.com/2014/01/15/tutorial-arduino-mediatek-3329-gps/.
This is the code i am using:
    // Example 19.1

    #include <SoftwareSerial.h>
    SoftwareSerial GPS(2,3); // configure software serial port -

    void setup()
    {
      GPS.begin(9600);
      Serial.begin(9600);
      pinMode(13,OUTPUT);
    }
    void loop()
    {
      byte a;
        if (GPS.available() > 0 )
      {
        a = GPS.read(); // get the byte of data from the GPS
        Serial.write(a);
        digitalWrite(13,HIGH);
        delay(1000);
        digitalWrite(13,LOW);
        delay(1000);
      }
    }

I am using an Arduino 101. The jumpers on the GPS shield are set up as follows:
I have attempted using both power simply from my Mac and an external 9V battery connected to the Arduino.
The 'blink' has been added the sketch to test whether data was being received but there was a problem with the serial monitor. This is not the case because the blink did not occur. It however did occur when moved outside of the if statement as you would expect.
Any help or suggestions would be much appreciated.

Sounds like hardware, if you are using an existing sketch and shield. Did you solder the pins onto the shield, or just push them in?

The shield came pre-assembled so didn't require any soldering. The jumpers used are removable and are just pushed on

You need to set the jumps as per the instructions that came with the shield ...
PAGE4 : short jumpers TX and MRX .... and RX and MTX