text:
Unable to read and write serial data between two arduino's (hc-05 paired) when using a sensor
What I did was that I wrote a piece of code that will-in-fact move a servo motor when a clap is detected using a sound impact sensor (fc-04).
The code for this is seen here and in fact does work:
#include "Arduino.h"
#include <Servo.h>
Servo myservo;//create servo object to control a servo
enum {
    SERIAL_BAUD        = 9600,
    SENSOR_DIGITAL_PIN =    2,
    SOUND_DELAY        =   1500, /* Delay to avoid duplicate detection */
};

void setup() {
    Serial.begin(SERIAL_BAUD);
    pinMode(SERIAL_BAUD, INPUT);
    myservo.attach(9);//attachs the servo on pin 9 to servo object
    myservo.write(0);//back to 0 degrees
    delay(1000);//wait for a second
}

void loop() {
    if (digitalRead(SENSOR_DIGITAL_PIN) == LOW) {
        static int count;

        Serial.print("Sound detected: ");
        Serial.println(++count);
        myservo.write(170);//goes to 15 degrees
        delay(3000);//wait for 3 seconds
        myservo.write(10);//back to 0 degrees
        delay(1000);//wait for a second

        // Wait a short bit to avoid multiple detection of the same sound.
        delay(SOUND_DELAY);
    }
}

On a seperate occasion I paired two arduinos together using two hc-05 bluetooth modeules making one a slave and another a master, the initial code I used for both of them are listed here:
//                 == SLAVE CODE ==

#include <Servo.h>
#define button 8

Servo myServo;
int state = 20;
int buttonState = 0;

void setup() {
  pinMode(button, INPUT);
  myServo.attach(9);
  Serial.begin(38400); // Default communication rate of the Bluetooth module
}

void loop() {
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.read(); // Reads the data from the serial port
 }
 // Controlling the servo motor
 myServo.write(state);
 delay(10);

 // Reading the button
 buttonState = digitalRead(button);
 if (buttonState == HIGH) {
   Serial.write('1'); // Sends '1' to the master to turn on LED
 }
 else {
   Serial.write('0');
 }
}

and
//                == MASTER CODE ==

#define ledPin 9

int state = 0;
int potValue = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.begin(38400); // Default communication rate of the Bluetooth module
}

void loop() {
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.read(); // Reads the data from the serial port
 }
 // Controlling the LED
 if (state == '1') {
  digitalWrite(ledPin, HIGH); // LED ON
  state = 0;
 }
 else if (state == '0') {
  digitalWrite(ledPin, LOW); // LED ON
  state = 0;
 }
 // Reading the potentiometer
 potValue = analogRead(A0);
 int potValueMapped = map(potValue, 0, 1023, 0, 255);
 Serial.write(potValueMapped); // Sends potValue to servo motor
 delay(10);
}

I attempted to use the master and slave code with the one with the servo and fc-04 so that the sound sensor will be on the master and the servo on the slave so that when ever I clap it will move the servo on the other arduino.
The new master and slave code that I used are :
//New slave
#include "Arduino.h"
#include <Servo.h>
int state = 0;
Servo myservo;

void setup() {
  Serial.begin(38400); // Default communication rate of the Bluetooth module
  myservo.attach(9);//attachs the servo on pin 9 to servo object
  myservo.write(0);//back to 0 degrees
  delay(1000);//wait for a second
  }

void loop() {
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.read(); // Reads the data from the serial port
 }
// Controlling the servo
 if (state == '1') {
  myservo.write(170);//goes to 15 degrees
  delay(3000);//wait for 3 seconds
  myservo.write(10);//back to 0 degrees
  delay(1000);//wait for a second
  state = 0;
 }
 else if (state == '0') {
  state = 0;
  }
}

//new Master
#include "Arduino.h"
#include <SoftwareSerial.h>
int state = 0;
SoftwareSerial BTserial(1, 0); // RX | TX

void setup() {
    Serial.begin(9600);
    pinMode(9600, INPUT);
    BTserial.begin(38400);

}

void loop() {
    if (digitalRead(2) == LOW) {
        static int count;
        BTserial.write('1');
        delay(1500);
    }
    else {
      BTserial.write('0');
    }
}

However the slave and master code for the servo and fc-04 is not working at all despite knowing that all the conponents work individually. What I am aware of is that the fc-04 uses serial communication to transfer data and so does the hc-05 bluetooth modules. This causes an issue because I believe from experience is that you can not have two serial communications being transmitted from the arduino at the same time which I need.
I have been at this for days and It is driving me nuts.
If I could have some help at all I will be much appreciated.

SoftwareSerial BTserial(1, 0); // RX | TX

Well, there's your problem.  You are starting SoftwareSerial on the Serial pins.  Don't do that!
For best results, hook your BT to pins 8 & 9 and use AltSoftSerial.  It is much more efficient than SoftwareSerial, and it will not interfere with Serial reads and writes.
If you really can't use those pins, pick two other pins and use my NeoSWSerial.  It is almost as efficient, and it works on any PinChange interrupt pins at 9600, 19200 or 38400 baud rates.

Gotcha , so because of what I was doing it causes crosstalk then.
When I have the chance tomorrow I will make the required changes and report back on the results.
Thanks


text:
Reading multiple cases on Serial
I am using a Leonardo board and am testing the APIs in the Serial type. The board is talking to a screen using serial.
The pseudo code is as follows (I show code relevant to Serial):
void setup(void) {
    Serial.begin(115200);
}

void loop(void) {

    if(Serial.available())
    {

        if (Serial.find(0x30))
        {
             func1();
        }

        if (Serial.find(0x31))
        {
             func2();
        }

    }

 }

 void func1()
 {
      // Serial.print() used multiple times

      asm volatile ("  jmp 0");
 }

 void func2()
 {
      // Serial.print() used multiple times

      asm volatile ("  jmp 0");
 }

