text:
Bluetooth module(HC05) works with Arduino Uno but not with breadboard (ATmega328)
I am currently working on a project that requires communication between an android phone(galaxy s4) and an ATmega328 microprocessor. To connect these devices wirelessly I'm using an HC05 bluetooth module and to understand the connection I'm using pre-built arduino codes(turn LEDs on and off) and an android app called blueterm.
This connection is established and able to transmit data when connected to the Arduino uno, but as soon as this chip is removed and connected to a standalone breadboard the connection fails. The standalone breadboard works fine and has been tested with many other projects and I have attached the breadboard connection below. The HC05 when connected to the breadboard changes the blinking pattern to notify the user it is connected but the serial connection is never made. Any help would be greatly appreciated, if any other information is needed feel free to ask.

It looks like the HC05 should be moved one row to the left.

It might be a bad angle but the last pin is not needed on the HC05 unless editing its internal settings. The connection is not changed when moving back to the arduino just the pins that go to the atmega328 are moved from the breadoard to the arduino.

I guess your module has a different pinout that the one I found online. I also check, but the Uno doesn't have any pull-up resistors, so that's not it. Does your atmega run off 3.3V too?

Are you sure pin TX (on the Bluetooth side) is connected to pin 0 on the chip, and RX is connected to pin 1?

I would like to give some suggestions: If BT module connects to a phone (LED is solid, no blinks) and no data received, i would do some tests like: connect Rx-Tx and check does MCU echo typed letter. Connect Rx-Tx of BT module and check on android does it echo typed message.

Some bypass capacitors on the ATMega and near the regulator wouldn't be a bad idea.  You have filter capacitors, but nothing physically close and compact enough to handle high frequency currents.  A bluethooth module is also a fairly high current device when it transmits, and yours is powered via a very surpentine route through the breadboard, past the ATmega.  Consider giving it its own connection directly to the regulator.

I too had the same issue. I used pullup 1k resistors for RX and TX. Then it works.

If the LED is blinking, the device is waiting to pair with another Bluetooth transceiver (your phone). Once paired, the LED will stay lit. The factory-set pairing code is usually 1234. I can't tell from the photograph how the HC-05 Rx & Tx are wired to your ATmega328, but note that it must be cross-connected; that is Rx -> Tx and Tx -> Rx.

I had this issue.  I was using SoftwareSerial to define the rx and tx pins as 3  and 2.  Worked fine on Arduino UNO but not on standalone ATMEGA328.  Solution was to not try and assign the rx and Tx pins but to connect HC 05 rx and tx pins direct to the RX and TX pins on the ATmega 328.

I had same issue and solved by below mentioned layout.


text:
Nodemcu OTA - no response issue
I was trying to use nodemcu for a project. No issues when uploading the OTA sample code. Added led blink to test. But when trying to upload the second sketch via OTA getting an error

no response from device.

Tried ping to the Nodemcu IP and no issue there. Have the OTA codes in both sketch.
When trying to upload the 2nd second, the led blink will stop for 2,3 seconds and resumes the normal blinking, gets an error in ide after.
How to check if there is any firewall issue?
IDE settings

Attaching code below
const char* ssid = STASSID;
const char* password = STAPSK;

void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);

  Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  // Port defaults to 8266
  // ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  // ArduinoOTA.setHostname("myesp8266");

  // No authentication by default
  // ArduinoOTA.setPassword("admin");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA.onStart([]() {
    String type;
    if (ArduinoOTA.getCommand() == U_FLASH) {
      type = "sketch";
    } else { // U_FS
      type = "filesystem";
    }

    // NOTE: if updating FS this would be the place to unmount FS using FS.end()
    Serial.println("Start updating " + type);
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) {
      Serial.println("Auth Failed");
    } else if (error == OTA_BEGIN_ERROR) {
      Serial.println("Begin Failed");
    } else if (error == OTA_CONNECT_ERROR) {
      Serial.println("Connect Failed");
    } else if (error == OTA_RECEIVE_ERROR) {
      Serial.println("Receive Failed");
    } else if (error == OTA_END_ERROR) {
      Serial.println("End Failed");
    }
  });
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  ArduinoOTA.handle();

  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  delay(100);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(100);

  Serial.println("Looping");
}

Are you calling ArduinoOTA.handle() fast enough in your sketch? Please show your code.

Hi, added the code I am using.

I suspect it's those delay() calls that are making it time out. You need to learn to write non-blocking code. Examine BlinkWithoutDelay.ino.

Tried the BlinkWithoutDelay code, still getting the same error.

You mean you compiled and manually uploaded the code over USB and then found it still wouldn't upload over OTA after that?

Yes, No issues when uploading the updated code via COM3 port, but can't upload via the network port.

Have you manually reset the board since uploading over USB?

Yes, manually reset the board after the first upload.

Let us continue this discussion in chat.

source: Stack Exchange

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

sort: votes


text:
Ignoring the first high output from the sensor
If the vibration sensor with Arduino detects two high inputs within 1 minute, I want the led to flash in one second.
My ability to write Arduino code is very low; I tried with millis() but I couldn't.
I want it to ignore the first high entrance.
Thank you for all the information you will give.
const byte sensor = 7;
const byte LED = 13;
unsigned long sensorMillis;
unsigned long ledTurnedOnAt;
unsigned long high_1 = 60000UL;
bool ledState = false;

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

void loop() {
  unsigned long currentMillis = millis();

  if (digitalRead(sensor) == HIGH) {
    sensorMillis = currentMillis;
    ledstate = true;
  }

  if (ledstate == HIGH) && ((unsigned long)(currentMillis - ledTurnedOnAt) <= high_1) {
    digitalWrite(8, HIGH);
    delay (1000);
    digitalWrite(8, LOW);
  }

  ledstate = false;
}

It works better if you ask a question about a specific thing you are getting stuck on.

Edit your question to show the code for your attempt, along with a description of how it fails to meet your goal. You'll also need to map out your desired logic in detail. First high reading is ignored. 2nd high reading lights LED. Then what? Do you want the LED to turn off once the vibration sensor shuts off, or after some period of time? Or do you want it to stay on forever once it turns on the first time?

I want it to ignore the first high input, I want the led to flash immediately with the second high input.

that is not a question ... it is a description of how you want the program to behave

You may want to read about The Finite State Machine.

thank you edgar Bonet

Try looking for the high in setup, it will then be ignored by your loop.

One simple solution could be:
Start by noticing the first time you get the HIGH input whit a simple if statement:
if (digitalRead(sensor) == HIGH) {
}

where sensor is the pin of the sensor according to your code.
When this statement is True, you are interested in remain here until one of two things happens:

either you interrupt some kind of loop with another HIGH input,
or the time you have set is passed.

One way of knowing elapsed times will be with the millis() function, that returns the milliseconds since the board began running.
We should get the elapsed time the first time we enter the loop:
if (digitalRead(sensor) == HIGH) {
  long startTime = millis();
}

Then, as I have said, we need to remain here for a specific amount of time. We could use the while loop, but, which condition needs to be true?
So we have a start time, lets said x and you need to stay in the loop for, let's say, y milliseconds. This is the same as saying that you want to stay in the loop until the time we enter the loop and a specific amount of milliseconds, x+y. When the millis() function gives us a greater number, we should exit the loop:
if (digitalRead(sensor) == HIGH) {
  long startTime = millis();
  while (millis() <= (startTime+1000))
//                              ^ The second you are interested, 1000 milliseconds.
}

Now, we have to check if there is another interrupt during this time, by using the same statement of the beginning:
if (digitalRead(sensor) == HIGH) {
  long startTime = millis();
  while (millis() <= (startTime+1000)) {
    if (digitalRead(sensor) == HIGH) {
      // 2 interrupts in less than 1000 millis!
    }
  }
}

Summarizing is nicer to declare a global with the specific time we want, instead of the 1000 value we are using now:
const long maxTimeInterval = 1000;

And changing it in our code (that is inside the loop())
if (digitalRead(sensor) == HIGH) {
  long startTime = millis();
  while (millis() <= (startTime+maxTimeInterval)) {
    if (digitalRead(sensor) == HIGH) {
      // 2 interrupts in less than 1000 millis!
      digitalWrite(LED, HIGH);
    }
  }
}

Hope this helps!

Start by noticing the first time you get the HIGH input whit a simple if statement Cannot see you your code doing so.

@DataFiddler I have all wrapped inside if (digitalRead(sensor) == HIGH) { ... }

Thank you very much. @Juan CA you are great. code works well.

@juan CA .I asked a lot of people, nobody succeeded. You succeeded easily.  You are wonderful. If you were close, I would like to give you a gift.

Thank you very much to all site administrators

const int sensor = 7;
const int LED = 13;
unsigned long sensorMillis;
unsigned long ledTurnedOnAt;
unsigned long high_1 = 60000UL;
bool ledState = false;
void setup() {
  pinMode(sensor, INPUT);
  pinMode(LED, OUTPUT);
  delay(1000); //Warm up Time
}

void loop() {
  unsigned long currentMillis = millis();

  if (digitalRead(sensor) == HIGH) {
    sensorMillis = currentMillis;
    ledstate = true;
  }

  if (ledstate == HIGH) && ((unsigned long)(currentMillis - ledTurnedOnAt) <= high_1) {
    digitalWrite(8, HIGH);
    delay (1000);
    digitalWrite(8, HIGH);
  }

  ledstate = false;
}

I haven't checked this because I don't have my hardware. However, I added a delay of 1 second in the setup as a warm up time. This in theory should ignore the first high. Hope it helped.

"N0m4d "Thank you very much for your attention and help

Or what about adding another global boolean;
bool firstTime = true;

and then amend you loop() code as follows;
if (digitalRead(sensor) == HIGH) {
    if (firstTime) firstTime = false;
    else {
        sensorMillis = currentMillis;
        ledstate = true;
    }
  }

thank you Rob W. i will try

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


