text:
Ethercard. Copying ip address into hisip
I've tried getting help from arduino.cc forum but they arent helping at all (more like being cryptic) i'm kinda a newb at this. And i'm seriously not getting help from there. 2 messages in 8 days from one person and they arent helping.
i have a project that does following
-connects to network
-Gets ip address
-finds UDP broadcaster
-Connections to a web server's hard coded ip address and grabs data
-displays it on a screen.
that works fine. but i been trying to get the UDP broadcaster's ip address into the http part of the code so it connects to the broadcaster without having to hard code the IP Address.
here is my code. i want to have the ip address thats is grabed by the udpSerialPrint stament and have it put into the ether.hisip and use it in the ether.browseUrl(PSTR("/arduino"), "", website, my_callback);
Hope you can help. Thank you.
#include "Arduino.h"
#include <Wire.h>
#include <EtherCard.h>
#include "NexText.h"
#include "NexPage.h"
#include <IPAddress.h>

// Present a "Will be back soon web page", as stand-in webserver.
// 2011-01-30 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

#define STATIC 0  // set to 1 to disable DHCP (adjust myip/gwip values below)

// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };

byte Ethernet::buffer[700];
static uint32_t timer;

const int buzzer = 9; //buzzer to arduino pin 9

String ipaddy;
String CurrentTime;
String MainBroadcastIP;
String MainBroadcastIP2;
String Solarwatts;
String BatteryA;
String BatterySOC;
String Housewatts;
String Systemname;
String Updatetime;
String BatteryV;

NexText txtstartup = NexText(0,1,"txtstartup");
NexText txtsystemname = NexText(0,2,"txtsystem");
NexText txtsolarw = NexText(0,3,"txtsolar");
NexText txtbatterya = NexText(0,4,"txtbatterya");
NexText txthousew = NexText(0,5,"txthousew");
NexText txtbatterySOC = NexText(0,6,"txtbatterySOC");
NexText txtupdatetime = NexText(0,7,"txtupdate");
NexPage PageMain1 = NexPage(0,8,"Main1");

const char website[] PROGMEM = "192.168.15.3";

NexTouch *nexListenList[] =
{
    &txtstartup,
    &PageMain1,
    &txtsystemname,
    &txtsolarw,
    &txtbatterya,
    &txthousew,
    &txtbatterySOC,
    &txtupdatetime,
    &PageMain1,
    NULL
};

void setup(){
  dbSerial.begin(9600);
  nexInit();

  Serial.println("\n[AC-DC Power Monitor]");
  pinMode(buzzer, OUTPUT);
  txtstartup.setText("Welcome! System is Starting");
  delay(2000);
  txtstartup.setText("Attempting to Obtain an \r IP Address");
  delay(2000);

  Serial.println("Initialising the Ethernet controller");
  //Mega is ether.begin(sizeof Ethernet::buffer, mymac, 53)
  //Duo is ether.begin(sizeof Ethernet::buffer, mymac, 10)
    if (ether.begin(sizeof Ethernet::buffer, mymac, 53) == 0) {
        Serial.println("Ethernet controller NOT initialised");
        txtstartup.setText("Network Card not detected!");
        while (true);
    }

    Serial.println("Attempting to get an IP address using DHCP");
    if (ether.dhcpSetup()) {
        ether.udpServerListenOnPort(&udpSerialPrint, 8888);
        ether.printIp("Got an IP address using DHCP: ", ether.myip);
        char a1[10],a2[10],a3[10],a4[10];
        sprintf(a1,"%d",ether.myip[0]);
        sprintf(a2,"%d",ether.myip[1]);
        sprintf(a3,"%d",ether.myip[2]);
        sprintf(a4,"%d",ether.myip[3]);
        ipaddy = String(a1) + "." + a2 + "." + a3 + "." + a4;
        String msgtext = "Got IP: " + ipaddy;
        txtstartup.setText(msgtext.c_str());
        tone(buzzer, 1000); // Send 1KHz sound signal...
        delay(250);        // ...for 1 sec
        noTone(buzzer);     // Stop sound...
        delay(250);        // ...for 1 sec
        tone(buzzer, 1000); // Send 1KHz sound signal...
        delay(250);        // ...for 1 sec
        noTone(buzzer);     // Stop sound...

    } else {
        tone(buzzer, 400); // Send 0.4KHz sound signal...
        delay(500);        // ...for 1 sec
        noTone(buzzer);     // Stop sound...
        delay(500);        // ...for 1 sec
        tone(buzzer, 400); // Send 0.4KHz sound signal...
        delay(500);        // ...for 1 sec
        noTone(buzzer);     // Stop sound.
        exit(0);
    }

    #if 1
      // use DNS to resolve the website's IP address
      if (!ether.dnsLookup(website))
        Serial.println("DNS failed");
    #elif 2
      // if website is a string containing an IP address instead of a domain name,
      // then use it directly. Note: the string can not be in PROGMEM.
      char websiteIP[] = "192.168.1.1";
      ether.parseIp(ether.hisip, websiteIP);
    #else
      // or provide a numeric IP address instead of a string
      byte hisip[] = { 192,168,1,1 };
      ether.copyIp(ether.hisip, hisip);
    #endif

    delay(2000);
    PageMain1.show();
    ether.printIp("SRV: ", ether.hisip);
}

void loop(){
        ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {
    timer = millis() + 1000;
    Serial.println();
    Serial.print("<<< REQ ");
    ether.hisport = 8181;
    ether.browseUrl(PSTR("/arduino"), "", website, my_callback);
  }

}

void checkserver()
{
    delay(1000);
    Serial.println();

}

void udpSerialPrint(word port, byte ip[4], const char *data, word len) {
IPAddress src(ip[0], ip[1], ip[2], ip[3]);
        char a1[10],a2[10],a3[10],a4[10];
        sprintf(a1,"%d",src[0]);
        sprintf(a2,"%d",src[1]);
        sprintf(a3,"%d",src[2]);
        sprintf(a4,"%d",src[3]);

        MainBroadcastIP = String(a1) + "." + a2 + "." + a3 + "." + a4;
      return;
}