I test using the Arduino IDE (1.8.0) and its Serial Monitor. When I send 0x30 over serial, the first if case gets triggered to invoke func1, but when I send 0x31, I cannot get the second if case (func2) to get triggered. This even happens when I test 0x31 first; the second if case never gets triggered. Can someone tell what I am doing wrong here and what is the right way to use serial ?
Edit For testing, one can use the pseudo code itself; I tested using different number of LED blinks in func1 & func2, and the problem still holds.
Edit 2 Based on Dave's answer, I tried a test with serial using sample code from
I did another test where I used the sample loop code for read (https://www.arduino.cc/en/Serial/Read) and tried typing 0 or 1 through serial monitor. I observed the following:
// Typed 0
I received: 48
I received: 13
I received: 10
// Typed 1
I received: 49
I received: 13
I received: 10

It is looping faster than the serial is delivered, so each time there is a byte delivered, it tests it against 0x30 until nothing is left, and then drops out, leaving nothing .available() for the next if(), so it fails out as well and starts up the loop() again.
I'd read a byte at a time and work with that:
int incomingByte = 0;   // for incoming serial data

void loop(void) {

if(Serial.available())
{
    incomingByte=Serial.read();

    if (incomingByte == 0x30)
    {
         func1();
    }

    if (incomingBute == 0x31)
    {
         func2();
    }

}

I tried your approach. Now I can trigger either case, but only once. So after uploading the code, I can try 0 or 1, and either case run fine. But on second try, none of the cases get triggered.

Check my edited question. I did another simple test to see behavior.

I tried removing the asm volatile statements from func1 and func2, and the original pseudocode now works. But I need a way to reset the program to the beginning. So I guess my question is whether there is a more stable way to reset the program to PC 0.

That's a different question.  Maybe http://playground.arduino.cc/Main/ArduinoReset would help.

source: Stack Exchange

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

sort: votes


text:
Playing a pcm file through a speaker with arduino
I'm trying to play an audio file through a speaker with arduino.
However, I do not want to use pre-constructed libraries such as the tmrpcm library.
I was instructed to perhaps even recreate the tmrpcm library, and my process so far is that I managed to extract the data chunk from the wav file in integers, and I also managed to turn the wav file into a pcm file.
I am currently studying http://playground.arduino.cc/Code/PCMAudio this link in order to gain more insight about how I might play the pcm file with the speaker. However, I'm stuck with the general concept of the code. In fact, I'm confused with the general concept of playing the pcm file through the speaker.
In my understanding, playing a music through the speaker works by outputting series of voltages to the speaker, so that the current in accordance with the magnetic field creates an outward force onto the voice coil with a certain frequency that creates the sound.
So my question is, what does the data in the pcm file actually mean? The integers cannot be frequencies, and by graphing it I can see that they are amplitudes in a waveform, but what kind of input they are continues to elude me.
So summing up my questions,

What is the theoretical aspect behind the link :http://playground.arduino.cc/Code/PCMAudio
What does the data in a pcm file (or even a wav file) actually represent?

Thank you so much.

Perhaps google for pcm to pwm

I read the entire first page of google on pcm to pwm, but I couldn't find a breakthrough. What would you suggest I look at closely from the google results?

I doubt there's any "breakthrough" information out there; but look up 1-bit delta-sigma DACs, because unless you attach a DAC or use a Due or Teensy 3, you'll be using 1 bit (toggled as needed) plus a low pass filter to generate your waveforms.  Also consider a simple-minded protocol where you use a fast-clocked ADC to read back output from low pass filter, turning a bit on when voltage should go up, or off when it should go down

You are right that the values in a wav file are amplitudes. 16 bit signed values to be precise.
And that amplitude is just a voltage. Negative values are normally a negative voltage, but they don't have to be. They can be just a voltage below a pre-determined mid voltage around which the wave swings (known as a DC offset).
To play the waveform you just have to generate the corresponding voltages at the right times. That is usually done using a timer so you get the frequency right. For instance a 44100Hz file has to have a sample voltage generated 44100 times per second. 44100 samples will be a sound clip lasting 1 second.
But of course the Arduino cannot generate a voltage, so instead PWM is used instead. Filtered through a low-pass filter it turns into a voltage. It also uses 50% duty cycle as "zero" for the waveform, which is scaled to fit into the resolution of the PWM.  The PWM has to be running at a considerably higher frequency than the sample frequency of the waveform so it has a chance to represent a voltage before it is asked to change again.

curious: would a DC offset harm speaker coils or lower output potential? Are arduinos fast enough to dither audio frequencies using PWM? thanks!

It can cause some distortion if the coil movement reaches its limit due to a magnetic offset. It also causes heating in the coil. You would normally remove the DC offset by passing it through a capacitor. And yes, the Arduino is fast enough for crude audio. Not wonderful, but tolerable for small projects.

For anything better you want a 32 bit chip and I2S.

@Majenko in case the wav file is 8bit and sampled at 33100Hz, then the wav file will contain the amplitudes(1 byte correspond to 1 amplitude level) to be sent out to the DAC every 1/44100 seconds. Please correct me if i am wrong.

That is correct, though it is very rare to find an 8-bit WAV file.

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


text:
Solid-state relay boards: Can they be used to switch audio signals?
So I tried to use one of those widely available solid-state relay boards to switch some 12V power, and I found out the hard way that they are not designed to switch DC current. They use some sort of variac that only works when AC voltage is applied. Do I have that right??
So I got this other project where I need to multiplex some audio signals in a mixer board, and I was already planning on using those solid-state relays before I learned all this. If I send audio through these relays, is it going to work as planned? Will I suffer any noticeable delay, signal degradation or attenuation?

no, it will sound terrible because of the internal capacitance, junction voltage drops, the SSR's lock-on state, and DC biasing (half-wave). they make cheap audio muxer ICs like the 74HC4051 that would be perfect. If you want cheap and available, BJTs can be used to some extent.

That's a nifty little breakout board. And much less bulky! I like it.

a breakout board will be 10X as expensive as the bare DIP, but that's still not much ;)

A solid-state relay seems to be the totally wrong tool for the job. The image you posted shows it is intended to switch 240V AC. So it is designed to switch something like a 240V light on and off.
Relays in general are things designed to connect one thing to another (eg. power to a light). They just aren't designed to switch audio signals.

I need to multiplex some audio signals in a mixer board, and I was already planning on using those solid-state relays before I learned all this

The expression "when the only tool you have is a hammer, everything looks like a nail" springs to mind.
There are chips designed to multiplex analog signals (as I describe on this page). That would be closer to what you need.
However that chip (the 74HC4067) is a "choose one input from many" sort of design. It isn't going to let you fade one audio signal in or out (neither would the relay for that matter).

"Relays in general are things designed to connect one thing to another (eg. power to a light). They just aren't designed to switch audio signals." I absolutely agree for SSRs. But, for an electromechanical relay why not? There's plenty of relay switching action happening in Audio Video Receivers during source selection.

@EnricBlanco: for turning a source on or off they would be fine, but for mixing they are useless.

Yeah, I'm not mixing, I'm selecting signals by turning them on and off.

And contrary to Nick's assertion, any type of relay is a reasonable go-to for switching signals on and off. dandavis's recommendation to use the 74HC4051 is a much more practical solution though.

The link I gave specifically mentions the 74HC4051 multiplexer / demultiplexer. In fact it was about it. I don't know why you said the "74HC4051 is a much more practical solution" when that was the exact solution I offered to you. The 74HC4067 is its 16-channel cousin, which would be useful if you need to multiplex 16 signals.

No. SSRs are completely wrong for switching audio.
Consider using the CD4066 chip. But be aware that will mean you'll need to ask a whole bunch of new questions I'm sure.
I hope this answer helps you.


text:
What is the point of a adafruit data logger
In order to play an audio file, I was suggested to get an Adafruit data logger, yet right now I am stuck with the project and I realized that I'm not using the data logger to its full potential.
Yet I am unable to comprehend the purpose of a data logger ; all I'm using it for is to read SD Cards, and I can do that with a SD Card reader. I did read the whole documentation, data sheet, etc, and I can see that it has some cool functions, but my question is still, why data logger?
I know this  might be a stupid question, but I genuinely don't get what the data logger is supposed to be a huge help of. Please help me.

i don't know either, that doesn't make sense to me. free advice is worth just that sometimes...

Do you mean the Adafruit Datalogger Shield, or the Adafruit Feather M0 "Adalogger"

IMHO it have RTC+SD reader+libraries, so with minimal effort (and knowledge) anybody can alling those connectors, copy-paste some invocation and make magic like a real wizard. The Arduino underlaying principle. Or you can read datasheets, write your own code and make such PCB in kitchen yourself and not pay their premium prices (opens with knowledge, tools and experience). Or you could do it yourself, but it would cost you a week of work, so it is cheaper just buy it and fix it to your needs (opens with good job and money). So there are at least 2 groups, who buy it and so Adafruit sells it :)

why data logger?... maybe you can ask the guy/guys who suggested it to you? maybe they had some valid reasons? conceptually a data logger is there to log data.

Are you referring to this?

That is a shield that has an SD card interface (with appropriate level-shifting for the SD card) plus a real-time clock.
The rest is "prototyping" area for you to install your own devices.

In order to play an audio file, I was suggested to get an Adafruit data logger

I don't see how this helps play audio files, however you might read the audio file from the SD card. Then you need to send it to a DAC (digital-to-analog converter) to convert the digital information to analogue.
The Adafruit data logger is fine for recording data (for example, temperatures) but I don't see why someone would recommend it for playing audio files (apart from the SD card interface).

my question is still, why data logger?

Better ask the person that recommended it, eh?


text:
Can an Arduino power itself off [not low power mode] via software?
I'm working on a sketch where an Arduino UNO performs no useful work after the first 10 minutes following power on.  It is not needed again until power to it is shut down, then re-enabled.  This may not happen for hours or even days.  No wake-up function is required, or deemed useful.
Of course, the Arduino could simply be left on as long as it's connected to its power source, but it will be placed remotely, and it seems [to me] safer to have it powered off. when not in use.
In essence, the Arduino is powered by a wall wart and plugged in with other devices fed by a switchable 120v power source.
I found a couple of possible hardware/software solutions to the problem but it isn't clear whether they would work in this situation.  Power consumption is not the issue here.

you can interrupt the input voltage with a relay that both an exgternal trigger and a GPIO pin can control. A brief trigger gives the relay power, which powers the uno. The uno writes the pin high in setup(), keeping the relay on. Once done, the pin is written low and the uno turns off.

Based on feedback, it seems clear that any solution to this problem will require the addition of hardware, and the use of a specific type of relay presents a simple solution that will satisfy my needs. In my situation, the requirement is for the Arduino to turn off after a specific amount of time. It really is not necessary for the Arduino itself to trigger the action, just that it is shut off once the interval lapses. As such, a very simple circuit can be constructed using a programmable timer relay delay switch to front-end the Arduino, setting the time delay that is needed. The Arduino is n

In general, an Arduino by itself has no control over its power input.  It can, of course, enter various Sleep modes, such as the Power-down mode with watch-dog-timer off, which uses 0.1  μA.
It isn't clear from the question what will turn the Arduino back on after it is off for a while, but if you have either a push-button or a signal to turn it back on, the Pololu 2808 Mini Pushbutton Power Switch will work as an Arduino-controlled off switch.  This board has On, Off, Ctrl, and button-contacts inputs.  If your Arduino raises the Off input, power shuts off cleanly.  To turn it back on, either connect the  button-contacts inputs together, or raise the On input, or pulse the Ctrl input.

No buttons or signals utilised.  The Arduino power supply would be cut off at some point by virtue of an unrelated action, i.e., it resides on a circuit that would be powered off for other reasons, e.g., to disable all attached devices.  I am just trying to work out how to power off the Arduino in advance of that action.
At some point, that circuit would be powered back on again, and consequently the Arduino would power up again, reboot, and run its sketch for a few minutes.  Once that is completed, the Arduino has nothing else to do until the entire sequence is repeated.

As far as I can tell, I am trying to achieve something here that is rather different that the objectives one usually encounters.

A battery-powered Arduino can go into deep sleep mode where it can use as little as 100 nA, and still be woken by a switch closure if required.
There doesn't seem to be much point to me to power down a mains-powered Arduino. What would be the purpose of that?  The small amount of current it would use via the wall-wart would be trivial. If you are worried about voltage spikes (eg. lightning) then you should protect the input pins (or your power supply) whether or not it is powered off.
It seems to me that you may as well do whatever you need to do, and then go into an infinite loop. Once the Arduino is re-powered it will do it again. You aren't saving much by attempting to power it off, indeed that introduces an extra point which might fail.

but it will be placed remotely, and it seems [to me] safer to have it powered off. when not in use.

Safer in what way? Any extra hardware you introduce to make the Arduino "safer" might itself introduce safety issues. It reminds me of the days when we had a UPS (Uninterruptable Power Supply). The UPS would fail more-or-less as often as the power did. In other words, you replaced one possible failure (the power failure) with another possible failure (the UPS failure).

I think, that OP thinks around the way - no power = no possible shortcuts from condesated watter drops or other external shortcut devices - the same reason many people plug of electronics from socket, when they leave for vacation.


text:
How to make two small micros communicate with my Arduino over BLE?
I want to do a project with an Arduino Uno and two other BLE (or regular bluetooth) capable modules. I want the Bluetooth modules to be hooked up to buttons (one button for each Bluetooth module). I then want the Bluetooth-capable modules to send the state of their buttons to a central Arduino board.
Is this possible? Can I have two different BLE boards connected to one Arduino?
I have a RedBear BLE (Bluetooth low energy) shield for my Arduino. What micro-controllers should I get for the peripheral modules? And where can I learn about pairing Bluetooth modules? Everything I read seems to be about pairing Bluetooth boards to a phone.
Can I do this all with BLE or am I going to need to get a new shield for my Arduino to talk with the two peripheral boards?
Thanks.

You can use SoftwareSerial to communicate with two modules from an uno. But You will have to wire 'em up separately, not through your shield. (making the total number of bluetooth modules 4.
You could also use your existing sheild and poll between the two remotes. I.e. disconnecting from one and connecting to the other at a regular interval.
For the micros and bluetooth for your button, you could use a HM10 with an ATtiny like in this instructable. He uses two HM10 modules to talk to each other. HM-10 is a popular BLE module. If you want regular bluetooth(2.0), you can use HC-05.

The page for the RedBear BLE shield that you note indicates that the BLE chip is the nRF8001, which it says supports peripheral (slave) role only. This means it must be connected to from a BLE Central role device.
Since you want your Uno to be the central device, listening for data from these 2 remote buttons, your RedBear shield won't work this way.
A short overview of BLE is available by AdaFruit.


text:
Burning a bootloader onto my Arduino MEGA 2560 without another arduino board, or isp board
My youtube video explains it. It's starting to get on my nerves.

Please explain your problem in text instead of a 4 minute video.

You need a programmer (isp or Arduino board as programmer). It is not possible to burn a bootloader without it. The USBasp version 2 plus a 10 to 6 pin adapter cost about 2 dollars.


text:
Read all relay output (high or low) from Bluetooth through Android app
I have written the following code for Arduino:
#define relay2 2
#define relay3 3
#define relay4 4
#define relay5 5
#define relay6 6
#define relay7 7
#define relay8 8
#define relay9 9
byte val;
void setup() {
  Serial.begin(9600);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  pinMode(relay5, OUTPUT);
  pinMode(relay6, OUTPUT);
  pinMode(relay7, OUTPUT);
  pinMode(relay8, OUTPUT);
}

void loop() {
  int a = 0;
  if (Serial.available()) {
    val = Serial.read();
    Serial.println(int(val));
    //Display received value on Serial Monitor
    //ASCII VALUES
    if (int(val) == 49) //Turn Light1 ON 1
      digitalWrite(relay2, HIGH);
    else if (int(val) == 50) //Turn Light1 OFF 2
      digitalWrite(relay2, LOW);
    if (int(val) == 51) //Turn Light2 ON
      digitalWrite(relay3, HIGH);
    else if (int(val) == 52) //Turn Light2 OFF
      digitalWrite(relay3, LOW);
    if (int(val) == 53) //Turn Light3 ON
      digitalWrite(relay4, HIGH);
    else if (int(val) == 54) //Turn Light3 OFF
      digitalWrite(relay4, LOW);
    if (int(val) == 55) //Turn AC ON
      digitalWrite(relay5, HIGH);
    else if (int(val) == 56) //Turn AC OFF
      digitalWrite(relay5, LOW);
    if (int(val) == 57) //Lock the DOOR
      digitalWrite(relay6, HIGH);
    else if (int(val) == 48) //Unlock the DOOR
      digitalWrite(relay6, LOW);
  }
}

Now on the Android side I have written the following code:
 //Bluetooth connection code ....
  mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

  mmSocket.connect();
  mmOutputStream = mmSocket.getOutputStream();
  mmInputStream = mmSocket.getInputStream();

  int byteCount = mmInputStream.available();
  if (byteCount > 0) {
    byte[] rawBytes = new byte[byteCount];
    mmInputStream.read(rawBytes);
    String string = new String(rawBytes);
    Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
  }

Now it works perfectly when I press a button to turn the light on/off. But I want to read all relay current status (high/low) when a Bluetooth connection is made.
So basically after connecting to the Bluetooth module I want all relay status.
How can I do that?

It's rather undocumented, but you can actually use digitalRead(relay2); on a pin (ex relay2) that is set to OUTPUT. I discovered it accidentally, and it worked exactly as expected, so i looked it up and it's legit. This is very handy to check an output pin's hi/lo state from a non-connected part of the code.
There is a tiny performance dip compared to reading just a variable, but it usually won't be noticed. If you need top performance, wrap the digitalWrite() with your own function, and set a variable with the new state:
int myState[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

void digitalWrite2(int pin, int value){
   myState[pin] = value; // copy setting to a global array
   digitalWrite(pin, value); // apply the setting as intended
}

Now, you can instantly get all the relay states from the myState array, provided they've been set with digitalWrite2. The other advantage to an array is that you can easily persist it to SPIFFs or EEPROM as-needed and recover the relay states on the next boot.

Changing the mode of the pins would be a pain, so you might be better to store the state of the relays within you Arduino code (a bool array) as long as you know what state they start in, then send the data back over the serial connection.
Define an array of pin numbers, an array of Boolean states and rework your code to change both arrays at the same time when a number comes in.

Hi , Can you please explain me in brief with some demo code or can you provide some reference link ? . I am new to arduino uno family. so i am learning step by step.


text:
What is this green board?

Hi I'm new to arduino and robotics itself. I have no idea what this giant green board is in the middle of the robot. I really need help!

In what way is this question related to the Arduino?

The green board is probably a custom PCB that controls the vehicle. Unfortunately, the image does not have enough quality to determine much else.

Create such PCB is possible in kitchen over one evening without anything costy (maybe except laser printer, if you want high density mask, but permanent marker can go long way too) , I made a lot of similar PCBs (but little smaller, just to fit my needs), like  https://wiki.gilhad.cz/mediawiki/images/8/8f/H-mustek-2-med.png

It's a sheet of FR-4 clad in copper, with much of the copper etched off to form a PCB. That is then coated in green UV cured paint (solder resist) and components are attached.
Other things are then plugged into it.
What function it performs depends on what the designer designed it to do.


text:
Reading Json object name in arduino
How do I read the Json object name in arduino? For { "pi" : "3.14" }, I want the arduino to automatically read the object name "pi" and then th value "3.14"
I'm using arduino Uno.

There is a brilliant JSON library called ArduinoJSON. It can be installed using the arduino library manager.
See https://bblanchon.github.io/ArduinoJson/doc/decoding/ for further details.
To loop through the keys, you can use:
https://bblanchon.github.io/ArduinoJson/api/jsonobject/begin_end/
or if you know the key, you can do jsonObject["pi"] to get the value


text:
How to make HC05 bluetooth module undiscoverable or limited discoverable
I want my HC05 module to be pairable only within a time window of pressing a button (connected to an Atmega328 which talks to the HC-05). This is a pretty normal way for most bluetooth devices i've used like headsets etc. Is there a way to make this happen with HC05?
Scrounging the net, I found that it is called LDM (Limited Discoverability Mode). But i couldn't find anything that told me how to get it done on HC05. I scanned through the AT commands set too, with no luck.

You could power-off the module, until the button is pressed? Then check if a connection is made within the timeframe, and otherwise power off again

That should work i guess. Will implement it and see.


text:
Arduino receives no external UART comms after Serial.begin(9600)
I face the following issue. I connected my RasPi (3b) with an Arduino Uno via RX/TX and a logic level converter. UART comms from the RasPi to the Arduino and vice-versa work fine on minicom and serial monitor. It also works fine from my qt program to the serial monitor, but as soon as I start a Serial.begin(9600,8N1) or Serial.begin(9600) function on the Arduino there seems to be no communication anymore at all between the two. Neither the expected result (toggle an LED, works from serial monitor), nor any blinking of the tx/ex LEDs onboard anymore. Issue occurs no matter if I provide power to the Arduino via USB or the 9v powercable. Any suggestions?

Are you saying the USB connection works, but as soon as you try and use pins 0/1 the USB connection breaks? That's logical, since the USB connection uses pins 0/1. There is only one Serial on the Uno, and that is pins 0/1, whether you directly wire them or use the USB port.

The funny thing is it works when my raspberry is wired to the Arduino and the Arduino is connected to my Mac on USB to read the serial monitor (there is no connection between the raspberry and the mac)

Mac (USB) - Arduino - (Wire TX/RX) Raspberry. Even if I disconnect the Mac (and toggle an LED for example when anything is received on the Arduino) nothing happens...

"no external UART comms ...": in those cases, try to see if internal UART comms works first.

Solved. I double crossed the rx/tx connection which made it wrong again... stupidity attacks


text:
Arduino play many piezo at once
I need to play sound on 10 piezos at once. How to do that without delay() function.

You could use the millis() function of your Arduino...

@Fusseldieb post example please

Use the blink-without-delay pattern https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay, a TimeMarker https://github.com/mikaelpatel/Arduino-Timemark or a Scheduler https://github.com/mikaelpatel/Arduino-Scheduler

Use the Timer library.
You can attach up to 10 events to each Timer object you declare. That will suit your use case.

Post a code please.

Why this code not work? `long ids[10];
void playNote(int pin, unsigned long freq) {
int ms = 1000/freq;
ids[pin] = t.oscillate(pin, ms / 2, HIGH);
}
void stopNote(int pin) {
t.stop(ids[pin]);
}`

Post a new question with your full code and not just a snippet, You'll get much better help. I'll also participate.


text:
Why would uninitialized SD-card module without card disable CAN-Bus shield?
(I am able to successfully initialize CAN-Bus shield and SD-card module w/ card in it.)
Now I have removed all code related to the SD-card module, yet I left the module (without the card in it) physically connected. This results in the CAN-Bus shield initialization failing.
When I insert the card into the SD-card module the CAN-Bus shield initializes successfully. (I am still not doing SD-card module initialization.)
Of course, I can just disconnect the SD-card module or leave the card in it... But I am trying to understand this black magic.
I have connected the SD-card module CS to pin 8, the CAN-Bus shield clone CS is connected to pin 10. I tried to set the SD-card module CS pin to OUTPUT and to HIGH. That had no effect.
the CAN-Bus shield + schematics: http://www.elecfreaks.com/estore/can-bus-shield.html [Resource -> Schematics]
the SD-card module: https://ebay.com/itm/161366316226?_trksid=p2057872.m2749.l2649

Maybe it have similarity to this: http://arduino.stackexchange.com/questions/31924/how-to-setup-an-i2c-bus-which-stays-valid-if-a-slave-is-powered-down-or-fails - the uninitialized device can brind the bus to some bad state, as it does not care about the bus at all

Would need a reference/link to the shield and schematics to answer that.

I think the SD-Card and the CAN Bus shield use the same pin and that is the problem.  I read that on a post on here last week.

@MikaelPatel http://www.elecfreaks.com/estore/can-bus-shield.html This is the product; there is Resource tab with Schematics link

@Matt Could be it. Maybe it would explain why I am not able to log any messages when actually connecting the whole ball of wires to the OBD2 access port. When testing on my PC both devices report "init OK" but then in the car I get no messages. Despite the wildly blinking LED on the shield. (That's why I stripped all the SD-card code in the first place.)

Here is the post, I knew I read it :)
http://arduino.stackexchange.com/questions/35198/can-bus-shield-sd-card-module-led-builtin-use-d13-possible-collision/35223#35223

@Matt :)) That was me asking. My understanding is the only pin on the SD-card module I can (and have to) "move around" is the CS. So I moved it to 8.

