text:
Getting the voltage of an 18650 battery with an Arduino
I'm using a Arduino Pro Mini (5v) to sense the voltage of an 18650 battery. The battery (that is being sensed)is also used to power the Pro Mini but the MCU is behind a boost-converter which outputs 5.05v. Would I be able sense the right voltage of the battery?

simulate this circuit – Schematic created using CircuitLab
The boost converter has an input voltage ranges to 0.9 to 5 volts and current of 600mA.

most cheap switch-modes are not isolated, so the ground is common. there's little/no reason to isolate unless there's inverted voltages.

Yes, if Vin- and Vout- are joined together inside the boost converter or share a common ground on the boost converter circuit board such as this one:

My boost converter is different but the IN- and OUT- is connected.


text:
Why doesn't Serial.read() read multiple character?
I used multiple of Serial.read() and Serial.parseInt() to get characters and a number ( like "xy123" ) on an Arduino UNO.
Then I checked the result on Serial monitor.
Unfortunately I couldn't get the character with second Serial.read().
Here's the code:
void setup(){
    Serial.begin(9600);
}

void loop(){
  if (Serial.available() >0) {

    // I want to reacive the characters like "xy123"
    char input1 = Serial.read();
    char input2 = Serial.read();
    int value = Serial.parseInt();

    Serial.println(input1); // ok
    Serial.println(input2); // * no good * (-1)
    Serial.println(value);  // ok

    // Writing some codes with input1 ,input2 and value ...
  }
// I don't want to use delay().
}

How do I get the second character?
Thanks.

Everything is explained here: https://majenko.co.uk/blog/reading-serial-arduino

what second character?

  if (Serial.available() >0) {

This is like saying "I won't go into that room until there is at least one dog in there".  Someone tells you there is a dog there. You go into the room and say "Hey, why aren't there two dogs there?".
If you want to read two bytes one approach is to wait until they are available:
  if (Serial.available() >= 2) {

but you did send two dogs into the tunnel leading to that room :-)

Exactly! But one hasn't arrived yet. :) Dogs move at a finite speed, the same way that serial communications does. In fact I think everything moves at a finite speed.

You did not read the second character, because the character did not arrive yet. Wait until it is available. read doesn't wait. parseInt has the waiting build-in.
You can wait for the second character by reading the two characters with the waiting function readBytes. It will wait a second for the next character.
char buff[2];
if (Serial.readBytes(buff, 2) == 2) {
  char input1 = buff[0];
  char input2 = buff[1];
...

If you send only one character, readBytes will wait one second for the next and the returns that one char was read.

source: Stack Exchange

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

sort: votes


text:
Is there a sensor to measure a distance between 2 point as in range [0-2 meter]?
I'm looking for a way of detecting if 2 pieces of hardware are within 2 meters of eachother or not. The idea is to build a prototype to lock computers automatically. I just need a recommendation on the sensor if it exists. Geofencing, bluetooth etc are not reliable enough.

Just point a ultrasonic sensor towards the chair in front of the PC. Or add a force sensor to the chair.

i would try an ultrasonic emitter for the wrist, like those "mosquito repelling" things, along with a sensitive mic on the other end. Audio fades very reliably at distance; twice as far is 25% as loud, and the dead-simple "buzzer" can be very low power compared to more complicated emitters.

You can use a lot of different methods with advantages/disadvantages:

Use an IR LED/receiver and calculate the distance of travelling of the lights. Disadvantage: you need a very precise timing mechanism (light is fast), also take latency into account for non-light parts, and hardware needs to be in visible range and pointing to each other with LEDs)
Use an ultrasonic sensor like SR-HC04. Disadvantage: devices must point to each other in a small precise angle.
Using an RF method and sending/receiving e.g. via nRF24L01+ 2.4 GHz trasnceivers, to check the difference in time between sending and receiving when very close or a few meters apart. However, there might be aspects that might distort the result (other receivers/transmitters, what kind of material is in between, nRF antenna placement/direction etc). Using lowest speed (most reliable), highest power.

I was thinking more of a bracelet like design, which will not work with both of these sensors. What are they using in these ankle bracelets for criminals? ;)

"What are they using in these ankle bracelets for criminals?" GPS

I doubt they will use GPS, since you don't have GPS in house and you can cover/circumvent GPS signals easily. So my bet is a signal that is sent and received and a time difference (travel) time is performed calculating distance.

no need to monitor a position of the bracelet in the house

It seems you are partly right, GPS + other mechanisms (sending to fixed location): https://en.wikipedia.org/wiki/Ankle_monitor   ... however, a device at a fixed location does not really help answering the question itself.

Yes to specify: I try to solve the "user forgets to lock the computer" problem with a hardware prototype. For fun.

I would do some tests starting with nRF24L01+ 2.4 GHz (if you have them) and check if you notice a difference in sending time and receiving time when very close or a few meters apart. However, there might be aspects that might distort the result (other receivers/transmitters, what kind of material is in between, nRF antenna placement/direction etc). Using lowest speed (most reliable), highest power.

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


text:
Timer for Control Motor using Limit Switch
Im not good in arduino, but I have project that control motor using limit switch.
The rule is:

When switch OFF, motor ON
When switch ON, motor OFF for 1 hour (i dont want use delay because cannot multitasking so it will be stopped another program which have to running in the same time)
After 1 hour, motor ON (although switch state still ON)

What type of timer I have to use? And how the code? Thanks. Sorry if i dont have any codes.

You can do a 1 hour delay with millis() (though it's not 100% accurate). If the time now, minus the time when the switch got pressed, is more than one hour then turn on the motor.

There is no need to do a complex thing like using extra timers for this. You can use non-blocking code with the millis() function, like in the BlinkWithoutDelay example of the Arduino IDE (You should really try it and understand how it works). The millis() function returns the number of milliseconds since the Arduino has powered up and it will overflow after about 50 days (and with the code from the mentioned example this wouldn't be a problem either).
Basically you save a timestamp of the last event and check, if it is time to do something. For your case I would add a boolean, indicating, that the motor should be off and that the state of the switch doesn't matter anymore. Then (I assume that you want to disable the motor again by switching to OFF and ON again) you would have to reset this variable, when the switch goes to OFF state again. Something like this:
boolean state=true; // on by default
unsigned long timestamp=0;

void loop(){
  if(switch_on() && state){
    state=false;
    // switch off the motor here
    timestamp = millis();
  }
  if(switch_off()){
    state=true;
  }
  if(!state && millis()-timestamp > INTERVAL){
    //switch on the motor here
  }
}

Be sure to have a good code for checking the switch state, since most mechanical buttons need debounce code. In the above code I replaced this with simple functions to illustrate the timing functionality.

you only need to debounce the switch OFF, when the motor starts up

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


text:
Pin Mapped Wemos D1 R1
I want to ask about Wemos d1 R1. Can I use those pins connected for different sensor?
For example I use pin D5 and D13 for switch and push button, or I use pin D7 and D11 for two different sensors.
Thanks.

well, D7 and D11 seem to be the same physical GPIO on the ESP8266, so, no, you probably can't use D7 and D11 for two different sensors

I need 13 pins for sensors and actuators. I use wemos d1 R1 because the actuators have to be controlled by telegram. So, any idea what I have to do if I can't use some pins for two different sensors?

esp8266 only ever has about 8 pins you can use

8 pins or 11 pins?

Available GPIO pins are 0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16 - so, yeah, 11, sorry (forgot to include Tx and Rx and GPIO16 - I never use those for obvious reasons) - note: I'm talking about GPIO pins, not the Dn pins, as you can see, D5 and D13 refer to a single GPIO (14) - in fact D11,D12,D13,D14, D15 are dupes of D7,D6,D5,D4,D5 respectively

depending on the type of sensor, however, you may have enough pins (e.g. you can, and do, put multiple DS18B20 temperature probes on one pin) - without knowing your full requirements, I'm guessing

the pinout of D1 R1 is unfortunate. R2 has it much better

I didn't know you could still send telegrams...

What do u mean? I will use all of pins to sensors and actuators (11pins). Could I still connect to telegram?

can i use TX pin to connect with sensor?

I would not recommend using TX as input. It outputs boot log at startup.


text:
Using UART to Set RTC
I'm using an Adafruit NRF8001 Low Energy Bluetooth module and a Real Time Clock module with my Arduino board. I want to connect to the BLE module using UART to set the clock. I'll also be using UART to set alarms.
I'm not sure which is the best way to take a string from the UART receiver and pull it apart into the hours, minutes, second, etc.
Any ideas? I did look at the Arduino JSON library but it seems a little buggy, and possibly overkill.
Any help would be very much appreciated :)

The simplest method is to keep it as a fixed format string with line termination.
Read one line in from serial into a character array (aka C string) and then chop it up.  As long as the string is in the correct format you can easily chop it around.
For instance, assume you chose the format YYYY-MM-DD HH:MM:SS\n which is quite common and easy to use, you may have data like this:
char *indata = "2015-08-22 17:23:48\n";

(\n is the new-line character)
Using simple char pointers you can get each substring quite easily:
First slice the string up into the component parts by replacing the separator tokens with character 0:
indata[4] = 0;
indata[7] = 0;
indata[10] = 0;
indata[13] = 0;
indata[16] = 0;

Then you can assign pointers to each segment:
char *year = indata;
char *month = indata + 5;
char *day = indata + 8;
char *hour = indata + 11;
char *minute = indata + 14;
char *second = indata + 17;

Or if you want it as integers, you can pass it straight to atoi:
int year = atoi(indata);
int month = atoi(indata + 5);
int day = atoi(indata + 8);
int hour = atoi(indata + 11);
int minute = atoi(indata + 14);
int second = atoi(indata + 17);

In fact, if passing it direct to atoi() you shouldn't need to even do the first stage, since it will stop parsing at the first non-numeric character.
There are more flexible ways of parsing the string too, using strtok(), but that is somewhat more advanced.
Note that this method is highly intolerant to invalid strings being passed, so you may want to first ensure that a) the string is the right length, and that b) there are the right separator tokens in the right placed, to validate that the string is properly formatted before proceeding.

Thank you @Majenjo. This might infact be the easiest way to do it. I can prepend the string with the item I want to update too. E.g. ST to set the clock, A1 to set alarm 1, A2 to set alarm to and so on.


