text:
Most efficient method to turn a gear extremely slowly?
I have a gear that needs to have roughly one rotation per day.  It does not have to be smooth or consistent.  So far, the best I have come up with is to have a stepper motor with an arduino that sleeps, wakes up once an hour maybe and turns the stepper a little bit.
Which arduino should I use for this and is there perhaps a simpler method?  Is there any way to fully cut power then when powered on the arduino advances the motor and then shuts off?
Any ideas?
I want to run off of a 9v battery and get as much time as possible.
edit: adding details as requested
the rotation needs to happen slowly over the 24 hour period.  The tube being turned is a light plastic 1" diameter tube that weighs about 2 lbs.

How big is the gear and how much torque does it need to deliver? Is the load active or static? Is it ok to sleep 24 hours or whatever and then do a whole rotation?  Perhaps you should edit the question to answer the above questions, and also say something about the overall purpose and context.

ok, edited to add details.

Using a 9V battery to power a motor that will rotate 2 lbs will probably not work as those batteries have too little energy. Also, sleeping an Arduino does not reduce its current consumption much (see my answer to a recent question: http://arduino.stackexchange.com/questions/31813/how-to-make-battery-last-for-months/31815#31815).

Steppers require current - and power, due to I^2*R losses) to hold a position. Power off, they free-wheel. What kind of efficiency do you need? A stepper might not be the most power efficient.
An escapement permits or causes a gear to index one position and prevents it turning any farther. In a clock, it permits a weight-driven or spring-driven shaft to index. You'll probably want one that drives the shaft as well, probably with a solenoid.
Another option that comes to mind and doesn't need an Arduino, is a clock motor. Gear down the hour hand 2:1 and you're done. Find a 24-hour clock motor and even that gearing will have been done for you.

A worm gear might be a good option if some holding force is required

Turning of the stepper in between, will result in reduced holding torque. This might be a problem.
I'd suggest using a AA battery pack. 4 AA batteries will give you around 5V. The Arduino doesn't require a precise 5V, so you don't need a voltage regulator.
I'd suggest using something like a Arduino Pro Mini, or Arduino Micro, as those don't have USB-to-Serial chips on the board, using up power all the time. Remove the power led, and put the uC to sleep as much as possible.
If you want accurate timing, you'd want to add and RTC module.


text:
manual square wave period is off
I'm generating a square wave with my Arduino UNO using the following:
#define pin 10 // data pin to control servo

// pulse width (in microseconds)
int pulsewidth = 2500; // 400 Hz

// wave period in microseconds
int period = 20000; // 50 Hz

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

void loop() {

  // turn pulse on for pulsewidth duration
  digitalWrite(pin, HIGH);
  delayMicroseconds(pulsewidth);

  // turn pulse off
  digitalWrite(pin, LOW);
  delayMicroseconds(period - pulsewidth);

}

When I check the wave freq on the scope it's reading something like 115Hz instead of 50Hz; however, the pulsewidth is correct (4Hz).
Why is this exactly?  Is it because digitalWrite() is slow?

If you want precise timing use the PWM pins. E.g. Using the Timer1 library

Your comment on the pulse width line is not correct.  2500 usec would be 400 Hz if it were a period.

Why is this exactly? Is it because digitalWrite() is slow?

There is "hidden" code in the main() function which is calling loop(). Also digitalWrite() is slow compared to what is possible. Last, the millis() ISR is executing in the background.
Try the below:
void loop() {

  while (1) {
    // turn pulse on for pulsewidth duration
    digitalWrite(pin, HIGH);
    delayMicroseconds(pulsewidth);

    // turn pulse off
    digitalWrite(pin, LOW);
    delayMicroseconds(period - pulsewidth);
  }
}

And then try turning off interrupts.
Cheers!

From Arduino reference on delayMicroseonds:

Currently, the largest value that will produce an accurate delay is 16383. This could change in future Arduino releases. For delays longer than a few thousand microseconds, you should use delay() instead.

Although the reference does not specify further what happens if delay > 16383, a look at the actual code explains this (in wiring.c):
/* Delay for the given number of microseconds.  Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */
void delayMicroseconds(unsigned int us)
{
...
#elif F_CPU >= 16000000L
    // for the 16 MHz clock on most Arduino boards

    // for a one-microsecond delay, simply return.  the overhead
    // of the function call takes 14 (16) cycles, which is 1us
    if (us <= 1) return; //  = 3 cycles, (4 when true)

    // the following loop takes 1/4 of a microsecond (4 cycles)
    // per iteration, so execute it four times for each microsecond of
    // delay requested.
    us <<= 2; // x4 us, = 4 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 19 (21) cycles above, remove 5, (5*4=20)
    // us is at least 8 so we can substract 5
    us -= 5; // = 2 cycles,
...

    // busy wait
    __asm__ __volatile__ (
        "1: sbiw %0,1" "\n\t" // 2 cycles
        "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
    );
    // return = 4 cycles
}

The line us <<= 2; explains why us should not exceed 16383, otherwise the left-shifted value will overflow (unsigned int is 16 bits on AVR).
In your situation, (20000-2500) << 2 will not be 70000 or 0x11170 in hexa (that does not fit into unsigned int), hence the result will be truncated to 0x1170 i.e. 4464, which will make the last part of the function (the busy wait) wait for the wrong duration.
In order to fix it, you have to split your second delayMicroseconds in one delay in milliseconds plus one delayMicroseconds:
delay(17);
delayMicroseconds(500);

source: Stack Exchange

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

sort: votes


text:
How can I run HC-05 on 8MHz Pro Mini?
I run an Arduino Pro Mini on ATMega328 3.3V 8MHz, and I am unable to send data over HC-05 breakout board on this frequency, and on 5V 16Mhz, it has no issues.
The Arduino code is down below:
#include <SoftwareSerial.h>
#include <Wire.h>
SoftwareSerial BT(10, 11);
byte value;
unsigned long pmillis_bt = 0;

void setup() {
  Serial.begin(19200);
  BT.begin(9600);
}
///////////////////main///////////////////

void loop () {
  if (millis() - pmillis_bt >= 100) {
    byte Data[3];
    byte cmmd[20];
    int insize;
    char str[256];
    int i = analogRead(A0);
    value = BT.read();
    Data[0] = 'a';
    Data[1] = i / 256;
    Data[2] = i % 256;
    sprintf(str, "%d", i, Data[0], Data[1], Data[2]);
    Serial.println(str);
    if (value == 49) {
      for (int j = 0; j < 3; j++)
        BT.write(Data[j]);
      value = 0;
    }
    pmillis_bt = millis();
  }
}

Basically Arduino Uno Is working On 5v Voltage Level so you can Directly connect the HC-05 Bluetooth module to it using it 4 lines VCC,TX,RX,GND.
But in Pro mini 3.3 V level due to you need to Generic 3.3V To 5V 2 Channel Logic Level Converter Bi-Directional Module
using this you can easily convert the vlotage level.
if you have to make using simple component also using
SparkFun Logic Level Converter - Bi-Directional

You are probably using the HC-05 Module with a power regulator and levelshifter designed for use with Arduinos that typically run with 5V. What you need is the plain HC-05 as can be found on AliExpress. Those run with 3.3V but it can be tricky to use them in prototypes.

I do use the breakout board though, not the ones with the pins.

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


text:
getHostByName always failing to find a valid ip
I'm using an arduino Uno and a CC3000 wifi shield. I installed Adafruit library in arduino to get access to Wifi network. I'm currently trying to run some samples that comes with the library. It successfully connects to Wifi network and returns

IP Addr: 192.168.137.101
Netmask: 255.255.255.0
Gateway: 192.168.137.10
DHCPsrv: 0.0.0.0
DNSserv: 8.8.8.8
localhost -> 172.217.22.46

Pinging 172.217.22.46...0 replies

