text:
println() changes values of variables
I have a function which returns a float value.
I want to see what value is returned so I print it just before the return statement.
Surprisingly, the value is 0 (it shouldn't be 0).
When I want to debug the function and print more things, the value is correct. I do not change anything, I just add a couple of printl().
Let's say:

float func() {
  float a = some math calculation;

  some easy math
  Serial.println(a);
  some easy math
  Serial.println(a);

  Serial.println(a);
  return a;
}

If I comment out println() lines, I get 0, which is a wrong value.
If the lines stay uncommented, I get a correct value.
Does anyone have idea why?
I use Arduino Due.

Perhaps if you showed us the actual code we might be able to help you...

Please post a  Minimal, Complete, and Verifiable example and not a snippet. Perhaps you are dividing by zero? That's "easy math" to do. :)

Thank you Nick :)
I used millis() to calculate time and then I divided by the time step. After I changed to micros() everything is as it should be. I think serial printing added necessary time to make the time step not null.

Can you still post the minimal complete verifiable examples so that others can benefit from your question? They will benefit in two ways 1) an example of why prints can make a difference - especially where timing is important and 2) why it is important to post a complete example to enable when asking a question (a big problem on this site).

I would suggest adding the "complete example" as a second code block prefixed by "edit - complete code block". Or, simply answer your own question and put the "complete code" in your answer.

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


text:
C++ Pointer Issues - Mangled Data
I am having trouble getting my head around pointers in C++, specifically how they behave when passed around or used within objects. As far as my understanding goes as long as pointers, or more specifically values/objects pointed to - do not go out of scope, I should be able to use that pointer.
I have been playing around with some test code on my Arduino Uno and I am bumping into behaviour I cannot explain.
I have read rather a lot on the topic of pointers in C++ and thought I had a good grasp of it. However, practice doesn't seem to match the theory in my head. I don't know if this is a lack of understanding or if the Arduino platform has idiosyncrasies that I am not aware of.
In my test code I have created two classes, Alpha and Beta. Alpha simply holds a C-type string in a member variable called alpha. Beta is designed to hold two Alpha instances in an array*.
*While this is "toy" code, the general structure mirrors my actual project. I have used this toy code as it more succinctly describes the set up and the issue I am facing.
pointers.h
#import "Arduino.h"
class Alpha {
    private:
        char alpha[20];
    public:
        Alpha();
        ~Alpha();
        char* getAlpha(char* s, int size=20);
        void setAlpha(char* value, int size=20);
        void debug();
};

class Beta {
    private:
        Alpha** alphas;
    public:
        Beta();
        ~Beta();
        Alpha* getAlpha(int index);
        void setAlpha(Alpha* alpha, int index);
        void doStuffWithAlpha(int index);
};

pointers.cpp
#import "pointers.h"

Alpha::Alpha() {
    setAlpha("Initial");
}

Alpha::~Alpha() {}

char* Alpha::getAlpha(char* s, int size/*=20*/) {
    *s = *alpha;
    return s; //return not strictly needed here since s is passed in
}

void Alpha::setAlpha(char* value, int size/*=20*/) {
    strncpy(alpha, value, size-1);
    alpha[size-1] = '\0';
}

void Alpha::debug() {
    Serial.println(alpha);
}

Beta::Beta() {
    alphas = new Alpha*[2];
}

Beta::~Beta() {}

Alpha* Beta::getAlpha(int index) {
    return alphas[index];
}

void Beta::setAlpha(Alpha* alpha, int index) {
    alphas[index] = alpha;
}

void Beta::doStuffWithAlpha(int index) {
    Alpha* alpha = getAlpha(index);
    /* Alpha* alpha = alphas[index]; */ //This doesn't work either - same outcome.
    alpha->debug();
}

sketch.ino
#import "pointers.h"
Alpha a1;
Alpha a2;
Beta b1;

void setup() {
    Serial.begin(9600);
    Serial.println("SETUP()");
    Serial.println();

    a1 = Alpha();
    a1.setAlpha("Hello");

    Serial.println("----- a1.debug -----");
    Serial.println("Expected: Hello");
    Serial.print("Actual: "); a1.debug();
    Serial.println();

    a2 = Alpha();
    a2.setAlpha("Goodbye");

    Serial.println("----- a2.debug -----");
    Serial.println("Expected: Goodbye");
    Serial.print("Actual: "); a2.debug();
    Serial.println();

    Beta b1 = Beta();
    b1.setAlpha(&a1, 0);
    b1.setAlpha(&a2, 1);

    Serial.println("----- b1.doStuffWithAlpha -----");
    Serial.println("Expected: Hello");
    Serial.print("Actual: "); b1.doStuffWithAlpha(0);
    Serial.println("Expected: Goodbye");
    Serial.print("Actual: "); b1.doStuffWithAlpha(1);
    Serial.println();
}

void loop() {
    Serial.println("LOOP()");
    Serial.println();

    Serial.println("----- a1.debug -----");
    Serial.println("Expected: Hello");
    Serial.print("Actual: "); a1.debug();
    Serial.println();

    Serial.println("----- b1.doStuffWithAlpha(0) ------");
    Serial.println("Expected: Hello");
    Serial.print("Actual: "); b1.doStuffWithAlpha(0);
    Serial.println();

    Serial.println("----- a2.debug -----");
    Serial.println("Expected: Goodbye");
    Serial.print("Actual:   "); a2.debug();
    Serial.println();

    Serial.println("----- b1.doStuffWithAlpha(1) ------");
    Serial.println("Expected: Goodbye");
    Serial.print("Actual:   "); b1.doStuffWithAlpha(1);
    Serial.println();

    delay(10000);
}

This sketch is quite straight-forward. It creates 2 Alpha objects and a Beta object and passes the two Alphas into Beta. The myriad Serial.print() statements produces the output below.
output
SETUP()

----- a1.debug -----
Expected: Hello
Actual:   Hello

----- a2.debug -----
Expected: Goodbye
Actual:   Goodbye

----- b1.doStuffWithAlpha -----
Expected: Hello
Actual:   Hello

Expected: Goodbye
Actual:   Goodbye

//everything is fine up to this point...

LOOP()

----- a1.debug -----
Expected: Hello
Actual:   Hello

----- b1.doStuffWithAlpha(0) ------
Expected: Hello
Actual:   CÃoçëyc=Lä^ÜŽYw¸Nv†Ý¿  //uh oh...

----- a2.debug -----
Expected: Goodbye
Actual:   Goodbye

----- b1.doStuffWithAlpha(1) ------
Expected: Goodbye
Actual:   ÿß/ï //uh oh again...

Everything works as expected when running a1 or a2.debug() or b1.doStuffWithAlpha() in the setup() function.
The result of a1.debug() and a2.debug() works as expected in the loop() function.
The issue, as you can see, is when running b1.doStuffWithAlpha(0) or b1.doStuffWithAlpha(1). The output is usually junk, which suggests to me the pointer has been mangled and points in the wrong place.
I don't understand what is happening between the transition from setup() to loop(). At first I thought the issue was the "Hello" and "Goodbye" strings going out of scope, but Alpha::setAlpha() makes a copy of the C-string. Also, accessing Alpha::debug() in loop() works, as shown above.
I have tried variations on the above code, such as using a struct or an int for alpha instead of a C-string and the results are the same: Mangled values.
Have I done something obviously silly that my scant C++ experience hasn't picked up on, or is there some fundamental Arduino shenanigans at play?

Problem is local shadow variable b1 in setup() function declared as Beta b1 = Beta();. In loop() is considered uninitialized global variable b1.

I agree that is probably the problem. Also in your destructor for Beta you should delete the pointers you allocate in the constructor. I'm not wildly keen on doing new in a constructor at static scope either because of the static initialization order fiasco.

@TMa I can't believe I missed that! I must have been looking at my own code for too long! @NickGammon I agree that I should have a destructor, it was left out for just this example. Regarding the use of new in a constructor, how else would I do it? Reading the link you gave, the initialisation fiasco only affects classes/types declared in different compilation units. My code has both classes defined in the same file.

If the project ever gets large enough that you have more than one compilation unit, it may affect you. What you can do is have a begin method which is called from setup (eg. like Serial). Alternatively (or as well) you could set the pointers to NULL in the constructor (which is safe) and then allocate them with new when they are needed.

source: Stack Exchange

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

sort: votes


text:
Measurement of pulse duration greater than 3mins
Is it possible to measure the width of a pulse which is longer than 3 minutes? The pulseIn function can only measure duration of maximum 3 minutes accurately.
I've tried using interrupts but haven't come up with a correct solution yet.
I'm measuring the duration of pulse (HIGH) generated by AND gate connected to the outputs of two comparators. AND gate output voltage is around 4.9 volts.
Any logical solution or idea would be appreciated. Thanks!

The concept is actually quite simple.
You need to record the time when the signal goes high, and record the time when it goes low. The pulse width is the difference between the two times.
Yes, you can do it with interrupts, but you don't need to if you're not trying to do anything else at the same time.
A simple polling code could be something like this:
while (digitalRead(pin) == LOW); // Wait for input to go high
unsigned long startTime = millis(); // Record start time
while (digitalRead(pin) == HIGH); // Wait for input to go low
unsigned long endTime = millis(); // Record end time
unsigned long pulseDuration = endTime - startTime;

You basically sit doing nothing until the leading rising edge of your pulse.  You then record the time, and again sit doing nothing - this time while looking for the trailing falling edge of the pulse.  Then record the end time and subtract the two.

I understand the concept but can you please suggest some ways to do it? I'm not an expert in Arduino programming. I'm helping my teacher in her project. Please suggest the simplest method as no other processing has to be done when the pulse duration is being calculated.

I am on my phone at the moment. I can post some sample code later on.

Thank you very much. I'll try this code and let you know if it works.

Problem solved! My professor is satisfied with the result. You're the best! Thanks.

Here is some code I used to time a ball running down a ramp:
const byte LED = 12;
const byte photoTransistor = 2;

unsigned long startTime;
volatile unsigned long elapsedTime;
volatile boolean done;