text:
How should I combine the codes for two sensors in 1 Arduino sketch?
Name of study: AUTOMATIC ELECTRIC FAN
We used an ultrasonic sensor for the switching on/off of our Fan and an LM35 SENSOR to control the speed regulation.
During our experiment, we use a LED instead of a Fan before we proceed to fan. Here is our code:
Description: Codes for LM35 Sensor using LED and Arduino Uno as Microcontroller)
#define led 9
float temp;

void setup ()
{
   pinMode(led, OUTPUT);
   Serial.begin(9600);
}

 void loop ()
{
    temp = analogRead (A0);
    temp = temp*0.48828125;
     if (temp < 31 )
  {
    digitalWrite(led, HIGH);
  }
  else {

    digitalWrite(led, LOW);
  }
    Serial.print("TEMPERATURE: ");
    Serial.print(temp);
    Serial.print("*C");
     Serial.println();
     delay(1000);
 }

Description: Code for ULTRASONIC SENSOR using two LED’s AND Arduinbo Uno as Microcontroller
#define trigPin 13
#define echoPin 12
#define led 6
#define led 5
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds (2);

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

  duration = pulseIn(echoPin, HIGH);
  distance = duration*0.034/2;
  if (distance < 100 )
  {
    digitalWrite(led, HIGH);
  }
  else {

    digitalWrite(led, LOW);
  }
  Serial.print("Distance:");
  Serial.println(distance);
  Serial.print("cm");
  delay(1000);
}

You need to edit your question, select the code, and tap the code format button. (It looks like open and close braces: {}. That will format the code so that it's readable. Right now it is decidedly not readable.

Thank You. You know how to combined the codes for the two sensors?

As I always say: Step 1: understand your existing code and how it works. Step 2: write a new program which incorporates what you learned in step 1.

@MichelKeijzers, I resisted the urge to edit the OPs code. I was trying to use their first post as a "teaching moment" for how questions should be formatted.

@DuncanC Sorry, I justed improved the layout without reading all comments.

You don't have two codes; the 2nd section has no setup() or loop().
If it did, then you could do this:

The stuff before setup() gets put together.
The stuff in setup() from one gets moved into the other. The empty setup() gets deleted.
The stuff in loop() from one gets moved into the other. The empty loop() gets deleted.

Take care of any duplicate names, pin assignments, etc.
Review the combined loop() code and adjust as needed to do what you want.

Thanks for the cleanup Michel, easier to read now.

You're welcome!


text:
Determine whether Arduino Uno board is faulty or not?
I'm just giving 9V supply to the Arduino Uno but along with its power led,  the transmission one is also blinking. Can anyone please tell me whether the board is faulty or not?

The RX and 'L' leds are off and the TX led is blinking and the power led is on? Then there is probably a sketch in the arduino uno that sends something to the serial monitor.

Use Arduino IDE, connect your Arduino to the PC, load examples -> Blink, program your Arduino and check if it does what supposed to do (if Blink loaded, then LED should blink only)

from the vast depth of information you have given, I can definitely tell you that the two LED's are not faulty

nobody can tell you whether the board is faulty  .... you have to  test it yourself


text:
Servo delay problems
So I had a test last week with the Arduino Uno starter kit. We got a task including the servo. I had to get the servo to go from 0 to 90 degrees and it was supposed to use 4 seconds to do so. Than back from 90 degrees to 0 again. My code is like this:
#include <Servo.h>

Servo myservo;
int pos = 0;
void setup() {
  myservo.attach(9);
}
void loop() {
  for (pos = 0; pos <= 90; pos += 1) {
    myservo.write(pos);
    delay(40);
  }
  for (pos = 90; pos >= 0; pos -= 1) {
    delay(13);
  }
}

As you see the delay should be just 40 and 13 milliseconds, but it used 4 seconds and 1.3 seconds. but since the code was, wrong I didn't pass on this task. So what have I done wrong.

9040ms = 3,6s. 9013ms=1,17s. So you have 3,6s for the first movement and 1,3s for the seconds movement. Please describe further, how this does not comply with the requirements, since you wrote, that it needs to take 4s and you saw 4s. Thats what I understood

90*40ms = 3,6s, but there is also a bit of overhead as myservo.write(pos); and the for loop also take some time to execute (there are also interrupts that could add some additional delays). But I'm guessing that this overhead is negligible. It might be that the examiner wanted you to take that into account. Note that even if you had a delay(44), you'd only get 3.96s, so you'd be 40ms off. The examiner might not like this.

Also your second loop isn't doing anything with the servo...

I would use the millis() function to set up a timing as accurate as possible.
Before starting your operations store the actual value of the millis() timer to a variable time_passed. After finishing your operation, in this case a 1° step of the Motor, wait until the 90's part of your desired time (4s) is reached. Then you increase your time_passed with the 90's part of your desired time bevor going on.
#include <Servo.h>

unsigned long time_passed;
unsigned long timestep = 4000 / 90; // necessary period to reach 4s in 90 steps
Servo myservo;
int pos = 0;

void setup() {
  myservo.attach(9);
}
void loop() {
  time_passed = millis();
  for (pos = 0; pos <= 90; pos += 1) {
    myservo.write(pos);
    while ( millis() - time_passed < timestep) {
    }
    time_passed = time_passed + timestep; // this was time_passed = millis(); at testing, but this should be even more accurate. Hope I made no mistake, since I tested only the previous Version ;-)

  }

  for (pos = 90; pos >= 0; pos -= 1) {
    myservo.write(pos);
    while ( millis() - time_passed < timestep) {
    }
    time_passed = time_passed + timestep; // this was time_passed = millis(); at testing, but this should be even more accurate. Hope I made no mistake, since I tested only the previous Version ;-)
  }
}


text:
Wire.h missing - Failing to upload I2C 16x2 LCD sketch
I am total newbie in Arduino and for the last 3 days I am trying to figure this out.
I would like to use an I2C display for a project. I have installed the LiquidCrystal_I2C, but when I try to upload it I get this wire.h missing message.
Could anyone please help me to understand and fix this?

+1 for saying help me to understand ......  too many people only want finished code

Please post code and error as text, not picture.

How do I post codes here?

That library is special. It expects to be placed in the same location as the Wire library.  You need to find the location of the Wire library and place this library alongside it.  So you have:
.../Wire/Wire.cpp
.../Wire/Wire.h
.../LiquidCrystal_I2C/LiquidCrystal_I2C.cpp
.../LiquidCrystal_I2C/LiquidCrystal_I2C.h

etc

Thank you for the reply.
I seems I have two copies of wire.cpp and wire.h in two different locations. Attached is a screenshot of their locations with respect to the LiquidCrystal_I2C.h and LiquidCrystal_I2C.cpp - is this the problem?
Screenshot: https://i.imgur.com/n7m8UTR.png

Just pick one. If they're all the same then it won't matter which.

how can I pick one? (sorry if it's a stupid question)


text:
How many Amps can a Nano Arduino hold for LED project
I'm really new at this, and here is my doubt. What if I need to light 120x WS2812B (5v)LEDs (link: LEDs) using an Arduino Nano? if it takes 60 mAh each pixel, the total amount needed should be around 7,200 mA.
Could I use the same 5V/ 8A power supply (PowerSupply) for the Nano board and lights? Is that possible?
Thanks in advance, and sorry my ignorance on this area.

Check your units.  Charge (e.g. in mAh a unit of electrical capacity, or how much current can be supplied over a given time).  Current is the rate of charge flow (e.g. in mA).  As written your question does not make sense.

Yes, 120 LEDs * 60 mA = 7200 mA = 7.2A
An Arduino Nano will use 19 mA (Arduino Nano Tech Spec). Of course, if you add a power LED, or other components it will add, but it will likely be less than a few 100 mA. So that totals to max 7.4A.
It's always good to have some headroom which is 0.6A in your case (that's enough).
Actually what's happening is as follows:
- Your 8 mA gives the current the components request
- Your Nano requests 19 mA
- Your LEDs require 7.200 mA.
As long as the voltage is the same (5V for both the LEDs, Nano, and adapter), and the components do not request more than 8 A summed up (with some headroom), the adapter will deliver the current needed. If all components request more than 8 A, than high likely the adapter will break (and possibly the attached components too).

Thanks Michel, I just wanted to make sure that I don't burn the board on my first attempt  ;)

You're welcome .. .you can wait for more answers, if an answer is helpful, upvote it, if the answer answers your question in a satisfactory way, accept the answer.

@juasmilla, why would you think that you would burn the Nano? .... how are you planning to connect the LEDs?

It can supply both, as long as they are supplied separately; the LEDs must not be supplied through the Nano board, but connected directly from the power supply.

Fine, connecting the ground on both I suppose... Thanks for all your inputs! brilliant Arduino World, and of course, its community!!

@Yes connect ground together


text:
Arduino Light Puzzle Help
This is my first time doing this type of thing and I have no background in coding.
It will compile however the code won't upload and I've been working on this for days.
Any help you can provide would be very much appreciated.
Error messages:
Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Uno"

Sketch uses 1898 bytes (5%) of program storage space. Maximum is 32256 bytes.
Global variables use 13 bytes (0%) of dynamic memory, leaving 2035 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\CHRIST~1\AppData\Local\Temp\arduino_build_870585/sketch_apr18.ino.hex:i

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x9c

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Code:
void setup() {
//constants
// set pin numbers:
int buttonPin1 = 6; //pushbutton pins
int buttonPin2 = 7;
int buttonPin3 = 8;
int buttonPin4 = 9;
int buttonPin5 = 10;
int buttonPin6 = 11;

int const led1 = 0;      //led pins
int const led2 = 1;
int const led3 = 2;
int const led4 = 3;
int const led5 = 4;
int const led6 = 5;

  //variables

  //led pins as outputs
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);

  //pushbuttons as inputs
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);
  pinMode(buttonPin4, INPUT);
  pinMode(buttonPin5, INPUT);
  pinMode(buttonPin6, INPUT);

  //activating leds
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);
  digitalWrite(led5, LOW);
  digitalWrite(led6, LOW);

  //selecting leds to begin game

  int ran1 = random(0, 1);
  int ran2 = random(0, 1);
  int ran3 = random(0, 1);
  int ran4 = random(0, 1);
  int ran5 = random(0, 1);
  int ran6 = random(0, 1);

  //ensuring 6 led=LOW does not occur | approximatley .02 percent chance running random code twice
  if (ran1 == 0) {
    if (ran2 == 0) {
      if (ran3 == 0) {
        if (ran4 == 0) {
          if (ran5 == 0) {
            if (ran6 == 0) {
              int ran1 = random(0, 1);
              int ran2 = random(0, 1);
              int ran3 = random(0, 1);
              int ran4 = random(0, 1);
              int ran5 = random(0, 1);
              int ran6 = random(0, 1);
            }
          }
        }
      }
    }
  }

  if (ran1 == 1) {
    digitalWrite(led1, HIGH);
  }
  else {
    digitalWrite(led1, LOW);
  }
  if (ran2 == 1) {
    digitalWrite(led2, HIGH);
  }
  else {
    digitalWrite(led2, LOW);
  }
  if (ran3 == 1) {
    digitalWrite(led3, HIGH);
  }
  else {
    digitalWrite(led3, LOW);
  }
  if (ran4 == 1) {
    digitalWrite(led4, HIGH);
  }
  else {
    digitalWrite(led4, LOW);
  }
  if (ran5 == 1) {
    digitalWrite(led5, HIGH);
  }
  else {
    digitalWrite(led5, LOW);
  }
  if (ran6 == 1) {
    digitalWrite(led6, HIGH);
  }
  else {
    digitalWrite(led6, LOW);
  }

  int buttonState1 = 0;
  int buttonState2 = 0;
  int buttonState3 = 0;
  int buttonState4 = 0;
  int buttonState5 = 0;
  int buttonState6 = 0;

}