But when it tries to connects to a remote service like "www.adafruit.com" or "www.google.com" it assigns ip to 0 which means the host ip unknown. My wifi-hotspot is capable of providing internet connection. Can anyone please tell me what can I do to access remote web site through Wifi from this configuration. Setup method of one of the sample codes that I tried is mentioned below.
void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  displayDriverMode();
  Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

  /* Initialise the module */
  Serial.println(F("\nInitialising the CC3000 ..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    while(1);
  }

  uint16_t firmware = checkFirmwareVersion();
  if (firmware < 0x113) {
    Serial.println(F("Wrong firmware version!"));
    for(;;);
  }

  displayMACAddress();

  /* Optional: Get the SSID list (not available in 'tiny' mode) */
#ifndef CC3000_TINY_DRIVER
  listSSIDResults();
#endif

  /* Delete any old connection data on the module */
  Serial.println(F("\nDeleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);

  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  while (! displayConnectionDetails()) {
    delay(1000);
  }

#ifndef CC3000_TINY_DRIVER
  /* Try looking up www.adafruit.com */
  uint32_t ip = 0;
  Serial.print(F("www.adafruit.com -> "));
  while  (ip  ==  0)  {
    if  (!  cc3000.getHostByName("www.adafruit.com", &ip))  {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }
  cc3000.printIPdotsRev(ip);
  Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip); Serial.print("...");
  uint8_t replies = cc3000.ping(ip, 5);
  Serial.print(replies); Serial.println(F(" replies"));
  if (replies)
    Serial.println(F("Ping successful!"));
#endif
  Serial.println(F("\n\nClosing the connection"));
  cc3000.disconnect();
}

You should display obtained DNS server address too. The domain names can't be resolved without valid DNS server setting.

@KIIV Sorry. I updated the question with DNS  and DHCP details.

My CC3000 wifi shield was not working correctly. So I replaced wifi shield with a new one and solved the problem. It is very hard to identify a hardware fault when it is partially working. It seems that CC3000 connecting to the WIFI network. That confuses me. But when I read about the problem and tried replacing with a new board which was successful. By the way I learnt that this same problem can be occur when you are using a public wifi connection (example- University Wifi Connection). This question is a good source that answers the 2nd kind of problem.


text:
What are the benfits of global variables over static class members?
On an embedded system we use global variables often to keep dynamic memory consumption on heap and stack low. But global variables are also considered bad programming practice if they aren't used in a global sense, i.e. they are used only inside one or two functions.
So I really want to make use of the possibilites to protect my code from myself. Of course, the instantiation mechanism of c++ is to avoid on an embedded system with low resources, like an arduino. So I write classes with static members (and member functions) only. Many of the libraries shipped with arduino seem to work this way, too.
I'm curious if there's a single drawback of moving static variables or even const arrays (designed for deposit in progmem) from global namespace to a class namespace and making them private?
I'm primarily interested in drawbacks arising from the combination of OOP with the arduino platform (using an arduino uno) with avr-gcc.

I can see no specific drawback in using static class members instead of global variables on Arduino. They will be managed the same in the end program.
The only difference I can see may arise based on how you design your classes (if design is correct, then no special problem shall arise):
Let's suppose you decale a class A:
class A {
    public:
    void f();
    void g();
    ...
    static void z();

    private:
    static int myStaticField;
    ...
};

if you need an instance of A for method f(), which does not need myStaticField, then that field exists anyway in your SRAM space.
But this is a corner-case, as in good OOD, myStaticField should be needed as soon as you need to work with class A (whatever method youwant to use).

But if I make instances of A, myStaticField will get reserved in RAM (or wherever) once only, won't it?

Yes, of course, that is the difference between static and non static members.


text:
Arduino communication to Raspberry Pi using HC-05
I'm using two HC-05 modules on two Arduino UNO boards. One of my modules connected successfully to a raspberry pi port. However the other doesn't want to connect, but sometimes it does and then randomly disconnects. When I did manage to connect both modules to port on the pi I had code written to send data to the pi and display it in the terminal but only one Arduino data would show up on the pi terminal even though both were sending data. Is there an easier way to connect the modules? I've been using the bluetooth manager tool on the pi
void setup() {
 Serial.begin(9600);
 pinMode(8, INPUT); // first sensor input
 pinMode(7, INPUT); // second sensor input
 pinMode(6, INPUT); // third sensor input
 pinMode(5, INPUT); // fourth sensor input

}

void loop()
{

    int sensordata_1 = digitalRead(8); // read status and store it into variable
     {
          if(sensordata_1 == LOW)        //  CAGE 1
          {
            Serial.println("Arduino 1 s1: 1");  //
          }
          else
          {
            Serial.println("Arduino 1 s1: 0");
          }
          delay(200);

    }
}

void setup() {
 Serial.begin(9600);
 pinMode(8, INPUT); // first sensor input
 pinMode(7, INPUT); // second sensor input
 pinMode(6, INPUT); // third sensor input
 pinMode(5, INPUT); // fourth sensor input

}

void loop()
{

    int sensordata_1 = digitalRead(8); // read status and store it into variable
     {
          if(sensordata_1 == LOW)        //  CAGE 1
          {
            Serial.println("Arduino 2 s1: 1");  //
          }
          else
          {
            Serial.println("Arduino 2 s1: 0");
          }
          delay(200);

    }
}

import serial
import time

port = serial.Serial("/dev/rfcomm2", baudrate=9600)
port_2 = serial.Serial("
port.flush() # This wil flush any input and output buffer, so it will
#avoid receiving or sending bad data

while True:

    if(port.in_waiting > 0):
        data = port.readline().decode('utf-8').rstrip() # decode will translate
        #the data from unicode to byte
        print(data)

port_2 = serial.Serial(" is most likely a copy and paste error on your part, but needs to be fixed if you want 2 serial ports to deal with
You only read from port in your Python while loop without touching port_2. This is the reason you only see output from one serial port
You should use a robust serial data packet-system. Right now you have no way of ensuring that the data received in Python is corrupt or not. You can easily use the pip-installable Python package pySerialTransfer and compatible Arduino library SerialTransfer.h (installable via the Arduino IDE's Libraries Manager).

For theory behind robust serial communication, check out the tutorials Serial Input Basics and Serial Input Advanced.

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


text:
How to use any module that has no library for arduino?
I am 2 years old in this Arduino world.
I am currently working on a project where I am about to make use of a fingerprint sensor. Now my question is that could we be able to make use of a sensor that we usually find in our mobile phones with ATmega328p microcontroller chip. And what if that there were no libraries written for Arduino so that will make my life easier. And I wonder how these tech companies make use of any sensor they would like to use without any trouble while there is no existing textbook that taught these employees while pursuing a degree in CSE or ECE about how to write code for a particular sensor. Now I know that there are certain protocols like SPI, I2C, UART, etc. But how do they do it, and how do they know about microcontrollers and IC's that were never taught to them in any degree or course? I always scratch my head while looking at the consumer electronics, and the IC's and Chips that they have on their PCB board were never found on google, And by chance, if an IC or microcontroller is found then I barely understand the datasheet or the documentation which was written in Chinese or some other language. I hope someone could help me understand how all this happens.

I assume the datasheet of the IC is the main thing you need. If that's not available, it's like reverse-engineering, but for a non trivial IC this mostly is not worth trying.

About the fingerprint sensors from mobile phones: You might find the answers to this question useful. They explain in detail, why it is not really worth the effort to try interfacing such a fingerprint sensor with Arduino.

How to use any module that has no library for arduino?

You need to read the datasheet of the module. It should explain in detail, how the module is used. When you understood, how it works, (and understanding it is really really important) you can start implementing it in code, for example by writing your own library. A library is just a wrapper around the interfacing code for that module. If the module uses common used interfaces or is even a commonly used component, you can often stand on the shoulders of giants by making use of other libraries in your library (for example using the Wire library in a library for a specific I2C sensor). That makes it easier.

But how do they do it, and how do they know about microcontrollers and IC's that were never taught to them in any degree or course?

The engineers don't get taught to use specific controllers or ICs. They get taught the fundamental principles, including common interfaces like I2C, SPI, UART, I2S ... . In the end it all comes down to the datasheet of a component. It should explain all details, that are needed to use the component correctly, or at least reference to further documents. For example most microcontroller datasheets directly explain, how I2C is implemented in these microcontrollers. You can use that to implement I2C communication, even without a preexisting library. Yes, that can be a tedious and complex task, but it is totally possible. Keep in mind, that most Arduino libraries are not written by the manufacturer of the used component, but by third party people (sometimes the community, sometimes resellers like Adafruit, e.g.).
I would say "it is not rocket sience", but yes, it can be rather difficult to dig into the very detail of interfacing a component. Without considering myself an especially smart guy, I'm writing a library for multi-master I2C communication on Attiny's (without having any degree in that field). I could start with code from others, which made the entry easier. But it also involves much time, to dig into it, write the code and test it correctly. It is difficult, but it is possible.

And by chance, if an IC or microcontroller is found then I barely understand the datasheet or the documentation which was written in Chinese or some other language.

Good manufacturers and resellers provide a datasheet in english for their products. That cannot be said for every product, that you can purchase. Writing documentation takes time and thus costs money. Chips directly from China (where most electronics is produced these days) might have less good or no documentation at all, though these chips are often way cheaper. As a hobbyist you should stick to the good documentated components, if you don't want to really dig into it.

the IC's and Chips that they have on their PCB board were never found on google

PCB designs are only found in the internet, if they are published under some open source license (or if they were illegally leaked by someone). If a company doesn't want to publish it's product designs, that is totally ok.
About the components in consumer electronics: I think you refer to that the chips often don't have a googleable product number/marking to find a datasheet. That is because often these chips are custom chips, made maybe only for this company or even this specific product. Why would they want to publish a datasheet for it? They are not meant for public use for all. The design of components is often a good kept secret, that the companies are not willing to share, since it generates their revenue.
Hobbyists and small companies use publicly available, good and publicly documented parts to make their life and investment in the project easier. Big companies can easily hire people to design a custom chip, that will only contain the needed features. (With mass produced products you can save money this way, by not always needing to buy even the unused resources of a standard controller). Another reason to use a custom (maybe even a not programmable) chip is to keep the code in it secret.

All in all keep in mind, that the hobbyist world of Arduino and the world of consumer electronics like smart phones are rather different. Sure, they rely on the same principles, but the way, how things are done and created, is very different.

Thank you so much for such a piece of detailed information. So what should I consider to learn so that I could be knowledgeable enough to develop my own custom IC? Are there any books and references for this.

To be honest: No I cannot recommend things to learn for this. There are certainly many good books out there, but I don't know enough about this field to recommend anything. Designing your own IC is way over anything here. It is not something, that you can easily learn. And you are on the wrong site here to ask for it, since Arduino is not about custom IC design. Why do you want to design your own IC in the first place? From your question I assumed, that you are not doing this as a job

I just asked to give it a try . I am actually not ready to design any custom IC. And by the way I am very much passionate to create a product and sell it. I have an idea and I wanted my imagination to get real . Since I am new to electronics as I am a CSE student. I always stick to software engineering projects. I have never really thought that I will be so much passionate about electronics as I am today. I wanted to tinker a new product that is making rounds all day in my head. But due to my background in electronics I feel like I am lost.

Electronics of IC internals are like electronics of discrete components, but much more complex. You first need to understand electronics in general, before you can even start with thinking about IC internals. I think this is out of your reach. Instead you can simply use publicly available parts to make your product and sell it. That will be way easier, especially if you want to start selling your product in this century. Take your passion and put it into normal electronics, not in designing ICs. When you have enough experience, you can still look into that topic.

Reading a datasheet is a bit of an art, and trying to start with something like an SPI sensor that lacks even demo code makes for a very steep learning curve.  If you want to learn about interfacing over one of these buses, try getting something like an LM75 temperature sensor, for which there are decent datasheets.  Then try to interface without too much googling - and without using a single line of code you don't understand

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


text:
Pause running program using a pushbutton
I have a program that flashes three LED in sequence indefinitely. How can O program a pushbutton to pause the program in the middle of the code?
Also, can I modify the code so that pressing the button a second time would speed up the flashing of the LED?
Each time I try to use a pushbutton to pause the program, it only pauses it once the program loops back to the beginning.
Here's my code at the moment (sorry, it's not very clean):
int ledpins[]   = {4, 5, 6};
int buttonpin   = 3;
int buttonstate = 0;

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

  for (int pin = 6; pin > 3; pin--) {
    pinMode(ledpins[pin], OUTPUT);
  }
  pinMode(buttonpin, INPUT);
}

void loop() {
  buttonstate = digitalRead(buttonpin);
  if (buttonstate == HIGH) {
    digitalWrite(ledpins, HIGH);
  }
  if (buttonstate == LOW) {
    for (int pin = 4; pin < 7; pin++) {
      digitalWrite(pin, HIGH);
      delay(200);
      digitalWrite(pin, LOW);
    }
    for (int pin = 6; pin > 3; pin--) {
      digitalWrite(pin, HIGH);
      delay(200);
      digitalWrite(pin, LOW);
    }
  }
}

Take a look at 'Blink without delay'.

please reformat you code so that it is properly indented and properly spaced

In setup(), you are accessing ledpins[6], which is out of bounds. 2) In loop(), digitalWrite(ledpins, HIGH) makes no sense, as ledpins is not an integer.

The problem in this code is that the for loops are blocking with delay for 1.2 seconds and only once that ends does the code come back around to check the button.  You should instead use the loop function itself to handle the looping and use the Blink Without Delay method of timing to handle the timing.  In that way the loop function is never blocked from running and can run thousands of times per second, never missing any presses of the buttons.  And also in this way you would be able to pause the program at any point, not just once every 1.2 seconds.

I would just use a pin interrupt and if the button is pressed the interrupt routine sets a flag (ie flag=1). Then in you loop just have a statement that says calls a function that is just a while loop which waits until flag variable is 0 again.  The interrupt function just toggles the flag variable every time the button is pushed. So first time button is pressed the program loops and the second time the button is pressed program execution leaves the routine and goes back to your loop().


text:
Serial communication between multiple devices (or Arduinos)
What I know from my search on the internet, for both SPI and I2C protocols, communication between multiple devices needs a master, which initiates the communication, and slaves, which respond to the master's request. Basically slaves can't initiate a transfer.
Is there any way to make different devices communicate on their will? I'm not sure about UART, but I think the story is the same here. But I know that it is possible to use a USB hub to connect multiple USB devices to one port on the computer. How can that be done? Can I use the same principle with Arduino?
To clarify what I want to do, consider that I have different modules (might be Arduinos) with different characteristics. I want to connect them on a bus line to a master Arduino. The module connections should be indifferent so that the user doesn't have to worry about which port should be used to connect the module. For this reason, using an Arduino Mega with more serial interfaces doesn't solve the problem, because we don't know which device is connected to which port.

1-Wire protocol (with a single pin) is also an alternative.

Other examples are CAN bus (standard shields are available) and PS/2 (two-side initiation (set of LEDs (and other modes) and key presses, respectively), but not really a bus). The former is a lot more complex, but also a lot more robust (it doesn't even require a common ground).

Almost any serial communication system can be "bent" to make a multi-master system - some easier than others.  The biggest problem you have is that of detecting and handling collisions.
However, if you can get away with a master->slave(s) system whereby one node on your bus makes requests to the slave nodes to get them to do something and respond with information then the whole system is far far simpler.
That is the normal way that I2C and SPI work, although I2C does have multi-master in its specification (though the Arduino API doesn't handle it AFAIK).
The industry standard way of making a UART able to communicate with multiple devices is through converting it to a standard bus system, such as EIA-422 or EIA-485 (AKA RS-422/RS-485). A half-duplex multi-drop EIA-485 is probably the simplest to arrange, and there are breakout boards for the Arduino that will convert UART to EIA-485.
It is possible (if you are clever) to make UARTs directly work as a multi-drop bus, but it requires a deeper understanding of UART control registers and electrical characteristics to emulate either an open-collector or tri-state TX pin on the slaves.
Of course, for all devices to operate on the same bus they must all conform to the specified operation of the bus. For instance, for EIA-485 all the slaves must have the ability to switch the transceiver into TX mode when needed, and react only to requests from the master and never send anything unsolicited. Just hooking random devices up to a bus with a transceiver is never going to work.
As far as USB goes - that is a single master (the PC) and multiple slaves (your keyboard, mouse, printer, scanner, webcam, Arduino, etc). Hubs are just a way of wiring them all together and routing the signals to the different peripherals at the right speeds.

I2C protocol has Multi-master Arbitration Support, i.e. any I2C device can be master and slave. I2C is a multimaster bus
Master start communication, but master device can change. If one device wants to communicate, acts as a master. The problem is that before sending data you must be sure the bus is not busy with other master.
More information: https://www.i2c-bus.org/multimaster/
With UART is not possible to build a bus, only point to point communication.

Another option thats possible if you can control the firmware on each node, as in your case with multiple arduino's, is to create a ring bus using UART ports with multiple peers on it where each node would be responsible for forwarding packets to the next node.
The UART rx tz lines for nodes would have to be connected in a ring like this:

NodeA Tx => NodeB Rx
NodeB Tx => NodeC Rx
NodeC Tx => NodeA Rx

This would require design of a somewhat complicated protocol and controlling firmware on each node, and you would need to think through issues like:

how many devices can be supported on the ring
message size
how much memory is available to buffer messages on each node
how many message is each node allowed to send
etc.


text:
How does one get the correct serial port?
I don't have a correct serial port from the resource I'm working from - Getting Started with Arduino by Massimo Banzi and Micheal Shiloh. I'm using the Arduino Uno. I'm a complete noob to Arduino. In this image below, from the resource I'm working from, it specifies to use either of the ports: /dev/cu.usbmodemfa141 or /dev/tty.usbmodem.
Getting started with Arduino by Massimo Banzi and Michael Shiloh - Figure 3-2 shows a list of available serial ports.

I only have two available: /dev/cu.SSDC and /dev/cu.Bluetooth-Incoming-port.
How do I get the 'correct' serial port? Correct being: /dev/cu.usbmodemfa141 or /dev/tty.usbmodem.
Here's some possibly useful information:
I'm using Mac OS - which I'm new to - Sierra version 10.13.2.
I only have two ports on the computer a USB type - C and a headphone jack. So I have an 'adapter' that allows me to 'daisy chain' the USB - B and USB - A for the Arduino cable into the port of my computer. If any additional information is required, feel free to ask for it and I'll try and get back to you ASAP. Thanks.

Is it a genuine Arduino Uno or some cheap Chinese POS?

He or she has asked the same question before, and it's apparently a genuine starter kit

Yes genuine it's a genuine starter kit.

Any sources of information or suggestions would really help.

Sorry guys I solved it. It was really simple I just needed to plug the device in and it then detected the device and port name.

I had the same problem and had even fewer options under my Tools > Port menu. Looked at the user forums but most answers did not work for me. After watching a YouTube video, I fixed the problem by following its suggestion of installing the CH34X driver. There are some other suggested drivers if you search for some other related StackOverflow and StackExchange posts, but I did not test them (once the Mac-Arduino communication worked, I did not want to spend more time on this) and nor can I explain why this solution works.
I wrote a short article on this for myself. If you are interested, please take a quick look.
Best luck! :)


text:
Why does starting the serial monitor restart the sketch?
If I upload any sketch that sends serial data, I immediately see the TX/RX LEDs flash once the sketch is uploaded. If I then start the serial monitor, the sketch appears to restart.
A bare minimum sketch that shows this behaviour:
    void setup()
    {
        Serial.begin(9600);
        Serial.println("Setup");
    }

    void loop()
    {
      Serial.println("Loop");
      delay(1000);
    }

Tested with several boards and Mac and Windows versions of the IDE.
Example output - it goes back to "Setup" when I open the serial monitor:

Why is this?

I've never seen a sketch that uses serial not do this, so literally any sketch.

Related: Arduino serial port reset in Serial monitor & Python

Duplicate: Why does my Arduino seems to reboot every time that I open Serial Monitor?

I've got a separate problem. The Arduino leostick (and others) don't autoreset anymore. How do I renable it?

Weird. I don't think it happens to platformio or Arduino IDE on my Linux laptop, but I just noticed it with pio on Windows. It's a horrible 'feature'.

The Arduino uses the RTS (Request To Send) (and I think DTR (Data Terminal Ready)) signals to auto-reset. If you get a serial terminal that allows you to change the flow control settings you can change this functionality.
The Arduino terminal doesn't give you a lot of options and that's the default. Others will allow you to configure a lot more. Setting the flow control to none will allow you to connect/disconnect from the serial without resetting your board. it's quite useful for debugging when you want to be able to just plug in the connector and see the output without having to start the sketch over.
Another way to disable the auto reset is to put a pull up resistor on the reset pin.
Disabling Auto Reset On Serial Connection

Arduino Unos can be fixed with a 10 µF capacitor across RESET and GND. It works for the one installation I've used it for, so far …

I tried using PuTTY, connecting to the COM port the Arduino appears at (COM16 in my case). It is still resetting the Arduino if "Flow control" in Connection/Serial is set to "None" (the other options are "XON/XOFF", "RTS/CTS", and "DSR/DTR"). I used version 0.60 of PuTTY.

-cont: It was tried on an Arduino Uno R3.

The Duemilanove and Uno have a trace labeled "EN RESET" which controls this behavior. Scratch off that trace to disable auto-reset. Solder a wire across the pads to re-enable it.

The truth is always in the datasheets, the schematics and the code:
The Arduino UNO actually uses the /DTR line to trigger a reset, as you can see on the following datasheet:

The link to your schematic image is broken.

Thank you, I fixed it! I actually thought that SO was caching images, but looks like it's not, so I'll make sure to keep it always on.

done, thanks for the tip (I actually had my own site down for 10 days because I was doing some maintainance, which was just temporary)

Yes, but what actually happens? Is it due to the way the ATmega16U2 is programmed (asserting PD7 low when a COM port is opened by a program?)? Or following some standard for DTR?). And what is the implication of C5? - will it reset the main processor for both transitions (low to high & high to low)? What is the approximate pulse width (in microseconds) on the reset pin of the main processor and what does it look like?

OK, I have recorded the pulse on RESET at serial connect: https://i.sstatic.net/KV4Oa.png. You are welcome to use it in your answer.

How is this an answer? What we suppose to do with this information????

hey guys does it mean i should cut this wire?

if that's what you want, yes :)

What can RESET-EN do? Why is it there? It doesn't appear to be able to have any effect (appears to be short circuited). Or is it an error in the schematic? What is the explanation? Can you elaborate in your answer (this and other points)?

It actually does nothing, as you can see from the schematics. The reason it's there is that you can cut the DTR line between the RESET-EN legs to disable automatic reset, and if you want to reenable it, then you can solder together the two RESET-EN pads.

This fixes the problem
import os
import sys
import termios
import fcntl

        self.fd = sys.stdin.fileno()

        # Stop resetting the arduino on serial connect

        self.newattr = termios.tcgetattr(self.fd)
        self.newattr[2] = self.newattr[2] & ~termios.HUPCL
        termios.tcsetattr(self.fd, termios.TCSANOW, self.newattr)

Please provide some explanation as to why it fixes the issue.

Arduino uses the DTR line (data terminal ready)
So, with the Arduino Serial Monitor it is not possible to change the restart when established the rs232 connection.
But I'm using for example the freeware "HTerm" (under Windows). By default, it does not use the DTR signal.
Meanwhile I changed to the freeware "CoolTerm" (a bit more comfortable...): You have to deactivate "DTR Off" unter "Connection Options".
In Linux I'm using the "moserial". Under "PortSetup" you must deactivate the "handshake" ;-)
This way is more comfortable for me then adjusting the RESET pin. Also, its a nice benefit saving all the data in a log file for later analyzing…


text:
How do you take the simplest continuous reading from a Garmin Lidar Lite V4 using I2C on a Particle Boron v4.1.0?
Hey there Stack community.
I'm working with the Particle Boron v4.1.0.
I'm connecting a Garmin Lidar Lite V4 on I2C.
I'm using the LIDARLite_v4LED.h header file found in the library given for this device, "LIDAR-Lite" and my goal here is to op-check the sensor, by taking readings in the simplest way according to the .h file.
Wiring:
I've soldered 22AWG solid wire to each respective pin on the sensor:
GND : black, going directly to ground.
VCC : red, 3.3V pin on the Particle Boron.
I2C SDA : blue, SDA Pin0 on the Particle Boron with a 4.7K ohm pull-up resistor, connected to ground on one end, and running to Pin0 on the Boron.
I2C SCL : green, SCL Pin1 on the Particle Boron with a 4.7K ohm pull-up resistor, connected to ground on one end, and running to Pin1 on the Boron.
I've run an I2C scan which confirmed the address at 0x62.
According to the manual at: https://static.garmin.com/pumac/LIDAR-Lite%20LED%20v4%20Instructions_EN-US.pdf
To take a reading you must perform the following actions, which are embedded in the library's .h file functions:
"Obtaining Measurements from the I2C Interface
You can obtain measurement results from the I2C interface.

Write 0x04 to register 0x00.
Read register 0x01.
Repeat step 2 until bit 0 (LSB) goes low.
Read two bytes from 0x10 (low byte 0x10 then high byte 0x11) to obtain the 16-bit measured distance in centimeters."

#include <LIDARLite_v4LED.h>

const int I2CADDRESS = 0X62;
uint16_t distance;

LIDARLite_v4LED L1;

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

void loop() {
    L1.takeRange(I2CADDRESS);
    L1.waitForBusy(I2CADDRESS);
    L1.getBusyFlag(I2CADDRESS);
    distance = L1.readDistance(I2CADDRESS);
    Serial.printf("Distance = %u\n", distance);
}

When I run the code above the Serial Monitor shows 0 continuously for the reading, which is incorrect.
Do you happen to see what I'm doing wrong?
Here is what's happening in each respective function call above:
void LIDARLite_v4LED::takeRange(uint8_t lidarliteAddress)
{
    uint8_t dataByte = 0x04;

    write(0x00, &dataByte, 1, lidarliteAddress);
} /* LIDARLite_v4LED::takeRange */

void LIDARLite_v4LED::waitForBusy(uint8_t lidarliteAddress)
{
    uint8_t  busyFlag;

    do
    {
        busyFlag = getBusyFlag(lidarliteAddress);
    } while (busyFlag);

} /* LIDARLite_v4LED::waitForBusy */

uint8_t LIDARLite_v4LED::getBusyFlag(uint8_t lidarliteAddress)
{
    uint8_t  statusByte = 0;
    uint8_t  busyFlag; // busyFlag monitors when the device is done with a measurement

    // Read status register to check busy flag
    read(0x01, &statusByte, 1, lidarliteAddress);

    // STATUS bit 0 is busyFlag
    busyFlag = statusByte & 0x01;

    return busyFlag;
} /* LIDARLite_v4LED::getBusyFlag */

uint16_t LIDARLite_v4LED::readDistance(uint8_t lidarliteAddress)
{
    uint16_t  distance;
    uint8_t * dataBytes = (uint8_t *) &distance;
    // Read two bytes from registers 0x10 and 0x11
    read(0x10, dataBytes, 2, lidarliteAddress);
    return (distance);
} /* LIDARLite_v4LED::readDistance */

Thanks in advance for any assistance!
NOTE: The code doesn't show any errors. It's possible I damaged the chip on the sensor when I soldered, as I'm a newb to all of this! However, I've put two sensors together and tried them each separately with the same code, and got the same results in an attempt to rule this out. I did better soldering the second sensor, and find it highly unlikely I damaged them both.

Pull-up resistors need to be connected to VCC, not to ground... VCC is up, ground would be down.

Thank you romkey, I've corrected this. Unfortunately, I get exactly the same results having fixed the pull-up resistors. I have the resistors connected to 3.3V now.

According to the Wiring diagram found here: https://static.garmin.com/pumac/LIDAR-Lite_v3HP_Instructions_EN.pdf The resistors appear to be connected to ground. But it refers to them as pull-up resistors in the reference table. Now I'm uncertain if the resistors should be connected to ground or power...EDIT: SCRATCH THAT! I misread the wiring diagram, they are connected to power.

OH BOY! I solved it. I had to include wire.h and initiate Wire.begin(); in setup.

Hey glad you got it working! You figured out the hard part on your own :)

As romkey pointed out, I had the pull-up resistors wired wrong. Pull-up resistors are connected to power, not to ground.
Then I had to include wire.h and initiate Wire.begin(); in setup.


text:
Make one Arduino fire interrupt on another
Problem
I have an Arduino Duemilanove which needs to communicate with an Ardiuno Mega.  The only pin available on the Duemilanove is D13.  The Duemilanove is in charge of driving state on my robot, and the Mega is in charge of sensor readings and navigation.  The Mega needs to send drive state updates to the Duemilanove.  I2C, PWM, Serial, anything requiring different pins on the Duemilanove is out of the question at this point.
Idea
I plan to have the Duemilanove send the "pipe" pin high, triggering an interrupt on the Mega.  The ISR will send the current drive state to the Duemilanove which will change pinmode and read a digital pulse.  The length of the pulse is the drive state.
Roadblock
I am having trouble finding an example of how to set this up.  I can't get the ISR to fire, and I'm not sure why.
Mega Code
int pipe = 18;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(pipe, INPUT);
  attachInterrupt(digitalPinToInterrupt(pipe), driveStateISR, CHANGE);
}

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

}