String getValue(String data, char separator, int index)
{
    int found = 0;
    int strIndex[] = { 0, -1 };
    int maxIndex = data.length() - 1;

    for (int i = 0; i <= maxIndex && found <= index; i++) {
        if (data.charAt(i) == separator || i == maxIndex) {
            found++;
            strIndex[0] = strIndex[1] + 1;
            strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
    }
    return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

char* string2char(String command){
    if(command.length()!=0){
        char *p = const_cast<char*>(command.c_str());
        return p;
    }
}

static void my_callback (byte status, word off, word len) {
  Serial.println(">>>");
  Ethernet::buffer[off+300] = 0;
  String web = (const char*) Ethernet::buffer + off;
  Serial.println((const char*) Ethernet::buffer + off);
  int weblengh = web.length();
  String web2 = web.substring(131,weblengh);
  Serial.println("System Name: " + getValue(web2, ',', 0));
  Systemname = getValue(web2, ',', 0);
  Serial.println("Solar Watts: " + getValue(web2, ',', 1) + "W");
  Solarwatts = getValue(web2, ',', 1) + "W";
  Serial.println("House Watts: " + getValue(web2, ',', 2) + "W");
  Housewatts = getValue(web2, ',', 2) + "W";
  Serial.println("Battery SOC: " + getValue(web2, ',', 3) + "%");
  BatterySOC = getValue(web2, ',', 3) + "%";
  Serial.println("Battery Volts: " + getValue(web2, ',', 4) + "V");
  BatteryV = getValue(web2, ',', 4) + "V";
  Serial.println("Battery Amps: " + getValue(web2, ',', 5) + "A");
  BatteryA = getValue(web2, ',', 5) + "A";
  Serial.println("Battery Amps: " + getValue(web2, ',', 6));
  Serial.println("Battery Amps: " + getValue(web2, ',', 7));
  Serial.println("Time: " + getValue(web2, ',', 8));
  Updatetime = getValue(web2, ',', 8);

  txtsystemname.setText(Systemname.c_str());
  txtsolarw.setText(Solarwatts.c_str());
  txthousew.setText(Housewatts.c_str());
  txtbatterySOC.setText(BatterySOC.c_str());
  txtbatterya.setText(BatteryA.c_str());
  txtupdatetime.setText(Updatetime.c_str());

}

I would recommend isolating the issue and writing a small test sketch. It is very difficult for anybody to simply jump in and help.

Well, ether is global, so you can access it from your udpSerialPrint function. That function gets passed the IP address in the ip[4] array, so you can just use ether.copyIp(ether.hisip, ip); to set it.
I would also set a flag to say "I have got the IP address" and only attempt to do anything with the website when you know the IP address has been given to you.

I dont know what i;m doing wrong. but i have tried adding ether.copyIp(ether.hisip, ip) to the udpSerialPrint  statement and it didnt work.

Scratch that. i got it to work now., Thank you very much


text:
Including an arduino library in Eclipse Neon (undefined reference to)
I'm trying for the first time to use Arduino Libraries (Servo.h & Servo.cpp in this case) in Eclipse IDE.
So far I've managed to compile and run Arduino code using this tutorial (I suppose many of you already know it).
The problem comes when I add the Servo.cpp and Servo.h files and try to run the program:
    13:35:08 **** Incremental Build of configuration Release for project Servo ****
make all
arduinoEclipse/subdir.mk:268: warning: overriding commands for target `arduinoEclipse/wiring_pulse.o'
arduinoEclipse/subdir.mk:261: warning: ignoring old commands for target `arduinoEclipse/wiring_pulse.o'
Building file: ../ServoTest.cpp
Invoking: AVR C++ Compiler
avr-g++ -I"C:\arduino\arduinoEclipse" -Wall -Os -fpack-struct -fshort-enums -ffunction-sections -fdata-sections -funsigned-char -funsigned-bitfields -fno-exceptions -mmcu=atmega328p -DF_CPU=1600000UL -MMD -MP -MF"ServoTest.d" -MT"ServoTest.o" -c -o "ServoTest.o" "../ServoTest.cpp"
Finished building: ../ServoTest.cpp

Building target: Servo.elf
Invoking: AVR C++ Linker
avr-g++ -Wl,-Map,Servo.map,--cref -mrelax -Wl,--gc-sections -mmcu=atmega328p -o "Servo.elf"  ./arduinoEclipse/CDC.o ./arduinoEclipse/HardwareSerial.o ./arduinoEclipse/HardwareSerial0.o ./arduinoEclipse/HardwareSerial1.o ./arduinoEclipse/HardwareSerial2.o ./arduinoEclipse/HardwareSerial3.o ./arduinoEclipse/IPAddress.o ./arduinoEclipse/PluggableUSB.o ./arduinoEclipse/Print.o ./arduinoEclipse/Servo.o ./arduinoEclipse/Stream.o ./arduinoEclipse/Tone.o ./arduinoEclipse/USBCore.o ./arduinoEclipse/WInterrupts.o ./arduinoEclipse/WMath.o ./arduinoEclipse/WString.o ./arduinoEclipse/abi.o ./arduinoEclipse/hooks.o ./arduinoEclipse/main.o ./arduinoEclipse/new.o ./arduinoEclipse/wiring.o ./arduinoEclipse/wiring_analog.o ./arduinoEclipse/wiring_digital.o ./arduinoEclipse/wiring_pulse.o ./arduinoEclipse/wiring_shift.o  ./ServoTest.o
./ServoTest.o: In function `setup':
ServoTest.cpp:(.text.setup+0x8): undefined reference to `Servo::attach(int)'
./ServoTest.o: In function `loop':
ServoTest.cpp:(.text.loop+0x20): undefined reference to `Servo::writeMicroseconds(int)'
ServoTest.cpp:(.text.loop+0x5a): undefined reference to `Servo::writeMicroseconds(int)'
ServoTest.cpp:(.text.loop+0xbc): undefined reference to `Servo::write(int)'
./ServoTest.o: In function `_GLOBAL__sub_I_myservo':
ServoTest.cpp:(.text.startup._GLOBAL__sub_I_myservo+0x4): undefined reference to `Servo::Servo()'
collect2.exe: error: ld returned 1 exit status
make: *** [Servo.elf] Error 1

As you can see in the console output, it compiles correctly, but when it comes to the linker, it doesn't find the function references from the Servo.cpp.
As I have seen in this post, the problem comes from the fact that I need also to generate an .a (static library) file in order to link both .h and .cpp files. Still, I have no idea how I am supposed to generate this file.
For this project, I have just added in arduinoEclipse folder all the .cpp and .h files from C:\arduino\hardware\arduino\avr\cores\arduino, C:\arduino\hardware\arduino\avr\variants\standard & C:\arduino\libraries\Servo.
Do you see what I could be missing?
Thank you in advance

The article explains 2 roads. You should at least tell which one you took.

I'm using AVR Plugin

The arduino build process is described here: https://www.arduino.cc/en/Hacking/BuildProcess
You do not really need to build a archive. You can link all your source files but that will result in a far bigger file to upload to the embedded device.
The normal CDT process to build a archive is by having 2 projects. One for the "archive" one for your sketch and then use project dependencies.
However since Arduino IDE 1.5 this process is hard to maintain because changing settings for your sketch may force you to change your archive compilation settings.
As far as I know; out of the box CDT does not support creating a library and linking it to a "executable" in one project. This is something Sloeber (road 1 in the article) has added.
I know this because I'm authoring Sloeber.

I don't have eclipse handy right now, so I may not have the menu options verbatim here, but with eclipse there are more steps to including a library than just writing the line in the code.  Go to the project in the project explorer and right click the project name.  Hit import and select the option for importing Arduino libraries into the sketch.  It should bring up a dialog with a list of all the libraries you have installed and you can choose from there.  Then there will be a folder in your project called includes IIRC and it will have a link to the library that you imported.  Now when you compile it will find the library.

There is no "import arduino libraries" if you followed road 2 in the article. This is so because "import arduino libraries" is part of Sloeber.
Note that the latest versions of sloeber just adding the include is sufficient in many cases.
Also note that there is a menu item Arduino which contains "import arduino libraries"

Thanks for the correction.  I just assumed that the poster was using the Arduino plugin for Eclipse.

source: Stack Exchange

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

sort: votes


text:
Does an Arduino get worn out by too much command execution?
Excuse me if it is a silly question, but I couldn't find an answer.
I've been wondering for a while whether an Arduino (or generally any other micro-controller) gets happy if the code is light and it does not have to execute too much operations. Does a code that has too many ifs, too many loops and all sort of complicated calculations wear out an Arduino sooner than a code that just blinks an LED?

Also see linked questions ....

No, the code doesn't "wear out" the MCU. In general no matter what you are doing roughly the same level of activity is being performed. Even delay() does lots of work while it's "idling".
There are commands to make the CPU do less - place it in an IDLE or SLEEP mode - but these are used to save power rather than to reduce "wear" on the MCU.
Of course there are specific things that do have a limited lifetime and you can only use them a limited amount of times - things like writing to EEPROM and writing to the Flash memory - so you don't want to be doing those all the time. Other than that, no, no matter what you are doing it doesn't wear the MCU out.

But all semiconductos age, don't they? hot carrier injection and bias temperature instability are the mechanisms I remember. Of course it would take many many years.

@MV. Yes, but what you run on the microcontroller doesn't really affect it. Whatever you are doing you are running the CPU at (roughly) the same level. You're using all of it (pretty much) all of the time.

Won't code indirectly influence generated heat? Hot components could wear down faster.

Only a very tiny tiny amount. Even when doing 'nothing' it is working hard and processing.

Thank you for your reply. Now I can lean back and write codes as complex as I want and do not worry about life span of my Arduino! But is it also the case for constantly interacting with external components? Reading sensors, SPI communication and so on?

You can very quickly ruin your EEPROM if you write to it aggressively. To make life a little easier, AVRC provides dedicated update commands which only perform the write if the value has changed, which has many use-cases (e.g. a regularly written but rarely changed status code), but is no silver bullet. I believe EEPROM fails on a byte or word level, so you can work around this to some extent if you must.

@Mast It only makes a difference when parts of the system are actually powered-off when not in use - that's actually quite a complex thing to do, especially while taking latency into account (it takes a while to power things on - e.g. Intel Skylake takes about 70 clock cycles to enable the whole AVX). Checking what helps is easy enough - just measure how much power is being consumed; that's pretty much how much heat is being generated. Also, consider total energy use, not just power - e.g. slower code taking more time while saving power might be less efficient that faster code for a task.

It's not. Well, it might slowly wear out if you run it like 20 years....(like most other physical products)? At least it does not rely on code complexity but how many writing operation done in the same memory section. Moreover, when it wear out it will just get bricked and it won't become a simpler code like blinking the LED.
An Arduino (Uno) has three memory parts. SRAM, FLASH, and EEPROM. SRAM is more like a logical transistor gate. It won't wear out by storing variables. FLASH and EEPROM consist of floating gates. They slowly wear out when you write new data. From the datasheet of Ateml microcontroller, it states:

The Flash memory has an endurance of at least 10,000 write/erase cycles.  (From Chapter 8.2)
The EEPROM has an endurance of at least 100,000 write/erase cycles.  (From Chapter 8.4)

However, FLASH memory is a space for code execution. Writing operation is not be done while Arduino is running. You only write FLASH memory when you upload a new code. So it will wear out when you upload code at least 10,000 times.
If you really want you can make a special code to self-reprogram FLASH memory usually for the purpose of keeping variable data when Arduino is turned off. When you write this kind of program it will wear out slowly because FLASH memory doesn't have much writing endurance. That's why you will be suggested to use EEPROM which has much more life expectancy, if you want to keep data even when Arduino is turned off.
To sum up, it will wear out by re-writing FLASH or EEPROM memory, not by code execution.

For a hobbyist:
About the only life limiting software related issue might be writing to the FLASH memory as fast as you can from inside a program.  But few programs make use of variables that need to survive events like changing batteries.
About the only life limiting hardware related issue is over loading the outputs with low resistance loads (incandescent light bulbs), inductive loads (like directly driving mechanical relays) to name just two.  But the question is only about software.

... (or generally any other micro-controller) ...

The other answers are great, but there is one small exception.
Ferroelectric RAM (FRAM) is a form of memory that combines the non-volatility of flash and EEPROM, the writability of SRAM, and the density of DRAM.
However, read operations on FRAM are destructive to the data stored in the FRAM, and write operations are destructive to the FRAM construction itself (and since the data is destroyed by reading it, it must be written back each time). If your code is located in FRAM then running it will wear down the MCU in time. But given that FRAM has a write endurance in the millions of billions it is unlikely that the MCU will become inoperable due to FRAM in the lifetime of the device.
Examples of MCUs that use FRAM include TI's MSP430FRxx line.

In general if there is FRAM there is no other memory. Not even flash.

Probably not ... The Atmel chip might get warmer over time (even a delay does not prevent this), however if it has a possibility to release its heat I don't see a problem. But mostly only overclocking can cause really serious problems, or using the Arduino in a fully closed box or in a hot environment.
In comparison: many computers are running for years without switching off, the Atmel (chip) is in that sense no difference, as long as generated heat can be relieved.
You can read more about a heat sensor in Atmels here: Internal Temperature Sensor

The way Arduino implements delay, is by constantly checking if enough time has passed. So running a program, or having a delay uses the same amount of processing power.

I will update (remove) that part ... thanks!

There is a difference - most computers today have tons of power saving features; a lot of things power off when not needed, and this happens pretty much automatically. The Arduino also has ways to reduce power use, but you need to use them explicitly. If you need something that is powered-down most of the time, https://learn.sparkfun.com/tutorials/reducing-arduino-power-consumption is a great way to start. In particular, the lowpower sleep drops power consumption about a thousandfold - unlike delay, which just spins the CPU. This has its cost, of course :)

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


text:
Setting Time to UTC with Data Logger Shield (with RTC DS1387)
I own an Adafruit Data Logger Shield https://www.adafruit.com/product/1141
I followed this tutorial
https://learn.adafruit.com/adafruit-data-logger-shield/using-the-real-time-clock
This part of code
if (! rtc.initialized()) {
  Serial.println("RTC is NOT running!");
  // following line sets the RTC to the date & time this sketch was compiled
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

adjust RTC to computer date/time... but it's using computer local date/time.
I'd prefer to use UTC date/time but I haven't find a convenient way to do this (except modifying computer date/time which is not very convenient as I want to always be able to reprogram Arduino without hassle of changing local time each time).

F(__DATE__), F(__TIME__) gives compile time local date/time. There will be a few seconds error as the sketch must be uploaded and run to set the clock. Given this I would suggest that you modify the sketch by reading back the setting and adjust to UTC plus the seconds error.

Problem here is that I don't want to adjust my computer to UTC when I'm programming and to local otherwise. It should be possible to have a function on computer side to return UTC time instead of local time.

You are getting a string from the compiler. Modify it to UTC before setting the RTC (in the sketch).

Do you know where __DATE__ and __TIME__ macros are defined?

Yes, see here https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html

There are several approaches you could use.
• Edit 1: On your development system, you could write a shell script or a batch file to write a file, say myUTCtime.h, containing a source-code line like char *MyUTCtime = "23:59:01"; and somewhere in your sketch say #include "myUTCtime.h".  Eg, to create the file in Linux: echo "char *MyUTCtime = \"$(date -u '+%H:%M:%S')\";" > myUTCtime.h which on my system produced file myUTCtime.h containing char *MyUTCtime = "08:20:36";
• You could define a different time constant, for example by adding -DMyUTCtime="23:59:01" into the gcc or g++ command line.  (Substitute an appropriate time.)  On Linux, this might look like -DMyUTCtime=$(date -u '+%H:%M:%S').  In your code you would write #MyUTCtime in place of  __TIME__.  Edit 1: Note, this is difficult to automate when using the Arduino IDE.  It is somewhat easier if using an Arduino Makefile.  For example, on Linux one might say MyUTCtime=$(date -u '+%H:%M:%S') make (which defines MyUTCtime with the current UTC time, and passes the MyUTCtime into make) and within the makefile, say (eg)
ifdef MyUTCtime
  CPPFLAGS += -DMyUTCtime=${MyUTCtime}
endif

• You could write your sketch to accept a time-setting command via serial input.  To set the time, you would send the time-setting command and the current time in UTC, via serial monitor.
• As Mikael Patel mentioned, you could modify the __TIME__ string to represent UTC before using it to set the RTC.  Here is an example of how to add or subtract an appropriate offset to __TIME__ to adjust it to UTC.  For example, if your offset is an hour ahead of UTC, you would change
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

to
char *compileTime = __TIME__;
compileTime[1] += 1;
if (compileTime[1] > '9')   // Check for carry
   ++compileTime[0];        // Add the carry
rtc.adjust(DateTime(F(__DATE__), compileTime));

This code has at least two problems:
• If the compile occurs between 23:00:00 and midnight, the resulting hour will show as 24 instead of as 00 on the next day. One could of course adjust the day of the date, and if that overflows, adjust the month, and if that overflows, adjust the year; or, more simply, one could produce an error in the compile.
• While a 1-hour offset may be appropriate during DST, a 2-hour offset may be appropriate most of the year.  One could of course check the date and use a date-appropriate offset of 1 or 2.

I like the second bullet approach but I don't know where I can provide this option flag -D within Arduino IDE. I'm not even sure that's possible http://forum.arduino.cc/index.php?topic=48693.0

@scls, in Arduino IDE, some compiler flags can be supplied via boards.txt; so, it may be possible but is clumsy and difficult if so.  Note, in Edit 1 of the answer I replaced first bullet with a simple approach using an include file, and in bullet 2 made some comments about  entering stuff like -DMyUTCtime="23:59:01" as a compiler flag when using a makefile.


text:
Difference between Ultrasonic sensor and Distance Sensor?
What is the difference between an Ultrasonic Sensor and a Distance Sensor?

An ultrasonic sensor is one type of distance sensor.

What's the difference between a Ford and a Car...?

An ultrasonic sensor can usually develop and receive high frequency sound waves.  They can be used to measure distance by measuring the time of flight of the sound wave.
distance(meters)  = [speed_of_sound(meters/second)][1] x time_of_flight(seconds)
distance(meters) = 343(meters/second) x time_of_flight(seconds)

For example, say the time of flight was 0.01 seconds.
distance(meters) = 343(meters/second) x 0.01(seconds)
distance = 3.43 meters

This is just one way distance can be measured by a processor.  Other ways use different types of radiation such as electromagnetic radio and light radiation.  Some of these use time of flight. Others use more exotic phase techniques.  These types of detectors can be very accurate over long distances.  But are usually very costly.  They are commonly used for automated car driving.
A completely different approach uses triangulation or parallax of a light beam and a focused linear array light sensor.

These types of detectors normally operate over short distances and are cheap to make.  They are commonly used in places like copier machine to detect objects and paper.  Or in automated vacuums cleaners to detect floor edges such as stair drop offs.

A proximity sensor is a sensor able to detect the presence of nearby objects without any physical contact, see article proximity sensor.
In that article a lot of types are mentioned and ultrasonic sensors are one of them, so an ultrasonic is one of the types of distance sensors.
Types (copied from the above article):

Capacitive
Capacitive displacement sensor
Doppler effect (sensor based on effect)
Eddy-current
Inductive
Magnetic, including magnetic proximity fuse
Optical

Photocell (reflective)
Laser rangefinder
Passive (such as charge-coupled devices)
Passive thermal infrared

Radar
Reflection of ionising radiation
Sonar (typically active or passive)
Ultrasonic sensor (sonar which runs in air)
Fiber optics sensor
Hall effect sensor

You wrote: “A distance (or proximity) sensor uses a beam of electromagnetic radiation”. Not all of them do, and specifically, an ultrasonic sensor doesn't.

I edit my answer, thanks for the improvement.


text:
ESP8266 not working. No response

Hello. I have begun working with an ESP8266 and an Arduino Uno. The connection I used is shown below, except I am using an Arduino Uno. The rest of the connection is the same.
The code I'm using is:
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX

void setup() {
  Serial.begin(9600);
  ESPserial.begin(9600);
  Serial.println("");
  Serial.println("Remember to to set Both NL & CR in the serial monitor.");
  Serial.println("Ready");
  Serial.println("");
}

void loop() {
  if (ESPserial.available()) {
    Serial.write( ESPserial.read() );
  }
  if (Serial.available()) {
    ESPserial.write(Serial.read());
  }
}

But the serial monitor is only printing:

Remember to to set Both NL & CR in the serial monitor.
Ready

What to do?

assume same connection as in diagram. Still not working.

thanks dear..i have edited the ques. Can  u tell me i have to connect RST to GND. right?

thanks. Can u give me your email id. I have to complete a project. I need help.

still not working. i have connected the RST and CH_PD pin to 3.3V via 10K resistor.

I don't know then, sorry. Are you sure 9600 is the default baud rate for the ESP? Does resetting the ESP (quickly connect RST to GND) make anything appear, even junk?

Most esp's default Baud rate is 74880 or 115200 ... try connecting ESP directly to your computer (you'll need a USB->Serial board, FTDI or similar) and find which baud rate is correct

ESP8266 WiFi modules typically have a baud-rate of 115200. This not only won't work with a 9600 baud host but SoftwareSerial can't go that fast. Or, more precisely, it can generally push out characters at that speed but it can't keep up with incoming ones. See this answer for how to change the speed of your module to 9600 baud.
Short answer: You have to reconfigure your ESP module to 9600 baud to use it with SoftwareSerial. You can do it blind (transmit a baud-change command to it at 115200 baud, even though you won't be able to read the reply). Once done, it will remain at 9600 baud and successfully communicate in both directions.

ESP01 has two variants (blue PCB and black PCB), the old is configured to use 9600 baud (blue PCB) and the newer one uses 115200 baud (black PCB) as default.
There is also a difference in memory, 512kByte (4Mbit) or 1MB (8Mb) between the old and new version.
So try to change
ESPserial.begin(9600);

to
ESPserial.begin(115200);

And preferably both 9600 to 115200.

You need to pull RST high - that is, connect a 10k between +3.3v and the ESP8266-01's RST pin.

still not working. i have connected the RST and CH_PD pin to 3.3V via 10K resistor

gpio0 and gpio2 should also be high (gpio0 low for flash mode though) ... however, all my dev boards (for 07, 12E and 12F modules) have the pullups on 0 and 2 and a pulldown on 15. The base modules also seem to have a pullup on CH_PD and RST as well, so you can literally connect gnd/vcc/rx/tx and away you go -


text:
Arduino stopped working
my arduino uno stopped working. It shuts off itself every time i plug it in. This golden thing is ovetheating.
Do i have to replace it or buy a new uno or what.

That golden thing is the resettable fuse. You are drawing to much current which will trip ( and heat up) the fuse. Check you circuit for any shorts.

As Gerben has said, that "golden thing" is a resettable fuse (AKA polyfuse).
It's there to protect the USB port of your computer against excess current draw from a faulty board (which seems to be happening, by the way).
If nothing else is connected to the Arduino and the polyfuse keeps tripping, then the fault root cause is probably a short-circuit in the board. From here there are 2 possible scenarios:

Least likely: an external agent (metallic flakes, dirt, or something like that) might be causing the short-circuit. Inspect the board, clean it and electrically isolate it when plugging it again (avoid the solder joints getting in contact with a conductive surface, use a case or a mat).
More likely: a component has failed in short-circuit mode and is causing the excess current draw that trips the polyfuse. In that case you could try to debug the board (with at least a multimeter, and maybe other instruments) to locate the faulty component and replace it. That's not an easy task unless you precisely know what to do and where to look in the board. You might be better off buying a new board.

If you want to give the repair route a try, check this question. The schematic may be of some help to you. You might want to verify the integrity of the decoupling capacitor in first place.

If the OP has a socketed Arduino then he can remove the Atmega to see if it is the faulty component. Should help trace the short.

True. However, from the picture it looks like an CH340G arduino clone. Those usually have an SMD ATmega on board.

Oh! Sockets too expensive for that. :P

Yes, that's how they keep them cheap! :)


text:
8Ω speaker, what resistor values to use?
I want to connect 2 speakers of 8 ohm to 2 (different) pins of the Arduino.
However, for this example one speaker is enough.
I came across a lot of circuits without or with a single resistor which on other foras was not adviced, where one pin directly controls the speaker. This way (assuming 0,02A is the max recommended output for a pin), the resulting power is like 0.02A * 5V = 0.1W.
My speaker is 0.5W (8 ohm) and I want to hear how hard that is :-)
But it seems I have to use something with a transistor to isolate the path.
I came across this circuit:

However, when I would calculate the values or R1 and R2 myself I would get:

R2: Afaik, the recommended output for a pin is 0.02 A. This means:
V = I * R <=> 5 = 0.02 * R <=> R = 5 / 0.02 = 250Ω -> 270Ω (nearest higher value)
R1: my speaker is 0.5W, 8Ω.
P = V * I <=> 0.5 = 5 * I <=> I = 0.1A
V = I * R <=> 5 = 0.1 * R => R = 50Ω, which is Rtotal below:
Rtotal = Rspeaker + R1 <=> R1 = Rtotal - Rspeaker = 50 - 8 = 42Ω => 47Ω (nearest higher value)

This result in
V = I * R <=> 5 = I * (R1 + Rspeaker) <=> I = 5 / (47 + 8) = 5 / 55 = 0.0909 A
P = V * I = 5 * 0.0909 = 0.4545 W (so I lose 'just' 10%)
Are my calculations correct, and I assume the +5V pin of the Arduino will not have trouble giving 90.9 mA ?
Update:
I have some more questions regarding the accepted answer:

Would it mean if I use 7 transistors, all my voltages will be used for transistors and nothing is left (7 times 0.7 V which is approx. 5 V?)
**** Answer = No, a transistor will add Voltage so 7*0.7= 4.9Volt added ***
I assume I can better use as less as possible to 'switch' a transistor? * Answer = No, 0.7-Volt required, 5V is fine depending on the rating of the transducer   (but enough to be able to switch it) ? You say R2 can be smaller, but I can better make it higher not to waist voltage?  Answer = Changing the resistor will change the volume, look at the wattage rating for the speaker *
I already built the circuit below (but with a BC547 transistor) ... using a 0,25W R1 resistor. I guess I was lucky (?) * Answer = No, luck has no part, that transistor would work fine within the parameters used, look at the datasheet *
Regarding the base pin of the transistor ... by making the resistor higher (see item 2 above) ... that would help also not to burn the transistor pin? * Answer = No... please view the datasheet and ratings for the hw *
Again about the transistor, so I should make the resistor R2 in such a way that the gain times the mA is driving the speaker? (need to calculate this again) * Answer No, and I think you are thinking of "Gain" the wrong way, "Gain" is a "DB" measure and is for how well AC is transferred between antenna. *
You say to remove R1 completely ... but than I expect V = I * R <=> 5 = I * 8 => I = 0.625A ... P = V * I = 5 * 0,625 = 3.1W which blows the speaker? * Answer = Wrong way of looking at the 8-Ohm Impedance rating, Impedance is AC *

Also consider using an audio transformer, and see the linked questions.....

I'm voting to close this question as off-topic because it is about electronics and not about Arduino.

Basically you are right and it should work.
But if you want to go to details, it would be better look on AVR328 documentation, as nothing is as easy as it looks in Arduino tutorials.

maximum (really maximum) current on pin is 40mA for one DC pin and 200mA for all pins together (otherwise destruction of the processor is possible - never ever try to reach it), also  datasheet states:

Although each I/O port can source more than the test conditions (20mA
  at V CC = 5V, 10mA at V CC = 3V) under steady state conditions
  (non-transient), the following must be observed:
  ATmega48A/PA/88A/PA/168A/PA/328/P: 1] The sum of all I OH , for ports
  C0 - C5, D0- D4, ADC7, RESET should not exceed 150mA. 2] The sum of
  all I OH , for ports B0 - B5, D5 - D7, ADC6, XTAL1, XTAL2 should not
  exceed 150mA. If II OH exceeds the test condition, V OH may exceed the
  related specification. Pins are not guaranteed to source current
  greater than the listed test condition.