void loop() {

//constants
// set pin numbers:
int buttonPin1 = 6; //pushbutton pins
int buttonPin2 = 7;
int buttonPin3 = 8;
int buttonPin4 = 9;
int buttonPin5 = 10;
int buttonPin6 = 11;

int const led1 = 0;      //led pins
int const led2 = 1;
int const led3 = 2;
int const led4 = 3;
int const led5 = 4;
int const led6 = 5;

  int buttonState1 = 0;
  int buttonState2 = 0;
  int buttonState3 = 0;
  int buttonState4 = 0;
  int buttonState5 = 0;
  int buttonState6 = 0;

  //read each pushbutton
  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);
  buttonState3 = digitalRead(buttonPin3);
  buttonState4 = digitalRead(buttonPin4);
  buttonState5 = digitalRead(buttonPin5);
  buttonState6 = digitalRead(buttonPin6);

  // check if the pushbutton is pressed
  //button for leds 3 and 6
  if (buttonState1 == HIGH) {
    if (led3 == HIGH) {
      digitalWrite(led3, LOW);
    }
    else {
      digitalWrite(led3, HIGH);
    }
    if (led5 == HIGH) {
      digitalWrite(led6, LOW);
    }
    else {
      digitalWrite(led6, HIGH);

    }
  }
  //button for leds 1 and 4
  if (buttonState2 == HIGH) {
    if (led1 == HIGH) {
      digitalWrite(led1, LOW);
    }
    else {
      digitalWrite(led1, HIGH);
    }
    if (led4 == HIGH) {
      digitalWrite(led4, LOW);
    }
    else {
      digitalWrite(led4, HIGH);
    }
  }
  //button for leds 2 and 5
  if (buttonState3 == HIGH) {
    if (led2 == HIGH) {
      digitalWrite(led2, LOW);
    }
    else {
      digitalWrite(led2, HIGH);
    }
    if (led5 == HIGH) {
      digitalWrite(led5, LOW);
    }
    else {
      digitalWrite(led5, HIGH);
    }
  }
  //button for leds 2 and 6
  if (buttonState4 == HIGH) {
    if (led2 == HIGH) {
      digitalWrite(led2, LOW);
    }
    else {
      digitalWrite(led2, HIGH);
    }
    if (led6 == HIGH) {
      digitalWrite(led6, LOW);
    }
    else {
      digitalWrite(led6, HIGH);
    }
  }
  //button for leds 1 and 5
  if (buttonState5 == HIGH) {
    if (led1 == HIGH) {
      digitalWrite(led1, LOW);
    }
    else {
      digitalWrite(led1, HIGH);
    }
    if (led5 == HIGH) {
      digitalWrite(led5, LOW);
    }
    else {
      digitalWrite(led5, HIGH);
    }
  }
  //button for leds 3 and 4
  if (buttonState6 == HIGH) {
    if (led3 == HIGH) {
      digitalWrite(led3, LOW);
    }
    else {
      digitalWrite(led3, HIGH);
    }
    if (led4 == HIGH) {
      digitalWrite(led4, LOW);
    }
    else {
      digitalWrite(led4, HIGH);
    }
  }
  //flash all lights once for winning
  if (led1 == LOW) {
    if (led2 == LOW) {
      if (led3 == LOW) {
        if (led4 == LOW) {
          if (led5 == LOW) {
            if (led6 == LOW) {
              digitalWrite(led1, HIGH);
              delay(1500);
              digitalWrite(led1, LOW);
              digitalWrite(led2, HIGH);
              delay(1500);
              digitalWrite(led2, LOW);
              digitalWrite(led3, HIGH);
              delay(1500);
              digitalWrite(led3, LOW);
              digitalWrite(led4, HIGH);
              delay(1500);
              digitalWrite(led4, LOW);
              digitalWrite(led5, HIGH);
              delay(1500);
              digitalWrite(led5, LOW);
              digitalWrite(led6, HIGH);
              delay(1500);
              digitalWrite(led6, LOW);
            }
          }
        }
      }
    }
  }
}

I could compile your code just fine. No compiler errors. Though it's not that useful to define the pins as constants inside setup and loop. Just use global variables.

So the problem is not compilation but uploading. Have you chosen the correct COM port?

I believe so. It only lists one port "COM4(Arduino/Genuino Uno".

You also have logic errors in your code. You have if (led5 == HIGH), which will NOT check the state of the LEDs pin, but will compare the LEDs pin number, which is constant 4 here, to HIGH, which is defined as 1. This is always false. You have to do a digitalRead(led5)

Thank you for your help. I went through and changed all the logical errors.
l5=digitalRead(led5);
if (l1 == HIGH) {
digitalWrite(led1, LOW);           It doesn't have any issues from what I can tell other than it not uploading so I believe it is an issue with my computer now. Again thank you so much.


text:
Arduino TCP communication with Android phone
I am trying to communicate Arduino Uno with an android phone. What I trying to is:

Android device post a string to Arduino
Arduino post a integer to Android

So far I can post message from Android, received in Arduino board, but I can not post a integer to Android, nothing receive at Android
Arduino Code (Which can receive character "a", "b", "c", "d", and for case "z", I would like to send back the distance which is an int)  :
void loop()
{
  distance = Dist.getDistanceCentimeter();
  if(distance<=5 & distance>1)
  {
    back();
    delay(100);
    ting();
    distance=0;
  }
  if(Serial.available())
  {
    lkf = Serial.read();
  switch(lkf)
  {
  case 'a':
     front();
     servoX.write(90);
     lkf=0;
     break;
   case 'b':
     back();
     lkf=0;
     break;
   case 'c':
     left();
     lkf=0;
     break;
   case 'd':
     right();
     lkf=0;
     break;
  case 'z':
    Serial.write(distance);
    break;
    }
  }
 }

Android Code:
In Main Activity
@Override
protected TCPClient doInBackground(String... message) {

    //create TCPClient object
    mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
        @Override
        //check whether server return message
        public void messageReceived(String message) {
            f_sensor.setText(message);
            Log.d("test1","msg rece" + message);
            //publishProgress(message);
        }
    });
    mTcpClient.run();

    return null;
}

TCP Cilent
public class TCPClient {

    private String serverMessage;
    public static final String SERVERIP = "192.168.8.1"; //your computer IP address
    public static final int SERVERPORT = 2001;
    private OnMessageReceived mMessageListener = null;
    private boolean mRun = false;

    PrintWriter out;
    BufferedReader in;

    /**
     *  Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TCPClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     * @param message text entered by client
     */
    public void sendMessage(String message){
        if (out != null && !out.checkError()) {
            out.println(message);
            out.flush();
        }
    }

    public void stopClient(){
        mRun = false;
    }

    public void run() {

        mRun = true;

        try {
            //here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(SERVERIP);

            Log.e("TCP Client", "C: Connecting...");

            //create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, SERVERPORT);

            try {

                //send the message to the server
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                Log.e("TCP Client", "C: Sent.");

                Log.e("TCP Client", "C: Done.");

                //receive the message which the server sends back
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                //in this while the client listens for the messages sent by the server
                while (mRun) {
                    serverMessage = in.readLine();

                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);
                    }
                    serverMessage = null;

                }

                Log.d("test1",serverMessage);
                Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");

            } catch (Exception e) {

                Log.e("TCP", "S: Error", e);

            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.
                socket.close();
            }

        } catch (Exception e) {

            Log.e("TCP", "C: Error", e);

        }

    }

    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    //class at on asynckTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}

Your Android code purports to talk TCP, while your Arduino is talking Serial.  Somewhere in between is an unspecified translation which may be a source of trouble.  Your Android code looks improperly structured - you should not be creating a server object for a single use in an AsyncTask (which by default is now blocking) as you appear to be with doInBackground() but rather maintaining one within a background thread mechanism designed to continue running independent of others.  Finally, your Arduino code will only transmit when it receives something, and it is unclear that it is doing so.

Using serial.println instead of serial.write fixes the issue.

If you are going to use a readLine() type method on the receiver, yes, you will need to transmit a terminating newline.  However, a lot of others aspects of your design remain suspicious and potential sources of future issues, too - particularly the way you are doing threading on the Android side.

@ChrisStratton no, the issue's related to this: the .write() function sends the ASCII code, .print() converts it to a string. So Serial.write(65) would send A, Serial.print(65) would send 6, 5. The println would also add a newline character. So the issue is they were sending the ASCII code instead of the string composed of ASCII codes.

One issue.  My point is they have others as well.