text:
Pass Several Values to Library
Unfortunately I have yet to learn C++ though I have experience with C# and other non-C languages. After trying for the past 5 hours to pick up what I can from Stack and other sites I haven't found a workable solution that actually works with Arduino IDE (hence why I'm posting here and not stackoverflow).
Im trying to create a simple library to handle some analog inputs. I need to be able to compare the value from a pin to a list of values and handle the result accordingly. I can easily send the number of the pin to the constructor and read it. My issue is actually defining that list from the setup() function.
The list can be variable in length so I can't hard code an array in the library class and then pass values one by one. I can pass the length in the constructor but then I'm not really sure how to use it to initialize the array length without having the values to assign.
In C# or other languages I'd either use a list or pass the array directly. Neither of these seem to be an option with C++ (or at least I couldn't pass the array correctly). How could I solve this problem? If it helps I'm using a teensy++ 2.0.

I've chosen to undelete your question because there doesn't seem to be a reason for deletion. If you feel this was a mistake, feel free to reply to this comment. Thanks!

@jimjimmy1995 - please don't delete a question once you have an answer to it. The question and answer are intended to help other people in the future with similar problems. Thanks!

I deleted it before there were any answers as I realized my mistake when trying to pass the array. I no longer needed to ask the question and the solution was more fitting of stackoverflow.

Arrays in C/C++ are handled as a pointer.  That means the value of the pointer is the location in memory of the first element in the array.  The next element is at that starting address, plus the size of each element.  So for an array of 1-byte characters, each item in the array is at the very next address.  For 32-bit members, it's at +4, and so forth.
You're storing an array of values to compare with analogRead() - so uint16_t (aka: short int) will be large enough for each element, without wasting too much memory.  But we also need to store a count of them, I'll assume 32-bits is enough readings.
uint16_t *comparison_points;
uint32_t  comparison_point_count;

These can be declared statically like:
uint16_t  comparison_points[] = { 2, 4, 6, 8, 47 };
uint32_t  comparison_point_count = 5;

Giving you a comparison function like:
bool readingInSet(uint16_t reading, uint16_t *check_points, uint32_t check_points_length)
{
    bool found = false;
    for (uint32_t i=0; i<check_points_length; i++)
    {
        if (reading == check_points[i])
        {
            found = true;
            break;
        }
    }
    return found;
}

But you could also make the array into an object, embedding this functionality
class AnalogueVector
{
public:
    AnalogueVector(uint32_t size, uint16_t *points)
    {
        comparison_point_count = size;
        comparison_points = points;
    }

    bool readingIn(uint16_t reading)
    {
        bool found = false;
        for (uint32_t i=0; i<comparison_point_count; i++)
        {
            if (reading == comparison_points[i])
            {
                found = true;
                break;
            }
        }
        return found;
    }

private:
    uint16_t *comparison_points;
    uint32_t  comparison_point_count;
};

Giving a usage like:
uint16_t  comparison_points[] = { 2, 4, 6, 8, 47 };
uint32_t  comparison_point_count = 5;

AnalogueVector cmp_points(comparison_point_count, comparison_points);

if (cmp_points.readingIn(analogRead(A1)))
    Serial.println("Matched");
else
    Serial.println("no");

Obviously if you're reading these data points in from a file, or other external media, then you would need to allocate space for the items, and store them in the object.
As with most coding problems, there's multiple solutions.  Here I've tried to keep it simple, and explore different ways of handling array data, without getting to far away from that fact that an array in C/C++ is just a big contiguous block of data in memory somewhere.  The address of that data, (aka the pointer), is simply the address of that first element.

Here are a few examples how to pass vectors and variable number of arguments to a function in C/C++:
void foo(int* vector, size_t nmemb);

The function foo takes a vector of integers and the number of members, nmemb.
const size_t VECTOR_MAX = 5;
int vector[VECTOR_MAX] = { 0, 1, 3, 5, 7 };

foo(vector, VECTOR_MAX);

The next variant is generalization. A vector of whatever, number of members, and size of each member;
void fie(void* vector, size_t nmemb, size_t size);

This allows the function to handle different types of element.
fie(vector, VECTOR_MAX, sizeof(int));

Examples of usage are the standard library functions qsort() and bsearch().
The next variant is variable arguments. C/C++ allows the syntax "..." for a list of arguments.
void fum(size_t nmemb, ...);

This allows the following call:
fum(5, 0, 1, 3, 5, 7);

The implementation of function must be able to "parse" the argument list.
#include <stdarg.h>

void fum(size_t nmemb, ...)
{
  va_list ap;
  va_start(ap, nmemb);
  int arg;
  for (size_t i = 0; i < nmemb; i++) {
    va_arg(int, arg);
    ...
  }
  va_end(ap);
}

There are four primary methods to determine the number of arguments and value types; 1) number of arguments as parameter and fixed data type, 2) special end parameter value, 3) indirect through format descriptor such as printf() format string, and 4) attribute-value pairs.
Below is an example of variable number of arguments as attribute-value pairs.
void set_attrs(size nr, ...);

set_attrs(5, X_POS, 10, Y_POS, 110, R_COLOR, 0, G_COLOR, 255, B_COLOR, 0);

A usage of this notation can be found in Motif.

If the list is a static list you could conceivably pass a pointer to it in the constructor. Example:
class myClass {
  const int num_;
  const int * values_;

  public:

  // constructor
  myClass (const int num, const int * values) : num_ (num), values_ (values) { }

  // other stuff here

  // demo
  void printThem ();
};  // end of class myClass

void myClass::printThem ()
  {
  for (int i = 0; i < num_; i++)
    Serial.println (values_ [i]);
  } // end of myClass::printThem

const int NUMBER_OF_VALUES = 6;
const int myValues [NUMBER_OF_VALUES] = { 22, 33, 44, 55, 66, 77 };

// make an instance of the class with the wanted values
myClass foo (NUMBER_OF_VALUES, myValues);

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

  foo.printThem ();
  }  // end of setup

void loop ()
  {

  }  // end of loop

That is the simple method. The values in the list are passed to the constructor as a pointer, the class remembers the list and uses it when necessary.


text:
Why should a pin be set as an input if it can read input when set as output?
I recently created a circuit to read the value from two sets of buttons using only two analog pins. It involves setting one pin HIGH and reading the input on the other pin and then swapping. With both pins set to OUTPUT I can still read in values with analogRead() without having to keep switching pin modes.
My question is why is that the case? What is the point of setting a pin to INPUT if OUTPUT can still read in values? Are there any disadvantages of doing so?

Just don't expect this to work when changing to some other board. E.g. the Due or Teensy. Other than that there's probably no disadvantage.

The reason for this is because analogRead() has absolutely nothing to do with what mode the pin is in.  That mode only has any meaning in the scope of digital operations - i.e., when using digitalRead() and digitalWrite().  When using analogRead() the Arduino code switches the pin into analog mode first and then reads from it.

Why do the digital operations require a pin mode to be set while analog pins do not?

Because the digital operations are different to the analog operations.  When you do an analogRead the IO pin is isolated from the digital IO circuitry, so the pin mode (which affects the digital IO circuitry) has absolutely no effect on the operation.

It's like your car keys.  You use them for your car, but you don't use them for your bike, yet both of them are in the garage, and they both come out of the same doorway.

My question is why is that the case? What is the point of setting a pin to INPUT if OUTPUT can still read in values? Are there any disadvantages of doing so?