@Matt From what I understand the rest of the pins are supposed to be shared, i.e. it should not be an issue.

J. Z., please edit the info from your first two comments here and from your comments to Majenko's answer into the question ... more likely to get upvoted if question is more complete

fixed the shield url

Without seeing schematics this is purely supposition:
My guess is that the SD shield contains bi-directional level shifting. The MISO pin, which connects the DO pin of the SD card to the MCU, will have a 3.3V -> 5V level translator on it.  This, with no SD card inserted, will be floating (flapping around in the breeze) causing the output of the level translator to randomly produce digital signals on the MISO pin. These signals interfere with the MISO signals from your CAN shield.
How best to cure the problem very much depends on what level shifting is in the circuit and how it is controlled and wired. For that we will need to see schematics of both the CAN and SD card shields.

CAN-Shield: http://www.elecfreaks.com/estore/can-bus-shield.html [Resources -> Schematics]

SD-card: http://www.ebay.com/itm/161366316226?_trksid=p2057872.m2749.l2649 I can't seem to find more info on this little bugger.

Need a schematic of the SD card to know how the 74LVC125A is wired up - is it buffering the DO pin of the SD card or not?

Unfortunately I can't find any vendor name on that thing, or a product page... The link above is all I could find.

Then you would have to reverse engineer it. Shouldn't be hard with a DMM.