void driveStateISR(){

  Serial.println("ISR fired");
  pinMode(pipe, OUTPUT);

  digitalWrite(pipe, HIGH);
  delay(50);
  digitalWrite(pipe, LOW);

  Serial.println("Pulse sent!");

  pinMode(pipe, INPUT);

}

Duemilanove Code
int pipe = 13;

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

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(pipe, HIGH);
  delay(30);
  pinMode(pipe, INPUT);

  unsigned long duration = pulseIn(pipe, HIGH);

  Serial.println(duration);

  delay(3000);
}

Nothing happens at all.  I'm thinking the main framework is here, but since there aren't many examples of this out there I'd love to get some other eyes on the issue.  Thanks!

You should not do delay() or Serial.print() inside an ISR. That would cause it to hang. For more information see my page about interrupts and also How do interrupts work on the Arduino Uno and similar boards?

since it is one-way communication, it should be fairly simple, as long as you decide what the protocol you intend to use.
it could be pwm for example -> the duty cycle is the encoded data; or analog output; or uart tx; ...
after that, pick who the master is and who the slave is. generally it is (much) harder to code a slave so pick the slave that has the necessary hardware on the pin you have and go from there.

PWM would be nice, but I don't have an available analog input on the Duemilanove.  As far as I know I can't read an PWM signal using pin D13, which is the only I have available