so 20mA is not recomended but is maximum guaranteed to be provided under some more conditions met - if you can, you should use less (also even if it works for one module on one pin, it may fail mysteriously for mor modules on more pins).

Even if 20mA is guaranteed for one pin, the voltage on it would drop more then 0.5V if you drain so much
you cannot draw as much on too many pins together
also the maximum you can draw is less if you want higher frequency (I think the sound is not usually in category, where it matter too much)

In your equation 1 you used 5V/20mA, you should use 4.4V/20mA also keep in mind, that there is usually like 0.7V on base of open transistor (depends of type) - so the R2 can be even smaller, if you use only few pins.
About R1 - if you open the transistor, there can be like 0.2V on the collector, so the current is like 4.8V/6.8Ohm = 0.7A - on UNO board v3.0 is used NCP1117 as stabiliser, which can support even 1A (if powered not from USB, but 7V and higher source (if such source can give as much) so it could work too, but beware as it is about 4.8V*0.7A=3.4W so R1 should be able to stand at least as much if the pin is HIGH for any longer time. If the pin is oscilating, the SPKR adds it current to that, so the value can be even higher (I would not use anything under 5W for R1).
On the other hand - Q1 2N3904 can support Ic max 200mA, so you could burn it by setting the pin for HIGH (or for PWM with more like 20% HIGH or more - switching makes even more heat) so you should use othe transistor here.
And this Q1 have current gain over 30 even for such currents as 100mA, so you need just 1/30 of Ic go thru the base from pin (so you need supply only 3.3mA to have 100mA thru Q1, 6.6mA is able to force 200mA and burn the transistor, if not properly cooled. 20mA is clearly much more than needed anyway.)
I would suggest some darlington transistor here or something like that, if you want manipulate such currents.
If your speaker is 0.5W only, you will burn more power on the R1 than on the speaker - not good result. It would be better just manipulate the speaker directly (put it instead of R1 and leave the R1 and C1 out).
(but on usual Arduino setup the power source and all is usually so underrated, that there is a good chance, that it would not be able to supply enough power to burn your equipement out, just it would drop the voltage and maybe fail randomly. Who knows. Also breadboards and long thin wires with bad connection adds a lot of resistance and voltage drops and manufacturers publish as maximal rating what the product should survive, which is usually a lot les, than is needed to sure destroy it, so many experiments can survive even if they should burn on simple paper calculations - which is part of why Arduino is so popular - is cheap and usually does not burn even if managed out of specs.)

I have to read multiple times to understand everything (which I still don't) ... more questions now than answers :-) But very good points to take care of ... I will think of how to formulate further questions... Thank you for the long and detailed answers what to think more (what I didn't knew about).

Thank you very much for your answers, bfter reading the answer several more times I have 6 additional questions (sorry for my lack of electronic 'practical' knowledge). It seems the ideal world differs a lot from theoretical 'ideal' circuits from high school text books.

Yes, exactly :) Arduino is for easy start on easy tasks, if you need go deeper, a lot can be obtained in Electrical Engineering - even about Arduino (once you start thinking about it little more like microprocessor AVRxxx and some electrical circuits around - change of philosofy or point of view, physically it is exactly the same). Anyway I use Arduino both ways - like simple tool for simple tasks the simple way (sometimes it is much faster than any other setup) and as AVR328  on simple board, which can be used in anything anyway. Also I made my own PCBs and programmed them both ways.