Entirely replacing the poster's answer with your own words is not appropriate, especially when you still fail to state the cause of the specific observed issue (no data, not unexpected data).  If you want to offer your opinion do so in a comment, or post your own answer which may be judged by the community on its merits.

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


text:
Port manipulation using C code
I'm trying to manipulate the ports of Arduino using C code. I have attached an LED to pin 8 and a tact switch to pin 13 (with a pull down resistor). The code works fine, and the results are printed on the screen. So, when the button is pressed, the byte PINB & (1 << PB5) equals 32, or 0b00100000.
However, if I try to use
if( PINB &(1<<PB5) == 32){

or
if( PINB &(1<<PB5) == 0b00100000){

the LED doesn't respond.
Here's the full code:
void setup() {
  DDRB |= 0b00011111;
  Serial.begin(9600);
  }

void loop() {
  Serial.print("PINB &(1<<PB5)");
  Serial.println(PINB &(1<<PB5));

  if( PINB &(1<<PB5) ){
    PORTB |= (1<<PB0);
    }
  else{
    PORTB &= ~(1<<PB0);
    }
  }

What am I missing?

Are you saying the full code you've posted works, but it fails if you add == ...?

That's right , it fails with ==                             .

== has higher precedence than &, which means that your comparison will be performed incorrectly. But that doesn't matter, since you don't need to check if the port has a specific value, just if the appropriate bit is set.

You are right. If I use my_byte = PINB &(1<<PB5) and   if( my_byte = 0b00100000 ){ it works fine. Nevertheless, could you explain how the comparison with == and & works? Thank you.

Not really sure what needs to be explained. a & b == c is equivalent to a & (b == c).

That's what I wanted to know. Thank you again.

I found another solution based on your last remark. if(  (PINB &(1<<PB5) ) == 0b00100000){   works too

Eh. Like I said, you don't need to care about the exact value.

That's right, I just want to understand how it works

What @IgnacioVazquez-Abrams is trying to say, is that you can remove the == part all together. Just use if( PINB &(1<<PB5) ){ . As all values other than 0 are truthy.

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


text:
arduino - millis()
Copied from the Arduino reference - millis()

Tip: Note that the parameter for millis is an unsigned long, errors may be generated if a programmer tries to do math with other
  datatypes such as ints.

What kind of math? What kind of other type of processing is excluded while working with millis?
Could someone clarify this statement and/or give some example?

Whenever you write an equation in C/C++, the data types being operated on have a very real effect on the equation's output.
Each type like int, float, and unsigned long have different behaviors, and take a certain amount of space in memory to store.
int (on arduino) is store in 16 bits, with half of its values being given to negative numbers, half-1 given to positive values, and one value given to 0. That gives it a range of -2^15 (-32,768) to +2^15-1 (32,767).
unsigned long (on arduino) is 32 bits, but none are designated as negative. its range is then 0 to 2^32-1 (4294967295).

What kind of math? What kind of other type of processing is excluded
  while working with millis?

The crux of the issue is that it the time millis returns ever got past 32767 and you tried to store it in an int, the arduino couldn't do it, because an int can't hold that big of a number. The type of math this is off limits is math happening to smaller data types, not any specific operations. Maybe these examples will help:
  int i = 32767;
  Serial.println(i);
  //No problems here; it fits just fine

32767

  i = 32767 + 1;
  Serial.println(i);
  //Oh no, the value didn't fit

-32768

  unsigned long fake_millis = 42000;
  i = fake_millis;
  Serial.println(i);
  //This is an example of millis going past an int

-23536

  i = -10;
  unsigned int j = i;
  Serial.println(j);
  //no way to put a negative number in an unsigned value

65526

  uint32_t k = fake_millis;
  Serial.println(k);
  //unsigned long is a uint32_t on arduino; this works great!

42000

The way this is implemented is really quite genius; If you are interested in where these numbers come from and why they spill over in the way they do you should look into same explanations of two's complement number representations.

Just a simple question: Declaring "unsigned long fake_millis;" equals to "uint_32 fake_millis;" ?

Yes, those are equal on the arduino. The difference is unsigned long can change with different platforms (eg x86), uint32_t will always be 32 unsigned bits everywhere.

It should be noted that your second example (32767 + 1) yields undefined behavior, which is almost always a bad thing. Your other examples are documented behavior you can rely upon.

When you want to do stuff with millis() just remember to initialize your variable with type "uint32_t"
So do something like "uint32_t last_millis" where you will store the output of the "millis()" function.
Otherwise like the others said, it would overflow when going past 31,000 which will happen pretty quickly.


text:
Speed sensors for sport
Fair warning: I'm a newbie when it comes to Arduino, so if I'm not too great at describing things, let me know so I can learn!
I have recently built a fairly accurate laser timer to time sprinters through a section of a soccer pitch, giving a nice reading of their average speed through the zone.
The limitation is that we would love to be able to see their speed as a progressive measurement throughout the sprint.
My problem? I have NO idea where to start. Google has so far come up empty...
All I have is the following link, Best of the 2015 NHL All-Star Skills Competition, illustrating the sort of thing we would like to accomplish. The bit in question starts at around 0:35 when they are talking about sensors in the players' jerseys.
Any one able to point me in the right direction?

I'd think video processing would be a good, non-invasive, and relatively inexpensive.  Or duplicate a series of your laser timers for more resolution.

Really depends if your system has to "work on it's own", if you need the values directly and if it has to identify the different runners.

You can use photo cells. Just get some light sensors and direct lasers on to them. I got 100 lasers for £10 from eBay. You don't need to connect them to any controller, just connect them to a power supply to provide light for sensors. The sensors I got from eBay were, I think, 100 for about £5 or £10, then you can use an Arduino Mega and connect sensors to it.
When you cross the sensor, light will trigger and send a signal to Excel (you can use parallax program) and use Arduino code for interrupts when the sensor is triggered, you will get data to Excel (time and triggered sensor). If you call sensors like: first one 1 millisecond, 2 milliseconds, and so on, so you know what distance and what speed. But I think would be tricky if you need to measure a few guys simultaneously. It should work for single one though.

You have already answered this question. You could edit your previous answer and add this answer to that one.

Kinovea is good but this would be post processing not live. You need record video and then you can track each runner on time. Another one is Typhon program but it involves programming and calibrating (then you can track live).

An option would be to use a GPS module which would give you actual speed accurately, this data can be logged to EEPROM or SD and downloaded later or it can be sent wirelessly to a base station.
There is a wearable GPS module from adafruit, there are a few tutorials on getting started with it. You can the make a jacket or something light that can go onto the sprinters with the system attached.

You could use an IMU(Inertial measurement unit), this uses an Accelerometer, Gyro and Magnetometer. There is an article on using IMUs for measuring velocity of an object with basic modules and not using the expensive systems.
This article by CH Robotics covers a starting point, also googling this should give a whole load more of links. As the article says:

It depends entirely on how much accuracy is needed. In general, accelerometer-based position and velocity estimates from low-cost sensors ... are very poor and are simply unusable.

The next line in that article says "In general, accelerometer-based position and velocity estimates from low-cost sensors ... are very poor and are simply unusable", which I think is a much more accurate summarization of what CH Robotics was getting at.

@BrettAM - I was going to add that to discourage the use and left it out which was probably stupid.

You will likely need to buy a relativly high quality GPS for each runner. Alternatly, if you could get a camera mounted so it could see large portions on track from a good angle it could probably perform pretty well with the right optical recoginition code.
IMU's are not going to be capable of tracking a runners velocity. Even constrained to linear motion the position and velocity measurements from integrating a consumer accelerometer become garbage in a few seconds because of accumulated error. Once you add the fact that the sensor will not be level all the time and your angle estimation is at best within 1 degree, I'd estimate the velocity and position of a runner recorded by a normal 9-dof IMU would be irrelevent after at most 5 seconds.
Have a look at the table on this page for a detailed analysis of orientation based errors:http://www.chrobotics.com/library/accel-position-velocity

I would use an ultrasonic sensor pointed at them it will give you a list of distanced at the rate that the sensor collects information (e.g. 5Hz) this could be used to plot a graph of distance over time then a graph of speed over time, then acceleration over time ect.

Your are unlikely to get a sufficiently strong ultrasonic reflection over sprint distances, so this would require sensors along the course or active ultrasonic transponders on the runners.

Your best bet would be to use a module of Gyro, Accelerometer and Magnetometer much like MPU-9150. These devices communicate using I2C and you can log in data about the direction and the change in direction as well as acceleration. Using this data you can easily find out the speed in a particular direction and even overall data like the average speed, distance travelled, etc.
Another idea is using the accelerometer to measure a jerk.A jerk can be taken as a footstep and using appropriate calculations you can find out how much a person has moved throughout the sprint.
You can use ultrasonic sensors too which would tell you the position of the sprinter from a point but they have their disadvantages like small pressure changes due to air will affect the readings and you won't get accurate reading.


text:
Can you connect BH1790GLC and TMP117 sensors to an Arduino board?
I would like to use those two components for an upcoming project :

BH1790GLC heart rate sensor
TMP117 temperature sensor

I especially like the fact that they’re so tiny.
Could I connect them directly to an Arduino board or some other well-known microcontroller ?

Both of those sensors use I2C to communicate, so yes you can connect them to Arduino. but you gonna need a library and if the library doesn't exist you probably have lots of coding ahead of you. good luck. TMP117 library

Actually there are Arduino libraries available online for both of these sensors, which is one of the reasons why I chose them

Yes, the sensors will work with microcontroller(s). What you look for is the interface they use. In this case it is I2C interface. Be careful thou: You have to check voltage levels your microcontroller works with and selected sensor voltage level. Some of the Arduino works with 5V levels and some sensors may accept max of 3.3V or 4.5V on I2C pins. This is why you would need either:

Choose 3V powered microcontroller
Use 5V powered microcontroller (like Arduino Uno) and voltage level converter

Also worth to note that these two sensors would need some additional circuitry to work with your microcontroller. Before any commitment I would try to find a development board (a board with mentioned circuitry with easy to acces pins for providing necessary signals/voltages/ground/etc).
Good luck!


text:
How to choose a transmit pin in the IRremote library for an Arduino Uno?
I am looking for a way to choose a pin on the Arduino Uno. This pin will be used to send the signal of an IR LED. I am using the IRremote library.
e.g.
Below is the IR send demo which uses pulse width modulation pin 3 to send the IR signal. I want to change that pin to any other pin.
Any pointers will make me very happy thanks.
/*
 * IRremote: IRsendDemo - demonstrates sending IR codes with IRsend
 * An IR LED must be connected to Arduino PWM pin 3.
 * Version 0.1 July, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 */

#include <IRremote.h>

IRsend irsend;

void setup()
{
}

void loop() {
    for (int i = 0; i < 3; i++) {
        irsend.sendSony(0xa90, 12);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

Is the pin hardcoded into the library then? I recently had the same problem with the USB Host library. It is annoying when you can't define the pin yourself, although the authours of the library probably have their reasons for doing so. The line to change, for the Uno, seems to be line 138 in boarddefs.h, but I'm trying to find where IR_USE_TIMER2 is defined...

Line 195 in boarddefs.h you could try changing the 3 to another pin. It might work. I'll compose an answer out of these two comments.

As the pin does not appear to be able to be defined when creating an object from the IRsend class, it seems as if you will have to modify the IRremote library itself.
I recently had the same problem with the USB Host library, see Change select pin of USB Host library. It is annoying when you can't define the pin(s), that a particular library uses, yourself... However, the authors of the library probably have their reasons for doing so.
Looking through the various headers of the library, I found in boarddefs.h on lines 134-138:
// Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, Nano, etc
// ATmega48, ATmega88, ATmega168, ATmega328
#else
    //#define IR_USE_TIMER1   // tx = pin 9
    #define IR_USE_TIMER2     // tx = pin 3

So, the line to change, for the Uno, would seem to be line 138 in boarddefs.h
    #define IR_USE_TIMER2     // tx = pin 3

However, it is not, as that merely states that for the Arduino Uno IR_USE_TIMER2 is used...
Looking further down to where the Timers are defined, you will see the section for Timer 2, on line 146. In that section the transmit pin, for a number of versions of the Arduino, is defined as TIMER_PWM_PIN on lines 189-197:
#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) \
|| defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) \
|| defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) \
|| defined(__AVR_ATmega324PA__) || defined(__AVR_ATmega164A__) \
|| defined(__AVR_ATmega164P__)
#   define TIMER_PWM_PIN  14             // MightyCore
#else
#   define TIMER_PWM_PIN  3              // Arduino Duemilanove, Diecimila, LilyPad, etc
#endif                                   // ATmega48, ATmega88, ATmega168, ATmega328

You will have to change this line in the library, Line 196 in boarddefs.h:
#   define TIMER_PWM_PIN  3              // Arduino Duemilanove, Diecimila, LilyPad, etc

You could try changing the 3 so that you can use another pin. It might work. For example to use pin 5, en lieu of pin 3, change the 3 to a 5, like so:
#   define TIMER_PWM_PIN  5              // Arduino Duemilanove, Diecimila, LilyPad, etc

Be careful not to choose a pin that is used by something else, AND I think that the pin will need to be PWM capable.
Note that the definitions that are in boarddefs.h used to be in RemoteInt.h, in earlier versions of the library. See this comment at the very top:
// This file contains all board specific information. It was previously contained within
// IRremoteInt.h

So, make sure that you have the latest version of the IRremote library.

The above hack should also work for the Mega2560 as is uses the same timer, Timer 2, see lines 68-71:
// Arduino Mega
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    //#define IR_USE_TIMER1   // tx = pin 11
    #define IR_USE_TIMER2     // tx = pin 9

Other boards are also defined in this file. If you have another type of board, the timer may be different, but the process to find which line to change would be very similar...

Note that I have not tried this, so I would be interested to hear if it works or not.

Thanks for your answer. I have two questions: How do I know when a pin is being used by something else? Will I be able to choose more than one pin to do a task? e.g at the moment only pin 3 sends IR signal however, I would like pin3, pin 5 and pin6 to send IR signals.

Your code will tell you if a pin is being used. W.R.T. the IRremote library, the documentation will tell you which pins it is using. 2) Looking at the library it seems that you can not, or at least not without further modification. Maybe you could activate another Timer, by uncommenting out another line, and then use the pin of that timer (as each timer, appears to use its own separate pin - from looking at that header file). I am not sure. If you really want to do that, then ask/post a separate (related) question, as it is significantly different from your original question.. :-)

I tried to find where the pin is defined and gave up, I ended up swapping to pin9 by commenting out timer2, like this:
#define IR_USE_TIMER1   // tx = pin 9
//#define IR_USE_TIMER2     // tx = pin 3

Not ideal since I needed 9 also and I will add how annoying this library is that although I only need to receive signals and never send...it still takes up a pin for sending.
ANyway, the posts above helped me at least get my motor shield working, thanks guys.


text:
Strange characters after typing an AT command in serial monitor
I'm trying to test AT commands (I am working with an  Arduino Uno and a GSM/GPRS SIM900  shield; my system is ubuntu 14.10) . Yesterday when I was testing , all  ran well.. For example after typing AT+SAPBR=3,1,"APN","ooredoo" in the serial monitor it  showed me OK.. but But now it  shows me strange  characters.
This is my code
    #include <SoftwareSerial.h>
    SoftwareSerial GPRS(2,3);

void setup() {
  // put your setup code here, to run once:
 GPRS.begin(9600);
  Serial.begin(9600);
 Serial.write("start");

}

void loop() {

  // put your main code here, to run repeatedly:
     while(GPRS.available())
     Serial.write(GPRS.read());

  while(Serial.available())
    GPRS.write(Serial.read());

}

And this it is the result of AT+SAPBR=3,1,"APN","ooredoo" typed in the serial monitor

Thank you for helping me

Did you select the right baud rate? I get these strange characters when I have set it wrong.

i didn't change anything...it worked like this yesterday,but now i have this strange characters...what can be the problem?

You haven't changed any settings, but have you knocked a wire.  It could be a loose connection or a bad ground connection.

bad connection? i don't know..but the shield work normaly..the red led is on, the station led is also on and the net led blind every 3 seconds

for those who have this issue, i resolve this by changing the speed baud of my GPRS Shield :
GPRS.begin(2400);
Serial.begin(9600);

and if you want to test AT command directly on the serial monitor you must use 2400 anywhere
GPRS.begin(2400);
    Serial.begin(2400);

and don't forget to change also  the speed on the serial monitor to 2400
I hope this will help someone


text:
how to make GPRS/GSM SIM900 shield work with gps neo-6M module using Arduino UNO board
I'm a beginer to arduino program.i will like to make a program that will send latitude and longitude on my mysql database.so since 3 days i try to learn how to use all this material(GPRS/GSM SIM900 shield, gps neo-6M).But i only success to make them work alone.i also learn that i cannot use SoftwareSerial for GPRS/GSM SIM900 shield and  gps neo-6M at the same time.
so how can i make GPRS/GSM SIM900 shield and gps neo-6M work together using arduino uno
thank you for you help

This should provide the answer you need link

I think you are searching for a solution like this Interfacing GSM and GPS Module using Arduino where GPS and GSM modules can run together and receive data at the same time.
I tried bringing up both inside setup() and it blocked the other device. Here is some extract of the code (Note that rx,tx and baud rates may differ according to the modules).
SoftwareSerial gsm(7,8);
SoftwareSerial gps(3,4);

void setup() {
    Serial.begin(9600);
    gps.begin(9600);
    gsm.begin(4800); <--- This stopped receiving GPS updates
}

If you look for an advanced way of handling this situation, you may need to implement some light-weight threads (e.g Protothreads) and assign GPS and GSM modules to run in separate threads, so one device may not block send/receive of the other device. These Arduino forum answers may help for such approach.

I will suggest you to use TinyGPS to connect only via GPS and get the position, make sure you are testing outside with good view of the sky or the gps will never get a lock down.
Then when you are familiar with TinyGPS and how to get the location, add the GSM module to send over this information to your mysql server.


text:
NRF24L01 writing fail
My arduino uno with the NRF24L01 combination gives failed messages on writing.
Using the basic example code 'getting started' literally copied from:
http://tmrh20.github.io/RF24/GettingStarted_8ino-example.html, my serial monitor constantly writes 'failed' (See attached screenshot)
The setup is for my Arduino uno as described in the table on
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo#PP (Arduino pin for
TMRh20 RF24 Library)
The code:
/*
* Getting Started example sketch for nRF24L01+ radios
* This is a very basic example of how to send data from one node to another
* Updated: Dec 2014 by TMRh20
*/
#include <SPI.h>
#include "RF24.h"
#include <printf.h>

/****************** User Config ***************************/
/***      Set this radio as radio number 0 or 1         ***/
bool radioNumber = 1;
/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
RF24 radio(7,8);
/**********************************************************/
byte addresses[][6] = {"1Node","2Node"};
// Used to control whether this node is sending or receiving
bool role = 0;
void setup() {
  Serial.begin(115200);
  printf_begin();
  Serial.println(F("RF24/examples/GettingStarted"));
  Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));

  radio.begin();
  // Set the PA Level low to prevent power supply related issues since this is a
 // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  radio.setPALevel(RF24_PA_LOW);

  // Open a writing and reading pipe on each radio, with opposite addresses
  if(radioNumber){
    radio.openWritingPipe(addresses[1]);
    radio.openReadingPipe(1,addresses[0]);
  }else{
    radio.openWritingPipe(addresses[0]);
    radio.openReadingPipe(1,addresses[1]);
  }
  radio.printDetails();
  // Start the radio listening for data
  radio.startListening();
}
void loop() {

/****************** Ping Out Role ***************************/
if (role == 1)  {

    radio.stopListening();                                    // First, stop listening so we can talk.

    Serial.println(F("Now sending"));
    unsigned long start_time = micros();                             // Take the time, and send it.  This will block until complete
     if (!radio.write( &start_time, sizeof(unsigned long) )){
       Serial.println(F("failed"));
     }

    radio.startListening();                                    // Now, continue listening

    unsigned long started_waiting_at = micros();               // Set up a timeout period, get the current microseconds
    boolean timeout = false;                                   // Set up a variable to indicate if a response was received or not

    while ( ! radio.available() ){                             // While nothing is received
      if (micros() - started_waiting_at > 200000 ){            // If waited longer than 200ms, indicate timeout and exit while loop
          timeout = true;
          break;
      }
    }

    if ( timeout ){                                             // Describe the results
        Serial.println(F("Failed, response timed out."));
    }else{
        unsigned long got_time;                                 // Grab the response, compare, and send to debugging spew
        radio.read( &got_time, sizeof(unsigned long) );
        unsigned long end_time = micros();

        // Spew it
        Serial.print(F("Sent "));
        Serial.print(start_time);
        Serial.print(F(", Got response "));
        Serial.print(got_time);
        Serial.print(F(", Round-trip delay "));
        Serial.print(end_time-start_time);
        Serial.println(F(" microseconds"));
    }
    // Try again 1s later
    delay(1000);
  }
/****************** Pong Back Role ***************************/
  if ( role == 0 )
  {
    unsigned long got_time;

    if( radio.available()){
                                                                    // Variable for the received timestamp
      while (radio.available()) {                                   // While there is data ready
        radio.read( &got_time, sizeof(unsigned long) );             // Get the payload
      }

      radio.stopListening();                                        // First, stop listening so we can talk
      radio.write( &got_time, sizeof(unsigned long) );              // Send the final one back.
      radio.startListening();                                       // Now, resume listening so we catch the next packets.
      Serial.print(F("Sent response "));
      Serial.println(got_time);
   }
 }
/****************** Change Roles via Serial Commands ***************************/
  if ( Serial.available() )
  {
    char c = toupper(Serial.read());
    if ( c == 'T' && role == 0 ){
      Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
      role = 1;                  // Become the primary transmitter (ping out)

   }else
    if ( c == 'R' && role == 1 ){
      Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));
       role = 0;                // Become the primary receiver (pong back)
       radio.startListening();

    }
  }
} // Loop