text:
Arduino Wall Wart and Relay Board Power Supply
I am relatively new to Arduino, and have been doing a project to trigger an LED/alarm when movement is detected to be over a certain threshold value. I am using an Arduino Uno, an LED/buzzer (https://www.adafruit.com/product/2994), an MPU-6050 (https://playground.arduino.cc/Main/MPU-6050), and a 4 channel relay board (http://www.seeedstudio.com/blog/2013/02/28/shield-evolution-flexible-add-ons-for-arduino/relay-shield/ - sorry it's not very descriptive).
The LED/buzzer needs a 12V DC power supply, and I am using a wall wart to supply it. I am wondering how I am supposed to hook everything up - everything online tells me that the LED needs to be connected not only to the relay board, but to a power supply as well. However, my power supply is to the Arduino itself.
Based on the following picture, I would think that I would need to take the ground wire of the LED to the power source itself, then connect the power source to the relay board Common input.

Here is the circuit without the external power, using a small LED:

And here is the current setup (note that the cables were initially shifted over by 1 on the analog input, but I have fixed that since):

Is there a way to use the wall wart as the power supply? Do I even need the relay board?

You will need the relay board.  The Arduino output 5V and so you can't use it to directly power the 12V half of the circuit.
If you can split the power from the wall wart so it powers the 12V circuit and the barrel connector on the Arduino then that should work.  If you can, then you will need to ensure that the 0v of the Arduino and the 12v circuit are tied together, otherwise the two halves of the circuit will be using different versions of 0V and you will get interesting results.
If you want to use the setup in your second picture then no you don't need the relay board, but that's only because the whole circuit is 5V.
"How do you split the power?" I hear you say, "do I need any extra hardware?"
That depends, how attached are you to your wall wart's cable?  The way I have done it is to UNPLUG the wall wart, cut the cable in "half", strip a cm of each wire and plug both ends of it into two empty rows on you bread board.  Then use jumper wires to take an additional feed off to the 12V circuit.

CAUTION Ensure you get the polarity of the wires the right way around.  You can test this with a volt metre.  I suggest red electrical tape to mark the +ve wire.
IF YOU ARE NOT CONFIDENT DON'T DO IT!

Okay that makes sense, thank you. Since I am a newbie, I'm not sure how to split the power between the two. Does that require another piece of hardware, or is it done via the wiring from the Arduino?


text:
Using MMA8451 accelerometer to count steps
I'm trying to use an Adafruit MMA8451 accelerometer to create a pedometer-type device that counts steps. I'd like to initiate a counter that says "if the x-axis readout is > some threshold, add 1 to the counter" so that once the counter reaches a certain point, I'll be able to trigger a separate event (like an LED turning on). I'm an Arduino beginner, and would appreciate any pointers in the right direction as I work through this.
I'm using the Sparkfun Redboard and the Adafruit MMA8451, and wrote a loop to check whether the x-axis readout was over 5. If it's over 5, I want it to add 1 to the accumulator. However, it's accumulating 1 each readout regardless of what the 'x' reading actually is. Can anyone tell what I'm doing wrong? A nudge in the right direction would be much appreciated.
Code is here:
/**************************************************************************/
int lastStepCount = 0;
int accum = 0;

#include <Wire.h>
#include <Adafruit_MMA8451.h>
#include <Adafruit_Sensor.h>

Adafruit_MMA8451 mma = Adafruit_MMA8451();

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

  Serial.println("Adafruit MMA8451 test!");

  if (! mma.begin()) {
    Serial.println("Couldnt start");
    while (1);
  }
  Serial.println("MMA8451 found!");

  mma.setRange(MMA8451_RANGE_2_G);

  Serial.print("Range = "); Serial.print(2 << mma.getRange());
  Serial.println("G");

}

void loop() {
  // Read the 'raw' data in 14-bit counts
  mma.read();
  Serial.print("X:\t"); Serial.print(mma.x);
  Serial.print("\tY:\t"); Serial.print(mma.y);
  Serial.print("\tZ:\t"); Serial.print(mma.z);
  Serial.println();

  /* Get a new sensor event */
  sensors_event_t event;
  mma.getEvent(&event);

  /* Display the results (acceleration is measured in m/s^2) */
  Serial.print("X: \t"); Serial.print(event.acceleration.x); Serial.print("\t");
  Serial.print("Y: \t"); Serial.print(event.acceleration.y); Serial.print("\t");
  Serial.print("Z: \t"); Serial.print(event.acceleration.z); Serial.print("\t");
  Serial.println("m/s^2 ");

  /* initiate for loop to count movement— this is the piece I'm having trouble with */
  if (event.acceleration.x >= 5);
    accum = accum + 1;
  Serial.print("X Counter: "); Serial.print(accum);

  /* Get the orientation of the sensor */
  uint8_t o = mma.getOrientation();

  switch (o) {
    case MMA8451_PL_PUF:
      Serial.println("Portrait Up Front");
      break;
    case MMA8451_PL_PUB:
      Serial.println("Portrait Up Back");
      break;
    case MMA8451_PL_PDF:
      Serial.println("Portrait Down Front");
      break;
    case MMA8451_PL_PDB:
      Serial.println("Portrait Down Back");
      break;
    case MMA8451_PL_LRF:
      Serial.println("Landscape Right Front");
      break;
    case MMA8451_PL_LRB:
      Serial.println("Landscape Right Back");
      break;
    case MMA8451_PL_LLF:
      Serial.println("Landscape Left Front");
      break;
    case MMA8451_PL_LLB:
      Serial.println("Landscape Left Back");
      break;
  }
  Serial.println();
  delay(500);

}