At this point that is something beyond my skill/knowledge, will have to wait, soon or later the pieces will fall into place :) Thanks anyways!


text:
Forwarding serial output from a Nano to Uno that's used as the ISP
I'm trying to program a Nano by using an Uno as the ISP. So far, I've followed along with the example project for getting the Uno running as the ISP on https://www.arduino.cc/en/Tutorial/ArduinoISP.
After a bit of tinkering, it works, but the serial monitor won't work correctly. I'm uploading a super simple program that delays for 500 ms and prints to the log.
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("test");
  delay(500);
}

I've wired the TX pin on the Nano to the RX pin on the uno. The monitor updates every 500 ms as expected after doing so, but displays ��� instead of the word test. When I tried wiring TX -> TX, the serial monitor does not update. Does anyone have any insight what's missing here?

You can't really connect an ordinary Arduino's serial pins to both another device and the on-board USB serial converter at the same time.  You'd probably do best to use a separate USB serial converter for the target, otherwise you need to use software serial (or better a chip with a 2nd hardware port) and add some sort of selectable pass-through mode to your ISP sketch.  Possible, but not easy, try using the separate converter instead.

@ChrisStratton gotcha, thank's for the explanation. I tried to use the mini usb to connect the nano, but my computer doesn't seem to recognize it. It was still fun to learn about ISPs though

@ChrisStratton. Please, post your comment as an answer to close this question.

Can you try by writing on the uno a program to set the TX and RX pins as inputs? Just something like void setup() { pinMode(0, INPUT); pinMode(1, INPUT); } void loop() {}, then repeat again the test (I think you'll have to connect the nano TX to TX and nano RX to RX)

As Chris Stratton suggests in his comment above:

You can't really connect an ordinary Arduino's serial pins to both another device and the on-board USB serial converter at the same time.

To solve your serial monitor problem use a separate USB serial converter and connect that to your Arduino Nano.
If you don't have access to a dedicated USB serial converter you could use software serial on the Arduino Nano. This allows you to connect the Arduino Uno Rx pin to the software serial Tx pin. You will also need to program the Arduino Uno with a program that re-transmits the data it receives back out to the PC serial monitor.


text:
How to send messages to multiple numbers using Arduino uno & SIM800 module?
I am using following code to send message using Arduino Uno & SIM800 module.
But I need to send same message on multiple numbers then what changes should I make in my code.
const int buttonPin = 8;   // Main gate sensor 1
const int buttonPin1 = 7;  // Main gate sensor 2
const int buttonPin2 = 9;  // Store room sensor 1
const int buttonPin3 = 10; // Store room sensor 2

bool i = false;
bool j = false;
bool k = false;
bool l = false;

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

  pinMode(buttonPin, INPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);

  digitalWrite(buttonPin, LOW);
  digitalWrite(buttonPin1, LOW);
  digitalWrite(buttonPin2, LOW);
  digitalWrite(buttonPin3, LOW);

  delay(1000);
}
void loop()

{
  sensor1();
  sensor2();
}
  void sensor1()
  {
  if (digitalRead(buttonPin1)== LOW && digitalRead(buttonPin) == HIGH  && i == false)

  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91...................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main Gate is Closed");
    Serial.write(0x1A);
    delay(1000);
    i = true;
    j = false;

  }

  if (digitalRead(buttonPin)== LOW && digitalRead(buttonPin1) == HIGH &&  j == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91........................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main Gate is open");
    Serial.write(0x1A);
    delay(1000);
    j = true;
    i = false;
  }
  }
  void sensor2()
  {
  if (digitalRead(buttonPin2) == HIGH && digitalRead(buttonPin3)==LOW && k == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91....................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Closed");
    Serial.write(0x1A);
    delay(1000);
    k = true;
    l = false;
  }
  if (digitalRead(buttonPin3) == HIGH &&digitalRead(buttonPin2)== LOW && l == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91....................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Open");
    Serial.write(0x1A);
    delay(1000);
    l = true;
    k = false;
  }
}

Write a function that sends any message to any number and call it numerous times

@nilesh just add some delay between two massege
I modified your code check it
const int Main1 = 8;
const int Main2 = 9;
const int Store1 = 7;
const int Store2 = 10;
bool i = false;
bool j = false;
bool k = false;
bool l = false;

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

  pinMode(Main1, INPUT);
  pinMode(Main2, INPUT);
  pinMode(Store1, INPUT);
  pinMode(Store2, INPUT);

  digitalWrite(Main1, LOW);
  digitalWrite(Main2, LOW);
  digitalWrite(Store1, LOW);
  digitalWrite(Store2, LOW);

  delay(1000);
}
void loop()

{
  sensor1();
  sensor2();
}
void sensor1()
{
  if (digitalRead(Main1) == HIGH && digitalRead(Main2) == LOW && i == false)

  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-----------");// first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate closed");
    Serial.write(0x1A);
    delay(5000);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-----------");// Second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate closed");
    Serial.write(0x1A);
    delay(1000);
    i = true;
    j = false;

  }
  if (digitalRead(Main2) == HIGH && digitalRead(Main1) == LOW && j == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91---------------");//first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate Open");
    Serial.write(0x1A);
    delay(5000);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91--------------"); second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate Open");
    Serial.write(0x1A);
    delay(1000);
    j = true;
    i = false;
  }
}
void sensor2()
{
  if (digitalRead(Store1) == HIGH && digitalRead(Store2) == LOW && k == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
   Serial.print("+91-----------");// first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is closed");
    Serial.write(0x1A);
    delay(10000);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-----------");// second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Closed");
    Serial.write(0x1A);
    delay(1000);
    k = true;
    l = false;
  }
  if (digitalRead(Store2) == HIGH && digitalRead(Store1) == LOW && l == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
   Serial.print("+91-----------");// first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Open");
    Serial.write(0x1A);
    delay(5000);
    Serial.print("AT+CMGS=\"");
   Serial.print("+91-----------");// Second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Open");
    Serial.write(0x1A);
    delay(1000);
    l = true;
    k = false;
  }
}

thanks
bhupendra.sinkar727@gmail.com

I have same question but minor different.
sim.println("AT+CMGS="+91xxxxxxxxxx"\r");
i dont want to write this. i want to write mobile number on serial monitor in arduino and on that number, i want to send message. how can i do?

Try out this one. Here, I made the code for two number. Just simply add a new function for every new number. I hope it will help you.
const int buttonPin = 8;   // Main gate sensor 1
const int buttonPin1 = 7;  // Main gate sensor 2
const int buttonPin2 = 9;  // Store room sensor 1
const int buttonPin3 = 10; // Store room sensor 2

bool i = false;
bool j = false;
bool k = false;
bool l = false;

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

  pinMode(buttonPin, INPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);

  digitalWrite(buttonPin, LOW);
  digitalWrite(buttonPin1, LOW);
  digitalWrite(buttonPin2, LOW);
  digitalWrite(buttonPin3, LOW);

  delay(1000);
}
void loop()

{
  sensor1();
  sensor2();
}

void sensor1()
{
  if (digitalRead(buttonPin1)== LOW && digitalRead(buttonPin) == HIGH  && i == false)
  {
    numOneGateClose();
    numTwoGateClose();
    i = true;
    j = false;
  }

  if (digitalRead(buttonPin)== LOW && digitalRead(buttonPin1) == HIGH &&  j == false)
  {
   numOneGateOpen();
   numTwoGateOpen();
    j = true;
    i = false;
  }
}