While my other arduino has the same setup only radioNumber = 0 on that one.
The monitor output:

My setup:

EDIT:
Ok so i managed to run printDetails() (thanks for the help on that one)
This came up with:
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0x65646f4e31 0x65646f4e32
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0x65646f4e31
RX_PW_P0-6   = 0x20 0x20 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x02
RF_CH        = 0x4c
RF_SETUP     = 0x03
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_LOW

on arduino one, and with the following on arduino 2 with radionumber = 1
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0x65646f4e32 0x65646f4e31
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0x65646f4e32
RX_PW_P0-6   = 0x20 0x20 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x02
RF_CH        = 0x4c
RF_SETUP     = 0x03
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_LOW

Do you have the same setup for the receiver? How far is the receiver from your transmitter? The NRFs have some trouble if they are to close to one another.

Same setup, about 2 / 3 meters away. However, this more likely seems like a problem of transmitting rather than receiving because this says that transmitting is not even working right?

Sorry, you're correct. The timeout message threw me off. It seems like the Arduino is unable to communicate with the NRF. Try wiggling all the connections, to make sure they make good contact. Try calling the printDetails function.

hmm the connections seem fine... especially because both devices give the same error. (same setup). I have a small issue implementing the printDetails. when I add the line radio.printDetails(); anywhere, I don't see any response in my monitor?