Arduino is really good starting point for many people and even if I changed my point of view on it and do a lot with more sofisticated setups, I still use Arduino platform for a lot of simple projects, as it does not need more. But sometimes you hit the limits of "simple world" and have to learn more. And sometimes you do not hit it and can do a task in simple way and then it is good to return fully to Arduino world. Aech task needs its tools and usually the simples can be used, the faster you get result :) So don't worry, be happy and have a fun any way you enjoy :)

That's why I like Arduino ... it's a quite easy environment (and also it doesn't break down if I make stupid mistakes, so far I only broke a LED, a IR receiver and one LED in an 8x8 matrix). But the best is there is a lot of documentation that can be found (although sometimes contradictory), and help from users here (which is highly valuable).
I will try to answer my own questions (in the near future after reading more about it).

The speaker rating of 8 Ω is AC resistance, speaker impedance. Impedance (AC-Resistance) changes based on the frequency of the signal fed into it.
If you are worried about hurting the speaker and need to calculate power driving that particular "load", look at the speaker Wattage rating.
Say it is 1 W for example, and you are providing 5 V d.c., the amperage required will be: 0.2 A.
V * A = W
0.2 * 5 = 1

So the DC resistance is actually:
V = I * R (0.2 / 5 = 0.04 Ω).

Give it a higher amplitude... say 5.7 V to account for a transistor no resistor, and you get about 0.175 A. and a change in DC resistance again to 0.0301 Ω.
If the power supply is AC, the impedance needs to be matched to the speaker impedance to get best energy efficiency, otherwise the amplifier can be damaged.
For that circuit I suggest you place a variable resistor where the resistor is in your circuit to allow for a volume change. Also a flyback diode maybe a good idea, that will protect the speaker but take down voltage 0.7 V d.c. keep in mind you have that transistor there adding 0.7 V d.c.! so it evens things out too using that diode.
That diode placed on the high (+) side of the circuit, before the speaker and after the variable resistor.

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


text:
How do I use ultrasound to track a moving object?
I'm trying to create a small scale, dumb-downed version of the pitch tracking systems used to detect the speed and direction of baseballs.
I'm currently working with an HC-SRO4 sensor and an Arduino, but I'm unsure how to expand because a single sensor can't track an object that's not moving linearly (ie rising or falling as it moves). My team's idea was to make a grid of multiple HC-SRO4's connected to one Arduino, but we're worried that the delay will be too large if we try to turn them on sequentially to avoid interference.
How can we use ultrasound to track a moving ball?

I wouldn't worry too much about the path of the ball not being straight. If you assume it goes straight and it gets off-track by 8 degrees (which is quite significant), your speed calculation will be off by only 1%. And you probably won't be more accurate than that anyway. I would worry about the limited range of the HC-SR04 though.

Yes you can use ultrasound to track a moving target, but I really doubt it could be done with an Arduino.
You need to be able to ping the object at least 3 times in the time it takes to move your beam width.  3 times because if you know where it is with the centred ping you need to calculate the direction of travel by pinging either side of the centre to see if it is there.
You then need to track it in three dimensions.  To do this you will need multiple sensors ideally at least 3 for 2D and 3 for 3D, so at least 6.  3 sensors in a plane will give you a reasonable degree of accuracy, but you beam width is key to this, the narrower the better.
Now you have to triangulate the position of the object, well actually work out the area of probability (for both planes) you never 'know' where it is really.
Oh and all 6 sensors need to have different frequencies to prevent interference, you then need to add in reflection processing to reduce false signals.
Its just much easier to buy a Pixy camera and download the software that they have for visually tracking your balls.


text:
Something's wrong with my code for a 4 digit 7 segment clock display
I'm trying to do a clock using 4x7 segment displays but once I run the code the Display doesn't turn on
here's my Code that I'm like 90% sure that there's nothing wrong with it
bool A = 2;
bool B = 3;
bool C = 4;
bool D = 5;
bool E = 6;
bool F = 7;
bool G = 8;
int PWR1 = 10;
int PWR2 = 11;
int PWR3 = 12;
int PWR4 = 13;
int TimeSec = 0;
int TimeMin1 = 0;
int TimeMin2 = 0;
int TimeHour1 = 8;
int TimeHour2 = 0;
int Display = 0;
int Loop = 0;
int Digit = 0;
int Memory1 = 0;
int Memory2 = 0;
int Memory3 = 0;
int Memory4 = 0;
int Rewrite1 = 0;
int Rewrite2 = 0;
int Rewrite3 = 0;
int Rewrite4 = 0;

void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(C, OUTPUT);
  pinMode(D, OUTPUT);
  pinMode(E, OUTPUT);
  pinMode(F, OUTPUT);
  pinMode(G, OUTPUT);
  pinMode(PWR1, OUTPUT);
  pinMode(PWR2, OUTPUT);
  pinMode(PWR3, OUTPUT);
  pinMode(PWR4, OUTPUT);
}
void loop() {
  loop:
  delay(250);
  Digit = Digit + 1;
  if (Digit > 4) { Digit = 1; }
  if (Digit == 1) { goto digit1; }
  if (Digit == 2) { goto digit2; }
  if (Digit == 3) { goto digit3; }
  if (Digit == 4) { goto digit4; }

  // Supposedly turns on the 7-segment display that is next in line to have its digit edited but doesn't work?
  digit1:
  digitalWrite(PWR1, HIGH);
  digitalWrite(PWR2, LOW);
  digitalWrite(PWR3, LOW);
  digitalWrite(PWR4, LOW);
  Display = Memory1;
  goto skip;
  digit2:
  digitalWrite(PWR2, HIGH);
  digitalWrite(PWR1, LOW);
  digitalWrite(PWR3, LOW);
  digitalWrite(PWR4, LOW);
  Display = Memory2;
  goto skip;
  digit3:
  digitalWrite(PWR3, HIGH);
  digitalWrite(PWR1, LOW);
  digitalWrite(PWR2, LOW);
  digitalWrite(PWR4, LOW);
  Display = Memory3;
  goto skip;
  digit4:
  digitalWrite(PWR4, HIGH);
  digitalWrite(PWR1, LOW);
  digitalWrite(PWR2, LOW);
  digitalWrite(PWR3, LOW);
  Display = Memory4;
  skip:

   // Manual Turning on of LEDs is overcomplicated and can be made much shorter yes I know :(
   if (Display == 1) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(B, LOW);
    digitalWrite(C, LOW);
  }
  if (Display == 2) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(B, LOW);
    digitalWrite(G, LOW);
    digitalWrite(E, LOW);
    digitalWrite(D, LOW);
  }
  if (Display == 3) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(B, LOW);
    digitalWrite(C, LOW);
    digitalWrite(G, LOW);
    digitalWrite(D, LOW);
  }
  if (Display == 4) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(B, LOW);
    digitalWrite(G, LOW);
    digitalWrite(F, LOW);
    digitalWrite(C, LOW);
  }
  if (Display == 5) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(F, LOW);
    digitalWrite(G, LOW);
    digitalWrite(C, LOW);
    digitalWrite(D, LOW);
  }
  if (Display == 6) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(F, LOW);
    digitalWrite(G, LOW);
    digitalWrite(C, LOW);
    digitalWrite(D, LOW);
    digitalWrite(E, LOW);
  }
  if (Display == 7) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(B, LOW);
    digitalWrite(C, LOW);
  }
  if (Display == 8) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(B, LOW);
    digitalWrite(C, LOW);
    digitalWrite(D, LOW);
    digitalWrite(F, LOW);
    digitalWrite(G, LOW);
    digitalWrite(E, LOW);
  }
  if (Display == 9) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(B, LOW);
    digitalWrite(C, LOW);
    digitalWrite(D, LOW);
    digitalWrite(F, LOW);
    digitalWrite(G, LOW);
  }
  if (Display == 0) {
    digitalWrite(A, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(C, HIGH);
    digitalWrite(D, HIGH);
    digitalWrite(E, HIGH);
    digitalWrite(F, HIGH);
    digitalWrite(G, HIGH);
    digitalWrite(A, LOW);
    digitalWrite(B, LOW);
    digitalWrite(C, LOW);
    digitalWrite(D, LOW);
    digitalWrite(E, LOW);
    digitalWrite(F, LOW);
  }

  // Checks how many times it has looped over
  Loop = Loop + 1;
  if (Loop < 4) {goto loop;}
  else
  {
    // Resets Loop count and counts 1 second (normally it has a delay(1000) but the delay(250) on the loop to account for LED's turning on is counting for me )
    Loop = 0;
    TimeSec = (TimeSec + 1);
    if (TimeSec == 60) {
      TimeMin1 = (TimeMin1 + 1);
      Memory1 = TimeMin1;
      TimeSec = 0;
      if (TimeMin1 == 10) {
        TimeMin2 = (TimeMin2 + 1);
        Memory2 = TimeMin2;
        TimeMin1 = 0;
        Memory1 = TimeMin1;
        if (TimeMin2 == 7) {
          TimeHour1 = (TimeHour1 + 1);
          Memory3 = TimeHour1;
          TimeMin2 = 0;
          Memory2 = TimeMin2;
          if (TimeHour1 == 10) {
            TimeHour2 = 1;
            Memory4 = TimeHour2;
            TimeHour1 = 0;
            Memory3 = TimeHour1;
            if (TimeHour1 == 3 && TimeHour2 == 1) {
              TimeHour2 = 0;
              Memory4 = TimeHour2;
              TimeHour1 = 1;
              Memory3 = TimeHour1;
            }
          }
        }
      }
    }
  }
}