**Update: the output I'm getting is as follows. The "X Counter" accumulates even when the x-reading is well below 5...not sure what's going on:
X:  1Adafruit MMA8451 test!
MMA8451 found!
Range = 2G
X:  144 Y:  50  Z:  4052
X:  0.34    Y:  0.11    Z:  9.66    m/s^2
X Counter: 1Portrait Up Front

X:  138 Y:  62  Z:  4052
X:  0.34    Y:  0.11    Z:  9.70    m/s^2
X Counter: 2Portrait Up Front

X:  0   Y:  48  Z:  4040
X:  -0.02   Y:  0.11    Z:  9.67    m/s^2
X Counter: 3Portrait Up Front

X:  -780    Y:  106 Z:  3814
X:  -1.80   Y:  0.25    Z:  9.11    m/s^2
X Counter: 4Portrait Up Front

X:  -510    Y:  106 Z:  4008
X:  -1.46   Y:  0.20    Z:  9.68    m/s^2

What is your output?

Voting to close because it's a typing mistake / syntax error, and user has not returned since asking the question.

Change your if statement - remove ; (semicolon) from the end.
Use this:
if (event.acceleration.x >= 5)
accum = accum + 1;

Notice there is no semicolon after if statement

Mark as answer if it helped you.

The OP has not returned since asking the question, so I doubt it will ever be accepted. +1 for your answer.


text:
How to use a common anode 7-segment, 4-digit display?
Please take this question as an example to (my own) answer below.
I've got an 7 segment, 4 digit LED display, but I don't have any idea on how to wire it.
I don't understand the difference between common anode/cathode, and I don't have 2 pins per LED, which is strange.
Quite recently, a question on a "7 segment 4 digit common anode" got deleted.
At that very moment I was typing an answer.
Though, I still want to share my answer with you, or the person who asked it.
Please verify/update my answer with more information.
Specifically, could someone add working code, I can't at the moment.

Just curious. Did you post a question so you can answer it?

There is actually an option for that. However, the comments in my question also tell the "background story". I was answering a question, that got deleted. And felt a need to post my answer neverthless. So yes, I did. But it's a valid method and I had the answer before the question. So it made sense to me. If you've got a really good question (and answer), I could only encourage you to do the same, as it might come usefull to someone at some point.

Just as a complement to Paul's answer, I wrote a short program to show
how to drive the 7-segment 4-digit display of his figure:

This is actually a common cathode display, so the program assumes that,
as well as the particular wiring of the figure. The interesting part is
the refresh_display() function, which should be called periodically.
The algorithm is as follows:

drive the 7 anodes with the appropriate signals for one of the digits
we want to show
set HIGH the output that controls that digit's cathode through the
NPN transistor
wait for 2.5 ms (for a refresh rate of 100 Hz)
set LOW the cathode-controlling output
move to the next digit.

It should be noted that the waiting is done without blocking the CPU, by
using the technique described in the Blink Without
Delay Arduino
tutorial. Here is the program:
const int NB_DIGITS     = 4;  // 4-digit display
const int FIRST_ANODE   = 2;  // anodes a..g on pins 2..8
const int FIRST_CATHODE = 9;  // cathodes, right to left, on pins 9..12

// Digits to display, from right to left.
uint8_t digits[NB_DIGITS];

// Set all the used pins as outputs.
void init_display()
{
    for (int i = 0; i < 7; i++)
        pinMode(FIRST_ANODE + i, OUTPUT);
    for (int i = 0; i < NB_DIGITS; i++)
        pinMode(FIRST_CATHODE + i, OUTPUT);
}

// This should be called periodically.
void refresh_display()
{
    // Our 7-segment "font".
    static const uint8_t font[10] = {
        //abcdefg
        0b1111110, // 0
        0b0110000, // 1
        0b1101101, // 2
        0b1111001, // 3
        0b0110011, // 4
        0b1011011, // 5
        0b1011111, // 6
        0b1110000, // 7
        0b1111111, // 8
        0b1111011  // 9
    };

    // Wait for 2.5 ms before switching digits.
    static uint32_t last_switch;
    uint32_t now = micros();
    if (now - last_switch < 2500) return;
    last_switch = now;

    // Switch off the current digit.
    static uint8_t pos;
    digitalWrite(FIRST_CATHODE + pos, LOW);

    // Set the anodes for the next digit.
    pos = (pos + 1) % NB_DIGITS;
    uint8_t glyph = font[digits[pos]];
    for (int i = 0; i < 7; i++)
        digitalWrite(FIRST_ANODE + i, glyph & 1 << (6-i));

    // Switch digit on.
    digitalWrite(FIRST_CATHODE + pos, HIGH);
}

/***********************************************************************
 * Example usage.
 */

void setup()
{
    init_display();
}

void loop()
{
    uint32_t now = millis();

    // Change the number displayed every second.
    static uint32_t last_change;
    if (now - last_change >= 1000) {
        digits[3] = digits[2];
        digits[2] = digits[1];
        digits[1] = digits[0];
        digits[0] = (digits[0] + 1) % 10;
        last_change = now;
    }

    refresh_display();
}

Paul provided a link to a tutorial on
Parallax
that suggests using the
Multiplex7Seg
Arduino library. That library is more general than the example code
above, as it does not make assumptions about the pins used. But the big
difference between the library and this code is in the way the timings
are managed:

The library is driven by the Timer 2 overflow interrupt. This should
provide a very steady timing, at the cost of having one timer
dedicated to this job.
The code above relies on the user calling refresh_display() often
enough. It doesn't require dedicated hardware resources, but it
doesn't play well with programs that take too long to loop(): it
won't like you calling delay().

This is why I like open-source stuff. You can share workload with the rest of the world and create something really nice. Which is then shared with the rest of the world again :) You can learn a lot from other developers and that knowledge will be persistent and not just hidden from everyone else.

I have a question in mind regarding Tranistor's base resistor value. I've a great problem with calculating resistor value. What is the reason for using 4.7K resistor in four 2N2222 transistor? If a single segment consume 10mA then there will be maximum 80mA current drawing for all segment including DP. If V(BE *sat) = 1.3v and I(B) = 15mA then 300ohm will be enough. Is there any wrong with my calculation?

@maruf: The minimum required I_B is the expected I_C divided by the minimum transistor gain. If you want 80 mA on the collector and expect a gain of at least 100 (it may be optimistic, I did not check the datasheet), then you need at least 80/100 = 0.8 mA on the base. Then the maximum value of the base resistor is the voltage drop across it (about 5 V − 0.7 V) divided by that current, or about 5.3 kΩ.

I'll try and take you through the complete basics of LED's etc.
As 4-digit 7-segment displays are a combination of multiple "LED techniques".
Wiring LED's
LED's, or Light Emitting Diodes, are one of the fun things of Arduino.
Essentially, they're easy to use, power them up and they'll light up.
They can be annoying, because they have some kind of polarity, meaning that they will only work when you wire them right. If you reverse positive and negative voltage, they won't light up at all.
Annoying as it is, it's also quite usefull.
Cathode vs Anode
On a traditional LED, the long lead is the (+), Anode.
The other lead being the (-) Cathode.
"Or, if someone’s trimmed the legs, try finding the flat edge on the LED’s outer casing. The pin nearest the flat edge will be the negative, cathode pin." - Sparkfun
Source: https://learn.sparkfun.com/tutorials/polarity/diode-and-led-polarity

Basic wiring
I'm not sure if this is correct, since I ripped the image from the internet.