void sensor2()
{
  if (digitalRead(buttonPin2) == HIGH && digitalRead(buttonPin3)==LOW && k == false)
  {
    numOneRoomClose();
    numTwoRoomClose();
    k = true;
    l = false;
  }

  if (digitalRead(buttonPin3) == HIGH &&digitalRead(buttonPin2)== LOW && l == false)
  {
    numOneRoomOpen();
    numTwoRoomOpen();
    l = true;
    k = false;
  }
}

void numOneGateClose()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91...................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is Closed");
  Serial.write(0x1A);
  delay(1000);
}

void numTwoGateClose()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91...................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is Closed");
  Serial.write(0x1A);
  delay(1000);
}

void numOneGateOpen()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91........................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is open");
  Serial.write(0x1A);
  delay(1000);
}

void numTwoGateOpen()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91........................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is open");
  Serial.write(0x1A);
  delay(1000);
}

void numOneRoomClose()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91...................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is Closed");
  Serial.write(0x1A);
  delay(1000);
}

void numTwoRoomClose()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91...................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is Closed");
  Serial.write(0x1A);
  delay(1000);
}

void numOneRoomOpen()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91........................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is open");
  Serial.write(0x1A);
  delay(1000);
}

void numTwoRoomOpen()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91........................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is open");
  Serial.write(0x1A);
  delay(1000);
}

I would like to point out, that there really should be SEND MESSAGE method that would make the whole script shorter and easier to debug. Basic REUSE principle in programming.

it send message  to only first number

@NileshSurwade Have you write a different number on both functions? means you have to add different number in numOneSensor1() and numTwoSensor1(). And same things for numOneSensor2() and numTwoSensor2()

Lead by example. That code isn't a good example. As @Divisadero says, write a SEND MESSAGE function and reuse it many times.

@ Hasan sir, I added two different number in numOneSensor1() and numTwoSensor1(). And i done same thing for numOneSensor2() and numTwoSensor2(). But it does not work it only send massage on first number. Please help.

@NileshSurwade Ok, let me check and update my code again.

@NileshSurwade I update my code. I hope it will help.

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


text:
What would be the best way to sense the tank level of a 1000L water tank?
I want to read in the values to an arduino analog input.
The approaches I have been looking at are:
1.) A ultrasonic distance sensor; my concerns are that tehse are not usually waterproof.
2.) A pressure transducer; these tend to be very pricy.
3.) Some kind of level switch which provides digital input (Is water level here: yes/no?)
Would anyone happen to have some advice on what sort of sensor would be good for the application of reading in the tank level and using the information in a sketch?

Options 4 & 5: Resistive measurement between two probes (can cause electrolysis) and Capacative measurement between two insulated probes (harder to do but safer and can be used with corrosive / dangerous liquids).

http://www.instructables.com/id/Capacitive-Fluid-Level-Sensor/

You may find Robotics Stackexchange useful for this question.  (If you post there, delete here)

what's best to you depends on your objectives / criteria. a much better way for you to ask the question would be what are the pros / cons of various way of measuring tank levels? then you can judge for yourself which is best for you in that particular application.

There are some ultrasonic sensors that are specifically designed for this very application. I have used something simlar as a water level sensor, and they seem to be reliable. The sensor that I used was from MaxBotix, and had a range of up to 5m, resolution of 1mm, and both analog and serial data output. Interfacing it with an Arduino was very easy.
Have a look at This article for details

1.) A ultrasonic distance sensor; my concerns are that tehse are not usually waterproof.

Ultrasonic rays will ping through water till it transfer back from the bottom of tank. So it can not provide you the level of water.

2.) A pressure transducer; these tend to be very pricy.

Yes it will be very pricy.

3.) Some kind of level switch which provides digital input (Is water level here: yes/no?)

This option will be best and more reliable. You can use some water level indicator probes or magnetic float switch.
Probes/Electrode
When electrode is in contact with water it will pass current through it and give indication to system or controller.
Magnetic Float Switch
Magnetic float switch having magnet under water proof enclosure. When water level reach upto Float switch then circuit will be close and will give level signal to system.
In above to switches magnetic float switch will be best option. Because if water having High TDS then there will be erosion of electrode or element of TDS will gether around electrode and result in conductivity loss of rode.
And this is not possible in case of Magnetic Float switch as it is under water proof enclosure. It is also cheap solution.

You are mistaken about the ultrasonic. While a transducer well coupled to the water will measure its depth, one placed in air a distance from it will measure to the reflection off the surface, readily measuring the unused capacity. A return that's gone through the water/air interface twice would likely be too weak for the simple ones to detect, and besides they report only the first meaningful return.  Similarly, with an immersible sensor you might even be able to get a reading from the floor looking up through the water to the surface, though it's not clear that would be worth the trouble.


text:
Working or functionality of pinMode(), digitalWrite() and digitalRead()
I'm a newbie in Arduino. I find out a couple of examples.
Here, below arduino simple code I just uploaded.
Here, what is functionality or working of pinMode, digitalWrite and digitalRead ?
const int kPinLed = 7;
const int kPinBtn = 8;

void setup()
{
  pinMode(kPinLed, OUTPUT);
  pinMode(kPinBtn, INPUT_PULLUP);
}

void loop()
{
  if(digitalRead(kPinBtn) == LOW)
  {
    digitalWrite(kPinLed, HIGH);
  }
  else digitalWrite(kPinLed, LOW);
}

pinMode https://www.arduino.cc/en/Reference/pinMode

digitalWrite https://www.arduino.cc/en/Reference/digitalWrite

digitalRead https://www.arduino.cc/en/Reference/DigitalRead

And all you need to know - a tutorial https://www.arduino.cc/en/Tutorial/DigitalPins, have fun.

How a GPIO pin actually works in output mode: https://hackingmajenkoblog.wordpress.com/2017/03/20/what-exactly-is-a-gpio-pin/ (other modes to follow when I have written them).

{
  pinMode(kPinLed, OUTPUT);
  pinMode(kPinBtn, INPUT_PULLUP);
}

This block of code used to define mode of Pin i.e. making pin as Output pin or Input pin.
if(digitalRead(kPinBtn) == LOW)
{

}

This block of code is used to read value from defined digital pin either High or Low. And in return will give pin state High or Low. For example if we want to make LED ON which is connected to one of digital pin of Arduino at certain condition, we will define that pin under above block of code and can read state of that pin as High or Low.
 {
   digitalWrite(kPinLed, HIGH);
 }
 else digitalWrite(kPinLed, LOW);

This block of code is used to make Pin state High or Low i.e. Under certain condition this function will make pin state either High or Low.
To learn more, visit......
PinMode Click here
DigitalRead Click here
Digital Write Click here

Welcome to the world of Arduino!
To start off, the Arduino website has excellent descriptions of its various API functions, in your case -
https://www.arduino.cc/en/Reference/pinMode
https://www.arduino.cc/en/Reference/DigitalWrite
https://www.arduino.cc/en/Reference/DigitalWrite
Now to answer your question:
pinMode determines whether a specified pin behaves as input or output - does it read a signal to the Arduino (read from a a sensor, for example) or does it output to another component (a led to light it, a motor to move it). It achieves this by changing the impedance on the pin- high impedance for input, low for output.
IINPUT_PULLUP means both setting the pin to input mode, while 'pulling up' the input to be high when it is not explicitly low by an external component (whatever is connected to the pin)
  //configure the pin somePin to behave as output
  pinMode(somePin, OUTPUT);
  //configured the pin to behave as input, and 'pullup' the input to HIGH
  pinMode(somePin, INPUT_PULLUP);

Once you have set a pins mode to be input/output, you can read or write from it, depending on its mode.
If you configured a pin to be in input mode, you can use digitalRead
//read the value from someInputPin and store it in the variable 'num'
int num = digitalRead(someInputPin);

If you configured a pin to be in output mode , you can use digialWrite
//write the value from 'num' to someOutputPin, and by extension whatever connected to it
int num = HIGH;
digitalWrite(someOutputPin,num);

Very good question for every beginner. Let me explain.
pinMode() : This function set the functionality of pin. Means either INPUT or OUTPUT or INPUT_PULLUP.
INPUT use when you connect your arduino to the sensor.
OUTPUT use when you connect your arduino to LED, motor etc.
INPUT_PULLUP use when we require internal pull-up. For example, if we connect a pushbutton to our arduino then we require some pull-up resistor. Then this thing can be done by this INPUT_PULLUP. So we don't require any resistor in circuitry.
Now depend upon your circuit requirement you have to use proper pinMode.
Syntax: pinMode(pin, mode)
Where,
pin: the number of the pin whose mode you wish to set
mode: INPUT, OUTPUT, or INPUT_PULLUP.
You can see this thing in your code.
void setup()
{
  pinMode(kPinLed, OUTPUT);       // LED as OUTPUT
  pinMode(kPinBtn, INPUT_PULLUP); // Push Button as INPUT with pull-up.
}

digitalWrite(): This function set pin states either HIGH or LOW. Here, 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.
Syntax: digitalWrite(pin, value)
Where,
pin: the pin number
value: HIGH or LOW
Now, again in your code.
digitalWrite(kPinLed, HIGH); // Pin set as HIGH

digitalWrite(kPinLed, LOW);  // Pin set as LOW

digitalRead(): This function use to read the value from a specified digital pin, either HIGH or LOW.
Syntax: digitalRead(pin)
Where,
pin: the number of the digital pin you want to read (int)
And this thing in your code looks like.
if(digitalRead(kPinBtn) == LOW) // Check pin states : LOW or HIGH
{
  //Your code...
}

PinMode sets the mode or function of the pin, like input (when you connect it to a sensor), or output (when you connect it to a LED for example). There are also some variances (like pullup/pulldown for special cases).
In practice, when you set the value to LOW, 0 V will be put on the signal, and 5 V will be put when it is HIGH (at least on an Uno).
PinModes are normally set during setup (once), and DigitalRead/Writes in the loop since you want to change it dynamically.
Btw, the last pat of the example can be better written as:
digitalWrite(kPinLed, digitalRead(kPinBtn) == LOW ? HIGH : LOW);