And here's how it's Wired up
Also I think that I have to make a clock of my own for the Timer or else it will become a problem later on but I don't know how to make 2 loops so if someone can tell me how to do it (preferably in a way that I can understand xD) I'd be very grateful
Notes:

The Displays are Common Anode so to turn on a LED I used digitalWrite(ledpin, LOW) for a negative output
I'm not using a 4 digit 7-segment display -- I'm using 4 individual 7-segment displays
Resistors are 220 Ohm
The Picture was made using https://circuits.io
I'm still new at this so my code may have some newb mistakes or just stuff that was made overcomplicatedly simple if you know what I mean :P

UPDATE 1:
I fixed it now the problem was I was setting the variables to bool instead of integer but I still can't figure out how to do a self-sufficient clock because the current code now runs but doesn't turn on as fast as I need to

Regarding “here's my Code that I'm like 90% sure that there's nothing wrong with it”:  Because it doesn't work, you should instead be 100% sure there's something wrong with it.

There are several bugs that I spot right off the bat.  First off, you should never need goto in C++.  You should be able to use if, for, and while to completely eliminate those. goto makes code hard to follow and read, so it makes it nearly impossible for someone else to try to debug.  Be nice to yourself and forget that goto ever existed.  I would suggest hitting a C++ tutorial and learning about functions, because most of the places you've used goto, what you really needed was a function call.
Second is this:
bool A = 2;
bool B = 3;
bool C = 4;
bool D = 5;
bool E = 6;
bool F = 7;
bool G = 8;

A bool is meant to hold a true or false value, not a pin number.  You should use int here, or better yet save a few bytes and use byte.  But not bool.  The second issue here are the single capital letter variable names.  Those are always a bad idea.  Many of them (B and F for sure) are already defined as macros in the core.  They're not available for you to use.  Single letter variable names are bad form, but single capital letters are right out.
Third is the way you have the digits connected.  There should be a resistor for each segment, or you will have brightness differences depending on how many segments are in use at any one time.  But that can wait until you get the code worked out.
Finally, here is some code for working with 7-segment displays.  It's a lot easier to work with than the whole thing you've got written out.  See if you can follow it and ask questions if you don't understand.  This code would count 0 to 9 over and over on a single 7 segment display.
byte digits[] = {0b1111110 , 0b0110000, 0b1101101, 0b1111001,
0b0110011, 0b1011011, 0b1011111, 0b1110000, 0b1111111, 0b1111011};

// pins to segments g,f,e,d,c,b,a
byte pins[] = {3,4,5,6,7,8,9};

void displayNumber(int aNumber) {
  for (int i = 0; i < 7; i++) {
    digitalWrite(pins[i], digits[aNumber] & (1 << i));
  }
}

void setup(){
  for (int i = 0; i < 7; i++){
    pinMode(pins[i], OUTPUT);
  }
}

void loop(){
  for (int i = 0; i < 10; i++) {
    displayNumber(i);
    delay(1000);
  }
}

I thought goto was easier to follow as it's a custom label that would be easier to spot but if you say so :P --- I think I'm going to stick to my Overcomplicatedly simple code as it's easier for me to understand but I'll make a separate build to use your code so I can play around with it --- I'm still stuck at how to make a separate clock since I don't know how to make a 2nd loop that works simultaneously with another if it's even possible

The same argument you make for goto applies doubly to a function.  It gives you a definite place in the code to go to with a name that is easy to spot, but doesn't require all the convoluted logic to then skip sections.  When functions return they go right back to the same spot in the code where from they were called.  And they can bring back information with them. Learn about functions and you'll see what I mean.


text:
Problem with 2 decimal places/2 significant figures
Lora/GPS Shield + Arduino Uno + PLX-DAQ (latest custom version)
I have a problem on how to generate more than 1/2 decimal output.
Currently, I'm trying to generate GPS Lat and Long(code from TinyGPS++) on PLX-DAQ

Just like in the image. Latitude generated in 1/2 decimal places.
I'm trying to get more than 2 decimal places.
For example : from 3.2 to 3.123953
Coding link:
https://www.dropbox.com/s/rqjpnsc9pg33f9n/Coding.txt?dl=0
Thanks.

You're talking about the output from this line?
Serial.println( (String) "DATA,DATE,TIME," +flat+ "");

drop the use of the String class and make that two separate print statements.  Then you can use the second argument to print to define the precision.
Serial.print("DATA,DATE,TIME,");
Serial.println(flat, 6);

That gets the same end result output going out the serial line, but lets you specify the precision and avoids the nasty String class.

Okay, one problem solved. Now how do I get Longitude output same as latitude?

The same way.  Just print it.  I can't see where in the code you tried to print longitude so I'm not sure what exactly you want to do there.

This one.
Serial.print("DATA,DATE,TIME,"); Serial.println(flat, 6); //latitude Serial.println(flon,6); //longitude
But the output only latitude. It's like longitude output doesn't work.

Is it not there at all?  Or is it going to the next line?  Pay attention to when you use print and when you use println.  You should maybe print something in between like a space or a comma or something just to make sure they're separated so you can read them.

 float flat, flon;   Serial.print("DATA,DATE,TIME,");   Serial.println(flat, 6);   Serial.print(",");    Serial.print(flon, 6);
this is what i did. Sorry, I'm confuse.

Do you know what the difference is between print and println?  Would you care to answer the opening question in my last comment?

Serial.print ("abc");Serial.print("def"); = abcdef
Serial.println("abc"); Serial.println("def"); = abc
def
from what I know.. that's how it prints.
well I did managed to get an output for longitude
btw, thanks for your help.

Not quite.  println doesn't put a space, it puts a newline after whatever it prints.

oh, sorry. That not a space. i put "def" in newline. The format for comment here make it just like space.


text:
I am trying to combine an automatic door lock with an RFID MFRC522 with a IR REMOTE program
I am getting this error.
Arduino: 1.8.2 Hourly Build 2017/02/17 11:33 (Windows 8.1), Board: "Arduino/Genuino Uno"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