void ballPasses ()
{
  // if high, start timing
  if (digitalRead (photoTransistor) == HIGH)
    {
    startTime = micros ();
    }
  else
    {
    elapsedTime = micros () - startTime;
    done = true;
    }

  digitalWrite (LED, !digitalRead (LED));
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ("Timer sketch started.");
  pinMode (LED, OUTPUT);
  attachInterrupt (0, ballPasses, CHANGE);
}

void loop ()
  {
  if (!done)
    return;

  Serial.print ("Time taken = ");
  Serial.print (elapsedTime);
  Serial.println (" uS");
  done = false;
  }

Using micros() here is probably overkill, but that should be good for an interval up to 71 minutes.

An interesting code. Nice use of the flag 'done'. Thank you very much!

Hi @Nick-Gammon. I'm not sure it is important to mention but without timer rollover detection this code should only be used to measure events less than 70 minutes. (Did I do the math right on the rollover frequency?)

Well, I mentioned above that should be good for an interval up to 71 minutes. Yes, the rollover time is 71.58 minutes.

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


text:
How does Yun identify itself to Windows?
When I plug in my Yun, Windows pops up a box saying Windows needs to install driver software for your Arduino Yun.
What does Windows use to identify my device as an Arduino Yun? Is it written in a file somewhere, so I could for example, remove that driver prompt, or change it to Windows needs to install driver software for your Foo Bar?

It is written in what is called the USB String Descriptor.  I don't have my Yun to hand right now (it's acting as a wireless bridge temporarily), but all USB devices have these USB String Descriptors.  Here's an example for the Leonardo (which you can easily inspect on Linux):
$ sudo lsusb -v -d 2341:0036

Bus 001 Device 015: ID 2341:0036 Arduino SA
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               1.10
  bDeviceClass            2 Communications
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0         8
  idVendor           0x2341 Arduino SA
  idProduct          0x0036
  bcdDevice            0.01
  iManufacturer           2 Arduino LLC      <<== String descriptor ID 2
  iProduct                1 Arduino Leonardo <<== String descriptor ID 1
  iSerial                 0
  ... etc ...

Internally the strings are stored as an indexed table - there's two there, ID 1 and ID 2.  The Device Descriptor then has a couple of bytes in it that says "The manufacturer is string ID 2, and the product name is string ID 1".  The operating system then requests those string descriptors so it can display the friendly message for you.
If you want to change that name you basically have to both re-program the bootloader (which has the USB descriptors when in program upload mode) and the Arduino core (that has the string descriptors programmed into it).

authors: Дима Перильман


text:
Can I stack an Arduino to another Arduino?
I'm using Arduino clones, which have pin headers the same as Arduino's shields have (with extended "legs" below the board to be stackable).
Can I stack my Arduino (Mega) clone to an Arduino (Uno) clone without destroying both? Wouldn't it explode or something?
Just asking before trying it.
Thanks!

Is this a curiosity question or do you have a goal in mind? Just curious....

No, I don't think that is a good idea. You would basically short the pins of each of them together, plus their power supplies. The only way it might conceivably work was if one Arduino had all its pins as inputs and the other as outputs, otherwise they would be "fighting" each other to drive a pin high or low. You would also have connected together their Reset pins so they would both reset at the same time. And doing serial comms would be problematic as the serial ports would be fighting each other.

Also, uploading sketches would be virtually impossible, as when you started the upload, both would be reset, both bootloaders would try to read the incoming data, and reply at the same time. Plus, the Mega and the Uno have different uploading protocols. So at the very least, you would have to separate them every time you uploaded new code, to either one.


text:
Arduino ethernet shield not getting correct IP
I have a very simple sketch which I'm using to (try to) prove out an ethernet shield. The complete sketch is below. When I upload the sketch, the IP address that the shield gets is 0.140.140.140, which is incorrect. I just received the shield today from SparkFun, it is this one. Am I doing something wrong, or is my shield  and/or Arduino broken? The Arduino is an Uno R3. The sketch works otherwise (the LED blinks as expected).
Sketch:
#include <SPI.h>
#include <Ethernet.h>

// Network information
byte mac[] = {0xDE, 0xAD, 0xBE, 0xCF, 0xFE, 0xEE };
byte ip[] = { 172, 31, 42, 201 };

void setup() {
  pinMode(4,OUTPUT);
  digitalWrite(4, HIGH);
  delay(1);

  // initialize serial:
  Serial.begin(9600);
  Serial.println("Starting sketch...");
  Ethernet.begin(mac,ip);
  delay(1000);
  Serial.println(Ethernet.localIP());
  Serial.println("Setup done.");
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13,HIGH);
  delay(1000);
  digitalWrite(13,LOW);
  delay(1000);
  Serial.println(Ethernet.localIP());
}

The sketch you have written works perfectly with a cheap Ethernet Shield clone from eBay.  Those (and the older Arduino Ethernet Shields) use the Wiznet W5100 chip.
The new shields, of which you have one, use the newer, more powerful, Wiznet W5500 chip.
You can't use the old Ethernet library with the new Wiznet W5500 chip.  It doesn't work.
You have to use the "Ethernet 2" library as described here:

http://labs.arduino.org/Ethernet+2+Library

Note: this library is used to work with the new Ethernet shield (version 2) and Leonardo Eth that uses a new Controller W5500.

That page is linked from the product page you link to above.  If you had read the product page you would already know this.

Ok, my bad for not knowing to use the Ethernet 2 library... unfortunately,the page you linked to doesn't have a download link, and my IDE doesn't have the Ethernet2.h file available, so the sketch won't even verify with Ethernet2.h.

This is all a product of the fallout between the two superegos in Arduino.  The library (AFAIK) is bundled with the Arduino IDE that you can download from Arduino.org but not with the IDE That you can download from Arduino.cc.  These days you need both IDEs and you have to lick your finger and hold it up to see which way the wind is blowing to know which to use at that particular time.  The whole situation is getting incredibly childish and idiotic.

Well isn't that just wonderful. Another project goes to crap because people can't get along. Maybe it's time to look at a Raspberry Pi for this project.

If you're interested I have added Arduino.org (and its associated libraries including Ethernet2) top the beta version of UECIDE


text:
Unexpected output form Serial.println
So I have a teensy and an arduino uno connected together via I2C, however some very odd behavior is occurring, when monitoring the serial connection for shorter data sent over I2C I receive the expected serial output. However if the data is longer I only receive 2 characters. More strange even is that if I send the longer data again I receive none, but if I send the shorter data I receive the expected output. After sending the shorter data again sending the longer data will result is the odd 2 characters.
Uno code
     //#include
 #include <Wire.h>

boolean pinout = 0;
byte current[512];

void setup() {
  // put your setup code here, to run once:
  Wire.begin(1);
  Serial.begin(115200);
  Wire.onReceive(data);
  //DmxSimple.usePin(3);
  //DmxSimple.maxChannel(30);
}

void loop() {

}

void data(int numBytes){
//Serial.println("DATA RECIVED");

 delay(500);

 char input[20];
 int pos = 0;

 while(Wire.available()){
   input[pos++] = Wire.read();
  }
  input[pos++] = '\0';

  Serial.print("Recived \"");
  Serial.print(input);
  Serial.println("\"");

  char* next = strchr(input, ',');
  while(next != 0){
  *next = 0;
  next++;
  char* splitter = strchr(next, ':');
  if(splitter != 0){
  *splitter = 0;
  splitter++;
  int channel = atoi(next);
  int value = atoi(splitter);
      //DmxSimple.write(channel,value);
      Serial.print(channel); Serial.print(":"); Serial.println(value);
    }
  }
}

Teensy code
            #include <i2c_t3.h>
            //#include <ArduinoPebbleSerial.h>

     /*
    static const uint16_t SERVICE_ID = 0x1001;
static const uint16_t UPTIME_ATTRIBUTE_ID = 0x0002;
static const size_t UPTIME_ATTRIBUTE_LENGTH = 4;
static const uint16_t LAMP_ATTRIBUTE_ID = 0x0003;
static const size_t LAMP_ATTRIBUTE_LENGTH = 20;

static const uint16_t SERVICES[] = {SERVICE_ID};
static const uint8_t NUM_SERVICES = 1;

static const uint8_t PEBBLE_DATA_PIN = 1;
static uint8_t buffer[GET_PAYLOAD_BUFFER_SIZE(4)];

typedef struct __attribute__((packed)){
  uint8_t channel;
  uint8_t value;
} DMXP;*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Wire.begin();
  Serial.begin(9600);
  /*
 #if defined(__MK20DX256__) || defined(__MK20DX128__)
  // Teensy 3.0/3.1 uses hardware serial mode (pins 0/1) with RX/TX shorted together
 ArduinoPebbleSerial::begin_hardware(buffer, sizeof(buffer), Baud57600, SERVICES, NUM_SERVICES);
#elif defined(__AVR_ATmega32U4__)
 // Teensy 2.0 uses the one-wire software serial mode
 ArduinoPebbleSerial::begin_software(PEBBLE_DATA_PIN, buffer, sizeof(buffer), Baud57600, SERVICES,
                                  NUM_SERVICES);
#else
#error "This example will only work for the Teensy 2.0, 3.0, or 3.1 boards"
#endif
*/
/*for(int i = 1; i < 8; i++){
  sendChannel(i,0);
}
*/

}

/*
void handle_dmx_request(RequestType type, size_t length) {
if (type != RequestTypeWrite) {
  return;
}

DMXP cmd = *(DMXP*)buffer;
sendChannel(cmd.channel, cmd.value);

// ACK that the write request was received
ArduinoPebbleSerial::write(true, NULL, 0);
ArduinoPebbleSerial::notify(SERVICE_ID, UPTIME_ATTRIBUTE_ID);
}
*/

void loop() {

  /*
  if (ArduinoPebbleSerial::is_connected()) {
  digitalWrite(13,true);
} else {
  digitalWrite(13,false);
}

uint16_t service_id;
uint16_t attribute_id;
size_t length;
RequestType type;
if (ArduinoPebbleSerial::feed(&service_id, &attribute_id, &length, &type)) {
  // process the request
  if (service_id == SERVICE_ID) {
    switch (attribute_id) {
      case LAMP_ATTRIBUTE_ID:
        handle_dmx_request(type, length);
        break;
      default:
        break;
    }
  }
}
*/

}