Wiring an LED is quite easy, the Anode (+) connects to positive voltage, preferably through a current limiting resistor.
The Cathode (-) connects to ground (with a current limiting resistor, if you didn't have one on the positive side).
The current limiting resistor will avoid the LED from shorting out, damaging the LED or Microcontroller/Arduino.
Multiple LEDs, matrices, RGB leds
With multiple LED's you often have them with the positive side connected (+), "common Anode" or all connected to the (-) "common Cathode".
Basically it'll come down to this.

For a common cathode, you supply current to the pins that you want to have on.
For a common anode, you sink the current through the LED.
Multiplexing (multiple digit, 7-segments)
You should check out the tutorial of parallax: http://learn.parallax.com/4-digit-7-segment-led-display-arduino-demo

When you've got a lot of LED's, it's often smart to "multiplex" them. Usually you go through "groups" of LED's rapidly, so that it looks like they're all on at the same time.
Usually you sink current from a column of LED's and supply current to individual LED's of a row.
Or, you supply current to a column of LED's and sink current from individual LED's of a row.
So that you can choose which column to activate, and which LED's of that column to light up. Changing these columns/rows rapidly will enable you to control multiple LED's with a lot less pins.
There even are display controllers for this, if you don't want to take care of the switching in your software.
So when you have a 4 digit, multiplexed 7 segment, common anode
The diagram will be more like this:

http://www.mytutorialcafe.com/Microcontroller%20Application%20C%207segmen.htm


text:
How to use C++20 in Arduino IDE?
I'm writing a program for esp32 using the Arduino IDE that needs to count the number of '1' bits in a byte.
I found a post elsewhere that says there's a nice function in the standard library to do it: std::popcount(value)
... the catch is, it only exists in C++20.
Where is the C++ standard level defined in an Arduino IDE project, and what do I have to do to change whatever level it selected by default when I created the project to C++20?
Update
@jsotola's comment solved my immediate problem. That said, I was still curious about changing the C++ version used by Arduino IDE.
I'm still unsure about the present version, but it appears that at least as of approximately 2018, the version of C++ used by Arduino IDE is (was?) hardwired & not something you can easily change. The bundled C++ compiler itself can probably deal with newer versions, but the IDE itself instructs it to compile the code according to an older version of C++ (C++2011 or C++2014, I believe).
There's apparently still disagreement about just how much of the C++ standard library is available to code built using Arduino with ARM, and it's more of a spectrum than black & white.
In the case of 8-bit AVR, most of the C++ Standard Library is missing (though it's sometimes possible to forcibly put back the chunks that were ripped out... I distinctly remember finding a method a couple of years ago to restore sprint's ability to format floats if you're building for something like a Mega 2560 and don't have to particularly care about minimizing size).
The (as yet unconfirmed) impression I got last night is that as of 2024, there are standard library limits imposed by Arduino IDE, but not necessarily imposed by Arduino framework. Meaning, there are language features that won't work in Arduino IDE, but will (or at least, can be forcibly made to) work if you're using something like PlatformIO and VS Code.
Likewise, changing the target C++ level (11, 14, 17, 20, 23) is semi-straightforward if you're using PlatformIO + VS Code (or some other IDE that isn't "Arduino IDE"), but effectively impossible with Arduino IDE.
I got the impression that in most cases, almost any C++ standard library can be made to compile without errors and run from the canonical source code... but libraries that have never been optimized for something like esp32 might run really, really poorly compared to their performance on a PC, or even a Raspberry Pi.
Using the population-count/Hamming-distance example, a CPU like the one in an esp32 might actually have a proper instruction to do it (I don't actually know whether it does), but the code in the "canonical" C++ standard library, having never been tweaked to optimize it for esp32, might fail to use that optimized instruction & instead compile to code that does the task in just about the worst way possible.
In the specific context of ESP32, there are apparently a lot of of as-yet-unoptimized standard library classes that make poor choices about SRAM vs PSRAM (or make no choices at all, and just ignore PSRAM) when forcibly-compiled for esp32, and do bad things with dynamic memory allocation in general.
Some of those things have improved over time as other standard-library classes the standard-library classes depend upon have been improved and optimized for esp32, but until someone who knows what they're doing makes a point of really reviewing the way code in a library compiles for esp32 and optimizes for it, it's kind of a crapshoot as to whether it will compile "well", or compile to something that would horrify you if you looked at (and understood) the generated assembly language.
Take the above with a few kilograms of skeptical doubt. It's the result of a few hours of reading about a topic I don't have a particularly deep understanding of.

https://stackoverflow.com/questions/109023/count-the-number-of-set-bits-in-a-32-bit-integer#109025


text:
What is the best way to communicate with ESP8266-01 in LAN?
I've been working on this small project, not that small for me though, for a while. Because I also had classes and exams I didn't really have time for it. But almost everything was done except that I couldn't figure out the proper way of communicating with the ESP8266-01 and I need your help or guidance or any idea that may help.
Here is what I am trying to do:
I have an Arduino Uno, an L298N motor driver, an ESP8266-01 and a small DC motor, all connected properly to my Arduino. Besides that, I also have a gamepad for PC, which I would like to control the DC motor with over the ESP8266-01.
Here is what I've done so far:
I've used the SDL library in C to get the analog stick input from my gamepad and I am able to increase and decrease the speed with my gamepad.
I've also connected the ESP8266-01 to my WiFi and I can change the motor speed from terminal using telnet (via port 80). But not accurately.
What is left is to find a proper way to communicate with the ESP8266-01 so that it responds to every request and to connect these two together so that my project is done and I can control the DC motor with my gamepad.
I was searching for a proper way to communicate with the ESP8266-01 through the terminal. I've tried using telnet (via port 80) but sometimes for some reason the ESP8266-01 won't respond my request or sometimes I lose the connection and I get a respond like below:

telnet: Unable to connect to remote host: Connection refused

Below is the code that I am using for my Arduino to control the motor speed and also the direction of it.
#include <SoftwareSerial.h>
#define DEBUG true
SoftwareSerial esp8266(2, 3); //Rx, Tx
void espsend(String);
String sendData(String command, const int timeout, boolean debug);

void setup()
{
  Serial.begin(9600);    //For Serial monitor
  esp8266.begin(9600);   //ESP Baud rate
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(9, OUTPUT);    //for speed of the DC motor
  analogWrite(9, LOW);
  digitalWrite(12,HIGH); //for direction of the DC motor
  digitalWrite(13, LOW); //for direction of the DC motor

  sendData("AT+RST\r\n", 5000, DEBUG); // reset module
  sendData("AT+CWMODE=1\r\n", 5000, DEBUG); // configure as STA

  sendData("AT+CIPMUX=1\r\n", 3000, DEBUG); // configure for multiple connections
  sendData("AT+CWJAP=\"wifiID\",\"wifiPW\"\r\n", 3000, DEBUG);
  sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
  sendData("AT+CIPSERVER=1,80\r\n", 5000, DEBUG); // turn on server on port 80

}

int connectionId;
void loop()
{
  int velocity;
  char direction[]="direction=";
  char speed[]="speed=";
  char ipd[]="+IPD,";
  if (esp8266.available())
  {
    if(esp8266.find(ipd)){

    delay(1000);
    connectionId = esp8266.read() - 48;
    esp8266.find(speed);
    if(velocity = esp8266.parseInt()){
      analogWrite(9, velocity);
    }
    if(esp8266.find(direction)){
        delay(300);
        int direction2= esp8266.parseInt();
        if(direction2 == 1){
          digitalWrite(12,HIGH);
          digitalWrite(13,LOW);
    }else{
      digitalWrite(12,LOW);
      digitalWrite(13,HIGH);
    }
}
  String closeCommand = "AT+CIPCLOSE=";  //close the socket connection
  closeCommand += connectionId; // append connection id
  closeCommand += "\r\n";
  sendData(closeCommand, 2000, DEBUG);
    }
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";
  esp8266.print(command);
  long int time = millis();
  while ( (time + timeout) > millis())
  {
    while (esp8266.available())
    {
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }

  if (debug)
  {
    Serial.print(response); //displays the esp response messages in arduino Serial monitor
  }
  return response;
}

After uploading this code to my Arduino Uno, from the terminal I connect to the ESP8266-01 through telnet 192.168.1.40 80, then I send something like +IPD,1,speed=40. This works but not always and sometimes I lose connection.
What is the best way to communicate with the ESP8266-01 in this situation? I've searched on the Internet but I didn't really get anything useful. Using telnet is not always working and I don't know how fast my ESP8266-01 could respond to those requests, as I will be sending them like in miliseconds.

Program the ESP to receive values over TCP or WebSockets, and send it over Serial to the Arduino. Don't use AT commands.

@tttapa Do you mean to program the ESP using a USB to serial converter and using the ESP8266WiFi libraries on GitHub? Do you have links related to this or a generic topic name that I can search for? Thank you. :)

Yes. A Beginner's Guide to the ESP8266 and Programming the ESP8266 using an Arduino UNO

@tttapa Thank you sooo much! :) I couldn't program the ESP directly because I don't have a USB to UART converter but I will get it as soon as possible and try as you suggested.

Did you read the second article? You don't need a USB-to-Serial converter. Although, it'll be easier if you have one. But then again: why spend $2.50 on a USB-to-Serial adapter if you can get a Wemos D1 mini for $3.50 that has a USB-to-Serial converter built-in, and gives you access to all of the ESP8266's IO pins?

@tttapa Well I just did. And you are right, I just didn't want to mess with it but your guide seems clear enough so I can follow it through. Only thing I need is a regulator now I guess. By the way, about the ATmega16U2, I am using a clone one, so would that differ anyhow?

It should work with different chips than the ATmega16U2 as well, but maybe check that there is indeed a 1k resistor on its TX pin.

If you are actually finding that the ESP is turning OFF unexpectedly, you can try to upload a new firmware AT_v0.50_on_esp_iot_sdk_v1.4.0_150918 using the official firmware tool Espressif Official Flash download tool from http://bbs.espressif.com/viewtopic.php?f=57&t=433.

Well, if that is what "connection refused" means then I will try it too. Thanks for the suggestion. :)


text:
Communication between Arduino Uno and Mega
I am working on a project which uses a set of sensors (HC-SR04). These sensors use pins 2 to 13 of the Arduino Uno. Here you can find the board:
.
I also want to add an MP3 shield (VS1053B) to it and it fills all the pins on Arduino. So I decided to add an Arduino Mega and add the sensors to it and use the Arduino Uno and MP3 shield. The problem is with connecting these two Arduinos. As I said the MP3 shield fills A4 and A5 pins too, so I can not use them to communicate with the Mega. What other options do I have?

the MP3 shield you linked doesn't use A4 and A5

and perhaps it can be used on Mega with changed pin mapping

@Juraj but it fills all pins when I put it on Arduino,

@Juraj actually I am thinking about using only MEGA, But I have no idea about changing pin mapping

the SPI pins should the shield connected over the ICSP header. it is on the same place on Uno and Mega. the helper pins are then connect to other gpio pin numbers on Mega.

all pins will be the same if the shield uses the ICSP header for SPI comunication

if you have the usual stackable shield headers on the shield, the you can connect to pins not used by the shield

@Juraj I noticed that the shield uses ICSP pins but It also uses A4 and A5 In its wiki it says:D11, D12 and D13 are the MISO, MOSI and SCLK buses of the SPI interface by default.

nothing about A4 and A5 in wiki. Yes, D11, D12 and D13 are SPI connected to D labeled pins and to ICSP header.

You can multiplex the trigger line. With 3 pins you can address up to 8 sensors. If you multiplex the reply line as well (so you can abstract out the latency) you only need 2 additional pins for the actual trigger and reply.

So I do not need Adruino mega anymore? Can you give me a link about multiplexing the trigger line?sorry I am new to adruino

Salam, you could somewhat multiplex the HC-SR04 Ultrasonic Sensor by using I2C(IIC) instruction on how to convert those into I2C and by using OctoSonar library can be found here so that only the SDA(pin16) and SCL(pin17) pins on your Arduino UNO will be used.
https://hackaday.io/project/19950-hc-sr04-i2c-octopus-octosonar


text:
Nano + ESP8266 control pins with REST API
I connected and flashed successfully an ESP8266 module to a Nano. Now I want to control pins values with a REST API, but all the libraries I found are for using standalone ESP8266 modules (without Arduino) or for Arduino with some other modules like CC3000 etc. Can anybody recommend a library please?

break the problem into parts: 1. get the api to talk to the nano. 2. get the nano to control the pins. #1 is harder

i can communicate with nano and send AT commands thorough it so all i need is a library

we're getting to the key part: you can send commands to it. Thinking about it, you might not be able to accept http connections to it, as a server. That makes sense, because it would be hard to code the back and forth with the server over serial. TBH, using the ESP as a module is weak sauce; the ESP is far faster, has way more RAM and flash. it's usually easier to push data from your 5v sensors on a nano into the ESP and then talk to the world with the ESP. I don't know why everyone does it backwards at first...

You can use Firmata to control the Arduino pins, just having the ESP8266 publish a web page exposing the Firmata operations you desire to expose and sending the user actions to the Arduino via serial using the Firmata protocol.
To make your life easier you can consider your ESP8266 an equivalent of your serial console: everything you write from the ESP82667 becomes input data on the console for your Arduino and the other way around.
In Firmata, each command can be read from a generic Stream, with Serial being the default implementation.


text:
Using dynamic variables in URL
I am trying to upload longitude and latitude data into MySQK using a GPRS shield, Arduino Uno R3 and a GPS module. The idea is to get longitude and latitude data from the GPS and use the GPRS to post the information into my database.
I have to insert the latitude and longitude data into the URL like  this steetalert.co.zw/write_data.php?Longitude=12.124311,Latitude=27,766785. Values for longitude and latitude have to be dynamic not static. How do I go about this?

This isn't really an appropriate place to ask people to write entire programs for you. Post the code you've got so far and explain where you're having trouble.