(.text+0x0): multiple definition of `__vector_7'

libraries\REMOTE\IRremote.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

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

Here is the entire code:
#include <RFID.h>
#include <Wire.h>  // i2C Conection Library
#include <LiquidCrystal_I2C.h>  //Memanggil i2C LCD Library
LiquidCrystal_I2C lcd(0x3F, 16, 2);

#include <SPI.h>
#include <RFID.h>
#define SS_PIN 10
#define RST_PIN 9

RFID rfid(SS_PIN,RST_PIN);

const int buzzer = 7;   //Passive buzzer ke Pin D7 dan GND
const int doorLock = 8; //Driver Selenoid Door Lock/Relay input ke pin D8
int serNum[5];          //Variable buffer Scan Card

int cards[][5] = {      //ID Kartu yang diperbolehkan masuk
  {120, 181, 196 ,101, 14}

};

bool access = false;

int alarm = 0;
uint8_t alarmStat = 0;
uint8_t maxError = 5;
void setup(){
    Serial.begin(9600);
    lcd.begin();
    SPI.begin();
    rfid.init();

    pinMode(doorLock, OUTPUT);
    digitalWrite(doorLock, HIGH);

  tone (buzzer,1200);
  lcd.setCursor (0,0);
  lcd.print(F("  RFID System   "));
  lcd.setCursor (0,1);
  lcd.print(F(" Control Access "));
  delay (2000);
  lcd.clear();
  noTone (buzzer);
}

void loop(){
  if (alarm >= maxError){
    alarmStat = 1;    }

  if (alarmStat == 0){
  lcd.setCursor (0,0);
  lcd.print(F(" -System Ready- "));
  lcd.setCursor (0,1);
  lcd.print(F(" Scan Your Card "));

    if(rfid.isCard()){

        if(rfid.readCardSerial()){
            Serial.print(rfid.serNum[0]);
            Serial.print(" ");
            Serial.print(rfid.serNum[1]);
            Serial.print(" ");
            Serial.print(rfid.serNum[2]);
            Serial.print(" ");
            Serial.print(rfid.serNum[3]);
            Serial.print(" ");
            Serial.print(rfid.serNum[4]);
            Serial.println("");

            for(int x = 0; x < sizeof(cards); x++){
              for(int i = 0; i < sizeof(rfid.serNum); i++ ){
                  if(rfid.serNum[i] != cards[x][i]) {
                      access = false;
                      break;
                  } else {
                      access = true;
                  }
              }
              if(access) break;
            }
        }

       if(access){
          Serial.println("Welcome!");
          lcd.setCursor (0,0);
          lcd.print(F(" DOOR UNLOCKED!! :)"));
          lcd.setCursor (0,1);
          lcd.print("ID:");
          lcd.print(rfid.serNum[0]); lcd.print(rfid.serNum[1]);
          lcd.print(rfid.serNum[2]); lcd.print(rfid.serNum[3]);
          lcd.print(rfid.serNum[4]);
           digitalWrite(doorLock, LOW);
           tone (buzzer,900);
           delay(100);
           tone (buzzer,1200);
           delay(100);
           tone (buzzer,1800);
           delay(200);
           noTone(buzzer);
           delay(600);
           lcd.setCursor (0,0);
           lcd.print(F("WELCOME"));
           lcd.setCursor (0,1);
           lcd.print(F("AutoLock after "));
           for(int i=5; i>0; i--){
            lcd.setCursor (15,1); lcd.print(i);
            delay (1000);
           }
           digitalWrite(doorLock, HIGH);
           lcd.clear();
      } else {
           alarm = alarm+1;
           Serial.println("Not allowed!");
           lcd.setCursor (0,0);
           lcd.print(F(" ACCESS DENIED!!  "));
           lcd.setCursor (0,1);
         lcd.print("ID:");
           lcd.print(rfid.serNum[0]); lcd.print(rfid.serNum[1]);
           lcd.print(rfid.serNum[2]); lcd.print(rfid.serNum[3]);
           lcd.print(rfid.serNum[4]);
           tone (buzzer,900);
           delay(200);
           noTone(buzzer);
           delay(200);
           tone (buzzer,900);
           delay(200);
           noTone (buzzer);
           delay(500);
           lcd.clear();
       }
    }
    rfid.halt();
}
else {
  lcd.setCursor (0,0);
  lcd.print(F("-System LOCKED- "));
  lcd.setCursor (0,1);
  lcd.print(F(" Please Wait "));
for(int i=5; i>0; i--){
tone (buzzer,4000);

lcd.setCursor (13,1); lcd.print(i);
lcd.print(F("  "));delay (1000);}
noTone (buzzer);
alarmStat = 0;
alarm = 0;
  }
}

//code  of an IR REMOTE

#include <IRremote.h>

int RECV_PIN = 2; // the pin where you connect the output pin of TSOP4838
int lock =13 ;
int itsONled[] = {};
/* the initial state of LEDs is OFF (zero)
the first zero must remain zero but you can
change the others to 1's if you want a certain
led to light when the board is powered */
#define code1 26775 // code received from button 1

IRrecv irrecv(RECV_PIN);

decode_results results;

void remote()
{
  Serial.begin(9600);   // you can comment this line
  irrecv.enableIRIn();  // Start the receiver0
  pinMode(lock, OUTPUT);

}

void loop_1() {
  if (irrecv.decode(&results)) {
    unsigned int value = results.value;
    switch(value) {
       case code1:
         if(itsONled[1] == 1) {        // if first led is on then
            digitalWrite(lock, LOW);   // turn it off when button is pressed
            itsONled[1] = 0;           // and set its state as off
            Serial.println("ledl OFF");
         } else {                      // else if first led is off
             digitalWrite(lock, HIGH); // turn it on when the button is pressed
            Serial.println("led 1 ON");
             itsONled[1] = 1;          // and set its state as on
         }

          break;
    }

    Serial.println(value); // you can comment this line
    irrecv.resume(); // Receive the next value
  }
}

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem.  Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant.  Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem.

hai!! thanks for the reply , as u said i have attached my entire code to the question ... plzz help me out!!

The error message multiple definition of __vector_7 means that you have more than one interrupt handler defined for the interrupt that has interrupt vector 7.
Although the ATmega328x datasheet in a table called Interrupt Vectors in ATmega328 and ATmega328P refers to interrupt vector 7 as the Watchdog Time-out Interrupt, that probably is misleading, because only the following ISRs can be defined in Tone.cpp:
ISR(TIMER0_COMPA_vect)
ISR(TIMER1_COMPA_vect)
ISR(TIMER2_COMPA_vect)
ISR(TIMER3_COMPA_vect)
ISR(TIMER4_COMPA_vect)
ISR(TIMER5_COMPA_vect)

(These can be defined, but typically most are not.  All of them are conditional upon which MCU is selected.)
The article multiple definition of '__vector_7' at arduino.cc attributes the problem to the last of those ISRs, ISR(TIMER5_COMPA_vect).   Anyhow, in short, you might need to check what board or MCU you are compiling for, or may need to find a substitute for one of Tone or IRremote, the libraries that are both defining the ISR that has a conflict.
Edit 1: The article TimerFreeTone Library v1.5: Play tones without timers and therefore no conflicts at arduino.cc describes a TimerFreeTone v1.5 library that generates tones without using timers.  You might be able to use that library in place of the Tone library that has a conflict.

Thanks for the valuable reply ... I understood the problem  ... Can we assign a different interrupt for both the programs , my basic idea is to control doorlock with an RFID system as well as an IR REMOTE , individually both the programs with the output is working fine .. i wanted to combine both so that i can dump into a single program to access both features ... Plzz help me out with this .

@user33872, see edit 1

Thank u very much!! Compiled succesfully with both the programs , i commented all the tone libraries and added the TimerFreeTone v1.5 library to my sketch along with the program that you have attached (obatined at the article TimerFreeTone Library v1.5: Play tones without timers and therefore no conflicts at arduino.cc ) . I will go with the hands-on the hardware and get back to you! Your answers were VERY HELPFUL :)  Thanks!!

Hai very Good Morning .The combined sketch of RFID and IRremote in realtime is working absolutely fine , Thank you very much for helping me out with this .... and i encountered an another problem , i wanted a buzzer tone each and every time when i scan a vaild card and an invalid card . And after 5 times scanning an invalid card the entire system gets locked for some time(in the program 5 sec duration) .. For all these operations i wanted an buzzer tone .. how do i do it?

I don't know, due to not understanding some of the program and some of what you want to do.  By the way, have you read and understood the Blink Without Delay example? ¶ Note, in for(int x = 0; x < sizeof(cards); x++),  sizeof cards is the number of bytes in cards, that is, the number of entries times the size of each entry.  Try x < sizeof cards / sizeof cards[0]; instead.  (Parentheses are not needed after sizeof operator unless the argument is a datatype name instead of a variable name.)

You can't use tone and IRremote in the same sketch as they are both trying to use the same timer interrupt.
Don't use the hourly build.  It's not tested.  Get the latest stable version if you are working on your final project.  You don't want unknown bugs.  Let the beta testers use the hourly build.  For something like a final project you need things to work, so stick with the stable version, not the bleeding edge of development.

thanks for the reply !! so can anything be done if i want to use both tone and IRremote sketch as the single program... I s it possible to change the interrupt of which the programs are using and assign different interrupts to it ... can u guide me for this. please

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


text:
How can I get my Attiny85 interupt to trigger
I have an ATTiny85 set up to detect a magnet passing over a hall sensor. Every 2 detection's I want it to light up an LED.
I decided to do the code using the arduino IDE and the code is as follows:
const int hallPin = 2;     // the number of the hall effect pin
const int ledPin =  1;      // the number of the LED pin

// variables will change:
volatile int hallState = 0;         // variable for storing the hall counter

void setup() {

  pinMode(ledPin, OUTPUT);
  pinMode(hallPin, INPUT);
  digitalWrite(hallPin, HIGH);

  // Attach an interrupt to the ISR vector
  attachInterrupt(0, pin_ISR, FALLING);
}

void loop()
{
  if(hallState>1)
  {
      digitalWrite(ledPin,HIGH);
      delay(2000);
      digitalWrite(ledPin,LOW);
      delay(2000);
      hallState=0;
  }
}

void pin_ISR()
{
    hallState++;
}

I've dry run this a bunch of times and cant see anything wrong with it. I use the digitalWrite on the hall pin to enable the internal pullup. But the circuit just doesnt work.
Here is the circuit:

I connected a multi meter to the hall effect sensor on its own just to check if it was working. I added an external pull up using a 10k resistor and it worked as expected 5v when no magnet present and almost 0 volts when a magnet is brought in range.
So my guess is my interrupt routine isnt working in my code, what could I be doing wrong? I've read in the documentation that pin 0 is the correct interrupt pin on the attiny85
Edit: Adding Schematic

I would do some testing on different pieces of the project.

I would do some testing on different pieces of the project. It looks like your LED might be connected backward. I don't use that part so I wonder is "loop()" really the normal "main()" entry point? I would try the code in loop() by replacing "if(hallState>1)" with "if(1)" just to make sure the LED will actually blink. Do you need to enable interrupts or is that implied somehow?

Hi, thanks for the comment. I actually already tested the LED works by commenting out the IF statement and replacing the loops contents to turn the LED on for 2 seconds then off for 2 seconds. this worked fine and the LED did exactly that. This leads me to believe its the interrupt code thats a bit flaky

Have you tried writing it as a normal ISR and enabling the interrupt yourself instead of using attachInterrupt()?

@IgnacioVazquez-Abrams Not yet, I shall read up on how to do that and see if I can get that to work. Thanks for the suggestion.

Please add a schematic.

@uint128_t I have added the schematic as an edit at the bottom.

Your LED is backwards, for a start. Have you verified with a DMM/scope that the output of the hall-effect sensor is changing state? You will also want to make sure (by reading the source code) that pins are being mapped the way you think they are.

The LED is fine in the circuit its just backwards in the diagram. (short pin connected to ground) I've used a multi meter to verify the hall effect sensor voltage drops low when a magnet is brought in the vicinity.
As I said above i've tested using a 2 second timer in the loop turning the LED on and off, so there problem is not there. Its within the interrupt but im not sure where exactly. The problem with the ATTINY85 is theres no serial debug :(

"its just backwards in the diagram" - then draw a proper diagram. Draw a schematic of what you have actually connected up, otherwise it just wastes our time.

Pull-up resistor on reset is where? Decoupling capacitors on the supply rails?

Are you sure attachInterrupt(0, ... is correct? i.e., that 0 is the right interrupt? Maybe try with digitalPinToInterrupt(pin), as the documentation suggests.

@marcelm interesting thought. Though the Atmel documentation states that the interrupt can only be on pin 0

@Festivejelly the Atmel documentation will state nothing about "pin 0". That is an Arduino-esc abstraction of which there are many different version depending on what core library you use. The Atmel documentation will talk about "INT0" which is the alternative function of one of the pins (for the ATTiny85, this is on PB2).

@TomCarpenter I see that makes sense now. I made the erroneous assumption that meant pin0. With this in mind I should be able to fix this...

Okay so I think my code was okay. Its just for the attiny85 attachinterupt you still feed in 0 as the pin value but the actual pin is pb2 or physical pin 7... phew confusing. It still wasnt working so I added a pullup resistor between the positive hall pin and the digital out of the hall and voila! It now works. Thanks to all you guys pointing out my shoddy understanding of how the pins work.

You main problem is that you have wired up your MCU wrong.
Pin 5 (PB0) is not the external interrupt pin. Pin 7 (PB2) is the external interrupt 0 (INT0) pin.
As a result your code will not do anything when the hall sensor changes because it is not looking at it.

I would suggest not trying to use the attachInterrupt() abstraction. Instead I would simply enable the external interrupt directly:
GIMSK |= _BV(INT0);

And use a proper ISR handler:
ISR(INT0_vect) {
    //Your ISR code here.
}

Thats interesting, I think i've been getting confused between the pin numbers and the physical pin locations.

You were of course correct. Thanks for clearing that up. It makes a lot more sense now. I've plugged it into pin 5 because I read somewhere attachInterrupt had to be set to 0 so I figured the wire had to go to physical pin 5 (pb0). This is apparently not the case. I guess that function simply enabled the interrupt with the default value.


text:
programming arduino in pure c
I'm trying to flash pure c-code to arduino Mega2560 board from linux using avr-gcc & avrdude. Compilation is done , now trying to flash using avr-dude, getting error as "avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00"
I used below command to produce hex file
avr-gcc -mmcu=atmega2560 -DF_CPU=16000000UL led.c -o led.elf

In file included from led.c:3:0:
/usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler optimizations disabled; functions from  won't work as designed" [-Wcpp]
 # warning "Compiler optimizations disabled; functions from  won't work as designed"
And then
avr-objcopy -j .text -O ihex led.elf led.hex

finally for flashing
avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex

FYI: port is correct & RX pin is blinking i.e connection is perfect between computer & board

One note: -DF_CPU=1000000UL is 1MHz. I'm pretty sure Arduino Mega2560 runs on 16MHz. Anyway, you can try to use PlatformIO CLI (I'm using it on Linux machine and it works fine with several different Arduinos)

@KIIV , even @ 16Mhz , same probelm. any idea how to do without PlatformIO CLI?

Try prefixing your avrdude command with stty -F /dev/ttyACM3 hupcl &&

In file included from led.c:3:0:
  /usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler
  optimizations disabled; functions from won't work as designed"

You should start by fixing this. Simply add -Os to the compiler
command line. This means “optimize for size”, and is the standard
optimization option used with Arduinos.

avr-objcopy -j .text -O ihex led.elf led.hex

If your copy of avrdude was compiled with libelf (like the one supplied
with Ubuntu is), you don't need this: you can hand your elf file
directly to avrdude.

avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex

-F tells avrdude to not verify the device signature. -V tells it
to not verify the upload. I wouldn't use any of these options unless
I had a very good reason to do so. -c arduino is wrong: it selects the
upload protocol used by optiboot (used, e.g., in the Uno). The
Mega 2560 uses a different bootloader based on the “wiring”
protocol. I would also add the -D option (disable auto erase) because
I saw the Arduino IDE using it, and because without this option I get
the error:
avrdude: erasing chip
avrdude: stk500v2_command(): command failed

In the end, the upload command ends up being something like:
avrdude -p atmega2560 -c wiring -P /dev/ttyACM3 -b 115200 -D -U led.elf

thanks ! it is working. your explanation is clear. I'm new to avr, can you please direct me where to learn all those? @Edgar Bonet

@sankar: I don't have a good reference handy for that. I learned it the hard way, by looking at how the Arduino IDE and Sudar Muthu's Makefile do it, and by reading the man page of avrdude.


text:
How to make DC motor rotate a specific number of turns?
Can someone please give the code which can be used to rotate the dc motor a specific number of rotations like 2 rotations or 5 rotations. I'm using arduino uno board.

I'm voting to close this question as off-topic because this isn't a gimme da code site.

Hi @Rohit and welcome to the Arduino SE community. Unfortunately your question doesn't meet our quality standards. Please edit and improve it. How to ask

You can't. You either have to attach a sensor to the motor shaft to measure the numbers of rotations or use a stepper motor.

No! That is not how motors work.
If you need precision control you need to use a stepper motor or servo.
You could implement some solution with a geared motor and position sensor, but this really only works (imprecisely) with a slow rotation speed.

Can someone please give the code which can be used to rotate the dc motor a specific number of rotations like 2 rotations or 5 rotations.

fairly simple:
rotation_count = 0; //initialize rotation counter
motor_on();  //turn on the motor
while (rotation_count < DESIRED_COUNT) {
  rotation_count = count_rotation(); //update rotation count
};
motor_off(); //turn off the motor


text:
Servo motor and the servotimer2
I posted this a few days ago
Servomotor and music shield
and now I moving my servo motor and my musicshield (seeduino musicshield v2.0) together with and Arduino uno, in my other post they told me to put the library ServoTimer2 because I was having a conflict with the two libraries(the servo.h library and the musicshield library).
And I'm having a lot of trouble with the servotimer2 library, at first didn't work,  it gives me always this error:
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:117:14: error: conflicting declaration 'typedef bool boolean'
typedef bool boolean;
but I read that if I erase the //typedef uint8_t boolean; in the ServoTimer2.h It will be working. So I did it, and it works somehow.
Now, the musicshield is playing the songs and the servomotor is moving, but is not moving "properly" I mean it moves so little like 10° and moving back and so on, the servo motor is not moving the 90° or stopping the time I want it to stop.
I don't know if it's the code, I search and the servo.h and the servotimer2 library change only in the way you define your servo and pin.
So I tried this without the musicshield and it didn't work either, in this case the servomotor make some noise like a clock like tic, tic, tic, but don't move
#include <ServoTimer2.h>

ServoTimer2 servoNine;

int val;//for the servo

void setup() {
  servoNine.attach( 9 );

 }
void loop() {
val = 0  ;// start point
servoNine.write(val);
delay(100);

val = 90 ;//
servoNine.write(val);
delay(100);//

}

so, I think the problem is the code. The servomotor is not broken I tested that, with the normal servo.h and the same code and it's moving properly
#include <Servo.h>
Servo myservo;
int val;

void setup() {
  myservo.attach( 9 );
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
val = 0;//
myservo.write(val);
delay(100);

val = 90;//
myservo.write(val);
delay(100);
}

it moved! I runned the  example program and my servomotor it's behaving properly now,is an adaptation from the three servos example
the code I'm using is this
#include <ServoTimer2.h>  // the servo library

// define the pins for the servos
#define rollPin  9

ServoTimer2 servoRoll;    // declare variables for up to eight servos

void setup() {
  servoRoll.attach(rollPin);     // attach a pin to the servos and they will start pulsing

}

// this function just increments a value until it reaches a maximum
int incPulse(int val, int inc){
   if( val + inc  > 2000 )
      return 1000 ;
   else
       return val + inc;
}

void loop()
{
 int val;

   val = incPulse( servoRoll.read(), 1);
   servoRoll.write(val);

   delay(10);
}


text:
Three or more Arduino slaves sending bytes to 2 different I2C devices
I'm trying to connect 3 Arduinos with this scheme: Arduino1 Master, Arduino2 Slave, Arduino3 Slave. The slave devices need to communicate with each other and I'm trying to programming Arduino2 and transmit bytes to the other slave device Arduino3 and Master Arduino1 at the same time. Is that possible?
Master CODE:
#include <Wire.h>

void setup() {
  Wire.begin();
}

void loop() {
  Wire.requestFrom(0x04, 2);
  while (Wire.available()) {
    var1 = Wire.read();
    var2 = Wire.read();
  }
}

Arduino1 Slave:
#include <Wire.h>

void setup() {
  Wire.begin(0x05);
  Wire.onReceive(receiveEvent);
}

void loop() {
}

void receiveEvent(int howMany) {
  var1 = Wire.read();
  Serial.print("VAR1 is : ");
  Serial.println(var1);
}

Adrduino2 Slave code:(Where I think I'm wrong)
#include <Wire.h>
int var = 123;
int var2 = 123;
int var3 = 123;

void setup() {
  Wire.begin(0x04);
  Wire.onRequest(requestEvent);
}

void loop() {
  Wire.beginTransmission(0x05);
  Wire.write(var);
  Wire.endTransmission();
}

void requestEvent() {
  Wire.write(var1);
  Wire.write(var2);
}

Is this the correct way to make the Arduino2 send to 2 devices?

I hope I can ask a 'side' question ... in my project I eventually also want to make use of a master and some slaves Arduino's ... I2C seems very appropriate. Wonder if Wire might be better than I2C.

As soon as an Arduino starts writing data, it is a Master. Do you use Arduino Mega 2560 and Arduino Uno and Nano boards ? In theory those ATmega microcontrollers can handle collisions in a multi-Master bus, and in theory the Wire library handles collisions as well. However, everyone tries to avoid that, because it causes a lot of problems. You would even have to program a complete new layer in the code to re-transmit data until it was received without collision.
Select one Arduino board as Master, and use the Master to read and write data. If you want to transfer data from one Slave to the other Slave, then use Master to read the data from one Slave and write the data to the other Slave.
It is possible to use other busses between the two Slave Arduino boards.


text:
Convert to and from Unix Timestamp
What is the best way to convert between date, hours, min, seconds to Unix timestamp in milliseconds in Arduino? I need to have this conversion, since I'm using RTC (date, hours, min, secs etc) and communicating Unix timestamp over BLE
I found some snippet of codes online, but have not tested it extensively yet.

  byte second = epoch%60; epoch /= 60;
  byte minute = epoch%60; epoch /= 60;
  byte hour   = epoch%24; epoch /= 24;

  unsigned int years = epoch/(365*4+1)*4; epoch %= 365*4+1;
  unsigned int year;
  for (year=3; year>0; year--)
  {
      if (epoch >= days[year][0])
          break;
  }

  unsigned int month;
  for (month=11; month>0; month--)
  {
      if (epoch >= days[year][month])
          break;
  }

  year  = years+year;
  month = month+1;
  unsigned int day   = epoch - days[year][month]+1;

  unsigned int weekday  = (dayOfMonth += month < 3 ? year-- : year - 2, 23*month/9 + dayOfMonth + 4 + year/4- year/100 + year/400)%7;

And to convert to Unix timestamp:
unsigned long epoch = (((year/4*(365*4+1)+days[year%4][month]+dayOfMonth)*24+hour)*60+minute)*60+second;

Are there any library in Arduino that implement this? I would trade off reliability over size of the program.

I think that the two most used libraries are the Adafruit RTClib and the pjrc.com TimeLib.
They both have functions to convert the epoch, and they both are reliable. But both lack the timezone and the DaylightSavingTime.
I think you find the pjrc.com TimeLib just slightly more suitable to handle the epoch time (which is a 32-bit unsigned long defined as 'time_t').

+1 for TimeLib. I use it all the time for unix timestamps.

There is a standard way of doing those conversions in C, which is
through the functions defined in <time.h>. This API being standard,
you can test it in your computer. Recent versions of the avr-libc
support this: see time.h in avr-libc. These functions can handle
local time if you provide a function implementing the DST rules: see
set_dst(). Examples are provided for US and EU rules.

Awesome, I didn't know that the 'time.h' with timezone and also DST were included with the Arduino. Thanks. To connect a RTC chip with that time system is sadly not nice. Every second a system_tick() should be called. I just stay with the pjrc.com TimeLib for now.

@Jot That's not entirely correct. You can use a RTC to set the Arduino's internal clock, then call the internal clock for needed time info ... RTC in that case is merely a battery backed clock that is OCCASIONALLY used ... once per reboot and possibly every week or two for drift correction.

Here's an example to convert seconds (Unix time) to Date & Time using TimeLib.h:
#include <TimeLib.h>

unsigned long offset_days = 3;    // 3 days
unsigned long t_unix_date1, t_unix_date2;

void setup() {
  Serial.begin(115200);
  t_unix_date1 = 1564398600;
  Serial.print("t_unix_date1: ");
  Serial.println(t_unix_date1);
  offset_days = offset_days * 86400;    // convert number of days to seconds
  t_unix_date2 = 1564398600 + offset_days;
  Serial.print("t_unix_date2: ");
  Serial.println(t_unix_date2);
  printf("Date1: %4d-%02d-%02d %02d:%02d:%02d\n", year(t_unix_date1), month(t_unix_date1), day(t_unix_date1), hour(t_unix_date1), minute(t_unix_date1), second(t_unix_date1));
  printf("Date2: %4d-%02d-%02d %02d:%02d:%02d\n", year(t_unix_date2), month(t_unix_date2), day(t_unix_date2), hour(t_unix_date2), minute(t_unix_date2), second(t_unix_date2));
}

void loop() {

}


text:
Servotimer2, detach "stop"
I'm still struggling with the Servotimer2 library
I have an Arduino uno board with a servo motor with the servotimer2 library because I'm using a music shield beside the servomotor and the music shield library and the servo.h wasn't compatible.
But finally I make the two of them working together with the servotimer2.h but now I want my servo to rotate 90 or 180 and then "stop" for a minute and come back again, rotate, stop, rotate,stop, rotate, stop... short of thing so I read this what is commonly done to stop a servo after reaching desired point and now I know that servo can't stop, but they can detach
so I tried making something like this
#include <ServoTimer2.h>  // the servo library
#define rollPin  9

ServoTimer2 servoRoll;

void setup() {
  servoRoll.attach(rollPin);

}

// this function just increments a value until it reaches a maximum
int incPulse(int val, int inc){
   if( val + inc  > 2000 )
      return 1000 ;
   else
       return val + inc;

}

void loop()
{
   mover();
   parar();

}

void mover() {
 int val;

   servoRoll.attach(rollPin);
   val = incPulse( servoRoll.read(), 2);
   servoRoll.write(val);
   delay(10);

}
void parar() {

  servoRoll.detach();
     delay(100);
}

but the servo is only moving very slow and I think is not detaching in any moment. I'm quite lost, I'm very noobie and in the post(what is commonly done to stop a servo after reaching desired point) they said things like making while(true){} loop in the setup? or use millis() and other things that I don't understand quite well
But someone tried to do something like control the time the servo is stopping with the delay, so I tried something like this
#include <ServoTimer2.h>  // the servo library

// define the pins for the servos
#define rollPin  9

int pos = 0;

ServoTimer2 servoRoll;    // declare variables for up to eight servos

void setup() {
  servoRoll.attach(rollPin);     // attach a pin to the servos and they will start pulsing

}

//from https://learn.adafruit.com/multi-tasking-the-arduino-part-1/a-clean-sweep

void loop()
{
 for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    servoRoll.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    servoRoll.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }

}

but with this code, my servo is only moving once, and then stops and don't move again
and I think that my servo with the servotimer2 library is only moving with this
   int incPulse(int val, int inc){
   if( val + inc  > 2000 )
      return 1000 ;
   else
       return val + inc;
}

void loop()
{
 int val;

   val = incPulse( servoRoll.read(), 1);
   servoRoll.write(val);
  delay(10);
}

so, any ideas of what I'm doing wrong?

my servo is only moving once, and then stops You mean it turns 180° then no more? Once it has reached 180° (or 2000 µs) you need to decrease val by one to go the other way (from 2000 to 1000). For example:
int direction = 1;  // 1 or -1
void loop()
{
   int val;

   val = incPulse( servoRoll.read(), direction);
   servoRoll.write(val);
   if (direction <= 1000 || direction >= 2000) {
      direction = -direction;
   }
   delay(10);
}

thank you! can you explain me or redirect me to some place where I can learn more about  this kind of expressions " if (direction <= 1000 || direction >= 2000) {
direction = -direction;"

@Egm That is a "logical or" which means only one of the conditions has to be true for the body of the if statement to be executed. Search for "c logical operators".


text:
Open source PLC Wifi
I'm working on a project that involves a device called the plduino (aka Open Source PLC). This is the website for the device:
https://www.digital-loggers.com/plc.html
and the GitHub:
https://github.com/digitalloggers/PLDuino
Using the examples on the GitHub, I've been able to figure out other parts- storing on the SD card, the GUI, digital IO, etc. But I haven't been able to figure out the WiFi module (which seems to be through a ESP8266 device). I looked through the libraries directory on the GitHub link, but didn't find anything that looked like it connected to the internet or could send or receive data. The documentation says the device can connect to wifi, but is otherwise very little help.
Has anyone used this before? How do I make this device connect to wifi?

Fuses on the relays... cowardice.

This is not particularly easy to figure out. The ESP8266 is addressable via a serial port. The ESP8266 firmware is called NodeMCU, which sits on top of the ESP8266 firmware and allows you write Lua code to implement custom Wifi functions. The PLC comes with example Lua that starts a webserver and publishes a webpage that allows you to check and set the status of the PLC (but only if you connect to the PLC, which is in access point mode.)
If you want it to behave like wifi on a normal desktop computer, you have to do some Lua programming (I could not find any Lua code online that did basic things out of the box, but there are a fair number of examples and snippets on the NodeMCU sites.)
In spite of how cool this device is, I ultimately decided it was just too much work to get the Wifi integration working (the Arduino stuff is of course pretty easy). You also have the problem of how to get your data logs somewhere. Since the data is on the Duino and the ESP8266 is the web interface, you either have to poll the Duino (which the example code does) and upload to a site (e.g. AWS), or log the data on the Duino, then send it over the serial port for upload -- MORE Lua and Duino coding. Plus if you want to put your data on AWS IoT (for example) the Duino/NodeMCU technically does not support the TLS 1.2 and X.509 cert handling you need to register (although they are apparently some workarounds now.) Life. Is. Too. Short. For. That.
I switched to Raspberry Pi, which is about 1000 times simpler, even though it does not have the cool features like open collectors and optical isolators. I'm now looking at Pi enclosures, such as the nice BC packaging from Phoenix Contacts. I decided it was simpler to make my own custom PLC for my home HVAC automation project than it was to code the DL-PLC. Bummer. Maybe they'll do a Pi version of this someday.
The repositories for my DL-PLC and RPi projects are on GitHub (https://github.com/dglcinc/HVAC-plc and https://github.com/dglcinc/HVAC-pi), you may find my Lua code and implementation notes useful if you want to get the wifi working on the DL-PLC. I did get it working in station mode (so you can join it to your home access point, address it with a DHCP IP, etc.) but that's about as far as I got.

What does your controller drive? What sensors do you use, and how do they report to the controller?


text:
Image Breakdown
I've been trying to figure out a way to store an image on the Arduino, and I couldn't figure it out. What I've been trying to do with this image is the following:

Test that the arduino has the image by displaying on a touchscreen (I have the adafruit 2.8 inch touch screen)
Break down the image into an array, in which contains pixel by pixel color RGB color info of the image

int pictureData = [[100,50,0],[176,255,5],...]; // RGB Values within the array
How can I store an image and break it down as shown? Is there no way to do this? I would appreciate any help! Thank you very much!
I am using Arduino IDE for code and I have Arduino Uno/MEGA, which ever is necessary for this task. All info of screen is on adafruit: https://www.adafruit.com/product/376
The below image shows an example of displaying the image:

Please edit your question to include part number and a link to “adafruit 2.8 inch touch screen” and general specs, and image format (jpg, bmp, whatever) and its stored size.  This will reduce the amount of time people spend guessing the display's pixel count and the number of bytes in the image

@JamesWaldby-jwpat7 Thank you for your time. I added it to the question.

I presume you are trying to create a system that has one image stored, and want the image to be available without needing an SD card reader on the system.
If the logic of your program is small enough to fit into about 18KB of flash memory, you can store one 230KB image in flash on a Mega. (230KB+18KB+8KB = 256KB = Mega flash size.  8KB is Mega bootloader size.)  See the PROGMEM page at arduino.cc for examples of declaring and accessing arrays from flash.
If you end up needing lots more flash for the logic of your program, consider compressing the 18 bits of each pixel to 16 bits.  The 230KB figure is 240·320·3.  Each pixel on the display uses six bits per color, stored in three bytes per pixel.  Instead of keeping all the bits, you could clip the blue to its high four bits; ie, save 6-6-4 for RGB in two bytes instead of 6-6-6 in three bytes.  Or could clip two of the colors to their high five bits; eg, save 6-5-5 or 5-6-5.  At two bytes per pixel, an image would take 240·320·2 = 153600 bytes of flash, leaving roughly 94KB for program logic.
In all of these approaches, image data would be brought into RAM row by row or column by column, unpacked, and copied to the RAM buffers in the display.
One could also apply some compression algorithms to the image instead of using BMP format.
If you need more images than one, you could further reduce image quality, for example could save 3-3-2 high bits of color per pixel, or could save only every other pixel in a row or column or both, reducing storage to a half or fourth as much.  Or you could have one reasonably good image stored 6-6-4 at 16 bits per pixel, so about 154KB, plus several monochrome images stored one bit per pixel, or about 10KB each.

Edit 1: Re “how would I take an image and convert it into the RGB array?”, one straightforward approach is to write an image-converter program (that runs on your development system) to read an image file and output C code representing the image data in arrays; that is, to produce C-style arrays printed in ASCII.   Again, this recommendation is predicated on the notion that you are trying to create a system that has one image stored, and want the image to be available without needing an SD card reader on the system.
I recommend writing the image-converter program in Python.  See, for example, the accepted answer at  Convert an image to 2D array in python, to which you would need to add a few lines of code to write out C code to a file, so that you could include that code into a sketch.  Also see  How to get an array from RGB values of a bitmap image? and Working with .bmp files in python 3.
Some C-language examples appear in answers to  How to convert a .bmp image into Byte array using C Program and How to convert an image to WORD (uint16) array?, which are among the first links in a stackexchange search for “convert bmp image to array”.
Wikipedia's BMP file format article shows the layout of BMP files in general.  Using various image-handling libraries (as recommended in SE questions listed above) sidesteps having to deal with low-level BMP details.  However, you may be able to use a simple program or application to produce RGB565 color format files, eg as at Bitmap to RGB565 format on codeguru.com, and then write a simple program to convert that particular form to C-style arrays printed in ASCII.

Thanks, that was very helpful. But how would I take an image and convert it into the RGB array?

@AssafiCohen-Arazi, see edit 1

Note that if you have an image conversion program, you can convert the image to binary PPM, which is a format trivial to parse, or even to XPM, which is actually valid C code.

240 by 320 pixels.  That's 76800 pixels.  In your example it looks like you want 3 bytes per pixel, so that's 230400 bytes.  An Arduino Mega has 8K bytes of SRAM memory.  There's enough room in the memory on the Arduino Mega to hold 0.003% of your image.
Maybe you could store the image on an SD card and put it on the screen little piece by little piece, but that is going to be painfully slow.

Is there still a way to store the data of the image in an array?

And a follow up, how can you transfer the data of the image as the RGB array shown?

Is there still a way to store the data?  Do you really not understand that 230KB is never going to fit into an 8KB space?  Think of it this way, is there any way to put 230 gallons of water in an 8 gallon bucket?

You don't need to load the whole image (230KB) from flash memory (256 KB) into SRAM (8KB). And 8KiB out of 230.4KB is 3.6% not 0.003%.

@Delta_G O meant with the micro SD card so there is enough room, sorry for not explaining.