@Mart You have to initialize printf first for printDetails to work.

Thanks @Avamander I updated my initial question with the printDetails output. I have no clue what can be wrong

Looking at the pictures, I'm sure this issue is caused by too weak power supply. Try soldering a large decoupling capacitor to the module's VCC and GND pins directly, if that doesn't improve the situation use an external 3.3V regulator.

Cross posted to: https://github.com/nRF24/RF24/issues/445

I'm currently writing a driver (for fun) and noticed that if the clock line is not at the correct idle logic level when the CS pin goes low, the chip freaks out and gives me issues when reading/writing registers. This may or may not help you, but figured it would be worth a shot to mention it.
Edit: The chip expects CPOL 0, so I used a pull down resistor on the clock line. So it will by default idle low.

Rewrite your answer as an actual solution, if it is one.  Presently, it appears more of a comment.

Thanks, i'll try asap and post the result. Did you place a resistor between sck pin and ground? (assuming this layout: https://tmrh20.github.io/RF24/ )

I didn't need to physically place a resistor due to my MCU having them internally, but that should work fine. Maybe 10k?

See how/whether Arduino actually communicates with the master nRF, before tackling the problem of the tx/rx.
Use the code given below to print out the tx and rx radio registers (no libraries required except SPI).  You will need to use the right values for CE and CSN pins.  Post the data in your question, there are many several people on stack exchange who will be able to help you find the solution.
#include <SPI.h>
#define CE_pin 4
#define CSN_pin 5
#define MOSI_pin 11
#define MISO_pin 12
#define SCK_pin 13
byte data_in;

byte radio1_tx_addr[5] = {0xC5, 0xC5, 0xC5, 0xC5, 0xC5};
byte radio2_tx_addr[5] = {0x31, 0x31, 0x31, 0x31, 0x31};

void setup() {
  Serial.begin(115200);
  pinMode(CE_pin, OUTPUT);//chip enable set as output
  pinMode(CSN_pin, OUTPUT);//chip select pin as output
  pinMode(MOSI_pin, OUTPUT);//SPI data out
  pinMode(MISO_pin, INPUT); //SPI data in
  pinMode(SCK_pin, OUTPUT);//SPI clock out
  SPI.setBitOrder(MSBFIRST);//SPI Most Significant Bit First
  SPI.setDataMode(SPI_MODE0);// Mode 0 Rising edge of data, keep clock low
  SPI.setClockDivider(SPI_CLOCK_DIV2);//Run the data in at 16MHz/2 - 8MHz
  digitalWrite(CE_pin, HIGH);//RX mode
  digitalWrite(CSN_pin, HIGH);//SPI idle
  SPI.begin();//start up the SPI library
  delay(100);

  nrf_set_TX_ADDR(radio1_tx_addr); // set TX/RX addresses
  nrf_set_RX_ADDR_P1(radio2_tx_addr);

  Serial.print("CONFIG");
  nrf_read_register(0x00);
  Serial.print("EN_AA");
  nrf_read_register(0x01);
  Serial.print("EN_RXADDR");
  nrf_read_register(0x02);
  Serial.print("SETUP_AW");
  nrf_read_register(0x03);
  Serial.print("SETUP_RETR");
  nrf_read_register(0x04);
  Serial.print("RF_CH");
  nrf_read_register(0x05);
  Serial.print("RF_SETUP");
  nrf_read_register(0x06);
  Serial.print("STATUS");
  nrf_read_register(0x07);
  Serial.print("OBSERVE_TX");
  nrf_read_register(0x08);
  Serial.print("RPD");
  nrf_read_register(0x09);
  Serial.print("RX_ADDR_P0");
  nrf_read_register(0x0A);
  Serial.print("RX_ADDR_P1");
  nrf_read_register(0x0B);
  Serial.print("RX_ADDR_P2");
  nrf_read_register(0x0C);
  Serial.print("RX_ADDR_P3");
  nrf_read_register(0x0D);
  Serial.print("RX_ADDR_P4");
  nrf_read_register(0x0E);
  Serial.print("RX_ADDR_P5");
  nrf_read_register(0x0F);
  Serial.print("TX_ADDR");
  nrf_read_register(0x10);
  Serial.print("RX_PW_P0");
  nrf_read_register(0x11);
  Serial.print("RX_PW_P1");
  nrf_read_register(0x12);
  Serial.print("RX_PW_P2");
  nrf_read_register(0x13);
  Serial.print("RX_PW_P3");
  nrf_read_register(0x14);
  Serial.print("RX_PW_P4");
  nrf_read_register(0x15);
  Serial.print("RX_PW_P5");
  nrf_read_register(0x16);
  Serial.print("FIFO_STATUS");
  nrf_read_register(0x17);
  Serial.print("DYNPD");
  nrf_read_register(0x1C);
  Serial.print("FEATURE");
  nrf_read_register(0x1D);
}

void loop() {
}

void nrf_read_register(byte reg) {
  digitalWrite(CSN_pin, LOW);
  SPI.transfer(reg);
  data_in = SPI.transfer(0x00);
  digitalWrite(CSN_pin, HIGH);
  Serial.print(": 0x");
  Serial.print(reg,HEX);
  Serial.print(" => 0x");
  Serial.println(data_in,HEX);
  delay(10);
}

void nrf_set_TX_ADDR(byte x) {
  digitalWrite(CSN_pin, LOW);
  SPI.transfer(0x30);
  SPI.transfer(x[0]);
  SPI.transfer(x[1]);
  SPI.transfer(x[2]);
  SPI.transfer(x[3]);
  SPI.transfer(x[4]);
  digitalWrite(CSN_pin, HIGH);
  delay(10);
}

void nrf_set_RX_ADDR_P1(byte x) {
  digitalWrite(CSN_pin, LOW);
  SPI.transfer(0x2B);
  SPI.transfer(x[0]);
  SPI.transfer(x[1]);
  SPI.transfer(x[2]);
  SPI.transfer(x[3]);
  SPI.transfer(x[4]);
  digitalWrite(CSN_pin, HIGH);
  delay(10);
}

CONFIG: 0x0 => 0xF
EN_AA: 0x1 => 0x3F
EN_RXADDR: 0x2 => 0x2
SETUP_AW: 0x3 => 0x3
SETUP_RETR: 0x4 => 0x5F
RF_CH: 0x5 => 0x4C
RF_SETUP: 0x6 => 0x3
STATUS: 0x7 => 0xE
OBSERVE_TX: 0x8 => 0x0
RPD: 0x9 => 0x0
RX_ADDR_P0: 0xA => 0x31
RX_ADDR_P1: 0xB => 0x32
RX_ADDR_P2: 0xC => 0xC3
RX_ADDR_P3: 0xD => 0xC4
RX_ADDR_P4: 0xE => 0xC5
RX_ADDR_P5: 0xF => 0xC6
TX_ADDR: 0x10 => 0x31
RX_PW_P0: 0x11 => 0x20
RX_PW_P1: 0x12 => 0x20
RX_PW_P2: 0x13 => 0x0
RX_PW_P3: 0x14 => 0x0
RX_PW_P4: 0x15 => 0x0
RX_PW_P5: 0x16 => 0x0
FIFO_STATUS: 0x17 => 0x11
DYNPD: 0x1C => 0x0
FEATURE: 0x1D => 0x0