The ? operator (called ternary operator) checksk if the condition (digitalRead(kPinBtwn) == LOW is true, if so it will use the value behind ? otherwise the vvalue after : is used).

digitalWrite(kPinLed, !digitalRead(kPinBtn)); works also fine.


text:
Local variable usage in SRAM not counted
I use the following code to print the currently used SRAM space:
// this function will return the number of bytes currently free in RAM
// written by David A. Mellis
// based on code by Rob Faludi http://www.faludi.com

#include "TypeDefs.h"

int availableMemory()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

int printAvailableMemory(uint32 location)
{
  Serial.print(F("Available Memory at "));
  Serial.print(location);
  Serial.print(F(": "));
  Serial.println(availableMemory());
}

My main application (stripped) looks like:
...
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  printAvailableMemory(1);

  printAvailableMemory(2);

  test();
  printAvailableMemory(3);
}

void test()
{
  Preferences _prefs2;
  _prefs2.Set();
  printAvailableMemory(4);
}

While preference (.h) looks like:
#include "TypeDefs.h"

class Preferences
{
   private:
      uint8 _startChannel;
      uint8 _endChannel;
      uint8 _startNote;
      uint8 _endNote;
      uint8 _startCc;
      uint8 _endCc;
   ...
};

The output is:
Available memory at 1: 1065
Available memory at 2: 1065
Available memory at 4: 1065
Available memory at 3: 1065

I would expect the numbers (1065) would change, since a local variable (_prefs2) is made so at location 4 I would expect more space to be used.
Also, if I remove the _prefs2 code like below, the numbers stay the same.
void test()
{
    printAvailableMemory(4);
}

Why is the local variable not counted?

Local variables are allocated on the stack.

Are you actually doing something with _prefs2 other than setting it (which is what I assume .Set() does)? If not, the compiler may well have optimized it out. Check the generated assembly to see what happened.

Why is the local variable not counted?

Let us start with the function availableMemory(), what does it do?
int availableMemory()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

It returns the amount of memory between the top of stack (address of local variable v) and the heap end.
The answer lays in how the compiler works. One strategy that is used is function in-lining. This forces the functions test(), printAvailableMemory(), availableMemory(), etc. to be unfolded into loop() (which actually also gets unfolded into main()).
A common frame with the local variables is created and the variable for the top of the stack becomes one of them. You need a tougher test case to see how the stack top changes, e.g. tell the compiler not to in-line a function.
int availableMemory() __attribute__ ((noinline));

To check this generate the assembly listing for your sketch.
Cheers!

Thank you very much for this detailed answers. I should have known about inline compiling, I just am not used (anymore) to lower level languages (which I don't mean as offensive). Good to have such refresh about how compilers work.


text:
Deep sleep mode for the Uno without complicated circuits?
so I'm building something using an Uno that will run on batteries - so, I've watched a couple of these low power tutorials to lessen the energy consumption so the batteries can last longer, but they're not exactly what I want - they all require some sort of circuit. I've found this tutorial (http://www.engblaze.com/hush-little-microprocessor-avr-and-arduino-sleep-mode-basics/) which only needs an LED, and it's ideal, but I would like to know if you know of any other methods which would reduce consumption to less than 5mA without using any complicated circuits (other than unplugging the Uno)
Thank you!

Deep sleep mode for the Uno without complicated circuits?

Forget using an Arduino Uno if you want to do low power (less than 10 mA standby). There is too much extra circuits (LEDs, Voltage Regulators, etc) to allow that.
See for instance, https://www.gammon.com.au/forum/?id=11497
With an Arduino Pro Mini it is possible to achieve low power after removing the Power LED and cutting the Voltage Regulator.
The hardware/software support for low power cannot really be used before the board is design for that.
Cheers!

Thanks for your answer! Would this work by any chance?

Yes, that works fine. The suggested circuit basically turns off the Arduino board by disconnecting it from the battery. The button in the circuit will turn on the power of the board when pressed. This could be modified to an alarm signal from a RTC for time based start up.

The circuit (with or without RTC) could be mounted on a shield together with the battery pack to build a low-power unit.

Probably want to load your sketch with a Programmer so it runs immediately and does not wait out the bootloader starting up.  An advantage of using Power Down Deep Sleep is that an Interrupt wakes the processor and it can run immediately following the interrupt processor.  I made a remote control that way with an unmodified 8 MHz Promini and 3.7V, 1000mAH LiPo, would run about a month on a charge, and draw just a few mA when it went back to sleep after an RF transmission of the button press (433 MHz transmitter).  I think I just powered it via the VCC pin, bypassing the regulator.


text:
Arduino analog pins
How many sensors can be used by a arduino uno and mega separately.?
Does each sensor can use the ADC of arduino simultaneously? If not how to use all the sensors simultaneously if possible?

How many sensors can be used by a arduino uno and mega separately?

Assuming you mean analog signals. As many as the number of analog pins on those boards. This can be extended by using an analog multiplexer and additional digital pins. The total number of channels is number of analog pins minus one plus log2 of the number of digital pins used to select the input channel, e.g. 8 additional analog channels through a multiplexer will require 3 digital pins for channel selection.

Does each sensor can use the ADC of arduino simultaneously?

There is a single ADC module which takes approx. 112 us to convert an analog signal to 10-bit digital number. There is no simultaneous conversion of multiple channels.

If not how to use all the sensors simultaneously if possible?

All sensor can be connected but only one at a time is sampled and conversion to digital number.
Cheers!

All AVR- and ARM-based Arduinos have a single ADC, connected to multiple input channels. If you require simultaneous sampling of multiple sources then you will need to use one or more external ADCs.

If not how to use all the sensors simultaneously if possible?

a few ways:
1) use external adc;
2) use a sample-and-hold circuitry on the sensors;
3) find a mcu that has more than one adc modules; some pic24/dspics have that. some atxmegas have that. and some arm chips have that as well, to list a few.
4) use multiple avrs, each for a sensor;
...


text:
Arduino Nano TX LED is on
My Arduino nano make weired thing...
The TX LED is on when i define a Variable and a digital Pin as output. Do you now if it is a error in the code? If I upload a clear new sketch the LED is off.
~Nico
Code:

int ok = 1;
int err = 0;
int x1 = 2;
int x2 = 3;
int x3 = 4;
int x4 = 5;
int x5 = 6;
int x6 = 7;
int y1 = 8;
int y2 = 9;
int y3 = 10;
int y4 = 11;
int y5 = 12;
int y6 = 13;
int value1 = digitalRead(14);
int value2 = digitalRead(15);
int value3 = digitalRead(16);
int test = digitalRead(17);

void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(14, INPUT);
  pinMode(15, INPUT);
  pinMode(16, INPUT);
  pinMode(17, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

}

You configure serial pins as output, this may be your issue.

also, you're calling some digitalRead() before setup call, you would have to do that in the loop.

I tried some things to the pins and i foud something very interessting out. The value to be activated must be LOW instead of HIGH. That means that the TX and RX pins can be used as a normal digital pin but the activation value is inverted. I made a short video where I tested it. It is unlisted on YouTube: link     ~Nico

So... My decision was WRONG. The LED's in the Arduino are on if the pins are off. If the pins are on the LED's are off. For some reason the RX pin is on if you made him to an digital output. Would be awesome if some other people test it too to check if it is only for me or if it in a error of the Arduino Nano.  ~Nico

Both RX & TX pins are driving the onboard LEDs when set to LOW. Those 2 pins are tied to FT232RL chip to convert serial signal for USB. This may be the reason they are reacting to inverted logic. If you can avoid using these 2 pins, it would be better. you could also reflash the nano without disconnecting it from your own electronic parts for those 2 pins (reflashing may not work depending on what is connected on these pins).


text:
wiring a arduino led project
I am moving a project from breadboard and jumper cables.
It light a bunch of LEDs with different sets running of many almost every pin.
I need a few meters of cables.
I will a resistor on each led.
I have no idea what kinda cable/wire to use and googling cable gets me nowhere.
What kinda wire do people use?

I don't quite understand your question, but would ribbon cable fit the bill?

Otherwise, describe what sort of cable you're looking for (presumably you have some sort of idea) and someone may know what it's called.

When choosing wire for your project the main consideration is the amount of current. Second would be the distance.
For LEDs the current is generally low (milliamps) so something like a 20 or 22 gauge wire would be fine. You should be able to get it at a local hobby electronics shop or Amazon of course.
FYI, Wire gauge numbering is such that the lower the number the thicker wire. Thus 20 is thicker than 22.
You may find this AWG (American Wire Gauge) table helpful: http://www.powerstream.com/Wire_Size.htm

With careful choice of wire thickness and length paying close attention to the resistance-per-meter it may be possible to do away with the LED resistors entirely and use the resistance of the wire instead.


text:
Arduino IDE COM Port error on Windows 10
I have an Arduino micro, uno, and mega and none of them will connect to the com port on the Arduino IDE. I went to the device manager aand it is recognized but when I try to update the driver I get this:

Any help of how to fix this problem?

An easy thing to try but might not help: Use another USB port of your computer and see if the driver is reinstalled.
Otherwise, go to control panel and find the drivers (Device Manager), search for the Ports (COM & LPT) drivers and remove the driver for the Arduino manually, reconnect the Arduino and check if it is installed correctly. Possibly a wrong version of an Arduino driver is installed. If another driver is installed at COM3 (where is my Arduino), remove that driver and try again.

Option 1: Try to update or reinstall com port driver in control panel/device manager...
Option 2: There might be problem while installing Arduino IDE or problem occur during Arduino gets board and library updates over air itself. Try to reinstall IDE.


text:
Serial1 is not reading the Xbee on a Arduino Due
I am trying to test simple communication between a Xbee on my Arduino Due and a Xbee linked to XTCU. I attached jumper wires from RX and TX to RX1 and TX1 (Serial 1 hardware port) but I cannot send or receive data between the Xbees. I tested the Xbees previously with an Arduino Zero talking to the XTCU and it worked flawlessly.
Extra information: I am using a Xbee Shield on my Arduino Due (as shown in the picture)
char c,d;

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

}