void serialEvent(){
  if(Serial.read() == 't'){
  digitalWrite(13,true);
  Serial.println("Starting Controller");
  int chans[8] = {1,2,3,4,5,6,7,8};
  int vals[8] = {2,4,6,8,16,32,64,128};
  sendChannel(chans,vals,4);
  } else {
    sendChannel(1,1);
  }
  while(Serial.available()){
    Serial.println(Serial.read());
  }
}

void sendChannel(int chan, int val){
 char chno[8];
  itoa(chan,chno,10);
  char vano[8];
 itoa(val,vano,10);
 char message[20];
 int messagei = 0;
 for(int i = 0; i < 7; i++){
 if(chno[i] == '\0'){
   break;
  }
 message[messagei++] = chno[i];
}
 message[messagei++] = ':';
 for(int i = 0;i < 7; i++){
 if(vano[i] == '\0'){
  break;
 }
 message[messagei++] = vano[i];
 }
  //message[messagei++] = '\n';
//message[messagei++] = '\r';
message[messagei++] = '\0';

Serial.println(message);

Wire.beginTransmission(1);
Wire.write(message);
Wire.endTransmission();
}

void sendChannel(int chan[], int val[], int num){
 char message[20*num + 1];
 int at = 0;

 for(int i = 0; i < num; i++){
char chno[8];
itoa(chan[i],chno,10);
char vano[8];
itoa(val[i],vano,10);
for(int i = 0; i < 7; i++){
  if(chno[i] == '\0'){
    break;
  }
  message[at++] = chno[i];
}
message[at++] = ':';
for(int i = 0;i < 7; i++){
  if(vano[i] == '\0'){
    break;
  }
  message[at++] = vano[i];
  }
  if(i+1!=num){
  message[at++] = ',';
  } else {
  message[at++] = 0;
 }
 }

 char finalMessage[at+1];
 for(int i = 0; i <= at; i++){
finalMessage[i] = message[i];
 }

 Serial.println(finalMessage);

Wire.beginTransmission(1);
Wire.write(message);
Wire.endTransmission();

}