If you do a digitalRead you can read the current latched state of an output pin (it doesn't change it to input). In other words, you read what was last written to it.
If you do a digitalWrite of HIGH to an input pin it sets the internal pull-up. If you write LOW it disables the internal pull-up. If it switched it to output for you, you wouldn't be able to enable or disable the pull-up. (Note: this applies to older versions of the IDE, newer ones have a pinMode setting of INPUT_PULLUP).

What is the point of setting a pin to INPUT if OUTPUT can still read in values?

That certainly won't work with digitalRead because you are writing a value to the pin in OUTPUT mode, so you will merely read back what you are writing. In other words, you have activated the driver transistors, which will override whatever value you are trying to read.

It is good practice to define them, especially if you program something other then an arduino. For example a port pin on the PCF8574 (Peripheral device) is written as a 1 so you can read it, it has a small internal pull up. If you pull it low in this condition you will read a zero. If you write a zero you will always read a zero. Driving it to a 1 when set to zero can destroy the part. This configuration is also used on microcontrollers. There are hundreds of different port configurations and programming options, it is best to read the data and understand it first otherwise you may be purchasing another.

Because I/O pins can be used for either digital input or digital output and can be switched to perform in a given direction. Some of the pins also have an analog capability, either A-to-D conversion (input) or PWM (kind of a psuedo-analog output) but only in one direction permanently assigned by the hardware and therefore not switchable from one to the other.

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


text:
Send commands to Arduino from the WEB
I need to send Arduino some instructions from the web. Basically I would have a web app with a few buttons, and when I press them they send an instruction to Arduino to move for example a motor or turn a lamp. This has to function remotely, so not locally.
I'm using an Arduino Yùn.
How should I do this? Websocket? How? Thanks!

You should send commands through a socket, yes. You can either make your own on your own port or you can just make HTTP requests (for instance GET requests). Just search for a tutorial that shows how to do it with a webpage, then discard all the webpage design and implement just the get pages. From the remote web app, then, call these pages. Or just make your own protocol

It becomes lots easier if you see the yun as a linux computer with a arduino connected over serial.
Then the question becomes: what is the best way to send commands over the internet to a (linux) computer.
Answer: there are so many ways because there is no best way.
What are the main key drivers:
Your linux computer needs to be reachable from the internet. That means opening your local network(firewall). The firewall is there for a reason. Do you have the skills to open your firewall and still be safe? If so you can run a service (lots of options) and reach your yun from anywhere on the internet. Just as you do locally.
If not you will need to go to a polling system. You use a server which is on the internet and send you request to that server. Your yun polls that server to get the messages you send.
There is a third option: If you can open your firewall from the internet, and you are the only user of the service and you very rarely need the service you can temporarily open the firewall when you need it
.

The simplest way to do this would be to host a webpage with the buttons on the Yùn itself, like for example this here. There are loads of examples for stuff like this out there.
To access it "remotely" - I presume you mean from anywhere on the internet - you would have to forward a port from your home router to the Yùn, like this. This will make the Yùn accessible from the internet. You only have to know your outside address (Google: "Find my IP") and then you can access your arduino from all over the world.

Another option, if you can be limited to controlling your device from a mobile app, is blynk.cc. They provide mobile apps for Android and iOS, that let you build a control panel via drag-and-drop, and embedded platform libraries for Arduino, standalone ESP8266, RPi, and others, that talk both ways between the app and your embedded device, as well as between devices.
The embedded devices and the mobile apps communicate as clients to their servers (or to your server, if you choose to host the open-source server code) so you don't have to open any ports on your router or firewall.
You won't have the full freedom (or requirement!) of designing custom web-pages; but OTOH, you can be up and running with their example code in a few minutes.
I have a couple of room-temperature monitors on my desk that can report the temperature (plus history) to me anywhere I can get a web connection. I put two buttons on my panel to turn on, or blink, 2 LEDs on the board. With my feet up on the hearth I control the LEDs. There are slider-controls that can talk to the PWM ports as well. All the capabilities you need are there, at least to get started.


text:
Detect button press inside a for() cycle
I was working on a project with an LED strip, where I'd like to cycle through various effects with just a press of a button. The problem is that I don't know how to detect the press of the button to change effect while in for() cycling colors to have a rainbow effect (so it's a multitasking problem, I think).
Could you help me? :)
#include <Adafruit_NeoPixel.h>

#define pin 5
#define led 15
#define button 7
Adafruit_NeoPixel strip = Adafruit_NeoPixel (led,pin,NEO_RGB+NEO_KHZ800);

int doggo=0;

void setup(){
 strip.begin();
 pinMode(button,INPUT);
}
void loop(){

 int buttonVal=digitalRead(button);

 if(buttonVal==HIGH){
  doggo++;
  delay(300);
 }
 if (doggo>2){
  doggo=0;
 }
 while (doggo==0){
  //whole strip red
  for (int i=0;i<led;i++){
   strip.setPixelColor(i,255,0,0);
   strip.show();
  }
 }
 while (doggo==1){
  //rainbow effect
  uint16_t i, j;
  int rainbowSpeed=10;
  for(j=0; j<256*5; j++) {

   for(i=0; i< strip.numPixels(); i++) {

    strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    strip.show();

   }

  }

 delay(rainbowSpeed);

 }

 while (doggo==2){
  //whole strip blue
  for (int i=0;i<led;i++){
   strip.setPixelColor(i,0,0,255);
   strip.show();
  }
 }

}

uint32_t Wheel(byte WheelPos) {
 WheelPos = 255 - WheelPos;

 if(WheelPos < 85) {
  return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
 }
 if(WheelPos < 170) {
  WheelPos -= 85;
   return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
 }
 WheelPos -= 170;
 return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

You could use the Bounce2 library.
Call the update() method regularly and then check the state with read().
e.g.
for (...) {
  button.update();
  if (button.read() == HIGH) {
     //change pattern
     break;
  }
  // Do strip stuff.
}

As an added bonus the bounce library will debounce your button.

I finally solved!
I tried the Bounce2 library, but it acted really strange (the effects passed from the first one, then the third one, then the first one again for a fraction of second and automatically to the second one, plus other things :/ )
It looks like I just needed to add a normal digitalRead inside for() and a return, I don't usually make those errors xD

You should use a hardware interrupt. Depending on your microcontroller, you have different pins available.
Here is a reference for more details and syntax

Thanks, I correctly implemented the hardware interrupt since it works with single colors (there is no digitalRead in loop, just a attachInterrupt() in setup). Still, it doesn't work with the rainbow effect :(


text:
Formula to calculate energy required to power an Arduino board
Given an Arduino board with the following specs:
ATmega328 Arduino Nano AVR® ATmega MCU 8-Bit AVR Embedded Evaluation Board (link)
What is the mathematical formula to calculate how much energy/power would be required to keep the Arduino board on (meaning in "standby" mode, therefore not consuming any energy but the one required to keep it "alive")?
Please note I am new to all things electronics, Arduino but most importantly physics and maths. Thank you.

In the datasheet you can read how much every mode uses (normal mode, sleep mode etc). However, it also depends on which peripherals inside the CPU are active and all electronics around it. So make sure you read the datasheet of the entire development board, and not from the CPU itself.
The mathematical formula is reasonably simple: the total power is the sum of each component's Amperage * component's Voltage. But practicially this is hard to calculate.
The easiest way (but not mathematically) is probably just to measure the amperage in the development board, and the voltage and multipley them together.

Don't forget to account for the current required by the FT232RL (usb-to-serial) and the green power-led.

@Gerben that is what I meant to check the datasheet of the entire development board, not from the CPU itself.

I know. I just wanted to explicitly mention those.

@Gerben thanks ... and these a non negligible amount of current.

Thanks @MichelKeijzers et al. That is really helpful but still a bit "cryptic" for me (but mostly due to the fact that I am new to all this).
The reason I asked for how to calculate the amount of energy required to power the Arduino board is because I wanted to understand whether a solar panel (small, big, whichever fits the need) would be able to provide energy for the board to "do stuff" (provided the solar panel has the right amount of energy stored in it...).

In that case, try first without the solar panel. Do all the stuff you need on the Arduino. Than check how much voltage goes inside the Arduino (e.g. if you use the power adapter, check the voltage with a volt meter, if you use USB it's probably close to 5V). Than check the amperes you are using and multiply them together. However, depending on the the Arduino is doing it might fluctuate, so take the highest wattage (volts * amperes) to be safe.


text:
Compiler doesn't like function code
I am getting this error from the Visual Studio compiler (I use the Visual Studio add-in Visual Micro for Arduino).

ModelRailroadCrossingSignalController.ino:In function 'void loop()
  ModelRailroadCrossingSignalController.ino:210:15: error: too few arguments to function 'Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer, const char*)
  :onSignalSound()
  ModelRailroadCrossingSignalController.ino:note  declared here
  :Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
  Error compiling project sources

Here is the function and loop (all the defines and instances left out for brevity, they aren't the issue
void loop() {
// put your main code here, to run repeatedly

signalEntrySensor = checkEntrySensor();
if (signalEntrySensor == true) {
    if (crossingSignalInOperation == false)
    {
        Adafruit_VS1053_FilePlayer mp = onSignalSound(musicPlayer,"Trainxng.mp3");  //all other functions are called in the sound routine?
        if (debugMode)
        {
            Serial.println("Sound byte called");
        }
        while (mp.playingMusic) {
            // file is now playing in the 'background' so now's a good time
            // to do something else
            offRoadPower();
            lowerSignalArms();
            onSignalSound();
            startSignalFlashers();
            crossingSignalInOperation = true;
        }
    }
}

Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
// Play the train crossing sound file
if (debugMode)
{
    Serial.println(F("Playing track - "));
    Serial.print(fileName);
}
//all sound files are on the micro sd card on the music player shield
if (!mp.startPlayingFile(fileName)) {
    Serial.println(F("Could not open file "));
    Serial.print(fileName);
    while (1);
}
return mp;  }

I'm a C# guy, not ever using C++ until now, but this code should certainly work, not sure why the function is not compiling.

Related: http://arduino.stackexchange.com/questions/23059/proper-way-to-run-functions-in-loop

The clue is in the error...

too few arguments to function 'Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer, const char*)

You have defined the function as this:
Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {

And yet you then try and call it like this:
onSignalSound();

Spot the mismatch?
I suspect you don't want to be calling that function there since it seems to be in a bit where the sound has already been started.

not sure how i missed that, I had it commented out earlier


text:
is it possible to power esp8266 with button cell
is it possible to power esp8266 wifi module with button cell for long period(1 year ) real time applications??
 Needs only wifi features (no need of gpio)
what will be voltage and current of the cell??

This is worth a watch.

No. It has to wake up to do something and turn on the wifi. At that moment it requires too much power for a button cell. It needs about 150mA, mostly for wifi.
The BLE (Bluetooth Low Energy) is specifically designed for low power usage. Also some RF modules (433MHz, 868MHz, 915MHz) can be used with a small battery.

can you suggest an alternative for this problem

I agree it won't have the best lifespan, certainly not a year, but  the math shown is likely pessimistic. 150ma is on the high-end of estimations, especially for modules with the newer antenna and not far from the router. Also, those hi-energy pulses only last a ms or two; the avg draw on a short run is closer to 50ma. OP: 2 parallel coin cells can provide twice as much current, which solves potential early-shut-down issues, but not the short-lifespan ones...


text:
Toggle a led with a switch
My code:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

bool buttonState = 0;         // variable for reading the pushbutton status
bool ledState = 0;
void setup() {
  pinMode(ledPin, OUTPUT);   // initialize the LED pin as an output:
  pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}
void loop() {
  buttonState = digitalRead(buttonPin);// read the state of the pushbutton value:
  if (buttonState == HIGH)
 {
  ledState = !ledState;
 }
  if (ledState == HIGH)
 {
   digitalWrite(ledPin, HIGH); // turn LED on:
 }
   else
 {
    digitalWrite(ledPin, LOW); // turn LED off:
 }
}

So this is supposed to toggle a led's light on and off. currently it does do that but its not always the case. Currently, if the button is pressed on the arduino board, it has a 50-50 chance of changing its state. What part of the code is leading to this outcome?

Do you have a pullup (or pulldown) resistor on your button? If not, then use pinMode(buttonPin, INPUT_PULLUP); then invert button logic, i.e. value is LOW when pushed and HIGH otherwise.

In addition to the debouncing suggested by the other answers, you have a further problem: your loop() will whiz through in a very short time, and run again while your finger is still on the button, turning the light off.  And then run again, turning it back on again, and so on.
You need to wait for the button to be released before registering another change.
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

bool ledState = 0;

void setup() {
  pinMode(ledPin, OUTPUT);   // initialize the LED pin as an output:
  pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}

void loop() {
  bool buttonState = digitalRead(buttonPin);// read the state of the pushbutton value:
  if (buttonState == HIGH)
  {
    // Poor-man's debounce. There are much better ways of doing this!
    delay(20);

    ledState = !ledState;
    if (ledState == HIGH)
    {
      digitalWrite(ledPin, HIGH); // turn LED on:
    }
    else
    {
      digitalWrite(ledPin, LOW); // turn LED off:
    }

    // Wait for the button to be released
    while (digitalRead(buttonPin)) {}

    // Poor-man's debounce. There are much better ways of doing this!
    delay(20);
}

If you're connecting the button from pin 2 to ground and not using an external pull-up, it can lead to trouble. Either use an external pull-up or set the internal one:
pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input:

Also, you need to debounce the button.

The mechanical switches bounces. That's all. It's too fast for you to see it but MCU is much faster, so output state is switched many times before contacts are stabilized and no more bounces are causing "turning on and off".
The term you are looking for is debouncing

So how may I be able to stop this debounce? is it something I must change from software or Hardware?

If you look for the term debouncing (I don't know, maybe on google), you'll found out there are several ways how to do it. Usual way is "confirmation" of state after about 10ms.

@Utsav Or in this case you can add delay(50) and mentioned INPUT_PULLUP if you don't have external one and it should work just fine


text:
Purpose of capacitors in this project
I'm currently working on a project where I am making a wheeled robot using the Hack-e-bot library on the arduino. The circuit board which I have planned to put together through soldering will eventually look similar to this:

Here is a schematic:
I understand my circuit quite well but my mentor recommended using a capacitor for this and although I have got it on my schematic, I've never actually worked with capacitors before. Why should they be used in this project?

Using a capacitor for what purpose???

From the schematic, it seems to be a decoupling capacitor.

C1 is connected to Vcc and GND of the microcontroller, but it is hard to see. Since motors are used, an extra larger capacitor might reduce the noise and voltage dips caused by the motors. @Utsav, could you redraw the schematic ? Use GND symbols and put them at the bottom; don't try to make the picture small; If possible, keep the VCC in the top; Put labels for the pins of J1 and J2; Write the values for the capacitors and resistors; Write the type/name of the microcontroller in the schematic; A good schematic shows clearly the path of the sensor signals via the microcontroller to the motors.

I am assuming by the wording of the question that you are being advised to add another capacitor somewhere in your circuit in addition to the existing one? It's hard to know, since you are saying you have been advised to add a capacitor, yet your circuit already has a capacitor...  Also, I really pity D1's chances in life...

Oh, and "here's a random picture of a circuit board, and here's a plate of spaghetti" doesn't really help us much. I am not sure what you hoped to achieve by showing us some other circuit board, and you really need to read a few tutorials on how to lay out a schematic properly so that people can read it (though kudos for not making us suffer another Fritzing doodle...)

@Majenko sorry but I'm no expert at this, I tried to make sense, but guess not. I'll make sure I learn from my mistakes here and will try not to repeat them again! :)

Are you asking what the purpose of C1 is in your schematic, or are you asking about an additional capacitor somewhere else?

@Majenko I am asking what the purpose of C1 is in my schematic yes. But as Edgar pointed out this might be a decoupling capacitor?

Yes, that is what it is. But your schematic is lacking the required resistor inline with the LED "D1", without which you will either burn out your LED or make the circuit malfunction through clamping of the battery voltage.

See The care and feeding of LEDs

No. R2 is an LDR which is half of a voltage divider with R1. Nothing to do with the LED.

@Majenko wow yeah nevermind I noticed that too, I'll make sure to add a resistor inline with D1. Thank you

A capacitor is a device that can store (and release) charge. It is made up of 2 metallic electrodes (or plates) that are separated by a thin dielectric material.

When you apply a voltage over the two plates, an electric field is created. Positive charge will collect on one plate and negative charge on the other. - build-electronic-circuits.com

In short, a capacitor lets the AC component through and blocks the DC component.

Capacitors can be used in the following ways:
Decoupling Capacitors
(Also called Bypass capacitors)

A decoupling capacitor’s job is to supress high-frequency noise in power supply signals. They take tiny voltage ripples, which could otherwise be harmful to delicate ICs, out of the voltage supply.

Image reference http://www.seattlerobotics.org/encoder/jun97/basics.html

In a way, decoupling capacitors act as a very small, local power supply for ICs (almost like an uninterupptable power supply is to computers). If the power supply very temporarily drops its voltage (which is actually pretty common, especially when the circuit it’s powering is constantly switching its load requirements), a decoupling capacitor can briefly supply power at the correct voltage. This is why these capacitors are also called bypass caps; they can temporarily act as a power source, bypassing the power supply.
Decoupling capacitors connect between the power source (5V, 3.3V, etc.) and ground. It’s not uncommon to use two or more different-valued, even different types of capacitors to bypass the power supply, because some capacitor values will be better than others at filtering out certain frequencies of noise.
  - sparkfun.com

Power Supply Filtering
DC power supplies can be quite noisy on their own. Take the output of a bridge rectifier for example, there is a lot of ripple on the output. Capacitors are a perfect solution for reducing the ripple/noise of power supplies.

Image Reference: http://www.electronics-tutorials.ws/diode/diode_6.html

Capacitors are stubborn components, they’ll always try to resist sudden changes in voltage. The filter capacitor will charge up as the rectified voltage increases. When the rectified voltage coming into the cap starts its rapid decline, the capacitor will access its bank of stored energy, and it’ll discharge very slowly, supplying energy to the load. The capacitor shouldn’t fully discharge before the input rectified signal starts to increase again, recharging the cap. This dance plays out many times a second, over-and-over as long as the power supply is in use.

Also see Keelan's answer over at electronics stack exchange.
Signal Filtering

You can also combine capacitors and resistors to form filters that target specific frequencies. - build-electronic-circuits.com
They can block out low-frequency or DC signal-components while allowing higher frequencies to pass right through. They’re like a bouncer at a very exclusive club for high frequencies only. - sparkfun.com
For example in an audio system you can target the high frequencies to remove them (e.g. in a sub-woofer). This is called a low-pass filter.  - build-electronic-circuits.com

Image Reference: Wikipedia

Back to your application.
Motors are notoriously noisy. Your mentor has recommended a capacitor to decouple the noise of the motors and protect the IC from voltage drops/spikes.
Side note: D1 in your schematic is a power indication LED. It needs a current limiting resistor in series with the LED to limit the current and prevent the LED from burning out.

Resources:

https://learn.sparkfun.com/tutorials/capacitors
https://www.build-electronic-circuits.com/how-does-a-capacitor-work/
Basic Circuits - Bypass Capacitors
wikipedia.org/wiki/Capacitor
wikipedia.org/wiki/Decoupling_capacitor
Youtube - How a Capacitor Works - by Dr. Oliver Winn
explainthatstuff.com/capacitors

Based on the schematic shown, the capacitor acts as a decoupling or smoothing capacitor. When the circuit components such as a motor require a sudden source or produce a sudden spike of energy, this would help filter out the noise and balance the power line.
More info regarding decoupling capacitor may be found on wikipedia here.


text:
2 buttons pressed at the same time elevator logic
I have currently created a working elevator code where the elevator goes up when pressed a button, and stops at a floor when the sensor senses that it has reached the floor. This is how it works:
#define Buzzer 5

#define pwmMot 6

#define halPin 8

#define butto1 9  //level 1
#define butto2 10 //level 2
#define butto3 11 //level 3

#define SeEcho 12
#define SeTrig 13

int button1_status = 0;
int button2_status = 0;
int button3_status = 0;

int current_level = 1;
int required_level =-1;

void setup(){
  Serial.begin(9600);
  pinMode(Buzzer, OUTPUT);
  digitalWrite(Buzzer, HIGH);
  pinMode(halPin, INPUT);
  pinMode(butto1, INPUT);
  pinMode(butto2, INPUT);
  pinMode(butto3, INPUT);
  pinMode(SeTrig, OUTPUT);
  pinMode(SeEcho, INPUT);
  pinMode(pwmMot, OUTPUT);
  Serial.println("you are in level 1");
}

void emergencyStop(){
  analogWrite(pwmMot, 255);
}
int sensor() {
  unsigned long duration;
  int distance;
  digitalWrite(SeTrig, LOW);
  delayMicroseconds(2);
  digitalWrite(SeTrig, HIGH);
  delayMicroseconds(5);
  digitalWrite(SeTrig,LOW);
  duration = pulseIn(SeEcho,HIGH);
  distance = int(duration/2/29.412);
  return distance;
}

bool hallSen(){
  return digitalRead(halPin);
}

int going_up(){
  while (sensor() > 12){
    analogWrite(pwmMot, 1600);
  }
  return 1;
}

int going_down(){
  while (sensor() > 12){
    analogWrite(pwmMot, 570);
  }
  return 1;
}

void loop() {
  button1_status = digitalRead(butto1);
  button2_status = digitalRead(butto2);
  button3_status = digitalRead(butto3);
  required_level = button1_status == HIGH ? 1 : button2_status == HIGH ? 2 : button3_status == HIGH ? 3 : -1;
  if (required_level != -1 && required_level != current_level){
    while (current_level != required_level){
      if (current_level > required_level) Serial.println("Going Down"), current_level-=going_down();
      else if (current_level< required_level) Serial.println("Going Up"), current_level+=going_up();
      Serial.print("you are in level "); Serial.println(current_level);
      delay(1000);
    }
    analogWrite(pwmMot, 1550); //stop elevator
    digitalWrite(Buzzer, LOW);
    delay(100);
    digitalWrite(Buzzer, HIGH);
    required_level = -1;
  }
}

Now I am just curious as to how I will extend this so that for example if we are in level 1, both the levels 2 and 3 are pressed it should go to level 2 even if level 3 was pressed first. Or if we are in level 2 and both level 1 and 3 are pressed, it should go to the one that is pressed first as both levels are the same distance from level 2.

when you are at floor 1 you can't just jump to floor 3 you have to pass level 2 first, if you have a sensor there you can simply do something like if button2 = high && sensor2 = high {do that} else... i see a state machine in your future!

definitely a state machine

@newbie use == instead of =

@MichelKeijzers right, i was just demonstrating...

there is no such thing as a "two buttons pressed" scenario as far as the microcontroller is concerned ... the microcontroller checks the buttons sequentially ... that means you have one of two scenarios

if we are in level 1, both the levels 2 and 3 are pressed it should go
  to level 2 even if level 3 was pressed first.

For this to work, the program should remember which buttons (mind the
plural!) have been pressed. Thus, instead of remembering only one
request, as in
int required_level =-1;

it should have a boolean variable for each of the possible levels,
telling us whether a stop was requested for that level.
For convenience, I would number the levels from zero, and hold these
variables in an array:
const int LEVEL_COUNT = 3;
bool requested_stop[LEVEL_COUNT];

if we are in level 2 and both level 1 and 3 are pressed, it should go
  to the one that is pressed first as both levels are the same distance
  from level 2.

The part I emphasized doesn't make sense to me. The elevator should go
to the one that was pressed first, irrespective of the distances.
Imagine you are in an elevator at level 5, and press the button for
level 2. As the elevator just starts moving down, another rider presses
the button for level 6. Should the elevator immediately revert to going
up in order to reach level 6, which is closer? Of course not. If it is
going down, it should continue in that direction. Now, if the other
rider presses 3, it should stop by level 3 on its way down, even though
you pressed 2 first.
As stated by chrisl in a comment, a finite state machine is
definitely the solution for this kind of problems. I propose a state
machine with three states, STOPPED, GOING_UP, and GOING_DOWN:

when STOPPED, it should change to GOING_UP or GOING_DOWN as soon
as a button for another level is pressed
when GOING_UP, as soon as it reaches a level that has been
requested, it should change to STOPPED
same thing when GOING_DOWN.

And here is my proposed implementation:
void loop() {
    // Check the buttons.
    for (int i = 0; i < LEVEL_COUNT; i++)
        if (digitalRead(button[i]) == HIGH)
            requested_stop[i] = true;

    // Finite state machine.
    static enum { STOPPED, GOING_UP, GOING_DOWN } state = STOPPED;
    switch (state) {
    case STOPPED:
        requested_stop[current_level] = false;
        for (int i = 0; i < LEVEL_COUNT; i++) {
            if (requested_stop[i]) {
                if (i < current_level) {
                    analogWrite(pwmMot, PWM_DOWN);
                    state = GOING_DOWN;
                    break;
                } else if (i > current_level) {
                    analogWrite(pwmMot, PWM_UP);
                    state = GOING_UP;
                    break;
                }
            }
        }
        break;
    case GOING_UP:
        if (elevator_height() >= LEVEL_HEIGHT[current_level + 1]) {
            current_level++;
            if (requested_stop[current_level]) {
                analogWrite(pwmMot, PWM_STOP);
                state = STOPPED;
            }
        }
        break;
    case GOING_DOWN:
        if (elevator_height() <= LEVEL_HEIGHT[current_level - 1]) {
            current_level--;
            if (requested_stop[current_level]) {
                analogWrite(pwmMot, PWM_STOP);
                state = STOPPED;
            }
        }
        break;
    }
}

This code assumes you have written the function elevator_height() that
measures the height of the elevator, and have defined an array of
constants LEVEL_HEIGHT[].
Notice that this is still far from perfect. You should probably ensure
that each stop lasts at least some minimum duration. Otherwise, if the
elevator stops at level 1 while level 0 has also been requested, the
stop will only last an instant. This can be achieved by splitting the
STOPPED state in two distinct states, and switching from “waiting for
the riders to go in/out” to “waiting for a button to be pressed” on a
timeout. You may also want to ensure that, after a stop, the elevator
continues in the same direction if possible. Otherwise it will never
reach level 2 if some joker is repeatedly pressing 0 and 1.

There is a sensor in the elevator and a sensor in each level so instead of the level height logic (we dont have the required sensor to measure the level height) cant we say if elevator sensor matches level sensor and button pressed there then stop?

@Utsav: Yes. You would just have to replace the condition elevator_height() >= LEVEL_HEIGHT[current_level+1] by elevator_is_sensed_at_level(current_level+1). And similarly for the test for current_level-1.


text:
Powering arduino and sensors and motor damaging 16x2 LCD?
I have an application that requires reading sensors and moving a stepper motor.
The sensors draw about 200mA between them, and need 5V to work. (Too much to draw through the Arduino, I thought) The stepper is recommended to run off 12V, and is driven through a BigEasy board. And, of course, the Arduino needs 5V.
My actual setup has an old laptop power brick, which puts out nominally 12V. This is fed into a voltage regulator (one of the cheap ones with a voltmeter built in) which outputs a steady 5V, even if the input voltage changes a bit. So, I've got a reasonable 12V supply and a fairly fixed 5V supply.
From the 5V supply, I run wiring to the sensors, and from the 12V supply I wire the stepper driver.
The thing is, to power the Arduino, I thought I could just wire up a USB socket (only the power lines) and wire the USB socket to the 5V regulated output. Then I could either plug my arduino into my computer to program it, or plug it into the dummy usb socket to power it standalone.
This arrangement seemed to work for a while, but I've noticed strange behaviour with the 2x16 LCD board which is also attached. I should point out that the LCD takes it's power from the regulated 5V, not from the 5V rail of the Arduino, although the data lines go to the Arduino. The LCD has gone into a "lock-down" mode whereby it only displays half blocks on the top line and nothing else.
I'm wondering if it could be related to effectively powering the system with 2 supplies; one for the majority of the load through the old laptop power brick, and the Arduino through the USB port of my (also laptop) PC. Somewhere along the line, ground get connected to ground, but are all grounds equal?
Is there a standard solution for having the Arduino plugged into your development PC (so as to get debug messages through the Serial COM monitor) whilst still be able to safely power the high-draw loads of the rest of the system. I did consider powering the Arduino through it's barrel jack, but then I'll need an additional 7V supply. (The 5V regulated supply would be too much, and the 12V "semi-regulated" supply would be too much).
And can I do something to protect the next LCD that I use? (Stick a 5.2V Zener across the power pins to prevent spikes??)

Could you please post a picture of your setup. 2. Have you used bypass caps? 3. Are you sure that there isnt some loose connection between the LCD and the arduino?

Well, it's a bit of a rats nest, to be honest. As well as the sensors there are also some button boards, some peripheral boards with LEDs etc, All of which need 5V. I'm not sure a photo will be that useful. 2. No, I haven't done this yet. But when I test the LCD on another Arduino without any other attachments, it still doesn't work. I'm wondering if the LCD panel is permanently broken. 3. I've tried connecting to another arduino, still no luck. The thing is; are LCD boards sensitive to voltage spikes or reverse polarity.

In that case please upload the schematics. Have a look at http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino/ for some general info on protecting your circuit

I thought I could just wire up a USB socket (only the power lines) and wire the USB socket to the 5V regulated output. This sounds like a round-about way of doing it. Just plug the 5V regulated output into the 5V pin on the Arduino board. Make sure you have all the grounds connected.

If I simultaneously connect the Arduino to my laptop (to program it and see the serial messages) and connect 5V from the regulated supply to the Arduino 5V pin (and regulated ground to GND), aren't I effectively connecting the regulated supply to the laptop regulated supply? What happens if there is 4.9V on one and 5.1V on the other?

In some instances, it is a known issue that certain LCD's pull more power from the arduino than is sustainable depending on the power source.
A few suggestions:
Put something like a 100-200 ohm resister in the 5V to the LCD and connect just that and GND, then measure the voltage drop across said resister.  That will give you the current with ohms law, if its much more than 4mA its a faulty LCD or a fault in your wiring.
You should also check the pins for continuity errors, or shorts.
Another idea, is to make sure the voltage, and amperage coming from the 5vdc step down you are using is adequate for the task at hand.
And finally, you'll need to calculate the complete pull on your power source. i.e. you'll need to know how much load your bigeasy driver pulling from the 12vdc power supply, as well as how much your 5v stepdown is using. if they are exceeding the output of the PSU, you can run into issues.
I ran into a similar issue with my own project, using an arduino Uno with grbl + 3x easydriver motor controllers, & mega 2560 + lcdkeypad shield. Powering the easydrivers with 12vdc & using a voltage stepdown module also gave me issues, as it didn't provide enough current for the stepper motor drivers and the LCD + mega + uno from the 5vdc. I was overloading the power supply, and the 5v wasn't producing the correct power requirements.
I bought a better power supply that had 24, 12, 7, and 5v on it, and haven't had an issue since.


text:
Atmega328 board output voltage
I'm thinking about making my own "arduino" low power board but I have a question about the atmega328. Is the output voltage on the pins always 5v or it depends on the input voltage I gave to the atmega?
Thanks in advance.

What Majenko said. | Note that 'rolling your own' for experience and/or fun is fine BUT you can buy good quality Chinese made clones for less than the cost of the components.

@RussellMcMahon Yes, but the original and clones draw too much energy, I need something more simple that can save energy for a battery powered project. Thanks for the note anyways (:

The clones draw > minimum power only due to extra components on them Versions with no USB/serial IC are available (and even cheper) = Pro Mini. And regulator can be removed if safe Vcc can be provided. And onboard LED drive is optional. If desired all you have left is ~= uC IC and cryctal osc and current can be in the few microamps when doing nothing and not vastly more when crawling along with all or most peripherals off. There is a very good 'how to reduce '328 current draw article somewhere. Probably cited in this group and I can probably did it up.

Well, an atmega328p can run on its own internal oscillator to save even more power.. And you can integrate it directly on the board rather than using connectors, so it's more "professional"/smaller. It depends on the needs

It depends on the input voltage you give it.  If you run the ATMega328p at 3.3V then you get 3.3V out.  If you run it at 5V you get 5V out.
A word of caution about running at lower voltages:  The chip can't run as fast when it has a lower supply voltage - that's why you will see the 3.3V Arduino boards running at 8MHz (or 12MHz at a pinch).

Thanks very very very much. That's exactly what I needed to know (:


text:
LCD Shield and Arduino
I am trying to use a load cell (https://www.sparkfun.com/products/13331?_ga=1.55586472.2060096590.1479826091) and an HX711 chip with an arduino and LCD shield to display weight values on the LCD shield  when weight is added to the load cell. Does anyone know how I can connect all of these together?
Mainly, how do I connect the HX711 to the arduino while the LCD shield is already on the arduino?
Any help is welcomed , thanks.
Here is the LCD shield I am using I am using:
LCD Shield- https://www.dfrobot.com/index.php?route=product/product&product_id=51
Arduino- not sure which type of arduino to use.

You need to do a bit more research on your own. That load cell + HX711 is just a sensor and it connects to the Arduino in a way that many sensors do. Use Google to find projects like a thermometer with LCD readout and see how the sensor is connected there. Also research the differences (and commonalities) between the Arduino boards, that information can easily be found.

Note: While looking at specifications can infer compatibility, there is no substitute for prototyping.  It is always better to try something then ask for suggestions if it does not work as expected.
That said, I would suggest to look at the LCD you specified.  The LCD's physical shape appears to lock you into a legacy Arduino Uno layout.
On the LCD's web page is a list of pins used.
On the HX711 sparkfun.com web page is a diagram of pins used when using their HX711 software.
Check if there are any conflicts.  Even if there are none, it does not mean there will be no conflicts within the software you will need to run the LCD and the HX711.  You will have to either find someone who has successfully done exactly what you want to do or examine all the software involved your self.  Of course you could simply prototype the project to see if it works.

thank you for the feedback. I have been looking at this video on youtube (https://www.youtube.com/watch?v=6pzZ0NfQmsY) and it is exactly what I am trying to build however I cannot tell what he is using to connect his HX711 to the arduino. It appears the LCD shield is attached on top on the arduino, but I cannot see where the white wire to the arduino is connected. Any ideas?

He does not say, does he?  He does not even list his software - as there are youtube comments asking for it.  So it is not a good source of information.  Until you are more familiar with working with Arduinos, you should probably find reputable sources which publish good documentation and answer questions by email or in forums. I would suggest looking more closely at the link in the answer.  I believe if you do you will find not only where to connect the sensor but also where to get the software for the sensor.

It is fairly straight forward.

Read the data sheet to find out how you can communicate to hx711. There are tons of example code out there. I have a set of them for my own use as well. The device is quite simple to program too.
Find a few pins on the Arduino and configure your code, or others code, to use those pins.
I corporate that into your existing code.

That's like how you would approach 99.99 percent of the embedded project - read the data sheet and Code to the data sheet.
If you do run into specific issues, ask them here.


text:
How to control a DC motor via Arduino Uno as a slave and Mega 2560 as master?
Hi I want to control a DC motor using Arduino mega2560 and Arduino Uno as a slave. Mega have to process data from an ultrasonic sensor(measuring distance) and control the motor based on the input. I tried to google but couldn't find a better tutorial or code. I'm using Adafruit motor shield l293d. I have the idea about the wiring part just need a simple code.
Eg:

 if( distance < 20) {
   //send signal to slave to run the motor forward
 }else {
   //send signal to slave to stop the motor
 }

You might look at i2c communication examples, and motor shield examples.  Note that the older L293 based shields are very lossy compared to newer v2 shields with the TB6612FNG FET driver.  There's also no apparent reason in your question to use two distinct Arduinos for this - it would be farsimpler to use the Uno for everything.

I2C, SPI, UART, ... There are tons of protocols. UART is the simplest, but you won't be able to use the USB port (and so even program it) of the UNO without detaching the MEGA. The MEGA, OTOH, has several HW UART. The I2C is a bit more complicated, but not so much. You will be able to further expand the network in the future. The SPI is the fastest, but requires more wires (4, rather than 1 or 2). The UART will enable you to send back data from the UNO to the MEGA too, while I2C and SPI will require the MEGA to ask the UNO for information if you need to transfer back some data...

Serial is quite easy to implement and use the SoftSerial.
Example code for serial can be found in the Arduino IDE under the menu:
File | Examples | 04. Communication

Serial is arguably harder to implement between programs, because you don't have the natural message delineation of something like I2C or SPI.  Software serial also complicates other processor operations.


text:
SIM800L is not registering on network
I'm testing SIM800L module by registering to network manually and I'm getting an error message.
Here are the commands I tried.
AT+CSQ

+CSQ: 31,0

OK

AT+CBAND?

+CBAND: EGSM_MODE,ALL_BAND

OK

AT+COPS=?

+COPS: (1,"Bharat Karnataka","CellOne","40471"),(2,"Airtel","AIRTEL","40445"),(3,"Hutch-Kamataka","HUTCH","40486"),,(0-4),(0-2)

OK

AT+COPS=1,1,"40471"

ERROR

AT+COPS=1,1,"40471"  is this command right? My
SIM card is CellOne and it's 4G.
Power supply -7.4 li-ion 1100mAh battery with an adjustable 5V-5A buck converter(3.8v is supplied to SIM800L)

For the AT+COPS command you are setting manual with long alphanumeric network name but then using the numeric network name. Try AT+COPS=1,2,"40471"
REF
//Manually select T-mobile as carrier using short format alphanumeric network name
AT+COPS=1,0,"TMO"

//Manually select T-mobile as carrier using long format alphanumeric network name
AT+COPS=1,1,"T-Mobile USA"

//Manually select T-mobile as carrier using numeric network name
AT+COPS=1,2,"310260"

AT+CSQ checks the signal strength, you can check the reply range with a question mark,
AT+CSQ=?

+CSQ: (0-31,99),(0-7,99)

OK

The first number, 31, shows you have a good signal strength locally.

AT+CBAND? shows the mobile operating band set

AT+COPS=? will search for networks, your response indicates you found a few.


text:
How to connect L298N motor driver to 5v input supply?
I'm trying to connect 5v supply to a L298N motor driver at it's 12V-35V input pin but it's not working. If I'm connecting to 7.2V supply it's working. Is there any way to connect 5v supply? I want a constant 5v at output pins for motors.

You are either not telling us something or making someting up. Did you remember to supply 5V logic power to your L298N board? What do you have connected to "5V" terminal of L298N?

Without looking at the L298N dtatasheet, connecting 5V to an input labeled with 12V-35V seems not to be a good idea.

Short answer: Don't. A 12V-35V input pin needs to be supplied with... wait for it... 12V to 35V. A 5V supply won't be enough.

@Duncan C: Not true. As far as the pure motor power is concerned, the VIN terminal (aka 12V-35V terminal) is just a passive switched terminal. It can be supplied with any voltage the motor requires (as long as it doesn't cross the upper limit). 5V is perfectly fine, if that's what the motor needs. The only case when the lower voltage limit applies on the VIN terminal is when one plans to use the board's built-in linear regulator to obtain 5V logic supply from it. In that case one has to consider the voltage drop (around 2V), meaning that VIN should be at least 7V.

In fact, I have no idea who and why came up with the bizarre idea to label that terminal as 12V-35V. In newer boards it is simply labelled VIN. 12V-35V label makes no sense whatsoever. Apparently someone simply assumed that no one will ever want to use a lower voltage motor. I see conflicting information on the logic supply voltage though. Some sources say 7V, others: 5V. In practice the boards I tried work perfectly fine with 5V logic supply.

Note: Since all vendors (checked Mouser, Octopart, and Sparkfun) link to the L298 datasheet when listing the L298N I will assume they are reasonably equivalent.
I will assume that the "12V-35V input pin" is the V_S pin, despite that label. There are only two supply pins on the L298 with the following electrical characteristics:

V_S, Supply Voltage, pin 4, Operative Condition V_IH + 2.546V (max.: 46V)
V_SS, Logic Supply Voltage, pin 9, typical 5V (min.: 4.5V, max.: 7V)

with

V_IH, Input High Voltage, ranging from 2.3V to V_SS

Which would explain that the circuit works at 7.2V under the assumption that the logic inputs (enable A and B as well as inputs 1 through 4) are at close to 5V high levels. And here's the trick that might make it work: as noted V_S (the supply voltage) needs to be at a level of V_IH + 2.546V while V_IH could be as low as 2.3V and 2.3V + 2.546V < 5V. So driving the L298's logic inputs with a lower voltage for logic 1, i.e. closer to 2.3V high levels, could help.
Why is this? (source):

[..] The actual restriction is that the motor supply be somewhat greater than the logic "1" input, but that need not match the logic supply. [..]

A warning though:

this circuit is now operating at the fringes, one might call it shady at best, intolerable at worst
saturation voltage is related to output current and other parameters, e.g. temperature, so this might work now under certain conditions and fails horribly another day

Therefore better bets are:

use a higher supply voltage
ditch the L298 and its high voltage drop Darlingtons and use a MOSFET H-bridge motor driver, such as the TB6612FNG, see also
ditch the L298 and use single bipolar transistors, depending on the output current

Other things to check:
Make sure V_SS is connected to the logic supply voltage (see AnT's comment). Make sure GND of the Arduino's power supply is connected to the L298's GND.


text:
How many Ultrasonic sensors can be connected to an Arduino Uno R3?
How many Ultrasonic sensors (HC SR04 ) can be connected to an Arduino Uno R3 board?

As many as you like, but at some point you run out of pins to connect them.

You can make all your ECHO pins Open Drain by adding an N-channel MOSFET or NPN BJT, add a pullup to an input, and then have all your SR04's echoing to the same pin. Since you can really only trigger one at a time anyway you know which one the echo must be coming from even though they're all on the same pin. Note that this would invert the echo signal, so change your pulseIn() to compensate.

I am working on a project where I am using 6 sonar sensors in one Arduino Uno !

If you look into any example sketch, like this from sparkfun:
/**
 * HC-SR04 Demo
 * Demonstration of the HC-SR04 Ultrasonic Sensor
 * Date: August 3, 2016
 *
 * Description:
 *  Connect the ultrasonic sensor to the Arduino as per the
 *  hardware connections below. Run the sketch and open a serial
 *  monitor. The distance read from the sensor will be displayed
 *  in centimeters and inches.
 *
 * Hardware Connections:
 *  Arduino | HC-SR04
 *  -------------------
 *    5V    |   VCC
 *    7     |   Trig
 *    8     |   Echo
 *    GND   |   GND
 *
 * License:
 *  Public Domain
 */

// Pins
const int TRIG_PIN = 7;
const int ECHO_PIN = 8;

// Anything over 400 cm (23200 us pulse) is "out of range"
const unsigned int MAX_DIST = 23200;

void setup() {

  // The Trigger pin will tell the sensor to range find
  pinMode(TRIG_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);

  // We'll use the serial monitor to view the sensor output
  Serial.begin(9600);
}

void loop() {

  unsigned long t1;
  unsigned long t2;
  unsigned long pulse_width;
  float cm;
  float inches;

  // Hold the trigger pin high for at least 10 us
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Wait for pulse on echo pin
  while ( digitalRead(ECHO_PIN) == 0 );

  // Measure how long the echo pin was held high (pulse width)
  // Note: the micros() counter will overflow after ~70 min
  t1 = micros();
  while ( digitalRead(ECHO_PIN) == 1);
  t2 = micros();
  pulse_width = t2 - t1;

  // Calculate distance in centimeters and inches. The constants
  // are found in the datasheet, and calculated from the assumed speed
  //of sound in air at sea level (~340 m/s).
  cm = pulse_width / 58.0;
  inches = pulse_width / 148.0;

  // Print out results
  if ( pulse_width > MAX_DIST ) {
    Serial.println("Out of range");
  } else {
    Serial.print(cm);
    Serial.print(" cm \t");
    Serial.print(inches);
    Serial.println(" in");
  }

  // Wait at least 60ms before next measurement
  delay(60);
}

You can see it is used only two pins. So, as long as you can provide power to sensors and pins to it, you can have as much as you like. You can even expand with more IO pins using other electronics or go into some kind of multiplexing.


text:
Remote Wireless Tripwire
I've had an idea for an Arduino project, but I'm not sure where to start. My idea is this: have an Arduino Nano connected to an HC-SR04 ultrasonic sensor, as well as an nRF24L01+ radio. This will be the tripwire module, which will send an alert to a second Arduino (connected to another nRF24L01+ of course) whenever something passes by.
This wouldn't be a stationary unit, it would need to be able to be placed and sense in a variety of locations so the distance would need to be set on power up.
Another issue I'm running into is getting the nRF24L01+ units to work for this purpose. I want to know that the units are wirelessly connected, so having a packet sent every second or so lets the receiving unit know that they're connected, and an additional packet for the tripwire trigger sets off an indicator led.
Is this even possible?

You might find a pir sensor cheaper on $$ and power consumption if battery powered.

Welcome to Arduino StackExchange! This sounds like multiple questions to me. The only real question there: "Is this even possible?" would have the answer: Yes. If possible, reword it to fit more into the question-and-answer format that StackExchange uses.

This sounds very doable. The first point, tuning the distance threshold at startup, could be done with a bank of DIP switches or a potentiometer on an analog pin to set the value. You might include some startup code continuously pings the transducer and displays the result on an LED, until you press a button to tell it "use this".
The second, is a very typical communication technique - sending "hello" packets periodically to confirm that communication is up. In your case, the same packet could carry a hit/no-hit bit within it.

It would be easier and faster just to send triggered/not triggered status every second.

Just have it trigger, whenever the distance changes by more than x amount. That way there is no need to initialize, and it would also update if the surroundings change (e.g. someone places a trashcan in the path of the sensor) and doesn't just dumbly report a trigger all the time (instead of only when someone passes in front of the trashcan in the example).


text:
Cost-effective storage for prototyping
In my project I need to add some storage space and I don't want to use an SD card, because in the "final product" the user shouldn't be able to access the data on their own.
So I was considering the options here http://playground.arduino.cc/Main/InterfacingWithHardware#Storage but many of the technologies are either outdated, for example as reads here ADESTO is discontinuing production of dataflash, or they give too little memory, like the I2C EEPROM (which is 128KByte per chip and I would rather not go through the hassle of multiplexing lots of memory chips since I'd like to have 1MByte of storage at least), or are extremely overpriced and cannot be found on retail: some sites require you to buy 2000$ worth of chips or charge you 30$ for delivery, which kind of kills the fun of prototyping something.
I know I am being picky not wanting to use an SD for the prototype, but I would like to know if you ever faced this problem and how you solved it, or if you know some alternative solution which gives a good amount of memory (~1 or 2 MBytes at least) within reasonable costs.

Don't provide a slot in the casing to remove the SD card?  Once you use a standard memory technology in a discrete package, it is readable by someone who bothers to open the casing, though I suppose a soldered surface mount SPI flash less readily so than a socketed micro SD card.  Ultimately, you should think carefully about the wisdom of trying to prevent access, and if it is truly necessary your only real choice is to encrypt the data stored.

Yes, I guess that there will always be someone smart enough to be able to pry the device open and read/edit the memory content by himself if I don't encrypt the data. I'm slowly thinking that I might as well go for an SD and if I ever manage to build the final product I'll think of a way to deal with that.

Provided you only need a few megabytes you should be able to switch from a micro SD card in mmc mode on your prototype to a smaller, cheaper, more reliable soldered SPI flash by slighty changing your board and replacing the mmc SPI operation code with the far simpler steps needed to access an SPI flash.

You may not want to hear this, but the cheapest option would be an SD card, or a micro-SD card. You could solder it into place, thus making it quite hard for the end user to take it out and plug it into a reader.
Imagine you had this micro-SD card glued onto your board (making it hard to remove in the first place):

It isn't particularly obvious what it is, unless you recognize the shape. You could cover it with a blob of plastic to hide that. Then with the SPI wires soldered to the contacts, removing would be even harder.
That gives you gigabytes of storage, a file system, the works. And all for a few dollars.
A technically sophisticated user could probably prise it loose and get at the data (although if you used strong glue this could be quite hard) but they could also get at the contents of another storage chip too.

Well actually I didn't think that one could do that, so I guess this could become an option again, and yes, having the file system is definitely a big advantage! I'll consider it again, thank you!

Reflow Solder Your Micro SD to Ensure it Doesnt Go Anywhere

There are plenty of serial flash products available.  They are generally SPI chips (8 pin) and range in sizes up to about 64MBit (8MByte).  And they're cost effective.
Here's a selection: http://www.microchip.com/pagehandler/en-us/products/memory/flashmemory/sfhome.html
There are plenty of other manufacturers as well.  Your best bet is to hit your favourite online electronics store (mouser, digikey, etc) and shop around.

Thank you, I'll have a good look at these and try to find them in some store that does not charge me too much for the shipping (I live in Italy and mouser and digikey charge a lot so as I said in the post the shipping charges make the spi chips an expensive option)


text:
Arduino Uno with data logging shield has a problem switching power sources
I have the basic Adafruit "Light & Temperature data logger Tutorial kit" made, and it works well when connected to a PC, but when I unplug the PC USB connection and hook it up to another power source, it will not launch and run by itself. I have reset both the logger and Arduino board reset buttons, but it does not seem to start recording data to a new file. One of my power sources was a Solar panel / Solar Lithium Battery charger  (with the "Power Boost 500 basic 5V boost board, and an another alternate power source was a 6 x AA battery holder with a barrel jack connector. What am I missing here? I'm a newbie! Thanks.

what have you done to troubleshoot the problem?

Can you measure the right voltage at your power inputs? (9V at the barrel Jack vor 5V directly tied to the 5V-pin of the arduino)

I checked and changed to new AA batteries, and obtained 9V on the battery pack jack, and checked and obtained the 5V pin on the arduino also. The serial monitor will start showing data for a while on its own. When I come back and refresh the PC, it starts up again. I noticed that it had 6 readings initially, and then continued with reading number 20, 21, etc. The SD disk file however, did not show any additional of the missing readings!  I may have a program code issue (maybe?). (To "chrism" , and "jstotola").

My troubleshooting so far leads me to the likely issue of enough alternative power, and possibly the sketch feature that has to do with the "sync_interval" time before a number of readings is written to the disk. I had not appreciated this feature, and may have pulled out the SD to see what was recorded and lost a good number of readings.....AFAIK.


text:
Wiring parallel TFT with ESP32
I have this Parallel LCD TFT. I want to connect it with an ESP32 (NodeMCU). I am using the TFT_eSPI library.
In the TFT_eSPI documentation, it says that the connection should be as following:
// The ESP32 and TFT the pins used for testing are:
//#define TFT_CS   33  // Chip select control pin (library pulls permanently low
//#define TFT_DC   15  // Data Command control pin - use a pin in the range 0-31
//#define TFT_RST  32  // Reset pin, toggles on startup

//#define TFT_WR    4  // Write strobe control pin - use a pin in the range 0-31
//#define TFT_RD    2  // Read strobe control pin  - use a pin in the range 0-31
//#define TFT_D0   12  // Must use pins in the range 0-31 for the data bus
//#define TFT_D1   13  // so a single register write sets/clears all bits.
//#define TFT_D2   26  // Pins can be randomly assigned, this does not affect
//#define TFT_D3   25  // TFT screen update performance.
//#define TFT_D4   17
//#define TFT_D5   16
//#define TFT_D6   27
//#define TFT_D7   14

P.S. My tft does not have DC PIN. So, I wired nothing to GPIO15
After I wired the TFT, the ESP32 stop responding to flash process. and obviously, it did not run anything(even if I flash it without the screen and then wiring it again)
My question is:

What is the mistake did I do? How can I link this parallel LCD with ESP32

How did you wire the 5V pin of the display? When attached to an uno/mega2560 it gets power over this (and possibly the 3v3) pin.

DC is the same as RS (or LCD_RS on your board).

@LotPings External 5v power supply

Sorry for the Late reply, I had the same issue.
You cant have anything connected to pin 15 or 2 during flash


text:
ESP8266 and DHT22 frequent hangs
I have DHT22 sensor attached to an ESP8266. When running a sketch that read the sensor values, it suffer from frequent hangs (something like each 1 second).
All outputs are stopped (Sound from speaker or even the Serial output) during those hangs.
Here is a small Sketch to reproduce:
#include "DHT.h"
DHT dht(D1,DHT22);
void setup(){
  Serial.begin(115200);
}
void loop(){
  Serial.println(dht.readTemperature(true));
  Serial.println(dht.readHumidity());
  delay(1);
}

P.S. it is not about the small delay(1). Even if I read the sensor values each 1 second, this problem will occur. To make sure, you may run this example:
#include "DHT.h"
DHT dht(D1,DHT22);

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

unsigned long last = 0UL;
void loop(){
  if(millis() - last > 1000){
      Serial.println("#########" + String(dht.readTemperature(true)));
      Serial.println("#########" + String(dht.readHumidity()));
      last = millis();
  }
  Serial.println(String(rand()));
  delay(10);
}

After flashing it, opens serial monitor and you can see clearly the hangs (I put random number printing so your eyes can not cheat you by an cashed old value;) )

I have something with my nodemcu. Every day, at a random time, I get a shift in the values reported to thinger. Very odd, and I haven't got to the bottom of it yet.

@Majenko Does your setup also include a DHT22 with this library?

Certainly a dh22 though I don't know if it's the same library.

I just checked the library and it seems it disables all interrupts briefly while reading. That would explain the Serial (and other) blips, I think. It's not only blocking but also prevents others from interrupting it.

does it hang if you explicitly disable wifi (or use a brand-new ESP)?

@dandavis yes the same happens when WiFi was explicitly disabled

@TisteAndii Is this behavior the only way to make the library work? I mean should I accept it and go on. Or it could be done better?

@HumamHelfawi You can try this interrupt-driven library https://github.com/chaeplin/PietteTech_DHT-8266 and if it works, then make it an answer.


text:
Connecting LCD TFT shield to NodeMCU
I have the following screen:

I want to connect it to a NodeMCU device:

I read somewhere that it is not possible. However, I am not interested in the touch ability nor the SD card. I just want to draw something on the screen.
Is it possible to make the connection in somehow?

This is well possible. The TFT just has a SPI interface (SCLK, MISO, MOSI, CS) with additional DC and BL lines (DC = Data/Command, BL = no idea). You need a driver library for the LCD. What driver chip does it say it has? Do you have a buy link for the module?

The device appears to be this https://www.waveshare.com/wiki/2.8inch_TFT_Touch_Shield

BL = Back Light

The driver chip was identified by https://www.waveshare.com/wiki/2.8inch_TFT_Touch_Shield and https://www.waveshare.com/w/upload/8/84/2.8inch-TFT-Touch-Shield-UserManual-EN.pdf as being the HX8347D.
At https://github.com/jshnaidman/UTFT_ESP8266_HX8347D there seems to be a library, with which you can use the HX8347D display type to instantiate a UTFT object, with which you can draw. You can build upon this demo code.
The connections for the SPI interface are detailed here. BL (backlight) pin is detailed here. The pin number for the D/C pin must be given in the code in the constructor and can be chosen freely.
Other reference code (which you might have to port) are:

HX8347D by Majenko
Code from Watterott


text:
Using USB on a Leonardo to receive data from PC
I am new to the Leonardo, having only used a duemilanove before, and I am interested in using it's USB capabilities for a project.
Basically I need it to be an input and output device, communicating to an app on the PC (probably written in C#). I need to be able to handle button presses on the arduino and get data back from the PC to display on a display connected to the arduino.
I already have the basics done hardware wise (getting the keypad and displays working as I want them to), but now the tricky part is the USB communication. The only things I can find seem aimed at emulating a keyboard and mouse - I need 2 way communication data wise.
Are there any examples of something like this? I am sort of looking for the arduino equivalent of this: http://www.waitingforfriday.com/index.php/Building_a_PIC18F_USB_device
An alternative would be to just use serial, but I don't want to be fiddling with COM ports on the PC side - it just needs to be plugged in and work.
Would be grateful for any input on this subject, if it is even possible!

Congratulations, you've successfully found a project that goes beyond what the Arduino IDE provides for you out of the box. Your options are to 1) write a custom Arduino core that has additional/only the USB connections you need, or 2) do the same but with LUFA or ASF.

BytesGuy, from ArduinoBoardLeonardo at arduino.cc,  “on the Leonardo, the Serial class refers to USB (CDC) communication”.  That is, its Serial link is a USB link and does not involve any RS232-type serialization at either end of the link, merely the usual amount of link-level serialization that Universal Serial Bus entails.  So I see no reason not to use it, aside from its clunky API.

@IgnacioVazquez-Abrams Yeah I thought it was a bit ambitious :)

@jwpat7 Interesting, I will have to dig a bit deeper with that. I have only used Serial with the old FTDI style duemilanove.

On any version of Windows below 10 you will need to install drivers for the serial to work. It won't just "plug in an work".  For that I think you need to use the USB HID protocol, which is the bi-directional variant of the keyboard and mouse interface.


text:
Is it possible to create an electromagnetic wave using PWM?
What would be the simplest way of making an Arduino emit EM waves using PWM (or without)? Theoretically, oscillating a current through a wire would result in an electromagnetic wave, but I don't know if this is possible using an Arduino and if so, how?

I had a toy project a while ago that generated AM radio.

Code
Code for Uno or any Atmega328 based boards:
const byte ANTENNA = 9;

void setup()
  {
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)
  }  // end of setup

void loop()
  {
  pinMode (ANTENNA, OUTPUT);
  delay (500);
  pinMode (ANTENNA, INPUT);
  delay (300);
  }  // end of loop

Wiring
Plug a wire into digital pin 9:

Theory
The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 kHz, since one toggle turns the output on, and second toggle turns it off.
Then by turning the output pin on and off slowly you effectively have "keyed" output.
Obviously this would not have a long range, but you could amplify the output signal.

What does the timer code do?

It's a bit easier to understand if you look at the datasheet. I did a summary for Timer 1 (and the other two timers on the Atmega328) a while back.
Timer 1

The lines assigning to TCCR1A and TCCR1B set various bits as per the chart / datasheet. Then OCR1A is the value that the timer counts to, zero-relative, so it counts to 10.
The prescaler is set to 1, so each "tick" is 1/16000000 of a second (62.5 ns). Count 10 of them and you have 625 ns per tick. The timer is configured to toggle an output pin automatically. Since it takes two toggles (on and off) for one frequency "cycle" the period is 1.250 µs. The inverse of that is 800000. Thus the output frequency is 800000 Hz (800 kHz).

What does the timer code do? It seems quite cryptic to me.. :P


text:
Why is the piezo buzzer not making any sound?
My ciruit:

My code:
// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == LOW)
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
   tone(12,260);
  {
 }
  }
}

What I wish to do, is that when the button is pressed, and the Led's start to blink, I want the piezo buzzer to make a sound. I have never worked with them before so I am having troubles getting results. Is it that the setup is wrong or the code needs extra lines than just the tone(12,260); that I added?

General advice: get one thing working at a time. I don't think your button/flash code does what you want, even before you add the buzzer.

@MarkSmith Is this reference towards my previous question?

No, to this one.

Well my whole point of this project is to implement an alarm system. currently it works with the button acting as the alarm switch, led's as the lights and piezo for the sound. From the answer below, I have done this, however I couldn't understand any of the answers from my previous question (http://arduino.stackexchange.com/questions/35177/stop-leds-from-blinking) that allowed me to disable the alarm. That is really the only problem I am facing currently.

@Utsav Some issues will disappear if you stop using buttonState and start using digitalRead everywhere instead. You need current state of pin, not the state loaded looooong time ago. The buttonState won't magically change a state without any assigment into it!

Really the important thing is to understand what you're doing. You had five answers to your previous question -- you can ask for more explanations if things don't make sense. Using code you don't understand will get you into trouble sooner or later.

@MarkSmith the reason why I dont understand the answers you guys provide is because you think I understand everything and answer questions in a very complex way. You guys change the whole code and I don't understand some of the new "words" that I witness. Trust me, I appreciate all the work and I do want to learn but this is not a homework site so I can't ask small questions and expect a reply. The way I wrote the code above makes complete sense, but when you fiddle with it too much, I cannot understand. Other than that, I thank you and other members of this site who have helped me.

Both the code and the circuit have problems.
In the code:
• If the while (buttonState == LOW) loop is ever entered, it will never be left, because buttonState, the controlling variable, does not change within the loop.
The simplest fix is to remove the line bool buttonState = digitalRead(buttonPin); and replace while (buttonState == LOW) with while (!digitalRead(buttonPin)), which says to loop while digitalRead(buttonPin) is not true; ie, while it is false, or low.
• The empty braces, { } at the end of the while loop are superfluous and should be deleted.
In the circuit diagram:
• Neither of the leads of the buzzer is attached to the Arduino circuit, so it won't make any sound.  Note, tone(12,260); tells the Arduino to use pin 12 for tone output.
To fix this problem, run a wire from pin 12 to one side of the buzzer, and a wire to ground for the other side of the buzzer.
• A blue LED in series with a red LED might or might not turn on when supplied with 5 V.  For example, if the red LED takes 1.8 V and the blue LED takes 3.3 V to turn on, the 5.1 V total is too high to be turned on by 5 V signals.  Remove one of the two LEDs, and move the wires to the other LED to complete a circuit.


text:
How do I make specific tones with a piezo buzzer?
I am using a piezo buzzer and fiddling around with it a little bit. I currently have different tones with delays in between and I have to do a lot of trial and error for the piezo buzzer to play sounds like I want it to. Is there a better way to do this? because at this rate I will be stuck for a while.
I am trying to get the piezo buzzer to make the sound of an alarm. Any suggestion on how I can get it to sound exactly like an alarm or is trial and error the only way?

Posting your current code, might help us to better understand what it is you want to achieve (better).

are you using an active or passive buzzer? (they need different code)

It's very hard to know from your question what you are having trouble with.  I have a piano and I can hit the keys, but it takes me a long time to hit them in the right order and with the right timings to create a new symphony.
Anyway, if creating the sounds is the problem, have you looked at the Tone library?
Different alarms have different sounds.  I once heard an alarm which sounded like the start of Fuer Elise, so probably the notes were E and D#.  That would make their frequencies about 330Hz and 311Hz:
void loop()
{
    tone(pin, 330, 250);
    delay(300);
    tone(pin, 311, 250);
    delay(300);
}

The sound you linked to sounds to me like it starts on a C, and slides up gradually one octave.  One octave higher is double the frequency, so this code should do that:
void loop()
{
    const int startFreq = 523;  // C5 is 523Hz

    // Start at the given freqency, and increase gradually by
    // one octave (double the frequency)
    for (int freq=startFreq ; freq<= (startFreq*2) ; ++freq)
    {
        tone(pin, freq, 10);
        delay(3);
    }
}

Like I said I want to make the piezo buzzer implement an alarm. However, I need to have right tones. I have to find this right tone, and its hard for me to get there. maybe there is an easier way to implement the type of sound you are wanting to produce. Does this make it more clear?

What is the pin? because its not declared in the scope?

It's the pin number that you have the buzzer on. You could find that out by reading the links in my post, and you would learn much more than by copying and pasting code you don't understand.

A specific alarm I was looking for was like a fire alarm

https://www.youtube.com/watch?v=lo4yJbjkMWA like this one

That sounds to me like it's starting on a C and sliding up one octave. See if you can write code to do that. If you can't, I'll do it tomorrow when I'm on a proper computer. Do you have the tone library working and generating sounds?

Yes I do have the tone library. Thank you very much I'll let you know if I get it done

Nah mate, tried to get there today (was close) but I was still doing the same trial and error. If you can help me out, that'd be great thanks.

hmm..I don't know why but the piezo makes no sound. Maybe if I put the code and the circuir in the post, you might see why?

You can see for yourself https://circuits.io/circuits/4202932-the-unnamed-circuit/edit

Does it make no sound ever, or only with my code?  Please include in your question example code, using the tone library, with which it makes some sound, because I don't know what I'm debugging here.

Well for my particular code (which I have provided you the circuit and the code) I have not used the tone libraby. Why is it that the library must be included. I have used the piezo before with other projects which made sound just fine... I think its the problem with the for loop, because I removed it and kept the other lines and it produced sound, still not the way I wanted it to sound like :/.

It's alright. I don't want to be nagging. This is not a homework site so i'll just let it pass. Thanks for all that you could offer.

authors: Андрей Шаламов