void loop()
{
// put your main code here, to run repeatedly:
if (Serial1.available())
{
 c = Serial1.read();
 Serial.print(c);
}
else if (Serial.available())
{
 d = Serial.read();
 Serial1.print(d);
}

}

My wiring is attached. What am I doing wrong?

Are you using an Xbee shield? And doesn't it connect to pin 0 (RX) and 1 (TX)?

@MikaelPatel  Yes, I am using a Xbee Shield. Yes, but since there is no SoftwareSerial library, I have to use one of the multiple hardware serial ports to read data from the Xbee, hence the jumper wires.

So you have cut the pins from the Xbee Shield? Pin 0 and 1 are not connect to the corresponding pins on the due?

The pins used for SoftwareSerial are pins 2 and 3 (according to the documentation of the shield). I guess you could put them in input mode and connect to a hardware serial port (Serial1).

@MikaelPatel Actually, my jumper wire setup was correct but I had to flick a switch on the shield to communicate via UART. Thank you for your responses, though! I have another question (in the answers). I'm probably missing something simple in my code.

I fixed my problem. I stupidly left the Xbee Shield on DLINE instead of UART. Now there is communication between the radio modules. I have another question. When I type a character into XTCU, it "receives" the exact character from the Arduino Due. I have used this basic code with other Arduinos before and this has never happened.
Extra information: The serial monitor solely prints out received data.
I attached an example.

Please accept your own answer to close this question.

Has there been any update on this problem?  Your post has been incredibly helpful as I've been looking for ways to use a Due and an Xbee (specifically with the Sparkfun Xbee shield).
I haven't been able to solve this entirely, but I've noticed a few things;
First of all if you delete the second Serial.available, it does not change the functionality of the code at all, still works the same way.  I believe this has to do with the hardware Tx and Rx pins on the Due.
What seems to be happening is that if you use XCTU to send information to the Due, XCTU sends the data out, in which the Due receives it.  Then it bounces back and seemingly resends it from the Due to XCTU again, without displaying in the serial monitor.  I'm probably wrong in my observations but very curious if there's an answer to this.  Hope to hear back from someone soon.  Thanks!
EDIT
Upon thinking about it, I figured out a work around.  As stated in one of the comments earlier, you still have the shield's Rx and Tx pins connected to the Due.  This is what's giving you double values on XCTU.  The Due receives the input from XCTU and immediately sends it back out to XCTU.  A simple fix is bending the Rx and Tx pins out slightly so they are not connected to the Due but all of the other pins remain in place.  I hope this ends up being helpful!

There is no second Serial.available the other one is Serial1.available with 1 at the end.

Yes, I figured out that work around a few weeks back! Sorry I didn't say anything!


text:
Linking Arduino and Matlab
My project is based on controlling a moving fan using different hand gestures. I am using image processing toolbox from matlab to detect and identify various hand movements.I want to link my matlab codes to arduino for hardware implementation. How to link these two?

this may help: arduino support from matlab. Firmata may also be what you need to link matlab to arduino.

Seems like Serial is often used but then you need a protocol. You can use everything from textual or binary blocks to more advanced parsing. To give you more advice you would need to describe what you want to communicate and how often (for the bandwidth and response time calculation).

This block of code can give you some idea...
% create an arduino object

a = arduino('com3', 'uno');

% start the loop to blink led for 10 seconds

for i = 1:10

    writeDigitalPin(a, 'D11', 1);

    pause(0.5);

    writeDigitalPin(a, 'D11', 0);

    pause(0.5);

end

% end communication with arduino

clear a

For more details on this code and working of it you can visit....
Here


text:
Why is there no smooth value from ADXL335?
I have written this code to read x-acceleration from ADXL335.

Why is the value toggling between 342, 343, 344 even at rest? Is there anything I need to do to get a smooth curve?
How to increase resolution? (I'm using a Mega 2560)

int Xcurr,Ycurr,Zcurr;
int Xpre=0,Ypre=0,Zpre=0;
int res=0;
// these constants describe the pins. They won't change:
const int groundpin = A1;
// analog input pin 4 -- ground
const int powerpin = A0;
// analog input pin 5 -- voltage
const int xpin = A3;
// x-axis of the accelerometer
const int ypin = A2;
// y-axis
const int zpin = A4;
// z-axis (only on 3-axis models)
const int stpin = A5;

void setup() {
  Serial.begin(9600);
  pinMode(groundpin, OUTPUT);
  pinMode(powerpin, OUTPUT);
  digitalWrite(groundpin, LOW);
  digitalWrite(powerpin, HIGH);
  pinMode(stpin, OUTPUT);
  digitalWrite(stpin, LOW);
}

void loop() {
  Xcurr=analogRead(xpin);
  Serial.print(Xcurr);Serial.print("\n");
  delay(100);
}

It's called LSB noise, and it is what the ADC does. Just average the values over time (rolling average) to smooth it.

It is called moving average, the calculations you can use to prevent such problems can be found at wikipedia
In principle, what you do is take the average over the last x measurements to take away the peaks.


text:
How to change the baud rate of ESP8266 (12E) using an Arduino Uno?
I have with me an Arduino UNO and an ESP8266 (12E) WiFi Module. I need to make a webserver using the two. I read that the default baud rate for ESP8266 is 115200, and that the software serial pins can't handle such high speeds. I dont have an USB-UART converter at hand. Is there a way to use my Arduino as one to change the baud rate, so that I can interface with the chip using the software serial pins of the Arduino later.

if you have an uno you don't need a usb-uart; just rx-tx, tx-rx, g-g, uno's rst-gnd

@dandavis Okay. In that case on which pin should I connect the voltage divider to reduce the logic levels to 3.3V?

you don't actually need one just to flash an ESP, but you would "stepdown" the uno's TX pin for long-term connectivity, the 5v-tolerant ESP's pins put out enough for the uno w/o modification. using a red LED instead of a wire for the uno's TX to the esp's RX suffices.

You can use this block of code in Arduino to set baud rate...
void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {}

Change value in serial.begin() as per your value.

Use SoftwareSerial library for your module and define your own tx and rx pins like this and then you can define baud rate for your specified serial pins.
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9); // RX, TX for your module
void setup(){
   mySerial.begin(115200);
}

for more details visit https://www.arduino.cc/en/Reference/SoftwareSerialBegin

But from what I heard, SoftwareSerial doesn't support such high baud rates.

go to this link https://www.arduino.cc/en/Reference/SoftwareSerialBegin

Yeah, okay. It says it's supported. Thanks. It seems there's a lot of misinformation on the internet.

SoftwareSerial can't receive reliably at higher than 9600 baud, but it can transmit reliably enough for you to command the ESP board to change its baud rate to 9600. From then on, use SoftwareSerial at 9600 baud.

You can use the SoftwareSerial library and define your own tx and rx pin and set baud rate according to your requirement.
#include <SoftwareSerial.h>   // SoftwareSerial library
SoftwareSerial mySerial(2,3); // RX, TX for your module

void setup()
{
   mySerial.begin(9600);      // Set your buad rate
}

And you can also do without this library.
void setup()
{
  Serial.begin(9600);        // Set your baud rate
}


text:
Problem connecting 10W led + Led driver Directly Arduino Uno
can anyone give me an advice on connecting an 10W led + 12 volt drive to an Arduino Uno? it works without the board but when i tried to connect to Uno it doesn't work anymore. Thankyou

advice: don't do it.

Not unless you tell us what equipment you are using...

Yes, Thankyou, I'm using Led Driver Driver
Input Voltage: 12-24V DC
Output Voltage: 9-12V
Output Current: 900mA+-5%
can support 10pcs high power 10W led 3 in serial and 3 in parallel
http://www.ebay.com/itm/331653946252?_trksid=p2057872.m2749.l2649&var=540791276944&ssPageName=STRK%3AMEBIDX%3AIT

To operate LED using Arduino you will need a switch that can be operated using electronic switch like transistor, Mosfet or Relay board.
More easy and reliable option would be using Relay Board.
You can visit this link and can get more idea....
http://www.electroschematics.com/8975/arduino-control-relay/

wow, thankyou so much, this is what i bought from ebay an Led driver
Input Voltage: 12-24V DC
Output Voltage: 9-12V
Output Current: 900mA+-5%
can support 10pcs high power 10W led 3 in serial and 3 in parallel
http://www.ebay.com/itm/331653946252?_trksid=p2057872.m2749.l2649&var=540791276944&ssPageName=STRK%3AMEBIDX%3AIT

You'll need a switch such as a transistor, and capable of handling 10W, to be driven by the Arduino and connect/disconnect the LED to an external 12v supply. There are many examples on the web. Remember to connect the 12v and 5v grounds together.


text:
Arduino Shield on Breadboard
I would like to ask if I can stack directly Adafruit PN532 RFID Shield onto my breadboard. Or do I need something for that? Thank you.

no, but shields typically only use a portion of the pins, the rest are passed-through; this means a few dupont connectors can get a shield up and running; no need to connect "extra" pins" for the shield "top"

Chances are the offset headers won't allow the shield to directly plug into a breadboard.
As @Majenko noted, shields have a header that is offset by 0.16" from the other headers. Since a breadboard is a strict 0.1" grid that header won't fit into the holes.

@Mazaryk is right.
Shields have a header that is offset by 0.16" from the other headers. Since a breadboard is a strict 0.1" grid that header won't fit into the holes.

There was a Kickstarter project a few years ago to make just such an adapter. You might get in touch with the developer to find out whether he's made (or is planning) another run.


text:
Passing variable value in structure object
in this code i want to pass value of variable char array 'pass' in object "MyObject". But i am getting this error.
    Arduino: 1.6.11 (Windows 8.1), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

C:\Users\XXX\Desktop\EEPROM_put\EEPROM_put.ino: In function 'void setup()':