It looks like you need to know how to create a string that contains:
steetalert.co.zw/write_data.php?Longitude=12.124311,Latitude=27,766785
Its quite easy (I think) try this:
const int cDecimalPlaces(6);
String szLon = String(fLongitude, cDecimalPlaces);
String szLat = String(fLatitude, cDecimalPlaces);
String szUrl = "steetalert.co.zw/write_data.php?Longitude=" + szLon ",Latitude=" + szLat;

Normally I would use sprint or a Format function, but I can't find those in the reference.

authors: Олег Разницын


text:
Gravity fan does not work when powered by 3.3V ESP8266
The gravity fan has 3 pins. I connected one pin to the ground, one pin to the digital pin numbered 2 on ESP8266. I uploaded this code but the fan doesn't run at all. The fan supposedly uses a 5V power supply but the ESP8266 only supplies 3.3V. Could this be the problem?
void setup() {
  pinMode(2, OUTPUT);
}

void loop() {
  digitalWrite(2, HIGH);
}

If the fan needs 5V power you need to give it 5V power. 3.3V logic is not 5V power.

Don't power stuff from I/O pins. An LED may work, but a fan will require too much power and also has a possibility to generate power (when turned by hand/wind) and may damage the pin.

The ESP can only supply 12 milliamperes of current. The fan most likely uses a whole lot more. You could for example uses a transistor to turn on the fan.


text:
ESP32: Disable Brownout Detector
I have an ESP-WROOM-32 and I'm using Arduino IDE to push code on it. My ESP is powered via 2 AA batteries and got one power supply problem.
It works well on new battery but after a bit, I will always get this error repeatedly:

ets Jun  8 2016 00:22:57
rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0,
  SPIWP:0xee
  clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
  mode:DIO, clock div:2 load:0x3fff0018,len:4 load:0x3fff001c,len:812
  load:0x40078000,len:0 load:0x40078000,len:11584 entry 0x40078a60
Brownout detector was triggered

So, I know that it's possible to disable that feature in ESP32. My question is how to do it?
What I have done that didn't work:
Add this code in my Arduino IDE:
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
setup(){
    WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
}

Change Arduino\hardware\espressif\esp32\tools\sdk\sdkconfig with:
CONFIG_BROWNOUT_DET=                //previous was "=y"
CONFIG_BROWNOUT_DET_LVL_SEL_0=      //previous was "=y"
CONFIG_BROWNOUT_DET_LVL_SEL_1=
CONFIG_BROWNOUT_DET_LVL_SEL_2=
CONFIG_BROWNOUT_DET_LVL_SEL_3=
CONFIG_BROWNOUT_DET_LVL_SEL_4=
CONFIG_BROWNOUT_DET_LVL_SEL_5=
CONFIG_BROWNOUT_DET_LVL_SEL_6=
CONFIG_BROWNOUT_DET_LVL_SEL_7=
CONFIG_BROWNOUT_DET_LVL=           //previous was "=0"

Why do you want to disable it? It's there for a reason: Your batteries are too flat to reliably power the ESP-32.

Because the manufacturer of the device told me to do it, but he's using ESP-IDF and I prefer to code with Arduino

What kind of batteries are you using?

I'm using 2 AA batteries each 1.5V

I asked what kind, not what size.  Alkeline? Zinc Carbon? NiMH?

Alkaline Plus Power by Panasonic

At 100mA average current you can expect those to last about 20 minutes before they go below the minimum voltage for the ESP-32.

Are there any batteries than I can use AA size that can power up my ESP-32 and last more than 20 minutes ?

For battery operation you have to use very aggressive power saving modes of operation.

I already have sleep mode for the device. It wakes up every 15 minutes to send data to a server via wifi then go back to sleep. Maybe LiFePO4 batteries will solve the problem ?

You might have more luck getting an answer by asking the authors of the ESP plugin for the Arduino IDE, since they are far more intimate with the internal workings of the ESP-32 and ESP8266 that we are here.

Alkaline battery will start at 1.5v but very quickly drop to around 1.2v and stay between 1.1 and 1.2 for most of its discharge depending on current until it's flat and it drops below 1.1v.  That means 2xAA is getting you 2.2V to 2.4V for most of the battery's life except the first little bit. You need 3xAA (alkaline, but also most other types) for reliable operation of a 3.3V MCU, plus an LDO. Disable brownout detection if you know what you're doing and know that your application can reach a certain undervoltage without consequence.

For me brownout issue was solved by removing the esp32 from Arduino IDE board manager + removing files from disk and use install procedure "Using Arduino IDE with the development repository" - https://github.com/espressif/arduino-esp32/
I guess it will use newer version of arduino-esp32 that has some brownout protection due to CONFIG_REDUCE_PHY_TX_POWER being activated by default. Also you should probably learn how to decrease wifi power + deep sleep for longer battery usage.

Maybe it's silly but I added a delay to my script before I got the error.
Serial.println("Delay 5s Brownout detector was triggered");
delay(5000);


text:
Sketch Memory and EEPROM
Since I'm running out of sketch memory, I've decided to use the 512 bytes of EEPROM memory by using EEPROM.put(addr,variable). But every time I use this my sketch memory use in gradually increasing. What am I missing in writing data to EEPROM? Why is the sketch memory use increasing? I'm using Arduino Pro Mini.

The same answer than to your previous question

@gre_gor  NO  , im asking why is the sketch memory increasing when i use EEPROM.put call .@Mikael Patel has delivered an appropiate answer see that :)

What am i Missing in writing data to EEPROM ? Why is the Sketch memory getting increased ?

Reading and writing to EEPROM will increase program memory size. They are function calls. One way to reduce code is to read/write blocks instead of single bytes. Post some code and we can help you rewrite to something smaller. There are plenty of tricks.

authors: Артур Габриелян

authors: Дмитрий Гуреев