You are at least talking to the radio.  All settings are default except CONFIG: 0x0 => 0xF (PRX mode, powered up, crc=2 enabled) SETUP_RETR: 0x4 => 0x5F (up to 15 retransmit attempts) RF_CH: 0x5 => 0x4C (channel 2476 MHz) RX_PW_P0: 0x11 => 0x20 (32-byte payload) RX_PW_P1: 0x12 => 0x20 (32-byte payload).  See section 9 of the nRF data sheet for index of the register values.

One of the radios needs to be PTX (primary transmitter), the data you posted above show the radio is set to PRX (primary receiver).  Make sure receiver and transmitters have common pipe addresses and use the same radio frequency. Upvote answer, please, if it is helpful to you.

Okay, thanks! so if I'm able to talk to the radio, why will the writing result in a fail? Are these settings incorrect? I just took them out of the box like this and started working with them like described above without editing settings.

For each Arduino controlling the TX/RX radios, put my code into your program at the end of setup section and copy here what the output is.  There are many things which can be wrong.  Also check one of the radios has bool radioNumber = 0; and the other bool radioNumber = 1;

CONFIG: 0x0 => 0xF
EN_AA: 0x1 => 0x0
EN_RXADDR: 0x2 => 0x2
SETUP_AW: 0x3 => 0x3
SETUP_RETR: 0x4 => 0x5F
RF_CH: 0x5 => 0x4C
RF_SETUP: 0x6 => 0x3
STATUS: 0x7 => 0xE
OBSERVE_TX: 0x8 => 0x0
RPD: 0x9 => 0x0
RX_ADDR_P0: 0xA => 0x24
RX_ADDR_P1: 0xB => 0x15
RX_ADDR_P2: 0xC => 0xC3
RX_ADDR_P3: 0xD => 0xC4
RX_ADDR_P4: 0xE => 0xC5
RX_ADDR_P5: 0xF => 0xC6
TX_ADDR: 0x10 => 0x24
RX_PW_P0: 0x11 => 0x20
RX_PW_P1: 0x12 => 0x20
RX_PW_P2: 0x13 => 0x0
RX_PW_P3: 0x14 => 0x0
RX_PW_P4: 0x15 => 0x0
RX_PW_P5: 0x16 => 0x0
FIFO_STATUS: 0x17 => 0x11
DYNPD: 0x1C => 0x0
FEATURE: 0x1D => 0x0

radionumber is 1 on the first arduino, 2 on the second

TX and RX addresses are not opposite, they are same on each Arduino. See this by comparing RX_ADDR_P0 with TX_ADDR: 0x24 on one Arduino, 0x31 on the other.  Try swapping radio.openReadingPipe(1,addresses[0]); for radio.openReadingPipe(1,addresses[1]); and vice versa

All fine and stuff, but shouldn't the nrf24 library from tmrh20 fix this? Your last suggestion didn't work.. (and upvoting is something i can't do yet)

I don't know about that library, but from the information you gave, it appeared the problem was that the addresses set incorrectly.  TX address of radio 1 should equal RX address (of relevant data pipe) for radio 2, and vice versa.  I will add to my answer code that will let you set the addresses manually.

Let us continue this discussion in chat.


text:
How to choose SDA/SCL pair on Arduino Due?
On Arduino Due, there are two pairs of SDA/SCL pins that I can use for I2C. There is SDA0 and SCL0  at, respectively, pins 20 and 21 and another near AREF. How do I choose which one of them I use? I also read that pins 20 and 21 have built-in pull-up resistors, is that true?

The easiest/quickest way would be to experiment.  Attach an I2C device and use I2CScanner to detect it, then repeat with the other pins.  As to the pull-up you could use a volt metre to test that (I think)

Pins 20 and 21 are the default I2C pins. A lot of libraries assume you use these, and would require some extra work to get working with SDA1/SCL1.
They also have their pullup resistors already present on the board of the Due (see schematic).
So just use pins 20 and 21, unless you have a good reason to use the other.

How to choose SDA/SCL pain on due from software.
wire.h has two instances of TwoWire i.e. Wire and Wire1.
Wire uses
#define PIN_WIRE_SDA         (20u)
#define PIN_WIRE_SCL         (21u)

and Wire1
#define PIN_WIRE1_SDA        (70u)
#define PIN_WIRE1_SCL        (71u)

observe which instance is used by your library
e.g.
#define WIRE Wire1 or #define WIRE Wire

if library is using Wire then its default i2c at pin 20 and 21.
if library is using Wire1 then its i2c at pin 70 and 71 near AREF.
make changes accordingly. if you want to use default i2c use "Wire" instance or
if you want to use i2c near AREF use "Wire1".
most important don't forget to modify Wire1.begin() or Wire.begin() accordingly.
as mentioned in earlier comment second i2c (pin 70 and 71 near AREF) doesn't have pullup resistor handle it while using second i2c.


text:
Reading and sending with Arduino?
I am using Arduino in an IOT application where I have to read impulses coming from a sensor and send a mean value of these impulses without missing any impulse while sending the value so is it possible to achieve such operation knowing that Arduino is a single core chip.
I read about Protothreading libraries but it may miss an impulse during the check phase so I want to know if there is another solution

One word: Interrupts. Google them.

Post some more details of what you are trying to achieve.  You want to count pulses?  Interrupts as Majenko said.

yes i need to count pulses so i dont want that at the moment when i send a value, i miss a pulse

I have googled for polthread and pollthread, and can't find anything. Can't you provide a link. Regardless, count each impulse in a ISR (one statement should do it) and in the loop() you can calculate and output the mean using 'millis()`

sorry ,its protothreading here is a link https://www.hackster.io/reanimationxp/how-to-multithread-an-arduino-protothreading-tutorial-dd2c37

@Majenko if i use interrups every time i get an impulse wont it disturb the sending function ? knowing that i have to send a value every period of time

Unless the sending function relies on timing critical bit banging, no, you won't "disturb" it. What is this mythical "sending function"? What are you using to communicate? How are you controlling it?

i am sending my mean value over Lora network to a gateway

Although the Arduino only has one CPU core and can only execute one program instruction at a time, it's not limited to only doing one thing at a time.
An MCU is a complex device with lots and lots of peripheral devices built into it. The CPU is only one small block of the overall device.
Much of a program is merely instructions telling the peripherals how to perform.
For instance, when sending data through Serial the CPU doesn't say "Send this bit. Now wait. Now send this bit. Now wait again" - instead it just says "Here's this byte to send. Now go and send it and tell me when you're done". The UART peripheral then sends the byte by itself with no further input from the CPU leaving the CPU free to do other things.
Then there's the Timer peripherals.  The CPU sets them up to count from a clock source, and do different things depending on different events, like a specific number is reached in the counting, etc. The CPU has no need to go "Count up one. Count up one. Count up one." - it just goes "Count up from 0 using this clock source and tell me when you reach 100" (for example).
Similarly, there are "External Interrupts". The CPU doesn't need to sit watching an IO pin all the time, going "Have you changed yet? Have you changed yet? Have you changed yet?" - it just goes "Tell me when you have changed" and the CPU goes off to do other things.
Of course, all these things have caveats. The biggest is that if the CPU is doing something very timing critical, such as "bit banging" serial data manually through a GPIO pin (for example with SoftwareSerial) it can be set to ignore all these interrupt signals from the peripherals. That means, if you're using an "External Interrupt" to count pulses, and you have to use SoftwareSerial to communicate, it's possible that SoftwareSerial's sending or receiving routines could cause the detection of a pulse to be either delayed (not really a problem) or to be missed completely.
So you don't want to use SoftwareSerial if it can be avoided if you want to use External Interrupts for this kind of operation.
The other option is to use a timer. I mentioned that they just count up from 0 (or they can count down, too) using a configurable clock source. That counting happens completely independently of the CPU, and carries on regardless of whether interrupts are enabled or disabled. And the great new is that most timers can be configured (depending on which Arduino you use) to use an external signal as the clock source for the counting.
That means you can configure a timer to count your pulses for you regardless of what the CPU is doing. All you have to do is every so often (how often depends on how frequently your pulses arrive - the timer has a limit on how many it can count before it overflows) ask the timer for what it has counted up to and reset its count to 0. That could be done as part of your "sending" routine. Get the count, reset it to 0, and send the results.

what if the frequency that i am counting is variable? can the timer solution still work

Yes. It just cares about edges. As long as the number of pulses you need to count is less than the maximum the timer can count (or you "expand" it using the overflow interrupt) within the period at which you read-and-reset the count it doesn't care what the frequency is (as long as it's below 1/2 the system clock frequency).

i get ur solution however if i use the timer as a counter how would i know the time during witch i counted my pulses to get a mean value ?

There is more than one timer. Timer0 drives millis().


text:
Hall sensor noise removal
I am using Arduino Duemilanove and a hall effect sensor to calculate the speed of a motor.  When I used sensor out directly to Interrupt0, the rising edges of noise were also detected. So the speed calculation went wrong.
So now  sensor is connected to A0.and a threshold is put. Pin No 13 is connected to Interrupt 0(Pin 2). I use the following code.
volatile byte count;
 const int analogPin = A0;
 const int digitalPin=13;
 const int threshold =20;
 unsigned int rpm;
 unsigned long starttime;

 void setup()
 {
   pinMode(digitalPin,OUTPUT);
   digitalWrite(analogPin,HIGH);
   digitalWrite(digitalPin,HIGH);
   Serial.begin(9600);
   attachInterrupt(0,sense,FALLING);
   rpm=0;
   starttime=0;
   count=0;
 }
 void loop()
 {
   int sensorValue = analogRead(analogPin);
   Serial.println(sensorValue);
   if (sensorValue < threshold)
   {
     digitalWrite(digitalPin,LOW);
     if (count>=20)
     {
       rpm=60*1000*count/(millis()-starttime);
       starttime=millis();
       count=0;
       Serial.println(rpm,DEC);
     }
   }
   else
   {
     digitalWrite(digitalPin,HIGH);
   }

 }
 void sense()
 {
  count++;
 }