EEPROM_put:17: error: array must be initialized with a brace-enclosed initializer

};

^

exit status 1
array must be initialized with a brace-enclosed initializer

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

when i change pass to *pass, result of EEPROM.get() is 1 and 6, instead of 1, 62345, 7539514682.
#include <EEPROM.h>
struct MyObject {
boolean stat;
char password[6];
char mobile[11];
};

char pass[6]="62345";
void setup() {
Serial.begin(9600);
while (!Serial);
MyObject customVar = {
  1,
  pass,
  "7539514682"
 };
EEPROM.put(1, customVar);
Serial.print("Written custom data type!");
}

void loop() {

}

Use class and constructor
#include <EEPROM.h>
class MyObject {
    boolean stat;
    char password[6];
    char mobile[11];
  public:
    MyObject(bool tempStat, char tempPassword[], char tempMobile[])
    {
      stat = tempStat;
      strcpy(password, tempPassword);//As suggested by mikael
      strcpy(mobile, tempMobile);
    }
};

char pass[6] = "62345";
void setup() {
  Serial.begin(9600);
  while (!Serial);
  MyObject customVar(true, pass, "7539514682");
  EEPROM.put(1, customVar);
  Serial.print("Written custom data type!");
}

getting output like this:
Read custom object from EEPROM:
1
62345 7539514682T
7539514682T

What is the expected Output

Should copy with the sizeof(password) and not break on zero? strcpy() might be easier.

Sorry forgot NULL terminating character. Made changes

@Sniper still not getting correct output, now getting some random characters, output is :
1
62ÿ! 75
75
Expected output is 1, 62345, 7539514682

Did strcpy worked?

While the method from Sniper's answer works, it involves copying the
data, which is something you often want to avoid on an Arduino. The
simplest fix to your problem is probably to initialize your password
field with a literal string, just like you did with the mobile field:
MyObject customVar = {
    1,
    "62345",
    "7539514682"
};

or maybe, if you want the password to be written near the top of the
program,
#define PASS "62345"

MyObject customVar = {
    1,
    PASS,
    "7539514682"
};

Another option is to not store the strings in the object. Instead, store
them elsewhere and have the object only hold pointers to them:
struct MyObject {
    boolean stat;
    const char *password;
    const char *mobile;
};

char pass[6] = "62345";

[...]

MyObject customVar = {
    1,
    pass,
    "7539514682"
};

Note that, in this case, the mobile number is stored by the compiler as
an unnamed string constant. Because it is constant, the mobile field
has been typed as const char *. I typed the password field
identically for symmetry, but in this use case it need not be const.


text:
Hex to binary, LED blinking
I need to write a program that takes a user inputted HEX value and converts it to binary, then an LED blinks according to the number of 1's in the binary. For instance, if the value is 0xABC then there are number of 1's are 7 so LED will blink 7 times.
I only just started Arduino so not sure how to let user input a value nor do I know how to convert HEX to BIN but I'm assuming that once I convert the HEX to BIN I can just use a loop to count the number of 1's yet I'm unsure as to actually how to do that. This is what I've written so far.
  byte val=0xABC;
int ledPin=13;

int countSetBits(unsigned int n)
{
    unsigned int c;
    for (c=0;n>0;n=n&(n-1))
        c++;
    return c;
}

void blink(int n)
{
    for (int i = 0; i < n; i++)
    {
        digitalWrite(ledPin,HIGH);
        delay(500);
        digitalWrite(ledPin, LOW);
        delay(500);
    }
}

void setup()
{
    Serial.begin(9600);
    pinMode(ledPin,OUTPUT);
    blink(countSetBits(val));
}

void loop()
{   }

Any help would be appreciated.
EDIT: If I want to take a number from a user and then make the LED blink according to the number of 1's in its binary form, how would I implement that?

byte val=0xABC; that's not going to fit in a byte. Use an int instead (int val=0xABC;)

You are almost there. Now you just have to read and parse the hex
numbers supplied by the user.
The simplest way to accept numeric user input is with
Serial.parseInt(). This is not always ideal since it involves blocking
the program until it either receives an invalid character or the reading
times out. It is also not applicable to your situation because it only
works with decimal numbers.
The better standard way to get the input is to put the incoming bytes
into a buffer until you catch a specific character designated as an end
of message marker. This is typically a CR ('\r' in C++) or an LF
('\n'). This technique is more involved than just calling parseInt()
but it is often preferred because it can be done in a non-blocking way.
See for example this simple command line interpreter.
In your case, however, you do not need to buffer the incoming bytes. You
can instead parse the hex number while you read it, like this:
void loop()
{
    if (Serial.available()) {
        static unsigned int val;
        int c = Serial.read();
        if (c >= '0' && c <= '9') {
            val = 16 * val + (c - '0');
        } else if (c >= 'a' && c <= 'f') {
            val = 16 * val + (c - 'a' + 10);
        } else if (c >= 'A' && c <= 'F') {
            val = 16 * val + (c - 'A' + 10);
        } else {  // End of number.
            blink(countSetBits(val));
            val = 0;  // reset for next round
        }
    }
}

If I add this to the loop section of my program will it work? I don't have a board to test on right now

I tested it on an Uno using Serial.println(val, 16); instead of blink(countSetBits(val));, and it did correctly echo the values I entered with screen.

You might do it much simpler... Create a fixed array that for each hex character possible (0..F) has the number of 1's counted.
Than iterate through the string, sum up the values of 1's from the array and make a LED blink that many times.
Something in pseudo code:
// Number of 1's: 0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
boolean ones[] = {0, 1, 1, 2, 1, 2, 2, 3, 1, ...                };
string str = "ABC";
int total = 0;
for (index = 0; index < str.length; index++)
{
   if string[index] <= '9'
       total += ones[string[index] - '0'];
   else
       total += ones[string[index] - 'A' + 10];
}

You could use BIT SHIFTING looks flash, but is actually really useful.
const unsigned char value = 0x55;  // Input
int blinks = 0;                    // Times to blink.

for (int i = 0; i < 8; ++i)
{
    blinks += ((value >> i) & 0x01); // Could just blink the light if its true.
}

(value >> i) takes value and moves the number right i places.  So if value is Hex 55 (0x55) that is 01010101 in binary.  On the first time around the loop when i is 0 (value >> 0) will be 0x55 (unchanged).   0x55 & 0x01 is a logical and between the two numbers, so any bits that are set in both will be set in the result.  Since 0x01 only has the least significant bit set (LSB) then we only need to look at the LSB of 0x55, which we know is set.  therefore blinks is incremented by one.
On the second time around the loop value >> i is 0x2A (00101010) because value has been shifted right one place.  So 0x2A & 0x01 = 0, so blink isn't altered.
etc.
The answer at the end of the loop is blinks == 4.

The OP already solved the problem of counting the bits set, and his solution looks more efficient than yours.

I just timed both solutions, both inside a function taking a uint8_t argument and returning an int. The OP's function takes from 14 to 86 cycles, depending on the number of set bits found. Yours takes 281 CPU cycles irrespective of its input.

Any help would be appreciated.

your code is in pretty good shape - there are some minor issues that need to be taken care of. the countSetBits() is a fairly standard implementation and in this case returns the right value:

I sped up the blinky rate for convenience.
a good starting out place.


text:
How many pins are needed for a sensor?
I'm currently looking to buy an Arduino, but never touched robotics before. Would anyone be able to give me an idea how many pins a sensor such a magnetometer would use? This is for Arduino Uno.
Sorry if this is stupid, just really have no idea how to approach Arduino design without having one here and can't get one for a few weeks at the least.
Thanks!

Below image is the answer to your question.

According to this image, magnetometer required four pins of arduino.
GND of magnetometer ----> Arduino GND
Vcc of magnetometer ----> Arduino 3.3 Volt
SDA of magnetometer ----> Arduino Analog Pin 4
SCL of magnetometer ----> Arduino Analog Pin 5
I hope it will help you.

Would anyone be able to give me an idea how many pins a sensor such a
  magnetometer would use?

Here below image provides the connection and pin requirements for magnetometer...

According to image magnetometer will require 4 pins of Arduino 2 pins of supply i.e +3 volt and Ground and other two pins will be any two Analog pins of Arduino.
And to connect other sensors with Arduino, you can find datasheet of desired sensor and can find how many pins that sensor is going to use.

Probably wrong about  “any two Analog pins” bit.  A4, A5 on Uno are SDA, SCL, two of the lines required for hardware-based I2C.  See eg 3-axis magnetometer breakout wiring and test at adafruit

How many pins are needed for a sensor?

As many pins as are needed for that sensor.
Every sensor is different. The datasheet or manual for the sensor or the chip or other device that the sensor is based around will tell you how the interface to it works - what each pin does, how you use it, etc.
It is up to you to read that documentation and learn how the sensor works to then be able to plan how best to connect it to your Arduino.
Some sensors require specific connections, such as the two I2C pins in your example sensor. Others may need the SPI pins. Then there are sensors that use analog inputs. That may be one pin for, say, an LDR, or three pins in the case of a 3-axis accelerometer.
In short: RTFM.

One, maybe two. It's impossible to say for sure without a concrete example.
I would recommend looking up the type of sensor(s) you want to use, and read the data sheet(s). Things you'll want to consider are things like operating voltage (3.3v or 5v), current draw (>40mA?), are any additional passive components required (capacitors, resistors, ...), etc.
Data sheets will describe in great detail, how to use a specific device.

If you are satisfied with this answer, it's good form to select it and indicate your question as answered :)

Broadly speaking, look for sensors/outputs that use I2C or SPI interfaces. If you use I2c, you can wire all your sensors with two digital pins. This is especially important with multi-axis sensors that would otherwise chew up 3-6 pins each.
I2C is probably easier because SPI need one extra pin per device, in addition to the 2 base pins. Still, that's about 10 devices on one UNO, IF you spend the extra $1 or $2 on the SPI/I2C sensors/LCDs/etc instead of going for what at first seems like a cheaper part.