(If modifying the teensy code to run on a second arduino replace the line #include <i2c_t3.h> with #include <Wire.h> no other changes should be necessary)
To use the Teensy code open a serial terminal to access it, press 't' to send a long packet, or any other character to send a shorter one.

In future please use "code quoting" for referencing include directives. As you can see from your post (unless it is fixed now) things in angled brackets are treated as HTML and don't render properly.

Your code is short enough to include in the post. Please post it rather than sending people of to GitHub for short amounts of simple code. Use "code formatting" - select the code and hit Ctrl+K to indent if four spaces and then it should be very readable.

Your code which I will reproduce here as it wasn't in the question has a major issue:
//#include <DmxSimple.h>

#include <Wire.h>

boolean pinout = 0;
byte current[512];

void setup() {
  // put your setup code here, to run once:
  Wire.begin(1);
  Serial.begin(115200);
  Wire.onReceive(data);
  //DmxSimple.usePin(3);
  //DmxSimple.maxChannel(30);
}

void loop() {

}

void data(int numBytes){
  //Serial.println("DATA RECIVED");

  delay(500);

  char input[20];
  int pos = 0;

  while(Wire.available()){
    input[pos++] = Wire.read();
  }
  input[pos++] = '\0';

  Serial.print("Recived \"");
  Serial.print(input);
  Serial.println("\"");

  char* next = strchr(input, ',');
  while(next != 0){
   *next = 0;
   next++;
    char* splitter = strchr(next, ':');
    if(splitter != 0){
      *splitter = 0;      Wire.onReceive(data);
  //DmxSimple.usePin(3);
  //DmxSimple.maxChannel(30);
}

Your function data does Serial.prints. It is called as an interrupt service routine effectively, and thus should not do serial prints:
      Wire.onReceive(data);
    }

    void loop() {

    }

    void data(int numBytes){

...

      Serial.print("Recived \"");
      Serial.print(input);
      Serial.println("\"");

More strange even is that if I send the longer data again I receive none, ...

Yep, that will definitely happen. The serial printing "blocks" if you print a lot, and thus the code will hang indefinitely.

  delay(500);

You definitely should not use delay in an interrupt routine. It will almost certainly hang because the timer interrupts which are needed for delay to work are not being serviced.

  Wire.begin(1);

You should not be choosing to use I2C address 1. It is reserved. See:
7-bit, 8-bit, and 10-bit I2C Slave Addressing and I2C specification (pdf)
Slave Address   R/W Bit     Description
000 0000    0   General call address
000 0000    1   START byte(1)
000 0001    X   CBUS address(2)
000 0010    X   Reserved for different bus format (3)
000 0011    X   Reserved for future purposes
000 01XX    X   Hs-mode master code
111 10XX    X   10-bit slave addressing
111 11XX    X   Reserved for future purposes

(1) No device is allowed to acknowledge at the reception of the START byte.
(2) The CBUS address has been reserved to enable the inter-mixing of CBUS compatible and I2C-bus compatible devices in the same system. I2C-bus compatible devices are not allowed to respond on reception of this address.
(3) The address reserved for a different bus format is included to enable I2C and other protocols to be mixed. Only I2C-bus compatible devices that can work with such formats and protocols are allowed to respond to this address.


text:
Unable to set up Intel Edison on Windows
I am new to hobby electronics and have hit a dead end with my Intel Edison (which hopefully will not join the pile of useless components I have wasted my money on), and would appreciate some help with the setup procedure. The main problem is that I cannot connect to my Edison via the middle (lets call it "A") micro-USB port in order to get it into a working condition.
My objective is to connect to it's build-in Linux via SSH with the USB cables connected after installing the latest flash image.
I am using an Edison with an Arduino breakout board.
Here is the sequence of steps I followed:

I connected a 12V 2.6A AC to DC adapter to power the board. (Via the barrel connector). The green light came on to indicate it is powered.
I connected the "A" micro-USB port (i.e. not the one on the edge) to my computer.

At this point I could access the drive through Windows Explorer, however this changed when I executed the next step:

I installed the software from step 2 at https://software.intel.com/en-us/iot/library/edison-getting-started.
Something went wrong during the subsequent installation process. I don't know what.

At this point I could no longer access the drive. It would only appear as an "Unknown device" in Windows Device Manager. In order to try and fix this I gave up on the option where it is mounted as a Windows Drive.

I connected to the micro-USB port at the edge of the Arduino board and disconnected A.
I went to Windows Device Manager and found the connected device on COM6
I installed Putty and connected to COM6 with a baud of 115200.
The console showed a blank screen with a green cursor in the top left.
I waited 30 seconds for it to boot.
I hit Cntrl+C because I still saw the same screen from step 9.

I then saw this on the console:

Unknown boot mode: boot
Saving Environment to MMC...
Writing to MMC(0)... done
Resetting to default boot mode and reboot...
resetting ...

******************************
PSH KERNEL VERSION: b0182b2b
                WR: 20104000
******************************

SCU IPC: 0x800000d0  0xfffce92c

PSH miaHOB version: TNG.B0.VVBD.0000000c

microkernel built 11:24:08 Feb  5 2015

******* PSH loader *******
PCM page cache size = 192 KB
Cache Constraint = 0 Pages
Arming IPC driver ..
Adding page store pool ..
PagestoreAddr(IMR Start Address) = 0x04899000
pageStoreSize(IMR Size)          = 0x00080000

*** Ready to receive application ***

U-Boot 2014.04 (Jun 19 2015 - 12:05:55)

       Watchdog enabled
DRAM:  980.6 MiB
MMC:   tangier_sdhci: 0
In:    serial
Out:   serial
Err:   serial
Hit any key to stop autoboot:  0
Target:ifwi
Partitioning already done...
Partitioning already done...
Saving Environment to MMC...
Writing to redundant MMC(0)... done
GADGET DRIVER: usb_dnl_dfu

I have no idea what to do next.

I fixed it by following these steps (through trial and error, I don't really understand what I did but it works ...)
I am using Windows 8.1, 64 bit edition.

Download the Edison firmware from https://software.intel.com/en-us/iot/hardware/edison/downloads. For me it was http://downloadmirror.intel.com/25028/eng/edison-image-ww25.5-15.zip.
Extract the zip file.
Start the Windows Command Prompt as Administrator.
The extracted archive should contain a file called "flashall.bat". Change to the directory containing the file.
Connect all micro-USB ports and the barrel connector. At this point Windows did not recognize the Edison as a flash disk. This is part of what I was fixing.
Follow the steps in my question until the output on the console (also from my question) appears.
Run "flashall --recovery"
Run "flashall". When "Please plug and reboot the board" appears, disconnect the A (or middle) USB port and the barrel connector for the power. At this point everything is switched off. Then reconnect A and the barrel connector to reboot the board.
Wait about 5 minutes for the rest of the process to run automatically.

At this point everything should work again.
You should see this on the command line in Windows:

C:\Users\_\Desktop\edison-image-ww25.5-15>flashall --recovery
Starting Recovery mode
Please plug and reboot the board
Flashing IFWI
!!! You should install xfstk tools, please visit http://xfstk.sourceforge.net/

C:\Users\_\Desktop\edison-image-ww25.5-15>flashall
Using U-boot target: edison-blankrndis
Now waiting for dfu device 8087:0a99
Please plug and reboot the board
Dfu device found
Flashing IFWI
Download        [=========================] 100%      4194304 bytes
Download done.
Download        [=========================] 100%      4194304 bytes
Download done.
Flashing U-Boot
Download        [=========================] 100%       237568 bytes
Download done.
Flashing U-Boot Environment
Download        [=========================] 100%        65536 bytes
Download done.
Flashing U-Boot Environment Backup
Download        [=========================] 100%        65536 bytes
Download done.
Rebooting to apply partiton changes
Dfu device found
Flashing boot partition (kernel)
Download        [=========================] 100%      6111232 bytes
Download done.
Flashing rootfs, (it can take up to 5 minutes... Please be patient)
Download        [=========================] 100%    566330368 bytes
Download done.
Rebooting
U-boot & Kernel System Flash Success...
Your board needs to reboot to complete the flashing procedure, please do not unplug it for 2 minutes.

C:\Users\_\Desktop\edison-image-ww25.5-15>


text:
Arduino Pin won't go LOW
I have something strange going on with an output. When the following code is called the LED goes on, but it stays on, there is no blinking. If I comment out the set HIGH statement the LED never comes on (as expected).
#define devicePin 10

void setup() {
  pinMode(devicePin, OUTPUT);
}

void loop() {
    digitalWrite(devicePin, HIGH);
    delay(2000);
    digitalWrite(devicePin, LOW);
}

Could I have damaged the board in some way?

After you drive the pin low, you immediately go to the beginning of the loop and set the pin high (if you have an oscilloscope, you might see a very short downward pulse).
So, add another delay after digitalWrite(devicePin, LOW).

you forgot to add a delay after digitalWrite(devicePin, LOW);
#define devicePin 10

void setup() {
  pinMode(devicePin, OUTPUT);
}

void loop() {
    digitalWrite(devicePin, HIGH);
    delay(2000);
    digitalWrite(devicePin, LOW);
    delay(2000);
}

Yes, the pin is going low. I tested it for you:

It went low for 6 µs, once every 2 seconds. :)

Overall, this is the effect:

As you can see, high for most of the time.

Yeh, I can't believe I missed it.
BTW: what did you use to monitor it and create those screens?

My trusty Tektronix TDS 2002 oscilloscope. To get the output I get the scope to output in PCX format through its RS232 port, route it through a RS232 to TTL converter, connect that to a FTDI cable, and capture it on my computer. That scope was made in the days before they had plug-in USB drives.

One more question, what would you recommend now for an entry level scope?

You are probably best off with one of the Saleae Logic scopes/logic analyzers. Something like the Logic 4 is only $109 and has one analog and 3 digital channels. Or one of the higher models if you can afford it. I find the Logic very very useful for decoding SPI/I2C/Serial data streams. You could make this a separate question, others may also want to chip in with their suggestions.


text:
Consulting and inserting a string into an array if it doesn't exist (Arduino IDE) 1
Sorry that I repeat my question, I can't enter to my user...
In the project I'm doing, I connect an arduino mega with ethernet and Post some Strings to the server. The arduino mega has a receiver(315MHz). I have some arduinos nano connected with PIR sensors that sends a some int with transmitters (315MHz). What I want to do is a list in my arduino mega that stores the values sent by the arduinos nanos to use them to my server (using POST). my question is the following:
If I had an empty array, what I would like to do is
listOfSensors[]={}

void funtion (String sensor){
    if (sensor is inside listOfSensors){
         //dont do anything
    }
    else {
         add sensor to listOfSensors
    }

I have been looking for hours, but I haven't found anything so far... Anyone has any idea? Thanks!!

Don't just double-post. Work out how to log into your earlier user. I'm sure StackExchange has ways of retrieving your password, or whatever-it-is that went wrong.

I registered with my mail but I didn't confirmed, then I accesed with my facebook, wich is related with my mail, so when I try to access the other account it says I'm already registered...I know I shouldn't but I really can't acces to my account

In C there is no such thing as an "empty array".  All arrays have a finite pre-defined size.
String sensors[10]; // Room for up to 10 sensors

The usual way of storing an unknown number of entries that will be added to "as and when" is to use a linked list or doubly-linked list.
A linked list is a list of items where each item also contains a pointer to say where the next item in the list is located.
Also you shouldn't use the String class as it is not good when working with linked lists (or in general - stick to C strings).
Warning: linked lists aren't for the faint of heart.
First you would define a struct to store the data you want in the linked list:
struct sensor {
    char *name;
    int currentValue;
    struct sensor *next;
};

That would store the name of the sensor ("name"), the current value from the sensor ("currentValue") and also contains a pointer ("*next") to the next entry in the list.  That last bit is the most important.
Now you create a "head" pointer variable to start your list off:
struct sensor *mySensors = NULL;

That starts out as NULL to say "This variable has nothing in it at the moment".
Now that was the easy part.  The hard part is adding entries to the list...
A couple of helper functions can be of use here.  Let's start by defining a function that will look for a specific entry by name in the list:
struct sensor *findSensor(const char *name) {
    for (struct sensor *scan = mySensors; *scan; scan = scan->next) {
        if (strcmp(scan->name , name) == 0) {
            return scan;
        }
    }
    return NULL;
}

That will start off with a pointer variable scan pointing to the first entry in the linked list (mySensors).  While it's pointing to a valid entry (not NULL) compare the name to the given string and if they match then return the entry we are pointing to.  Next point to whatever the "next" pointer is pointing to, so you move down the list.
Now to add a sensor:
struct sensor *addSensor(const char *name, int value) {
    // First look to see if it exists:
    struct sensor existing = findSensor(name);
    if (existing != NULL) { // We found it
        existing->currentValue = value; // Update the value
        return existing;
    }
    // We haven't got it in our list, so create a new entry:
    struct sensor newsensor = (struct sensor *)malloc(sizeof(struct sensor));
    // And fill in the data:
    newsensor->name = strdup(name); // Create a COPY of the string
    newsensor->currentValue = value; // Store the value
    newsensor->next = NULL;
    // IMPORTANT: The new entry must point to NULL to mark the end of the list:
    newsensor->next = NULL;

    // Now where to add it in the list? Is there even a list?
    if (mySensors == NULL) {
        // No? Then we just make our new entry the head of the list:
        mySensors = newsensor;
        return newsensor;
    }
    // Otherwise we need to scan through the whole list to find
    // where the tail of the list is:

    struct sensor *scan = mySensors;
    // While the current entry points to a valid next entry
    while (scan->next) {
        // move on to that next entry
        scan = scan->next;
    }
    // There must be no valid next entry now (scan->next == NULL), so
    //  add our new sensor as the next valid entry:
    scan->next = newsensor;
    return newsensor;
}

Removing a sensor from the list is a much more involved process (even more than adding a sensor).  You need to "splice" the list around the deleted entry.  I'll add detail on that if you need it, but by the sound of things you won't be removing entries, only adding them.
The routines shown there (I haven't actually tested them, but it is standard code I write all the time) aren't as efficient as they could be.  If you are adding and removing entries all the time and you end up with quite a large list it can take longer and longer to scan right through the list to find the last entry to add to.  If that is the case you can maintain a "tail" pointer that you always update to point to the last added entry whenever you add one.  That can then be used to rapidly add to the end of the list without having to scan through the whole list every time.
Another optimisation if you do a lot of scanning around within a list is to make a doubly linked list.  This is just like the linked list above except it works in both directions.  Not only do you store a next pointer, you also store a previous pointer.  You can now scan in either direction - from head to tail or from tail to head, or hopping around at will inside the list.  That is especially useful if you want to do things like ordering the list alphabetically.

If you only need to add items of a fixed size to your sensor list (i.e. you don't need to delete items or sort them), you can use an uninitialized array large enough for the maximum number of items it will need to hold:
#define MAXSENSORS 30               // max sensor count
#define SNAMELEN 12                 // max sensor name length

struct sensorData {
    char sname[SNAMELEN+1];
    uint16_t svalue;
};                                  // defines data for 1 sensor

uint8_t sensorCount = 0;
struct sensorData listOfSensors[MAXSENSORS]={0}; // array of sensor data, initialized to 0, 0, ...

You'll also need an unsigned int (perhaps only a byte) to keep track of the count of items in the array, which you'll increment every time you add another sensor (up to the maximum number).
I think this is what you meant by "empty array". You would add your next sensor data at listOfSensors[i], then increment i. Likewise, you would search for a sensor in the array from listOfSensors[0] to listOfSensors[i-1].


text:
Convert the Serial.Println to string
I'm working with VirtualWire and I'm trying to get a string value out of the Serial.println in the loop. I've tried create a string and add the message[i] , but surprisingly message[i] becomes an int when added. Serial.println outputs the string correctly, but the string that I get from message[i] is just numbers...
#include <VirtualWire.h>
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
String sensorname;
void setup(){
  Serial.begin(9600);
  Serial.println("Device is ready");
  // Initialize the IO and ISR
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  }
void loop(){

  if (vw_get_message(message, &messageLength)){
    Serial.print("Received: ");
    for (int i = 0; i < messageLength; i++){
      Serial.write(message[i]);
      sensorname += message[i];
      }
      Serial.println();
      Serial.pintln("Name of sensor: " + sensorname);
      sensorname="";  //Reestart the string
      }
}

I'm quite new with VirtualWire so I don't know if there is command to get the message and pass it directly to string...Any help will be appreciated!
EDIT
I think I dind't express myself well. In my original question I didn't add the String sensor name
The Response I get in the Serial is the following:
Device is ready
SensorA
Name of sensor: 8310111011511111465

My aim is to instead of having as sensorname=8310111011511111465, have sensorname=SensorA

Those numbers are the numerical ASCII representation of the characters.
83 = S
101 = e
110 = n
... etc ...

(Find the whole list here: http://www.asciitable.com/)
The reason you are ending up with numbers is because of the type of variable you are receiving the data into - a byte.
A byte stores a number between 0 and 255.  When you add that byte to a String the compiler assumes you want to append a number, since it is a numerical type that you are using.
If you instead tell it to use a char type then the compiler should realise "Ah, this is the numeric representation of a character - I will add the character instead".
You can either change the whole array type:
char message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages

Or cast the variable to be the right type when you append it:
  sensorname += (char)message[i];

Or better still, don't use the String class since it is really too heavyweight and prone to memory issues for use on a little microcontroller.  Stick to C strings. They take a little more getting used to, but are so much more microcontroller friendly.

Thanks, Majeko, that did the trick! In my case I want to use this value to post it into a webserver, but what you suggestest can't be applied because I have to post as a string no? Thanks again!

A "String" is just a "C string" with dynamic allocation and lots of helper functions.  It's rare for a library author to only ever allow you to use String objects.  C strings are far more commonly supported than String objects.


text:
How does arduino fetch instruction string from sms and execute?
I am working on a project in which i have to send commands using sms (GSM shield) to the arduino uno to control dc motor. What i want to know is that how can i define the instruction strings that i can send in form of sms and arduino uno reads it and executes it.
P.S. I am a total beginner at arduino coding so please help me out.

You can define them in any way you want - they are strings, they just contain text.  It's up to you to decide what you want that text to say and how you want the Arduino to act when it gets that text.,

Your GSM shield will receive the SMS which your Arduino code can retrieve as a string of characters (that description hides a mountain of detail, most of which you won't need to know). It doesn't care what the content of the SMS message is.
Your Arduino code will have to translate from the message text to motor-control commands so you want some text commands that will be easy to parse, but not so trivial that any random message might wrongly be interpreted as legitimate commands.
The digit pair "15" might command motor 1 to speed 5. But you wouldn't want any message with a couple of digits in it to change a motor. (You didn't say you had multiple motors, and if not you can leave that part out).
Let's make the message distinctive enough that it's unlikely to appear in some other context, yet simple enough to distinguish as legitimate. It would be nice if it's simple to thumb-type, too!
"motor,1,5" could convey the same information as the "15" in our first example, doesn't limit you one-digit values, isn't likely to appear in a "Hey Dude, lunch at 12:15?" type of conversation, is easy to parse and isn't too long to type on a tiny keyboard. You could extend it later, so "motor,1,+2" could mean to increase motor 1's speed by two units, "motor,1,off" could mean power it down (not just zero speed), and "motor,all,off", well, that's probably obvious.
Look up the function sscanf() [oops: not sprintf()] for one way to parse the incoming strings and collect their data.
Update: sscanf() does the reverse of sprintf(): It reads a string, collects values from it, and assigns them to variables. Search sscanf on the web for a description of its use.
Here is a sample program that reads a few possible SMS messages, checks whether they are motor commands (according to my simple example SMS above), and if it is, assigns the contained values to some variables in your program. You can see by the return values of sscanf() whether and how many conversions it made from each message, thus your code can tell whether a received SMS looks like a motor command, as well as what the command values are:
/*
 * sscanf example - Uses sscanf to test and collect data from a
 * a command string.
 */

#include <WProgram.h>

void test_sscanf(const char *sms);

// Sample of SMS messages to test whether our sscanf() format string
// can recognize good ones and reject bad ones. Experiment by adding
// ones of your own:
const char *SMS[] =
{
   "motor,1,5",
   "Hello World,3,2",
   "motor 123 456",
   "moto, 7, 13",
   "motorized, 4, 11"
};

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

   delay(1000);     // delay for user to launch a terminal (if you're quick)

   // Test each SMS example in the SMS array
   for( uint8_t s = 0; s < sizeof(SMS)/sizeof(char *); ++s ){
      test_sscanf(SMS[s]);  // test one SMS string
   }
}

void loop() {
   ;            // nothing to do here
}

// Tests a sample SMS, prints the number of variables it assigned, and what
// their values were. '0' means it didn't assign any, probably because the
// command-word failed to match.
void test_sscanf(const char *sms)
{
   int16_t assigned, values[2];

   // Print the SMS and convert it.
   Serial.print("\nSMS: \""); Serial.print(sms); Serial.println("\"");
   assigned = sscanf(sms, "motor,%d,%d", &values[0], &values[1]);

   // Display the results
   Serial.print(assigned);  Serial.println(" values assigned"); // How many values? A good command has 2.
   if( assigned > 0 ){
      for( uint8_t i = 0; i < assigned; ++i){
     Serial.print("value["); Serial.print(i+1); Serial.print("] = "); // print each assigned value
     Serial.println(values[i]);
      }
   }
}

So basically i have to define a variable with datatype 'char' then in the if-while-else loop we match the sms with the predefined value of the variable.

You would first match "motor," (in my example) to decide whether this string is really a motor command. Then you would convert the two following numeric values and use them to control your motor.

how do i do that?

and i forgot to mention i am using single 24v dc motor with driver ic ofcourse.

I am unable to understand >sscanf()

Ok got that i just have to do it myself now. And appreciate your help man. Thanks a ton


text:
Simple Arduino Code Not Working
When I upload this code LED at pin 13 goes HIGH and that's it. My goal is to make it blink in the order specified in the array. What am I doing wrong?
int Array[] = {1,1,1,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0};
int Data = 13;
int i = 0;

void setup() {
    pinMode(Data, OUTPUT);
}

void loop() {
    int x = Array[i];
    delay(200);
    digitalWrite(Data, x);
    i = i+1;
    if (i==23) {
        i=0;
    }
}

What you're doing wrong is living your life at a normal speed.
The LED will be blinking, but so fast you can't see it change.
Without adding some delays in there you will just see the LED light up.

Still not working after i added 200ms delay

@ArduinoNoob Please don't edit the solution into your question.  Also, if Majenko's answer solved your problem, mark it as accepted by clicking the check mark underneath the answer's score.


text:
Why doesn't the LED turn on in this circuit?
I'm experimenting with buttons and LEDs and I would like my code to change a LED's brightness once a button is pressed. I connect the LED to the PWD digital pin.
My circuit looks like this one:

This is the code I'm using:
int switchPin = 8;
int ledPin = 11;
boolean lastButton = LOW;
boolean currentButton = LOW;
int ledLevel = 0;

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

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

void loop() {
    currentButton = debounce(lastButton);
    if (lastButton == LOW && currentButton == HIGH) {
        ledLevel = ledLevel + 51;
    }
    lastButton = currentButton;

    if (ledLevel > 255) ledLevel = 0;
    analogWrite(ledPin, ledLevel);
}

Though, the LED never turns on, but the light on the Arduino is on. I made sure the leads of the LED were in the right spot. Why doesn't the LED turn on?

Because you don't actually have a circuit?  One side of the LED doesn't connect to anything.

Thanks a lot for your answer, Majenko. Do I have to use a wire to connect things. Could you please propose a fix for this? Thanks. As you figured out, I'm very new to this.

One leg of the LED connects to the strip with a red line painted next to it.  That then doesn't connect to anything unless you connect it to something.  You should connect it to either +5V or GND depending on which way round your LED is.  I can never tell which way the LEDs are in those awful fritzing drawings.

Those breadboards do not automatically connect the top red line to the bottom red line (nor the blue ones). You have to do that yourself, if that is what you want.


text:
Not waking up more than once?
I'm trying the following code on an Uno. I'm pulling the high side of a pull down 10K resistor to 5V, but it can only be woken once. Just once. Does anyone know why this might be the case?
It works fine if I use LOW for attachInterrupt along with a pull-up resistor though. Just not with RISING and a pull-down.
#include <avr/sleep.h>
#include <avr/power.h>

int pin2 = 2;

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

  /* Setup the pin direction. */
  pinMode(pin2, INPUT);

  Serial.println("Initialisation complete.");

}

void pin2Interrupt(void)
{
  /* This will bring us back from sleep. */

  /* We detach the interrupt to stop it from
   * continuously firing while the interrupt pin
   * is high.
   */
  detachInterrupt(digitalPinToInterrupt(pin2));
}

void enterSleep(void)
{

  sleep_enable();

  /* Setup pin2 as an interrupt and attach handler. */
  attachInterrupt(digitalPinToInterrupt(pin2), pin2Interrupt, RISING);
  delay(100);

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_mode();

  /* The program will continue from here. */

  /* First thing to do is disable sleep. */
  sleep_disable();
}

int seconds=0;
void loop()
{
  delay(1000);
  seconds++;

  Serial.print("Awake for ");
  Serial.print(seconds, DEC);
  Serial.println(" second");

  if(seconds >= 3)
  {
    Serial.println("Entering sleep");
    delay(200);
    seconds = 0;
    enterSleep();
  }
}

I think I have seen somewhere in the past a problem with detaching an interrupt from within an interrupt handler.  You shouldn't need to detach and attach the interrupt handler all the time - just leave it attached.

@Majenko But you wouldn't want interrupts to keep firing whilst it's going to sleep, right?

I don't understand that question.  What do you mean by "going to sleep"? It's either asleep or awake. You need interrupts enabled while it's asleep so you can wake up. Does it really matter to you if an empty interrupt handler gets triggered if you press the button while it's awake?

Based on the examples here, it says "In the interrupt service routine (ISR) for a level interrupt, the interrupt must be detached otherwise the interrupt will keep happening and the ISR will be repeatedly called until the pin changes state." So it sounds like it's essential to detach - no?

Read the last word in your attachInterrupt call.  What does it say?

You mean RISING? Yeah, I'm trying to pull the pin high rather than low.

That means that the pin has to transition from low to high to trigger the interrupt.  It only does it at the moment the pin changes, not all the time it's HIGH. You have an EDGE interrupt, not a LEVEL interrupt. It will only trigger once per press of the button (discounting bounces).

Indeed. However, AFAIK, the Uno doesn't not support the HIGH argument. Is there an alternative? My chip pulls the interrupt high, so I thought LOW wouldn't be appropriate.

You are using the alternative! RISING means TRIGGER ONCE WHEN IT RISES which is what you want WITHOUT having to manually disable the interrupt!

I'm pulling the high side of a pull down 10K resistor to 5V, but it can only be woken once.  - you mean you are pulling it up, right?

@NickGammon Sorry. Yes, that's right.

So, really on a rising interrupt you want to put the 10k resistor to ground, yes? That's what I did in my test below.

For a RISING interrupt you never need to disconnect the interrupt to prevent repeat triggering.
A RISING interrupt specifically only triggers the once when the input pin transitions from LOW to HIGH rather than all the time it's in a state like a level interrupt.
Attach the interrupt once in setup() and leave it alone after that.  Your interrupt handler routine can be completely empty.  It will only ever be triggered at the exact moment you press the button.  To trigger it again you will just need to press the button again.

Probably your switch is bouncing and giving two interrupts. The first wakens it, and the second is lying there waiting until you attach the interrupt again. Then it fires, detaches the interrupt, then you go to sleep, never to awaken.
Clear any pending interrupt before doing the attachInterrupt:
EIFR = bit (INTF0);  // clear flag for interrupt 0

See Interrupts.
It is also wise to have interrupts off while setting up for sleep.

Example code:
#include <avr/sleep.h>

const byte LED = 13;

// interrupt service routine in sleep mode
void wake ()
{
  sleep_disable ();         // first thing after waking from sleep
}  // end of wake

void sleepNow ()
{
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  noInterrupts ();          // make sure we don't get interrupted before we sleep
  sleep_enable ();          // enables the sleep bit in the mcucr register
  EIFR = bit (INTF0);       // clear flag for interrupt 0
  attachInterrupt (0, wake, RISING);  // wake up on rising edge
  interrupts ();           // interrupts allowed now, next instruction WILL be executed
  sleep_cpu ();            // here the device is put to sleep
  detachInterrupt (0);      // stop this interrupt until next time
}  // end of sleepNow

void setup ()
  {
  pinMode (LED, OUTPUT);
  }  // end of setup

void loop ()
  {
  sleepNow ();
  digitalWrite (LED, HIGH);
  delay (1000);
  digitalWrite (LED, LOW);
  }  // end of loop

Tested and works OK.

Note: Since this is a rising interrupt you should have a pull-down resistor on the pin, and you trigger the interrupt by connecting the pin to +5 V.


text:
Can't get software serial to work
So I have two Arduinos (Arduino Nano) and I'm trying to get them to communicate via SoftwareSerial.  I have the 'sending' Arduino's D10 pin connected to the 'recieving' Arduino's D11 pin, and vice versa.  On my sending Arduino, I have the following code:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);

void setup() {
  pinMode(2, OUTPUT);
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.isListening()){
    digitalWrite(2, HIGH);
  }
  mySerial.write(5);
}

and on my receiving Arduino, I have:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(11, 10);

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

  Serial.begin(9600);

  mySerial.begin(9600);
}

void loop() {
  mySerial.listen();
  if (mySerial.available()>0) {
    digitalWrite(2, HIGH);
    char inByte = mySerial.read();
    Serial.write(inByte);
  }
  digitalWrite(2, LOW);
}

(with D2 being hooked up to an LED for both).
I can't get it to read anything.  Nothing seems to be available for the receiving Arduino (the LED is off).  What am I doing wrong?

Sender:
SoftwareSerial mySerial(10, 11);  // Rx, Tx

Receiver:
SoftwareSerial mySerial(11, 10);  // Rx, Tx

I have the 'sending' Arduino's D10 pin connected to the 'receiving' Arduino's D11 pin, and vice versa.

So you have the sending Arduino's Rx connected to the receiving Arduino's Rx. Therefore it won't work. You need to connect Rx to Tx.

  mySerial.listen();

You don't need that in this simple example.

I agree with Nick above but want to add this simplify your code like this:

if (mySerial.available()) {
    digitalWrite(2, HIGH);
    Serial.write(mySerial.read());
  }

I have had to catch serial data from a printer feed before and this turned out to be the best way to catch all the data if you place it in a variable first it has to change the variable every time that you receive a byte but this way it places all in a buffer then sends it out
BTW I had to save to a F-RAM device and that worked the same way but instead of sending it I had it saved to a variable while using ReadString() in stead of read().

Re “if you place it in a variable first it has to change the variable every time that you receive a byte”: A local variable, used like in the original post, will be allocated by the compiler to a CPU register. What you are proposing is not more efficient.

like i said in the answer at the bottom I used a variable but nothing else and that is what made it work for simplifying the code to get it to work on the first go use the simplest version you can get then build on that.

I don't quite understand what you are writing, but the sentence starting with “if you place it in a variable first” sounds like you imply that using a temporary variable is a cause of inefficiency. If that is what you mean, it is wrong. If it's not what you mean, then you should edit the answer in order to clarify the sentence.

no maybe my language is really letting me down
to put it in simplest terms you should try to minimize the processes happening on a serial event and you should keep away from delays and all of that and if you are purely trying something out do it in the simplest way available being the one i suggested (i believe but could be wrong)  and then build on to that
it just makes debugging a breeze and not a schlep

as for the variable I found it to be a good solution by itself having nothing else keeping the mcu busy while receiving data not saying that is the only function that your MCU should have but rather in the data receive event that should be kept to the minimum and that you should not even try something like a delay in there and once again keep your code simple and straight forward

Lots of words and still not getting clearer. Please, answer this simple question: Are you, yes or no, implying that char inByte=mySerial.read();Serial.write(inByte); is less efficient (i.e. it keeps the MCU more busy) than Serial.write(mySerial.read());?

well you are for one putting the data in a variable and then sending it out so you tell me
I am only giving my opinion and as far I know keeping it simple makes it work

Let us continue this discussion in chat.

Yeah never Agree with someone hey

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


text:
Storing array in PROGMEM
I have an array of a lot of numbers (1 and 0) but i can't store them since arduino does not have enough space. How can i save an array of example 00110 in PROGMEM, then read from PROGMEM and set x to be equal lets say, third int in the array?

How many is "a lot", and how wasteful is the datatype you have chosen?

4000 elements and each element is a number like 1 or 0 to set a pin high or low.

Stored as int variables (as you seem to suggest) that's a massive 8KB.  Packed into individual bits of a byte that's a mere 500 bytes.

I can store it in PROGMEM

The Arduino website tells you all about how to use PROGMEM.  Have you considered reading that? https://www.arduino.cc/en/Reference/PROGMEM

Yes i didn't understand it well i need a code for my case

There is suitable code right there on the page for you. What more do you need?

Can you please send me the part of the code for storing an Array of 1's and 0's and then setting a variable as a value from that array?

Look at the bits of that code pertaining to the variable "charSet" - it has everything you need.

It's not about storing array but declaring const char PROGMEM myarray[50] = {0x45, 0x47}; in source code , etc. It's elementar task appearing in many examples.

After i store the array in PROGMEM how do i set a variable to have a value of a element inside that array?

Store them with const byte PROGMEM with bit 0 as MSb and bit 7 as LSb per byte. E.g. 011100100101001010101011 would become const byte[] var PROGMEM {0x72, 0x52, 0xab}
Use the following macro to retrieve them (untested):
#define loadbit(mem, pos) ((pgm_read_byte(&(mem[pos / 8])) >> (7 - (pos % 8))) & 0x01)

So if you had const byte[] data PROGMEM {0x72, 0x52, 0xab}; you would call loadbit(data, 3) and it would return bit 3 starting with 0 on the left, i.e. 1.
Naturally if you needed more than one bit at a time there are probably situation-specific routines that could be used, but without knowing anything about the actual program the above will work.

What data type is that? 0x72? Is that hex? And how do i convert big data chunks of binary into that data type?

8 bits at a time.

@Arduino I usually write a Perl or PHP script (depending on what the source of the data is) to convert it into C source code.

As noted in Ignacio's answer, you can pack your bits of data into bytes and access them via pgm_read_byte() calls.  If (for coding convenience, not for efficiency) you prefer to pack the bits into larger units, you can use word and dword access functions, as listed in AVR pgmspace.h documentation.  The _near and _far suffixes denote 16 or 32 bit pointers, respectively; for an Uno with its 32K flash memory, _near is always suitable.  See PROGMEM documentation at arduino.cc for further discussion.
Here's an example program that accesses and prints data from program memory in 16-bit chunks:
void setup() {
  Serial.begin(115200);         // initialize serial port
}
int k=0;
const uint16_t fnums[] PROGMEM {191, 272, 353, 434, 515, 646, 767, 888};
void loop() {
  uint16_t b = pgm_read_word_near(fnums+k);
  Serial.print(k);  Serial.print(" ");
  Serial.print(b);  Serial.println();
  k = (k+1)%8;
  delay(1000);
}

To pack your 4000 bits of data in the first place, write a C or Python program that runs on a host computer and writes out array definitions that you can cut and paste into a sketch.  Here's an example (in Python) that packs bits into bytes:
data = [1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1]

first = 1; byt = 0
for i, b in enumerate(data):
  if i%8==0:
    if first:
       print 'const uint8_t fnums[] PROGMEM {',
       first = 0
    else:
       print '{},'.format(byt),
       byt = 0
  byt = (byt<<1) | b        # add bit into byte being built

print byt<<(8-i%8), '};'

Here is what the program produces:
const uint8_t fnums[] PROGMEM { 197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 262 };

If you want that code to instead pack bits into 16-bit words, change 8 to 16 in four places.  Note, the code stores bits in the “bit 0 as MSb and bit 7 as LSb” order mentioned in Ignacio's answer.  Thus, data[0] is stored in the high bit of fnums[0], data[8] is stored in the high bit of fnums[1] , and so forth.

The thing is that (E)LPM only loads a single byte at a time regardless, so using larger types causes the program to do more work for no gain.

Yes, I meant to mention that byte access uses fewer instructions.   However, for some kinds of data (not necessarily this data),  coding convenience rather than efficiency may be important.  Added a note to answer.

How do i convert bits into bytes like in vazquez-abrams example?

@Arduino, see edit.  Also, upvote answers you find useful

Building on the excellent other answers by jwpat7 and
Ignacio Vazquez-Abrams, you could conceivably convert your bits into a table using Lua:
data = { 1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,
         0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,
         1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,
         0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,
         0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1 }

output = 0
bit = 0

for _, num in ipairs (data) do
  assert (num == 0 or num == 1, "Number must be 0 or 1")
  output = (output * 2) + num
  bit = bit + 1
  if bit >= 8 then
    io.write (output .. ", ")
    output = 0
    bit = 0
  end -- if
end --for

print ""

Output from above:
197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 131,

Now you can make a simple function to pull a particular bit out of PROGMEM:
const byte myTable [] PROGMEM = {
  197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 131,
  };

bool getBit (const unsigned int which)
  {
  const unsigned int whichByte = which / 8;
  const byte whichBit = which & 0x07;
  return bitRead (pgm_read_byte (&myTable [whichByte]), 7 - whichBit);
  }  // end of getBit

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Starting");

  for (int i = 0; i < sizeof (myTable) * 8; i++)
    {
    Serial.print (int (getBit (i)));
    Serial.print (", ");
    }
  Serial.println ();
  }  // end of setup

void loop ()
  {
  }  // end of loop

Output from above:
Starting
1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1,


text:
Can I automatically loop inside a library?
I want to write a little library;
the unlibrarized functionality does:
checking in every loop-cycle some inputs,
doing some calculations with it
and finally setting a boolean to either true or false.
How do I periodically check the inputs inside the library?
I know that I could add a function-call  to the library in the loop()-function. But I would prefer to just check the boolean in the loop.
Is there a way, to instantiate a class and start an periodically function by doing so? And if, how does this constant checking affect/coexist with my 'normal' loop()-function?

Generally speaking, no, you can not take control of the processor away from the main "thread" in a library. The normal solution is to provide an update method or something like that. you could do the calculations in a function that returns your boolean answer, then the loop code is basically the same with or without asynchronous updating.
If you can use interrupts to read your input, either as an external interrupt or on an internal timer interrupt, then what you want could be achieved because the interrupt would take control away from the main execution context and give it to you.
Interrupt routines need to be fast and simple though, and it makes the "cost" of using the library higher, since there is a limited number of interrupts/timers and other libraries may require the one you code yours to use.
Of course, the more powerful arduinos that actually run an os will have support for multiprocessing which you could leverage to get the behavior you want. This answer is intended for a standard AVR based arduino (uno, mega, etc.)

I know that I could add a function-call to the library in the loop()-function. But I would prefer to just check the boolean in the loop.

What's the difference?
In the loop you can call something like:
void loop ()
  {
...
  if (mylibrary.ready ())
    {
    // it's time to act!
    }
...
  }

You can make a function, that returns a boolean type, which tells you if the thing you need to do is ready. That function does the checking before returning true or false.
After all, you are planning to check the boolean periodically, presumably often enough to notice it changing, why not have that be the point of noticing whatever-it-is you need to notice?

Yes, your are right! That's also the way I decided to go. Though, I tried to achieved this to have a more convenient implementation of the library: This if(ready==true) could theoretically be somewhere in loop(). But my periodically checking is VERY time-sensitive. If I call the function to check in the if(), I have to be sure, that there is no delay which alters the result.

Now it is like:
void loop()
{
freqdetec.checkFreq();
if (freqdetec.freqChanged()) {
// do stuff
}
}
The benefit from separating it into two calls is first, that it is more obvious what the single calls are doing, and second, I can place the checkFreq() in the beginning of the loop(), to avoid having it cluttered somewhere.

As another person answered, if it is highly time-sensitive you could use an interrupt (if this is a switch you are checking), or a timer firing periodically (if you need to test something like an analog reading).


text:
Arduino crashed my computer when I plug in the USB cable
I have a 2008 Mac that hardly ever crashes. But from time to time (not always) it crashes (the whole computer shuts down as if the power has been cut off) when I plug in an Arduino via USB.
What could cause this?

I've done some testing and the constant in when this occurs seems to be a cheap PIR sensor from eBay. It works some of the time.
Should I get another sensor? Or is there something about PIR sensors that makes them prone to this? It has a lot of caps... Is there another kind of motion sensor?

A faulty cable or board.

What sort of fault?

Which Arduino? Genuine, clone or knock-off? I ask because some of the cheaper ones require unusual USB drivers.

This has happened with multiple micros, from genuine one to a nodemcu esp8266... I'm thinking it's the long micro usb cord that came with my headphones... are short cords better?

Try a different USB cable, see what happens.

Well it could be that something shorts on the board and it draws too much power from mac and it shuts down to protect the motherboard. Most of the times it would just disconnect usb port, but it also could trigger some interrupt on mac itself. Do you have Lab PSU to test if there is a short circuit?

I looked for a short and found none. In the end I resolved it by moving the power supply for my potentiometer from 3.3v to 5v. I don't know why that would matter... but now it's fine.

@futurebird Power supply for your potentiometer?

I'm using the pot for user input. It's connected to power ground and an analog pin.

"It has a lot of caps" implies that the device actually will "look like" a short circuit until those capacitors are charged.  If the total capacitance is high and the USB protection circuit sensitive, it could indeed trip.

Finding resolution in moving the potentiometer to the current-limited 3v3 pin suggests that the potentiometer or something sharing its supply is drawing too much current.  The little 3v3 regulator can't supply enough to load down the USB port, and so would be being abused as a sort of inrush limiter - might be working, but not a very good idea.

It could possibly be that there is a fault that is causing a short circuit. This short circuit could be in the board itself or the USB cable that connects the Arduino. The USB port on the Mac should have protection to protect against a short circuit. Your comments have indicated that you have tested for a short and found none - but this is helpful for others that are looking for a solution.
In your comments you mention that you solved this by changing the positive rail of your potentiometer from 3.3V rail to the 5V rail.

I had this problem with a Chinese knock-off of an Arduino Nano -- looks like it was actually because I had previously installed some CH341 drivers that no longer work with Sierra.
Removing those drivers (sudo rm -r /Library/Extensions/usbserial.kext) stopped the crash (full computer shutdown when I plugged in the Arduino, even through an externally powered USB hub), but unfortunately my Mac doesn't seem to recognize the Arduino.
It looks like there is a newer version of the driver (1.4, 2017-01-11,  downloadable from here), or the 1.3 version is available as a homebrew cask if you tap that repo.
I am a little wary about installing a driver from a random Chinese site. If you want, you can unzip the driver and unpackage the .pkg file with pkgutil --expand package-name.pkg destination-folder. There are a couple subfolders including a Payload that you can inspect a little with zcat -- way over my head.
Alternatively, it looks like this repo may have a C++ driver that may work.

As n8henrie said this is an issue regarding drivers with Mac OS. I updated to Mac OS Mojave (Full disclosure I run a Hackintosh system) and plugging in the arduino nana would cause a massive kept stall causing my computer to loop (if playing a video it would loop back and forth) and I’d need to turn off the PSU in order to successfully boot. However by deleting the current drive I used (CH341) the board would no longer do this (note- I tried 3 boards from different sellers, with 1 genuine and 2 Chinese) in High Sierra this did not happen however


text:
serial communication between several arduinos to pc
Is possible the communication between several Arduinos to one serial port in the PC ?
If I have ARD_A, ARD_B,... ARD_Z running with some code like this
void setup()
{
    Serial.begin(9600);
}

void loop()
{
    while (Serial.available() > 0)
    {
       String stringID = Serial.read()
       int nFound = stringID.indexOf("@ARD_01");
                    // ---> Id is unique for each arduino
       if ( nFound > 0 )
          Serial.print("this is @ARD_01 responding sending some data");
     }
}

And in the pc there is an exe sending a string:
"@ARD_01 I want your data"
   process the data
"@ARD_02 I want your data"
   process the data
"@ARD_03 I want your data"
   process the data

Not directly, no.  A PC's serial port - either a "real" one or a USB one, can only communicate with one device.
The Arduino, though, is a USB device, so you can just plug them all into a USB hub or a bunch of hubs - each one will get its own COM port.  Managing all those COM ports can be kind of tricky though, especially when you have a lot of devices.
Another option, one that is more widely used when you want to communicate with a lot of slave devices from one master device is to use a multidrop network.  RS-485 is the most popular of these.  It allows you to connect many slave devices to one set of serial wires and the master sends instructions to a slave, and the slave may respond with data and information on request.
RS-485 requires special hardware to interface normal TTL level RS-232 (UART) ports to the bus.
You can read more about RS-485 here: https://en.wikipedia.org/wiki/RS-485

What If I say yes you can communicate with different Arduino on the same serial port by changing the baud rate for each Arduino :) with simple VB.net API

Then I reply with how do you isolate all the Arduino tx lines from each other so they can talk back to the pc? (btw, I know the answer just testing if you do)

I didn't mean to test you or anything :) I just made that before with 2 arduinos by build a small vb.net API, 2 baud rate each one will receive the data from specific Arduino, if the other Arduino in different baud rate send data too, the API will ignore it simply because the data will not make any sense

It's not a question of not making sense, its a question of preventing physical damage to the arduinos. If one tx is high and the other tx is low you have an effective short circuit that can damage the tx pins of both arduinos. While it is possible to do it you have to know what you are doing, and if you know what you are doing you'll do it properly and use an industry standard solution.

oh It's work but as what you have said, TX,RX pins will be damaged, Thanks for notify me for that :)


text:
NRF24 Mixing with/without antenna
Is it possible to have the NRF24 module on an Arduino Mini transmitting to an NRF24 with SMA antenna on a Mega?  In that case, would the antenna on the Mega help pickup the signal of the transmitting Arduino Mini?

See https://www.youtube.com/watch?v=gtM832Z0ujE for an extensive comparison between different types of modules and antennas. What specific model are you talking about? A PA+LNA model, or just one with an SMA antenna instead of the prevalent  PCB antenna?

@Gerben  Just the antenna http://www.aliexpress.com/item/NRF24L01-Wireless-Transceiver-Module-SMA-Antenna-Microcontroll-for-Arduino-2-4G/32230572315.html?spm=2114.031010208.3.2.NyZjhh&ws_ab_test=201526_5,201527_4_71_72_73_74_75,201409_3

The regular antenna and PCB antenna have different polarization, so not ideal. But you will still get some extended range.

Yes, and yes.
A module without an antenna is exactly the same as a module with an antenna, it's just that the antenna is part of the PCB. Yes, the module with the antenna will have more sensitivity (able to receive fainter signals) as well as more transmitting power.
The same is true of the modules with the power amplifier.  They again have even more sensitivity and transmitting power.
It is quite common to have a single powerful transceiver with power amplifier and antenna as a base station and then smaller modules as the remote slave devices.  Especially if you couple the base station with a suitable parabolic or uni-directional high gain antenna to point directly at where the slave devices are.

Your answer is mainly right, but I have to warn that most models with an antenna are fake. You will have compatibility issues when there is a mixed environment with both original and fake chips.

As an update, I purchased this and it worked http://www.aliexpress.com/item/NRF24L01-Wireless-Transceiver-Module-SMA-Antenna-Microcontroll-for-Arduino-2-4G/32230572315.html?spm=2114.031010208.3.2.NyZjhh&ws_ab_test=201526_5,201527_4_71_72_73_74_75,201409_3 I get about 2 meters extra range compared to no antenna when using it through a concrete wall.


text:
HC-06 data receiving
I've written a script in Python which sends data through the PC's Bluetooth to HC-06 on Arduino.
state is an integer from 0 to 1000 (it is controlled through the potentiometer).
...
gaugeSocket.send(str(state))
...

I can't get the right character-to-integer conversion on Arduino (from HC-06 serial).
Arduino code:
SoftwareSerial mySerial(10, 11); // RX, TX
char buf[2];
int i=0;
int data;
int ledPin = 9;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(57600);
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.available()) {
    for(;i<2;){
      buf = mySerial.read();
      i++;
    }
    i = 0;
    Serial.print(buf);
    data = atoi(buf);
  }
    analogWrite(ledPin, data/10); //To see how code behaves on LED
}