But I get actual speed only in between. The speed changes back . I feel there is some problem with the sampling or rpm updation. Looking forward for help

You could try adding an RC filter to filter out the noise, before feeding it into the INT0 pin.

I don't see the point of using attachInterrupt here since this is your code that artificially triggers interrupts by writing to digitalPin. Hence I think your sense function is not called as many times as you would expect. Also, where does the value 20 for threshold come from?

It sounds like you need a debouncing circuit.
You can do it in code, but you are then trying to execute more code in you interrupt handler.
I would go for a hardware version.  I don't have the circuit to hand but if you search for a 'Schmidtt Trigger' based debouncing circuit.  You can implement it with 5 resistors, a capacitor, a LM386 OpAmp and a CMOS XOR IC (Inverts the signal which the inverting Schmidtt trigger inverts).
What happens is the Schmidtt trigger goes low when the input passes a certain voltage.  It remains low until the voltage passes the low voltage threshold at which point it goes high.  The CMOS XOR IC (I think its a 4004??) takes two inputs and inverts them.  It also adds extra hysteresis which further damps the bouncing.
The values of your resistors affect the thresholds, but there are plenty of calculators on the web that will solve the values for you.
The LM386 has two channels and the CMOS usually has 4 so it becomes quite easy to debounce multiple signals.
Hope that helps.

       rpm=60*1000*count/(millis()-starttime);

Since rpm is an unsigned int (which has a maximum of 65535) you will almost certainly overflow if count is more than 1, which will give you negative numbers, or incorrect positive numbers.
Plus, outputting to serial constantly will cause the program to lock up waiting for the serial buffer to empty, which will throw out any timings you are doing.
I suggest making rpm unsigned long (or float as you seem to have done already) and only display the RPM every second or so.

Also see my page Using the Arduino Analog Comparator. This is a much faster way of detecting an analog signal merely passing some threshold. This only takes a few microseconds compared to 104 µS for a single analogRead. In the ISR then you just add one to a counter (which is the number of times it passes the threshold). Every second take this counter, and work out the RPM, then zero it. Make sure you make a copy of the counter in a protected way as shown on my page about Interrupts.

A possibility I am toying with for a similar problem is realizing that there will always be a delay between valid sensor readings.  For example, imagine you had a maximum speed of 10 revolutions/second.  That would mean that there would be a maximum of 10 sensor inputs/second or 1 interrupt every 100 msecs.
If you changed your interrupt processing logic to something like:
if (millis() - timeOfLastSensorReading >= 10) {
   count++;
   timeOfLastSensorReading = millis();
}

Then your logic would become "Only register a sensor change if at least 10 msecs has passed since the last reading".
You might have to tune the values based on your real situation ... but it might go a long way to eliminate some aspects of false readings.


text:
Where to get the potentiometer that comes with Arduino kit
Does anyone know where I can get the potentiometer that comes with the Arduino kit? You can see them here.
They are sold out on their website.

There is a radio shack in your town. Kailus-Kona. You can pick up any pot you like there

It's just any old trimmer pot. It's nothing special. Why do you feel you need that specific one? Any pot (of the right value) will do.  What value is it? (That datasheet is a generic one for all values).
Visit your favourite electronics retailer (IRL or on line) and pick a pot that is a suitable value and jiffles your tipples.

10k. I just want these because I've used them and know they work for what I want. Try to find anything like these on Amazon. None of them have knobs.

Amazon is not an electronics retailer.  Any linear tracked 10K pot "will work" for you. Everything else is just looks.

Ok please find me a link to any site that sells trimmer pots with knobs.

https://www.google.com/search?q=trimmer+pot+knob&ie=utf-8&oe=utf-8#q=trimmer+pot+knob&tbm=shop

Here's one, https://www.sparkfun.com/products/9288 but it's not a trimmer pot

That google search didn't help. I tried that.

Please, tell me why you feel you need a trim pot with a knob? Why not a trim pot without a knob, or a normal pot? What is so special about a trim pot with a knob?

Because it's perfect for a servo that only rotates 180 degrees. And I need the knob to turn it. lol

What on god's earth has the style of pot got to do with the fact that a servo rotates 180°?

I thought a trimmer pot turns only 180 degrees. The Arudino one I have does. I ordered some other ones and they spin in circles.

They spin in circles because you force them past the end of the track. Keep doing that and you will probably break them.  If you want to have a pot only work for 180° then program it to only work for 180° - don't rely on finding a very esoteric pot that can't be found. Settle for a cheap generic one and do the rest in software.

Software isn't going to stop the knob from spinning around. Like I said the Arduino ones found above do exactly what I need. They aren't like volume knobs, they rotate only a certain amount.

Normal pots only rotate a certain amount. Cheap trim pots can very easily be forced around too far, often without knowing it.  The actual sensitive area will only be somewhere between 180 and 270°.


text:
ESP8266 ASCII to HEX convertion and checking
I am trying to convert ASCII to hex and check if the hex is equal to that hex that I want.
For example:
1B 42 05 it means B in ASCII, I need to check if that hex is equal to 1B 42 05.
Here I need to send converted hex code from ASCII code by using SoftwareSerial.
Example:
02 20 2D 33 30 32 35 30 20 6B 67 0D 0A 03

I have to convert to
-30250 kg

you can't convert 1B to HEX because it IS HEXadecimal representation of a number. it is like if you would say that you need to convert 42 to a decimal number. you can convert string "1B" to a byte value.

1B 42 05 is more than just a B ...... please consult ASCII tables

Your example looks like a serial protocol string... 02 20 2D 33 30 32 35 30 20 6B 67 0D 0A 03 corresponds to <stx> -30250 kg<cr><lf><etx>. So you have to do a bit more than just hex to ascii

A little explanation about HEX and ASCII:
About HEX
Raw computer data consists of zeros and ones. For humans it is difficult to read a (long) row of zeros and ones. You can represent such a row (of a certain length) by a decimal number, but then the relation with the underlying bits is not directly clear. For this reason the hexadecimal (HEX) representation is used (hexadeca comes from Greek and means 16.
Four bits can represent 16 different situations (= 16 different combinations of zeros and ones). The HEX digit belonging to each combination is:
0000 = 0; 0001 = 1; 0010 = 2; 0011 = 3; 0100 = 4; 0101 = 5; 0110 = 6; 0111 = 7
1000 = 8; 1001 = 9; 1010 = A; 1011 = B; 1100 = C; 1101 = D; 1110 = E; 1111 = F
When you memorize these 16 cases (from which the first 10 are easy because it is juist binary counting), you know immediately which bit-pattern belongs to a hexadecimal number and vice versa. For example: the HEX value 5A = 01011010.
About ASCII
Computer data contain not only numbers, but also text. As the computer can only handle bits (zeros and/or ones) we have to decide how letters (characters) are presented by bit patterns. And preferably in a standardized way, in order that different computers can handle each others text. Unfortunately there is more than one standard, but one that is very much used is the ASCII standard (see: https://en.wikipedia.org/wiki/ASCII).
The ASCII standard uses 7 bits codes and defines not only characters but also 'control codes' e.g. for 'line feed' and 'carriage return'. Often these 7 bits are stored in one byte (with the leftmost 8th bit set to 0) and can than be represented by two HEX digits.
Without further information nobody can tell what a row of bits represents. That's one of the reasons datatypes are used. They tell us what the row of bits represents and how many bits (or bytes) are used for the representation.
So the HEX representation of your row of 3 bytes is "1B 42 05" and, when these are characters, could stand for (look at the ASCII table): "ESCAPE B ENQ". In which 'ESCAPE' and 'ENQ' are control codes which meaning depends on the communication protocol.
The second row (of 14 bytes) could stand for: "STX SPACE - 3 0 2 5 0 SPACE k g CR LF ETX". STX and ETX stand for 'START OF TEXT' and 'END OF TEXT'. 'LF' stands for 'LINE FEED' and 'CR'stands for 'CARRIAGE RETURN'.
I hope that with this explanation you have a better idea about HEX and ASCII and that you now will be able to figure out how to handle your data.

Converting an ASCII HEX digit is simple enough.  Here's a little function I use all the time:
uint8_t h2d(char hex) {
    if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
    return(hex & 0xf);
}

Pass it a single HEX digit as a char variable and it returns a number between 0 and 15.
To convert a pair of characters into an 8-bit value just call it twice with each character, shift one of them 4 bits to the left, and OR them together.  For instance:
uint8_t h2d2(char h1, char h2) {
    return (h2d(h1)<<4) | h2d(h2);
}

That would give you a number between 0 and 255 (or 016 and FF16, or 08 and 3778...)
How you receive and split up the incoming data properly is a whole other topic, but this and this could probably help you.


text:
The Arduino IDE can’t find my Arduino Uno
My Arduino has all of its LEDs on. The Rx, Tx and L LEDs are all on and my computer can’t see it (it's an SMD edition).

It can have many reasons, but you can try the following:
First time use?

Check if you need to install a special driver for CH340

Environment/Software problems

Try another USB port
Change USB cable
Restart Arduino IDE
Restart computer
Reinstall Arduino IDE

Hardware problems

Test using another Arduino
Test using another computer/laptop
Replace USB cable
The Arduino is (partly) broken, nothing much to do here

Is it an "official" Arduino purchased from their website? If it isn't, chances are you need to install CH340 drivers for your computer before the Arduino will be recognized. Drivers can be found here Have you successfully used this device with your computer before?

The USB interface chip controls the Rx & Tx lights.  I suspect you fried it.
Does the '328P feel warm or hot to the touch? That's usually a sign that it has been damaged.