text:
Why isn't the RPM displayed on the LCD?
I manage to control a brushless motor using a 4x3 keypad. I am able to key in the speed (using a servo value of 0-180) and the time for the motor to run. Besides that, while the motor spins according to the speed and time entered, I am using an Infrared Obstacle Avoidance Sensor module to calculate the RPM. However, I cannot seem to be getting the RPM to display on the LCD screen. I copy-pasted the Infrared Obstacle Avoidance Sensor module code from https://www.instructables.com/id/Simple-Motor-Speed-Tester-Tachometer/.
I have tried the code from the link on my sensor and it works very well. However, when I incorporate the IR coding from the link with my speed and time control coding, the code from the link does not seem to work.
So, why does the code from the link cannot function when I combine it with my code? How do I resolve this problem?
Below is the code, I am hoping for any guidance and advice from the experts. Thanks in advance. Any suggestion or changes are welcome.
#include <Keypad.h>
#include <Wire.h>  // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
Servo myservo;
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
// Set the LCD I2C address

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] =
{
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {9,8,7,6}; //row pinouts of the keypad (L1, L2, L3, L4)
byte colPins[COLS] = {5,4,3}; //column pinouts of the keypad (R1, R2, R3)
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const int dataIN = 2; //IR sensor INPUT
unsigned long prevmillis; // To store time
unsigned long duration; // To store time difference
int rpm; // RPM value
boolean currentstate; // Current state of IR input scan
boolean prevstate; // State of IR sensor in previous scan

void setup() {
  pinMode(dataIN,INPUT);
  Serial.begin(9600);
  lcd.begin(20,4);
  myservo.attach(11);
  prevmillis = 0;
  prevstate = LOW;
  lcd.setCursor(4,1);
  lcd.print("SPIN COATER");
  lcd.setCursor(6,2);
  lcd.print("MACHINE");
  delay(5000);
  lcd.clear();
  lcd.setCursor(3,1);
  lcd.print("S = speed(sv)");
  lcd.setCursor(3,2);
  lcd.print("T = time(sec)");
  delay(5000);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Servo value (sv):");
  lcd.setCursor (3,2);
  lcd.print("Between 103-180");
  delay (10000);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("S=");
  lcd.setCursor(0,1);
  lcd.print("T=");
  lcd.setCursor(0,2);
  lcd.print("S=");
  lcd.setCursor(0,3);
  lcd.print("T=");
  lcd.setCursor(10,0);
  lcd.print("S=");
  lcd.setCursor(10,1);
  lcd.print("T=");
  lcd.setCursor(10,2);
  lcd.print("RPM");
}

void loop() {
  // RPM Measurement
  currentstate = digitalRead(dataIN); // Read IR sensor state
  if(prevstate != currentstate) {
    // If there is change in input
    if(currentstate == HIGH) {
      // If input only changes from LOW to HIGH
      duration = ( micros() - prevmillis );
      // Time difference between revolution in microsecond
      rpm = (60000000/duration);
      // rpm = (1/ time millis)*1000*1000*60;
      prevmillis = micros();
      // store time for nect revolution calculation
    }
  }
  prevstate = currentstate;
  // store this scan (prev scan) data for next scan
  lcd.setCursor(10,3);
  lcd.print(rpm);
  int stage1speed = getTheNumber();
  lcd.setCursor(2,0);
  lcd.print(stage1speed);
  lcd.print("sv");
  int stage1time = getTheNumber();
  lcd.setCursor(2,1);
  lcd.print(stage1time);
  lcd.print("sec");
  int stage2speed = getTheNumber();
  lcd.setCursor(2,2);
  lcd.print(stage2speed);
  lcd.print("sv");
  int stage2time = getTheNumber();
  lcd.setCursor(2,3);
  lcd.print(stage2time);
  lcd.print("sec");
  int stage3speed = getTheNumber();
  lcd.setCursor(12,0);
  lcd.print(stage3speed);
  lcd.print("sv");
  int stage3time = getTheNumber();
  lcd.setCursor(12,1);
  lcd.print(stage3time);
  lcd.print("sec");
  if (stage1speed > 0 && stage1time > 0 && stage2speed > 0 && stage2time > 0 && stage2speed > 0 && stage2time > 0) {
    myservo.write(stage1speed);
    delay(stage1time*1000);
    myservo.write(stage2speed);
    delay(stage2time*1000);
    myservo.write(stage3speed);
    delay(stage3time*1000);
    myservo.write(0);
    stage1speed = 0;
    stage1time = 0;
    stage2speed = 0;
    stage2time =0;
    stage3speed = 0;
    stage3time =0;
  }
}

int getTheNumber() {
  char buffer[4];
  // Input up to 3 numbers until we find a * or #
  int i=0;
  while (1) {
    char key = keypad.getKey();
    // If it's a number AND we have space left, add to our string
    if ('0' <= key && key <= '9' && i < 3) {
      buffer[i] = key;
      i++;
    } else if ('#' == key && i > 0) {
      // If it's a * or #, end
      // Null terminate
      buffer[i] = 0;
      int value = atoi(buffer); // Convert to an integer
      break;
    }
  }
  return atoi(buffer);
}

Why you are using  'LiquidCrystal_12C.h  library for display ?

What LCD are you using?

Because my lcd have I2C shield. I'm using 20x4 LCD display with I2C shield.

Might need to consider the int range in this statement; "rpm = (60000000/duration);"

what is suitable for the rpm formula??

What LCD library are you using? Based on what is online, the LiquidCrystal_I2C.h instantiates with 3 arguments (+ 1 optional):

LiquidCrystal_I2C(uint8_t lcd_addr, uint8_t lcd_cols, uint8_t
  lcd_rows, uint8_t charsize = LCD_5x8DOTS);

So an example of creating an object of it would look like this:

LiquidCrystal_I2C(0x3F,16,2);

Whereas for LiquidCrystal.h, it instantiates with either 6, 7, 11 or 10 arguments:

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

I truly believe my lcd is not the problem. I am using a 20x4 LCD display with I2C shield. I have tried running the code from the website https://www.instructables.com/id/Simple-Motor-Speed-Tester-Tachometer/ . The changes I have made on the code from the website was changing the LCD command and use the command for LCD 20x4 I2C.  When I tested it, the rpm sensor works and the rpm displayed on the lcd.  However, combing it with my own coding of speed and time control, the sensor does not work and no rpm display on lcd

Did your check whether the if statement was executed? Coz if it does not, there would never be a delay in your main loop, and you would not be able to see anything in your LCD Display

Other than that, did you check whether the getTheNumber() function is working properly, outputting the correct values?

Before I add the rpm measurements code, the speed and time control coding work perfectly fine, just how I wanted it to be.  Now with the addition of rpm measurement code. The rpm of the spinning motor is not show on the LCD.   Is this have something with delay()??   Does the delay() causing the reading of rpm not shown of the LCD??  Is there any other way for me to change my coding so that the speed, timing and rpm  measurement work as a single functional unit?

Maybe you can try out something like multi-threading of the display (or Protothread for Arduino's case)? There are quite a few examples on it online.


text:
Arduino Uno - Multiple modules for HDMI switch device
I have an Arduino Uno device that uses the following modules:

16 PIN LED w/ Backlight
RFID - RC522 (RFID Reader)
HR911105A (LAN Module - HanRun)

These three modules use every digital pin available in the Uno (2-13) and
it works correctly. The problem is that I want to add a relay to this board. I am new to Arduino so I use tutorials and right now I do not fully understand how this works. So I have connected the IN pin of the relay to Uno pin 8 and the NO pin of the relay to Uno pin 13.
The problem is that when I don't use other modules the relay works correctly (using this code).
int relay_pin = 8;
int led_pin = 13;

void setup() {
  pinMode(relay_pin,OUTPUT);
  pinMode(led_pin,OUTPUT);
  digitalWrite(led_pin,HIGH);
}

void loop() {
  digitalWrite(relay_pin,HIGH);
  delay(5000);
  digitalWrite(relay_pin,LOW);
  delay(5000);
}

The remaining ports are 1 and 0, which I assume are TX/RX, and can't be used for relay (am I wrong?).
So obviously I should not be using those pins but I wonder which pins I am allowed to use simultaneously when using two or three modules at the same time.
Does it depend on the modules or are there some instructions?

What are you trying to do with the relay? What drives you to think you want to connect the NO pin to pin 13 of the Arduino?

@Majenko Turn on a LED - instructions in here link

Ohkay.... that's just ... bizarre.

Ah, I see why he thought it would be good to wire it that way - he has no clue about the Arduino's schematics or design and thought there was a resistor on that pin so you wouldn't have to use one. BZZZT. Incorrect. Disconnect the relay from pin 13. You have no reason to want to use that pin. You only need one pin for the relay.

@Majenko So i connect one pin straight to GND - other one to pin 8. Right ? and can i use pin 1 or 0 ?

The relay wiring diagram you are following is just plain bizarre and the strangest one I have ever seen.
Ignore it. It is completely incorrect.
You only need one pin to control a relay, so disconnect it from pin 13.
The switched side can connect to anywhere where you would normally use a switch - such as to switch power to an LED connected between +5V and GND with a suitable current limiting resistor.
You can use any available pin to control the relay, and that includes pins 0 or 1 if you aren't using serial communication.  Note that with the relay connected to one of those pins it will most likely activate and buzz while you upload a sketch - best to disconnect it at that point and reconnect it afterwards.

Devices like relays and LEDs need their own dedicated pin. They can't be shared with other functions or each other.
The only devices that can share pins are devices which connect to a bus, such as SPI or I2C.


text:
How to make ESP8266-1S module work on Arduino Uno?
I currently have an Arduino Uno with an ESP8266-1S. However I can't make them work... I use the ESP8266wifi.h library and its connection functions do return a true (returns true when received a valid IP), but I can't find it in my network...
When I send 'AT' ending with CR and NL on 115200 baud I still don't get a response.
Also, do I have to connect RX with RX and TX with TX or RX to TX and vice versa?
And also, do I need any converters? Because now I directly connect the TX and RX to the Arduino's TX and RX.
So this is how my board looks like:

So what am I doing wrong?

Are you sending the "AT" from code running on your Uno or are you sending it from the Serial Monitor (or any other terminal program running on your computer)?

I send it using the serial monitor from Arduino

ESP8266 WiFi module and 5V Arduino connection

you need to short rst to gnd on the uno to bypass the avr and use uno as an "ftdi"

do I have to connect RX with RX and TX with TX or RX to TX and vice versa?

If you want to do serial communication between a sketch running on the Arduino and the ESP8266 you must connect the RX pin on the Arduino to TX on the ESP8266 and the TX pin on the Arduino to TX on the ESP8266.
If you want to do serial communication between the Serial Monitor on your computer through the USB port on the Arduino to the ESP8266 you must connect the RX pin on the Arduino to TX on the ESP8266 and the TX pin on the Arduino to RX on the ESP8266.
TX stands for Transmit and RX stands for Receive. So it makes sense that you should connect the transmit pin to the receive pin in the first case. But why connect transmit to transmit and receive to receive in the second case? The reason is that you are not communicating between the main microcontroller (ATmega328P on the Uno) and the ESP8266. You are communicating between the USB-serial chip on the Uno (usually ATmega16U4 on the official Arduinos or CH340 on the clones) and the ESP8266. The main microcontroller is not being used at all, you're just using the Arduino as a bulky and inconvenient USB-serial adapter.
In fact some people will go so far as to remove the ATmega328P from their DIP Unos for this purpose. The RX pin on the USB-serial chip is connected to the TX pin on the main microcontroller as well as the TX header pin and vice versa for TX pin on the USB-serial chip. This means by connecting the ESP8266's TX pin to the TX pin on the Uno's header you are actually connecting it to the RX pin on the USB-serial chip. I would highly recommend getting a USB-serial adapter made for this purpose rather than trying to use an Arduino. You can buy FTDI FT232 or CH340 breakout boards on eBay or Aliexpress for < $2 USD w/ free shipping.

do I need any converters? Because now I directly connect the TX and RX to the Arduino's TX and RX

This is actually two questions. Let's address the easy one first. The TX pin of the ESP8266 is going to put out around 3 V. Even though the ATmega328P is running at 5 V this will still be seen as a high so no level conversion on that pin is necessary.
Now for the question of whether it's needed on the ~5 V level from the Arduino to the ESP8266 RX pin. There's a lot of disagreement on the question of whether the IO pins on the ESP8266 are 5 V tolerant. We certainly know that it's possible to connect the ESP8266 to 5 V levels as there are many projects published online that do this but the question is will this will shorten the life of the ESP8266?
The datasheet for the ESP8266 does not say the inputs are 5 V tolerant. There is a statement on the ESP8266 forum from a member of the Espressif (creator of the ESP8266) staff:
http://bbs.espressif.com/viewtopic.php?t=1145

We donot recommend you to apply 5V to IO.

We have a comment from someone on Facebook named "Teo Swee Ann" who appears to be the CEO of Espressif:
 https://www.facebook.com/groups/1499045113679103/permalink/1731855033731442/?comment_id=1732364133680532

i can reply officially here: it is 5V tolerant at the IO. while the supply voltage is at 3.3V.

So there is conflicting information and none of it has been presented in the most official manner, such as actually putting it in the datasheet. One thing we do know for sure, you will not harm the ESP8266 with 3.3 V levels. So the safest option is to avoid giving it 5 V inputs. However, as you are currently struggling just to get the most basic communication working the extra complication introduced by adding level shifting circuitry may not outweigh the possibility of reducing the life expectancy of your ESP8266.

Thank you for your great answer ,but I still have some questions: for serial com, do I have to connect the TX and RX both to the RX of Arduino? Or is it a typo? And when I try to upload the code, I get the espcomm_upload_mem failed error... And can I give the module 5V supply voltage for testing, or is that a total no-go?

That was a typo. I've fixed it now. Thanks for pointing that out. It should be TX-TX, RX-RX for communication from Serial Monitor to the ESP8266.

Regarding the espcomm_upload_mem failed error. Are you trying to upload code directly to the ESP8266 using the Arduino IDE? That's fine but be aware If you do that you will overwrite the AT firmware and will no longer be able to use the ESP8266wifi library on the Uno or control it from the Serial Monitor using AT commands unless you reinstall the AT firmware. Note that there is a library named ESP8266WiFi included with the Arduino ESP8266 core that has a similar name but is completely different from the ESP8266wifi library.

Regarding 5 V supply voltage. You should never power the ESP above 3.6 V and I wouldn't go much above 3.3 V to be safe. The discussion about 5 V tolerance is only for the IO pins. There has never been any confusion regarding the maximum supply voltage, that is stated clearly in the datasheet. Some ESP8266 boards do have voltage regulators that allow them to be powered by 5 V but they reduce the voltage to the ESP8266 to 3.3 V. The ESP-01 type module shown in your wiring diagram does not have the voltage regulator.


text:
Arduino Due's clock frequency
I want to change the clock frequency of the Arduino Due. The default value of the main clock, according to the SAM micro-controller, is 4 Mhz. But I found in some forums that it is 84 Mhz. But I need to work with it at 16 Mhz. Hence, I need to access to the low-level clocks of the Due and change its operating clock frequency.

How can I find the low-level registers of the Due in the Arduino IDE? Any header files for the Due to change its clocking?
Is it possible to write code for the Arduino Due via Atmel Studio 7? When I tried compiling code in AS7, Chip.h was not found. How to avoid this? Is it possible with "micro" IDE in AS7? Can I access registers of the Due via AS7 and change its clocking?
I cannot find the "sam" library in the Arduino IDE. Only avr is present. How can I find this sam library?

Also asked at http://forum.arduino.cc/index.php?topic=509923.msg3475820#msg3475820, which might give some context for the question.

How can I find the low-level registers of the Due in the Arduino IDE? Any header files for the Due to change its clocking?

Read the datasheet / programming manuals for the chip. The Arduino Due is arranged to run at 84MHz.

I cannot find the "sam" library in the Arduino IDE. Only avr is present. How can I find this sam library?

Install it. The IDE is (fairly) modular these days.
But I have to ask... why do you want to run at 16MHz?

Sorry for the late post ! I am performing SPI and I want to change the  clock frequency. My slave can maximum run at 16 mhz. I found a way to change the frequency by   SPI.setClockDivider(21); this sets to 4 mhz for SPI.