Serial print gives me this (if I turn potentiometer from 0 to 1000):

0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(60(1ÿ(00(16(0ÿ(23(0ÿ(30(0ÿ(3ÿ(60(43(0ÿ(49(0ÿ(53(0ÿ(5ÿ(90(69(0ÿ(88(0ÿ(10(00(10(00(10(

What am I missing? Is it because I'm sending it as a string? Or is my buffer not the correct size?

Here is your main problem:
if (mySerial.available()) {
    for(;i < 2;){
        buf = mySerial.read();
        i++;
    }
....

There you are saying "If there is at least one character available in the buffer then read lots of characters from the buffer".
You can't read characters that aren't there yet.
So your stream of data is interspersed with the integer -1 which means "I don't have any data to read!"
I explain it all here: http://hacking.majenko.co.uk/reading-serial-on-the-arduino
By the way - character -1 looks like this: ÿ
You are sending your data as text.  That means, to send the value 348 you are first sending the byte representation of the ASCII character "3", which is the decimal byte value 51.  Then you send the byte representation of the ASCII character "4", which is the decimal value 52, and finally you send the byte representation of the ASCII character "8", which is the decimal value 56.
You look to see if there is one byte available (if(mySerial.available())) and then read that byte into "buf" and increment "i" (by the way, "i" is never reset to 0 - your whole loop strategy is completely wrong, but that's a completely different issue).  You then read a second character and assign that to buf instead.
So if you have the character "3" in the serial buffer you then place that in "buf".  You then read whatever is next in the buffer, which 9 times out of 10 will be nothing, so read() returns -1.  So you just assign that to "buf" instead, replacing the "3" that was in there before.
But "buf" is a character array, and you are assigning a character to the whole array, which makes absolutely no sense (does the code even compile as you have shown it?).
Basically your whole reading routine is completely wrong and can never work no matter how much tweaking and advising we do.
The link I provided above describes not only how you should do the reading on the Arduino, but also how you should do the sending from the other end.  It is vitally important that you send something that says "This is the end of the number I am sending" so that the Arduino knows where one number ends and the next starts.  Normally that is done, when sending a textual representation of the number like this, by adding a line feed and/or carriage return at the end of your number.  So instead of sending "348" you send "248\n".
The Arduino then checks to see if there is one character available, and then it adds just that one character to the end of the buffer.  If, and only  if, that character is the delimiting character then you can take the buffer and translate it into an actual number and reset your buffer to be empty ready to receive the next number.
The link above has good example code showing you exactly how to do that.

Thanks, that was really helpful. But I still can't get it going. If I'm sending numbers from 0-1000, that means I'm sending 2 bytes. And when I want to read it like if(mySerial.available() >= 2) it's still a mess. Would you please be so kind to help me directly on this one?

Only if you're sending it as bytes. You're sending it as text though so it is between 1 and 4 bytes plus whatever you delimit with.

Use itoa instead of str.
str just converts the byte to an ASCII character. So 48 will become '0', 195 will become 'ÿ', and 191 will become '('.

I think you should check your baud rates. A mismatch in baud rates usually makes that symbol get printed on the screen.


text:
Human circuit trigger
The main idea is to create trigger which can be switched on by touching 2 plates on opposite walls. And these should be performed by few peoples holding each other hands.
Obviously human body has big resistance so I couldn't just connect these plates to ground and to one of Arduino pins.
There is a toy that do almost what I what (see it there). But I haven't found any information about how to create it by myself.
Do you have any ideas how to create it?

Interesting idea... I think it would be difficult to detect two people though. What if one person touches one plate by hand, and reaches for the other plate with a long metal rod?

Yeah, there are many ways to cheat but for office Halloween quest it should work just fine (it would be easier to find a few people than long metal rod). Also I've already found another project on amplifier + transistor. But firstly i'm going to check solution by @A3ruz as it looks like the simplest one.

The human body certainly has a measurable resistance. I measure around 1.5 MΩ holding the multimeter probes. Trying with two people holding hands still only gave 1.5 MΩ, so it seems the problem point might have been the contact with the probes.

Here's a DIY for the toy in the link you posted. It's not arduino but I hope it helps. https://en.vmaker.tw/archives/work/the-energy-stick

I just tried it (using my own method), and I got it working with very good sensitivity (should be fine for two people) using a TIP102 Darlington transistor and some resistors. Here is what I did:

R1, the 1M pulldown resistor on the first pin of the Darlington is necessary to keep the light off when nobody is touching the wires. Without this, the light will turn on and off frantically.
R2, the 1k resistor keeps the Arduino from draining too much current (since that would be bad for the pin) in the case that your A0 is in OUTPUT mode and set to LOW.
R3 keeps the LED (or in my case, an AC relay connected to an actual light) from draining too much current from the Arduino. Note: The LED leads may be backward (reverse polarity) in the provided diagram.
Here is the code:
// I release this code under the standard MIT licence;
// (in addition to whatever StackExchange implies);

const short triggerThreshold = 10;// Lower is more sensitive;

void setup() {
  pinMode(A0, INPUT);
  pinMode(A5, OUTPUT);
  digitalWrite(A5, LOW);
  delay(1);
}

void loop() {
  short value = analogRead(A0);
  digitalWrite(A5, (value > triggerThreshold) ? HIGH : LOW);
  delayMicroseconds(10000);// 10ms;
}

Note the triggerThreshold setting in the code. If you want more sensitivity, try changing the 10 to a 5. I just tried it, and it becomes extremely sensitive, yet it still appears to reliably stay off when I don't touch it. Naturally if you use large plates for touching, electrostatic in the air could set it off, so you may need to change this number to be higher to make it less sensitive, depending on your setup.

I had a lot of noise, so added a debounce function:
    // The input is noisy and flips high and low frequently.
    bool debouncedInput() {
      static uint16_t state = 0;
      // Get a simple 1 or 0 for input.
      short value = (analogRead(A0) > triggerThreshold) ? 1 : 0;
      // Bit shift state left, or against the new value and mask out high byte.
      state = (state<<1) | value | 0xfe00;
      return (state == 0xffff) ? HIGH : LOW;
    }
    void loop() {
      digitalWrite(A5, debouncedInput());
      delayMicroseconds(10000);// 10ms;
    }

You can do it with an Arduino !
Use any of the ADC pins
There will be change in the ADC i/p when there is some resistance b/w the pins !
Try both
+ve > (people) > ADC
-ve > (people) > ADC
Just do some trials and probably will notice the change in ADC pin outputs .
If you want to make  it more sensitive
Add a high resistance to the ADC pin
if you are giving +ve to touch plates add a resistance from ground to that ADC pin

Just make sure your power supply isn't earth referenced, so no current can flow thought the floor back to the arduino. But depending on the kind of floor and other factors this might not be a big issue.

No.  The ADC converter has too low of an input impedance to work with megaohm paths.  It is quite probable that detection can be accomplished, but by using either the dedicated comparator or possibly the ordinary digital input mode with an opposing resistor of several magaohms, not the ADC input mode.  If you really want to use the ADC, you will need to precede it with a high-impedance buffer amplifier

The idea is intriguing, but you are not limited to use electricity.
You could experiment with some other type of signal. Sound, for example.
That would be safer.


text:
Atmega168 Watchdog timer
I'm trying to use the watchdog timer to prevent the atmel from being stuck in a loop.
Right now, I have the watchdog timer in System Reset Mode, with a 8sec timer. I reset the timer in every loop while the system is active. But when it goes to sleep, it cannot clear the timer and the whole system resets. Essentially, the system sleeps > System Reset every 8 sec > goes back to sleep.
While this works, I initialize a lot of other hardware with the atmel, and doing it every 8 second seems like a waste of resources.
I want to use the watchdog interrupt somehow only to wake the system up briefly and stop the full system reset. Only if it's truly stuck, it will do a full system reboot. But i'm not sure how the ISR will work or how to reset the timer or toggle.
Here a basic rundown of what I was thinking about.
ISR(wdt_timer)
{
    how to stop the full system reboot?
    how to make the interrupt start again?
}
ISR(button_press)
{
      gotoSleep=0;
}

void watchdog_init()
{
    /* Reset the wdt. */
  wdt_reset(); //from wdt.h

  /* In order to change WDE or the prescaler, we need to
   * set WDCE (This will allow updates for 4 clock cycles).
   */
  WDTCSR |= (1<<WDCE) | (1<<WDE);

  /* set new watchdog timeout prescaler value */
  WDTCSR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */

  /* Enable the WD interrupt (note both interrupt and reset). */
  WDTCSR |= (1<<WDIE) | (1<<WDE);
}

void main ()
{
    watchdog_init();
    //and initialize all the other hardware and power supply

    while (true) //no need to step out of this loop
    {
        reset_watchdog();

        //
        //main program
        //

        if(go_to_sleep=1)  //command received through serial
        gotoSleep();

        //wake up here

    }

}

I think the way it goes is: at 8 sec-- interrupt triggered, at 16 second --system reset. Correct me if I'm wrong.

Each time the watchdog interrupt triggers, WDIE is reset. You will need to set it again in the loop if you want to continue capturing the interrupt rather than resetting the system.
Also, consider using <avr/wdt.h> and <avr/sleep.h> to handle (most of) the watchdog and sleep functionality.
EMPTY_INTERRUPT(WDT_vect);

void main ()
{
    watchdog_init();
    set_sleep_mode(SLEEP_MODE_STANDBY);
    //and initialize all the other hardware and power supply

    while (true) //no need to step out of this loop
    {
        wdt_reset()

        //
        //main program
        //

        if(go_to_sleep=1)  //command received through serial
        {
            sleep_enable();
            sleep_cpu();
            sleep_disable();
            WDTCSR |= _BV(WDIE);
        }
    }
}

the "wdt_reset()" from wdt.h only resets the time, not the WDE or WDIE, right?

It becomes a wdr opcode in the binary.

if(go_to_sleep=1) ? Surely: if(go_to_sleep==1)  (I realise it is pseudo-code, but still).

@NickGammon: I'm sure it will be fixed once the pseudocode is translated to C.