text:
How do I set up an ATTiny861A-PU for flashing with Arduino Uno?
I have found instructions for 8 pin Tiny but none for my 20 pin. How do I set this chip up on the breadboard for bootloading with Arduino?

First you need to find (or implement) an Arduino core for the MPU. After that comes the easy part - flashing the device.

@Bookshire did you "defined" attiny for Arduino IDE? have you installed ATTiny Core?

The principle is the same, it's all only ISP (In System Programming), and nothing different from any other microcontroller, that uses ISP. Look at the descriptions of the used pins for the 8-pin Attinys, then connect the pins with the same description on your 20-pin chip.
Namely you have to connect the pins MOSI, MISO, SCK, RESET, VCC and GND. MOSI and MISO are the data lines, SCK the clock signal. If you look into a pinout diagram or - even better - at the pin configuration diagram in the chips datasheet, you will see pins, that are marked this way. The rest of the pins is pretty much self explaining.

Since you are using an Uno as programmer and didn't have a capacitor between Reset and ground of the programmer, I will explain, why this capacitor is needed here.
The Atmega328p on the Uno doesn't have a native USB interface. So in order to connect it via USB to a PC, there is another microcontroller on the Uno (on original board the Atmega16U2), which has a native USB interface. This microcontroller then is the middleman between Atmega328P and PC. It connects to the Serial (UART) interface of the 328P and translates that to USB communication.
Everytime that the corresponding serial port is opened on the PC, the PC sends a DTR signal, which is connected to the 328P's reset pin. So, when the Arduino IDE tries to connect to the Serial port for flashing the Attiny, the Uno get's resetted and hence cannot flash the Attiny.
The capacitor between Reset and Ground will hold the Reset pin high for long enough, so that this reset does not happen and the Uno can do it's duty.
On Arduino boards with native USB interface this is not necessary, since they don't have this hardwired connection to a reset and they communicate directly over USB.

I have done as the instructions on arduino's site. I've used the "old style" when connecting them.
First I load the sketch and then I use burn bootloader.
This is the error I get:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding

What do you mean by "old style"? The error shows, that you have a problem with the programmer, not with the to-be-flashed chip. I assume, that you want to use an Arduino as ISP programmer. Have you uploaded the ArduinoISP sketch to it before trying to flash the ATtiny? Also do you have the capacitor between reset and ground of the Arduino?

Old style - Arduino homepage explaining the set up uses that terminology.
Use an Arduino as ISP - Yes, you assume correct.
Have you uploaded the scetch? - Yes, I am uploading the scetch to my Arduino before I try to flash.
Have a capacitor between reset and GND? - No, I have not added one. I am following the instructions from Arduino's homepage. What size is the capacitor supposed to be?

What type of Arduino do you use as programmer? The capacitor is important for all Arduinos, that don't have a native USB interface (for example Uno or Nano). This Arduino site states 10uF for it. I used 47uF successfully for flashing an Attiny.

I am using an Arduino Uno. I don't have capacitors of those sizes, so I will have to try this approach another day.

I appreciate the extra information of why it's needed, thanks. I have found one with the value 22uF/25V. Will this suffice?

Yes, that should work. If this is an electrolytic capacitor, be sure so use the correct polarity.

Well, atleast now I get a different error message. avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x20


text:
Trying to light an LED with one Button and have no idea what is wrong
New to Arduino. I am trying to use a single button to light and turn off a single LED. I followed an online tutorial (youtube video) and changed the code just a bit. I know it is for two LEDs but I tried it for one. I have no idea why it is not working. I don't see why it doesn't make sense but it just does not work.
Here is the code:

float LengthPush = 0; // LengthPush is the amount of time the button has been pressed.

int ShortPush = 100; // 100 ms push. Supposed to turn on the LED.
int LPush = 1000; // 1000 ms push. Supposed to turn it off.

int ButtonPin = 2;
int RLED = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(ButtonPin, INPUT_PULLUP);
  pinMode(RLED, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  while (digitalRead(ButtonPin) == LOW) {
    delay(100);
    LengthPush = LengthPush + 100;

    Serial.print("ms = ");
    Serial.println(LengthPush);
  }

  if (LengthPush >= LPush) {
    digitalWrite(RLED, LOW);
  } else if (ShortPush <= LengthPush < LPush) {
    digitalWrite(RLED, HIGH);
  }
  LengthPush = 0;
}

Are you getting compiler errors? If yes, you have to include them into your question. "Doesn't work" is not a good description. I would think, that the else if statement throws an error, because you try to compare 3 values in 1.

I just got it right!  My mistake was comparing 3 values. I thought i had to specify that the press length had to be more than 100ms, but less than 1000 if I wanted it to turn on. Turns out the compiler already does that. Thank you for answering.

Also you can remove the semicolons directly after each opening bracket {. Also try to align your code so that each nested { is indented one level according to its nested level.

I formatted your source code in Question. How do you like it?

@chrisl I suggest you to write your comment as an answer, so the OP can close the question

I think your problem lies in the else-if-statement, where you try to compare 3 different values. While this doesn't thrown a compiling error in my Arduino IDE, it will probably not do, what you are trying to achieve.
Instead you need to compare LengthPush with one value and then with the other. You can even do this inside the same if statement:
if(ShortPush <= LengthPush && LengthPush < LPush)

The && is the boolean AND operator, which means, that the if statement will be executed, if both statements around it will evaluate as true.

I'm not sure, what actually happens with your original code, since it doesn't throw a compilation error. It might be (and that's my theory here), that the program will first evaluate ShortPush <= LengthPush and then compare the result to LPush. Since boolean values evaluate as 0 or 1 in integer calculations, that messes up the whole intent of this. Take the case, that LengthPush is really in the required interval. Then the first part will evaluate as true, which means 1 as integer. Then this 1 get's compared to LPush, which is always higher, so the overall result is true. But the same result comes, when LengthPush is smaller than ShortPush.

source: Stack Exchange

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

sort: votes


text:
Can HC-05 Continuously Stream data and read data at the same time?
I am trying to have my Arduino Stream an Analog Signal using Bluetooth Module (HC-05) while being able to read commands from another Micro-controller using the same Bluetooth Module.
Currently, I am using Arduino Uno for this.

What you are asking for really depends on the underlying hardware.  There are so many different Arduino platforms using so many different processors.  And you didn't even specify which Arduino you have.  You didn't even specify the data rate you require for your project.

If you're using SoftwareSerial then probably no, you can't. SoftwareSerial is strictly half duplex. You can't receive while sending, and if you're sending a lot then you never have time to receive.

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


text:
Attempting to monitor serial output for a string to trigger function, apparently matching string is output but the function doesn't trigger
I'm working on my second Arduino project, and am somewhat stuck.
I'm running a PIR module from my Arduino Uno with the following sketch:
/*
 *  PIR Sensor test
 */

 int pirPin = 6;

 int minSecsBetweenEmails = 60; // 60 seconds

 long lastSend = -minSecsBetweenEmails * 1000l;

 void setup()
 {
  pinMode(pirPin, INPUT);

  Serial.begin(9600);
 }

 void loop() {
  long now = millis();
  if (digitalRead(pirPin) == HIGH)
    {
       if (now > (lastSend + minSecsBetweenEmails * 1000l))
        {
            Serial.println("MOVEMENT");
            lastSend = now;
        }
      else
        {
          Serial.println("Too soon");
        }
    }
        delay(500);
 }

I'm monitoring the COM3 port using the following in JupyterLab with PySerial.
import time
import serial
import smtplib

to = 'myemail@myemail.com'
GMAIL_USER = 'myemail@myemail.com'
GMAIL_PASS = '**********'

SUBJECT = 'MOTION pir'
TEXT = 'PIR sensor detected motion'

ser = serial.Serial('COM3', 9600)

def send_email():
    print("Sending Email")
    smtpserver = smtplib.smtp("smtp.gmail.com",587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(GMAIL_USER, GMAIL_PASS)
    header = str('To:' + TO + '\n' + 'From: ' + GMAIL_USER)
    header = header + '\n' + 'Subject:' + SUBJECT + '\n'
    print (header)
    msg - header + '\n' + TEXT + ' \n\n'
    smtpserver.sendmail(GMAIL_USER, TO, msg)
    smtpserver.close()

while True:
        message = ser.readline()
        print(message.decode('utf-8'))
        if message[0] == 'MOVEMENT' :
            send_email()
            time.sleep(0.5)

I believe my problem is with the ser.readline() function. I've been reading the docs, they seem to say I need to provide some kind of endpoint or timeout for the function to provide for EOF, but my goal was to have the
if message [0] == 'MOVEMENT' :

continuously evaluate the output lines from COM3...
Any input at all would be very much appreciated.
EDIT: Thanks to all three of you for your help! By changing the Python as shown below I was able to fulfill the if message[0] == 'MOVEMENT' :statement
Python should have been:
import time
import serial
import smtplib

to = 'myemail@myemail.com'
GMAIL_USER = 'myemail@myemail.com'
GMAIL_PASS = '**********'

SUBJECT = 'MOTION pir'
TEXT = 'PIR sensor detected motion'

ser = serial.Serial('COM3', 9600)

def send_email():
    print("Sending Email")
    smtpserver = smtplib.smtp("smtp.gmail.com",587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(GMAIL_USER, GMAIL_PASS)
    header = str('To:' + TO + '\n' + 'From: ' + GMAIL_USER)
    header = header + '\n' + 'Subject:' + SUBJECT + '\n'
    print (header)
    msg - header + '\n' + TEXT + ' \n\n'
    smtpserver.sendmail(GMAIL_USER, TO, msg)
    smtpserver.close()

while True:
        message = ser.readline()
        print(message)
        if message == b'MOVEMENT\r\n' :
            send_email()
            time.sleep(0.5)

Use the serial console to see what the Arduino is sending. If it is sending what you expect, then it is working properly, your problem lies in your Python code, and your question does not belong to this site. If it is not sending what you expect, then remove all the Python/SMTP stuff from your question, and make it focused on the Arduino sketch.

The readline usually reads line ending characters too. Are you sure it's not the case?

And are you sure you are not comparing first character from the message with whole string 'MOVEMENT'?

Note that your timing test will fail when millis() rolls over. You should rather write if (now - lastSend > minSecsBetweenEmails * 1000l), which is rollover-safe.

Edgar, thanks for the heads-up about the millis() rollover. I guess I misunderstood the breadth of this specific StackExchange community, I was under the impression that since I'm dealing with a specific Arduino implementation it would be relevant here, but I guess not. The Uno's output is exactly what I expect, so I'm thinking it's more of a Python issue.
KIIV, as to your first comment, I've tried to add the line ending characters to the string since I'm getting the correct output from the Uno, but no luck yet.

You're confusing readlines() with readline().  The former returns an array of lines, the latter a single line.  You need to drop the [0] since you're not working with an array of lines, and you need to include the line endings that the Arduino sends:
while True:
    message = ser.readline()
    print(message.decode('utf-8'))
    if message == 'MOVEMENT\r\n' :
        send_email()
        time.sleep(0.5)

Thanks Majenko. You're correct on my confusion between those functions. I've attempted to add the line ending characters but have yet to fulfill the if statement, so I'm going to continue investigating where I screwed up.


text:
Ultrasonic Flowmeter Using TDC-GP22 and Arduino Uno
I'm working on a project of Ultrasonic Flow Meter with TDC-GP22 using Arduino UNO. I used the library of leokoppel
In my code,the configurations of the registers are copied from the Application Note of GP22, from page 22 to page 25. I didn't use the temperature sensor so I jumped those steps related to that. No calibration neither. I just want to get some results of time of flight to be able to calculate the distance between two sensors for now.
My code for test:
#include "GP22.h"
#include <SPI.h>
#include <avr/io.h>

/*
 *
 * Test setup (Arduino Uno, through 5->3.3V level shift)

 *     10 -> SS
 *     11 -> MOSI
 *     12 -> MISO
 *     13 -> SCK
 *     2  -> INT
 *     5V -> VCC
 *     GND -> GND
 *     4 -> DS18B20 temperature sensor (optional)
 */

const bool DEBUG = 1;
const int FAST_MODE = 1;
const int PIN_INT = 2;

GP22 tdc(PIN_INT, DEBUG);

float cycleFactor_ns = 0;

void setup() {

  Serial.begin(115200);
  Serial.println("Go !");

  tdc.init();

  tdc.writeRegister(0, 0x430BE800);
  tdc.writeRegister(1, 0x21444000);
  tdc.writeRegister(2, 0xA0138800);
  tdc.writeRegister(3, 0xD0A24800);
  tdc.writeRegister(4, 0x10004000);
  tdc.writeRegister(5, 0x40000000);
  tdc.writeRegister(6, 0xC0C06100);

  tdc.printConfigRegisters();

  byte a = tdc.readRegister(READ_REG_1);

  Serial.println(a,HEX);
  Serial.println("Test communication: ");
  Serial.print(tdc.testCommunication());
 }

void loop() {

  tdc.sendOpcode(OPCODE_INIT);
  tdc.sendOpcode(OPCODE_START_TOF_RESTART);
  tdc.waitForInterrupt(10000000);

  delay(20);

  Serial.println(tdc.readRegister(READ_RES_3),HEX);
}

From oscilloscope I got the right number of fire pulses(20) with right frequency(1MHz):
Signal (the blue one is the signal of transmitter before amplification, green one is after amplification, yellow one is the signal of receiver)
But what I got from the code:

Go !

attached pinChangeISR_debug

Register 0: 0x430be800

Register 1: 0x21444000

Register 2: 0xa0138800

Register 3: 0xd0a24800

Register 4: 0x10004000

Register 5: 0x40000000

Register 6: 0xc0c06100

21

Test communication:

\/Test took 180 us

1

69978000

69978000

69978000

69978000

69978000

69978000

69978000

...

21 is the first byte of register 1, and 1 is the result of testcommunication(). These two means the test of communication is successful. But the results of reading RES_3 are always the same, and the  waitForInterrupt() doesn't work(maybe the code shouldn't be written like this) -- Timeout all the time.
What I expect, of course, is the result can change each time it measures.(impossible to get exactly the same measurement of ToF all the time)
Any help appreciated!

Have you solved your problem? I am also interested to read result of TDC GP22.

I've been working with the GP22. I was wondering if you ever got yours to work. I know the datasheet says to generate a start and stop pulse across the start and stop pins, that is the route I went. I was wondering if you've made any progress since your last post about it?


text:
Using the Broadcom AFBR-S50 with Arduino
I'm trying to interface with a Broadcom AFBR-S50MV85G ToF sensor over SPI using an Arduino, which is complicated by the fact that the provided library and reference application is written for Cortex M0-based NXP microcontrollers. The documentation says that implementing the SPI, IRQ, Debug and Timer interfaces would allow use with other platforms, but it doesn't explicitly state which functions require implementations, or if all of them do, and it's not demarcated within the source code either.
The documentation lists the available command words, but no register addresses, which I believe are used by the platform-independent compiled libraries that come with it. This leaves me with no way to interface manually over SPI, meaning that my only choice appears to be to attempt to implement the platform drivers myself, which will probably take me a significant amount of time.
Is there something else I should try before sinking time into something that may not give me results? Has anyone here used this sensor before, and if so, could you point me in the right direction?
P.S.: The documentation I'm referring to is included in the SDK provided in the downloads section of the product page, and I'm not sure I'd be allowed to rehost it somewhere else in order to link it here.

Welcome to the wonderful world of Broadcom. Unless you're a multi-billion dollar global technology giant, you won't get **** out of them.  And then only with multiple layers of NDAs.

@Majenko Yeah, I'm starting to realize that after trying to contact them directly. I couldn't get anything out of them - I tried going through Digi-Key, and even they got stonewalled. :/

Eben Upton had the same problem with the Pi. That's why graphics on the Pi are so crap - Broadcom won't give anyone the information they need to use the GPU. And he works for Broadcom! Everything on the Pi has basically been reverse engineered from other sources.  Broadcom are dicks.

@Majenko Wow, that's incredible, did not know that. Clears up a lot, actually. sigh Hopefully someone else has made the same mistake I did and had better luck.

I recently looked into this again, and it turns out that Broadcom had released a porting guide for this library in August 2020 (nearly a year after I originally posted this question) that should prove useful to anyone trying to make use of this sensor. It's for the STM32 platform, not Arduino, but it's the most detail Broadcom has provided with regards to this product, and should provide a starting point at least.
I happen to have access to the Nucleo board used in the guide, but I had some issues with following it in some cases due to some differences in the SDK file/directory structure. I did eventually get a passing build out of it, but couldn't get anything out of the sensor itself, which means that I either did something wrong, or had damaged the sensor in my earlier attempts to interface with it; at the time of my last attempt, I was leaning towards the latter. I don't think I'll be revisiting this unit any time soon, so hopefully others will have better luck. And if anyone does get it working, please do report back; I'm curious to know if I'd actually be able to use this thing if I were to buy another one.
P.S: I'm not marking this as answered because a) my question was technically for the Arduino, and b) I haven't been able to confirm that this is working.

I switched from Arduino to a Blackpill (STM32F411CE) and was able to get the sensor to work. I had to rebuild a STM32CubeIDE project based on their example, as I couldn't get theirs to work. The HAL tests they provide were particularly useful. The sensor works great, even in direct sunlight, unlike others such as the VL53L0X.

I also have been digging for information about the AFBR-S50MV85G and similar sensors for the past week.
Well, I am trying to port it to ATxmegas (ICs that are similar to those ATmegas used in the Arduino Family), but I decided to post my findings here because this is the first forum topic that I have found about this sensor family.
As Joseph mentioned, Broadcom has released a porting guide to Arm devices, but it does not help at all when it comes to porting to other microcontrollers.
Additionally, the minimum requirements of this lib according to Broadcom's porting guide are:

Minimum memory requirements:
RAM: 8kByte (4kByte Heap + 4kByte Stack)
ROM/Flash: 128 kByte

Because of that and other facts, I also conclude that it is not possible to port the available libraries to 8-bit microcontrollers nor develop a new one due to the lack of description about the SPI register structure.


text:
Arduino UNO and RS485 Communication Problem
I am learning Arduino, a beginner in programming. I want to use Arduino UNO to connect a wind direction sensor RS485. The problem is the output in the serial monitor, the return data from the wind direction sensor is unstable.

I need to get the return data from the wind direction sensor to get the wind direction. From the factory manual, they said sent a data to the sensor: 0x01 0x03 0x00 0x00 0x00 0x02 0xC4 0x0B and the sensor will return, like 0x01 0x03 0x04 0x06 0x48 0x00 0xA0 0x7A 0xD5
The wind direction dat at the above 5 and 6 position, the 0x00 0xA0 => 00A0H(HEX)=160 degree.
Tools:
Arduino Uno Board
Wind Direction Sensor
http://www.jnrsmcu.com/equipment/299.html
RS485 Board (3.3V)
https://www.waveshare.com/rs485-board-3.3v.htm
The following is my coding:
#include <SoftwareSerial.h>

SoftwareSerial RS485Serial(10, 11); // RX, TX

void setup()
{
    RS485Serial.begin(4800);   // set the data rate
    Serial.begin(4800);
    Serial.println("Start");

    pinMode(12, OUTPUT);
    digitalWrite(12, HIGH);  // Init Transceiver
}

byte buf[8];

int byteReceived;

void loop()
{
    digitalWrite(12, HIGH);

    byte wind[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B};
    RS485Serial.write(wind, sizeof(wind));
    Serial.flush();
    RS485Serial.flush();
    // Serial.print(wind[0], HEX);
    Serial.println("Send");

    digitalWrite(12, LOW);
    delayMicroseconds(200);

    RS485Serial.readBytes(buf, 8);
    delay(10);
    Serial.println(buf[0], HEX);
    Serial.println(buf[5], HEX);
    Serial.println(buf[6], HEX);
    Serial.flush();
    RS485Serial.flush();
    delay (1000);
}

Connection map:

Is there any documentation available in English for this sensor?

It's probably SoffwareSerial not being able to respond fast enough to the incoming data in time. You should hook up a logic analyser and check that the data being sent does in fact differ from the data you are receiving. If so, then you really need to use a development board that has a hardware UART that you can use. I would never ever recommend using SoftwareSerial for anything, ever. Period. Exclamation mark.

You could use SoftwareSerial for sending the outbound packet, and the hardware UART for both receiving the response (on RX) and talking to the PC (on TX). May be not be elegant, but it should be more reliable that trying to read from SoftwareSerial.

@Majenko recommend to us, your peons, a well-rounded tactical budget logic analyzer (case not necessary)

I use a little usb dongle I got from Alibaba or somewhere for $5...

I would suggest you simplify your setup to the point where you have a 'working baseline  configuration', and then start building the system up one step at a time from there.
Start by eliminating the SoftwareSerial interface as a possible contributor to the problem.  Get an Arduino Mega with multiple hardware serial ports.
Next, verify that you can send characters to the selected hardware serial port and receive those same characters back when the Txn and Rxn lines (the 'n' here is the selected hardware serial port number) are connected via a jumper wire. This is called a 'loopback' configuration and is a basic serial comms troubleshooting technique (software serial ports don't support simultaneous transmit and receive, so they don't support loopback testing).  Don't proceed until you have this step completed successfully.
Next, get a second RS-485 module and extend your previous 'loopback' configuration with the hardware serial port on the Mega to include the two RS-485 modules.  Then you should be able to send characters out to one RS-485 module and receive the same characters back from the other, by connecting TXn to DI on one of the two RS-485 modules, and Rxn to DO on the other.
At this point you will have verified all the communications connections, so you can be confident that whatever you send will actually show up at the DO port of the RS-485, and whatever shows up at the DI port of the RS-485 will actually make it back to your serial console.  Now you can connect the sensor and figure out any issues do to data formatting, command sequences, and the like.
This basic 'cut the problem in half' building block technique will work on any system, large or small, simple or complex.
Frank

I don't see any connection between the sensor's GND and your Arduino's. This is likely the problem if they're not connected, since a common GND is necessary even with RS-485.
Check the sensor's power supply, make sure it's actually within the advised 10-30 V range. Also check the polarity of the differential lines.
Have you tried using the provided configuration software?
flush() does nothing for SoftwareSerial ports since they have no TX buffer, so you can just get rid of those lines, including the unnecessary Serial.flush()
Finally, your device datasheet says to wait for at least 200 milliseconds not microseconds, before checking for a response. Though it really shouldn't matter since you're using readBytes() after that, which waits for a second anyways by default, before giving up. Instead, use a bigger buffer, say 20 bytes, then try to read just 8 (the expected length) into it with readBytes():
byte buf[20];
int rlen = RS485Serial.readBytes(buf, 8);

Then try to print rlen which tells you how many bytes were actually read and also print the whole response to verify the packet format is as it should be. You should get enough info from this to at least eliminate a bunch of possible problems.


text:
Output 3.3V when setting pin to high
I would like to pass 3.3V and Ground to an component. How can I achieve such a thing?
I for example would like to let a wire get 3.3V when I for example do digitalWrite(pin, HIGH). It is hard for me to explain this, so I created an illustration in the hope of better clarifying it.
Edit: I have an product that I have dismantled. On the PCB, there is a push button. I would like to solder some wires to the place where the button is so it can be controlled with an arduino (probably wemos d1). When plugging a cable in the 3.3v of the arduino and a cable from the ground, when connecting it to the push button it will cause a boot of the dismantled product. This explains why I would like to give power to a component ONLY when a pin is set high, so I can for example boot the product via a website / app eventually.

Are you trying to supply "power" to a component or just send a "low current" HIGH/LOW signal?

Supply power (3.3v) when a pin is set to high

How much power? 1 mA, 10mA, 500mA?

What is this mystery component?

Doesn't really matter, connecting the 3.3V directly to the component will already work so I guess it won't be too much

I've clarified it a bit more in the edit, sorry for the confusion @Majenko

The normal way is to use a P-channel MOSFET as a "high side" switch.

simulate this circuit – Schematic created using CircuitLab
R1 keeps it switched off under "normal" circumstances.  Driving D4 LOW makes M1 turn on and allow power through to the "component".
Make sure that the MOSFET has a threshold voltage of no more than (less than?) -3V (that is, somewhere between 0V and -3V - note: P-channel MOSFETs have their thresholds quoted as a negative voltage).
You could connect R1 to 3.3V instead of 5V, but since the  GPIO would have 5V on it when HIGH it would be wasting power while idling - so it's better to pull it to 5V instead.

I think I have kind of used the same principle as you described. I simply put a transistor between it, did some configuring and it worked. Thank you for the right answer and the help in the right direction!


text:
ESP-NOW: Master and Slave at the same time
I am interested to use ESP-NOW as a means to transmit data between two ESP32's back and forth, - each ESP receives and sends data, taking turns. The example library provides an example sketch for Slave and one for Master, which allows for one-directional data flow. However, I would like to use ESP-NOW for two-way communication. Is it possible to combine both of these sketches to allow the data to flow in both directions at the same time?

I'm assuming two ESP's won't be able to send data at the same exact time, so the best approach to start, I think, would be to wait until a packet has been received before sending one from the other end. Here's a snippet of code which I tried to use, but failed:

void setup()
{
  Serial.begin(115200);
  WiFi.mode(WIFI_MODE_APSTA);
  // configure device AP mode
  configDeviceAP();
  // This is the mac address of the Slave in AP Mode
  Serial.print("AP MAC: ");
  Serial.println(WiFi.softAPmacAddress());
  Serial.print("STA MAC: ");
  Serial.println(WiFi.macAddress());
  // Init ESPNow with a fallback logic
  InitESPNow();
  // Once ESPNow is successfully Init, we will register for recv CB to
  // get recv packer info.
  esp_now_register_recv_cb(OnDataRecv);
  esp_now_register_send_cb(OnDataSent);
}

unsigned long nextManage;

void loop()
{
  // In the loop we scan for slave
  ScanForSlave();
  // If Slave is found, it would be populate in `slave` variable
  // We will check if `slave` is defined and then we proceed further
  if (slave.channel == CHANNEL2)
  { // check if slave channel is defined
    // `slave` is defined
    // Add slave as peer if it has not been added already
    bool isPaired = manageSlave();
    nextManage = millis() + 10000;
    while (isPaired)
    {
      if (packetRecieved)
      {
        packetRecieved = false;
        // Send data to device
        sendData();
      }

      unsigned long t = millis();
      if (t > nextManage)
      {
        nextManage = t + 10000;
        // pair success or already paired
        isPaired = manageSlave();
      }
    }
    Serial.println("Slave pair failed!");
  }
}

"ESPNow" is part of the ESP IDF. You can read more here: https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/network/esp_now.html - it's not Arduino functionality, but something that is closed source and custom to ESP32.

@Majenko I see. Then the one I made on espressif forum would be more applicable I guess. I will keep this one up for a while just in case. Thanks


text:
Class member variable would not update
Code would not update variable inside drive method. The variable is updated inside the drive method, but it doesn't change in the rest of the class. I wrote a simple similar method in normal C++ and the variable actually updated in the rest of the class.
engine.hpp
#pragma once
#include <Arduino.h>

namespace engine
{
class Engine
{
public:
    Engine(const unsigned char t_motor, const unsigned char t_forward, const unsigned char t_backward);
    void drive(unsigned int t_speed, bool t_isForward = true);
    bool isMovingForward() const;
    void stop();

private:
    const unsigned char m_motor;
    const unsigned char m_forward;
    const unsigned char m_backward;

    // Movements
    bool m_isActive;
    bool m_isForward;
    unsigned int m_speed;
};
} // namespace engine

engine.cpp init list
Engine::Engine(const unsigned char t_motor, const unsigned char t_forward, const unsigned char t_backward)
    : m_motor(t_motor),
      m_forward(t_forward),
      m_backward(t_backward),
      m_isActive(false),
      m_isForward(true),
      m_speed(0U)
{
}

drive method
void Engine::drive(unsigned int t_speed, bool t_isForward)
{

    if (!m_isActive || m_isForward != t_isForward)
    {
        stop();

        // Set direction
        if (t_isForward)
        {
            digitalWrite(m_forward, HIGH);
            digitalWrite(m_backward, LOW);
        }
        else
        {
            digitalWrite(m_forward, LOW);
            digitalWrite(m_backward, HIGH);
        }

        m_isActive = true;
        m_isForward = t_isForward;
    }

    if (m_speed != t_speed)
    {
        m_speed = t_speed; // Updated here
        analogWrite(m_motor, t_speed);
    }
}

how do you know it didn't update?

What code do you use to test this?

I know it didn't update because when I check the m_speed variable after calling the drive method, the m_speed variable is set back to zero.

Downvote just for the profane user name.  Have some class man

I figured it out.
I was passing the engine objects as references instead of pointers.
main.cpp
// Engines
engine::Engine
    engine1(motors::Constants::MOTOR_1, motors::Constants::MOTOR_1_FORWARD, motors::Constants::MOTOR_1_BACKWARD),
    engine2(motors::Constants::MOTOR_2, motors::Constants::MOTOR_2_FORWARD, motors::Constants::MOTOR_2_BACKWARD),
    engine3(motors::Constants::MOTOR_3, motors::Constants::MOTOR_3_FORWARD, motors::Constants::MOTOR_3_BACKWARD),
    engine4(motors::Constants::MOTOR_4, motors::Constants::MOTOR_4_FORWARD, motors::Constants::MOTOR_4_BACKWARD);

engine_controller.cpp init list
EngineController::EngineController(engine::Engine &t_e1, engine::Engine &t_e2, engine::Engine &t_e3, engine::Engine &t_e4)
    : m_engine1(t_e1),
      m_engine2(t_e2),
      m_engine3(t_e3),
      m_engine4(t_e4),
      m_currentSpeed(EngineControllerConsts::MAX_SPEED),

      // Directions
      m_rights(0),
      m_lefts(0),

      m_rightDistance(-1),
      m_leftDistance(-1),

      m_lastForward(true),
      m_counter(0),

      m_lastForward1(true),
      m_lastForward2(true),
      m_turnsCounter(0)

{
}

The solution would be to use dynamic memory allocation.
main.cpp
// Engines
engine::Engine
    *engine1 = new engine::Engine(motors::Constants::MOTOR_1, motors::Constants::MOTOR_1_FORWARD, motors::Constants::MOTOR_1_BACKWARD),
    *engine2 = new engine::Engine(motors::Constants::MOTOR_2, motors::Constants::MOTOR_2_FORWARD, motors::Constants::MOTOR_2_BACKWARD),
    *engine3 = new engine::Engine(motors::Constants::MOTOR_3, motors::Constants::MOTOR_3_FORWARD, motors::Constants::MOTOR_3_BACKWARD),
    *engine4 = new engine::Engine(motors::Constants::MOTOR_4, motors::Constants::MOTOR_4_FORWARD, motors::Constants::MOTOR_4_BACKWARD);

engine_controller.cpp init list
EngineController::EngineController(
    engine::Engine *t_e1, engine::Engine *t_e2,
    engine::Engine *t_e3, engine::Engine *t_e4)
    : m_engine1(t_e1),
      m_engine2(t_e2),
      m_engine3(t_e3),
      m_engine4(t_e4),
      m_currentSpeed(EngineControllerConsts::MAX_SPEED),

      // Directions
      m_rights(0),
      m_lefts(0),

      m_rightDistance(-1),
      m_leftDistance(-1),

      m_lastForward(true),
      m_counter(0),

      m_lastForward1(true),
      m_lastForward2(true),
      m_turnsCounter(0)

{
}


text:
Cannot convert 'int (*)[size]' to 'int**'
Analyzing this and this answers under Arduino, which should be the proper way to pass a 2D array into a function?
The function should be applicable to different sizes of 2D arrays.
// NOT COMPILING EXAMPLE
void f(int** x,const int m, const int n){
// access x as x[0][0], x[0][1], etc...
}

void main{}{
    int x1[16][128];
    f(x1,16,128);
    int x2[64][16];
    f(x2,64,16);
}

the compiler must know the second dimension's size. one option is void f(int x[][128],const int m){

I'd rather use one dimensional array. It's not so hard to transform two dimensional indexes to one dimension.

According the prototype of f and the usage pattern for its x
argument, the function expects this argument to be a pointer to the
first element of an array of pointers to the first elements of arrays of
int. However, the matrix in main() is defined as an array of arrays
of int. If you try to pass this to a function, the matrix will decay
into a pointer to an array of int. That's not what you want.
If you want both dimensions of the matrix to be variable, the only
simple solution I see is to build an extra array of pointers (pointing
to the matrix rows) and pass that array to the function
int main() {
    int x[16][128];

    // Build an array of pointers to rows.
    int *px[16];
    for (int i = 0; i < 16; i++)
        px[i] = x[i];

    f(px, 16, 128);
}

For more information on this, see the section Arrays and Pointers in
the C FAQ, and more specifically the questions 6.16 (How can I
dynamically allocate a multidimensional array?) and 6.19 (How do I write
functions which accept two-dimensional arrays when the width is not
known at compile time?).


text:
OneWire with DS18B20 digital sensor only works on the I2C (20 and 21) pins of my Mega?
I am using an Arduino Mega to read a DS18B20 temperature sensor using the OneWire library in the code below which I got here:

#include <OneWire.h>

#define DS18S20_Pin 20 //DS18S20 Signal pin on digital 20

//Temperature chip i/o
OneWire ds(DS18S20_Pin);  // on digital pin 20

 #define DS18S20_ID 0x10
 #define DS18B20_ID 0x28
 float temp;

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

void loop(void) {
  boolean tempTest = getTemperature();
  Serial.println(tempTest);
  Serial.println(temp);

  delay(1000); //just here to slow down the output so it is easier to read

}

 boolean getTemperature(){
 byte i;
 byte present = 0;
 byte data[12];
 byte addr[8];
 //find a device
 if (!ds.search(addr)) {
 ds.reset_search();
 return false;
 }
 if (OneWire::crc8( addr, 7) != addr[7]) {
 return false;
 }
 if (addr[0] != DS18S20_ID && addr[0] != DS18B20_ID) {
 return false;
 }
 ds.reset();
 ds.select(addr);
 // Start conversion
 ds.write(0x44, 1);
 // Wait some time...
 delay(850);
 present = ds.reset();
 ds.select(addr);
 // Issue Read scratchpad command
 ds.write(0xBE);
 // Receive 9 bytes
 for ( i = 0; i < 9; i++) {
 data[i] = ds.read();
 }
 // Calculate temperature value
 temp = ( (data[1] << 8) + data[0] )*0.0625;
 return true;
 }

When I use this code with the sensor attached to pins digital pins 20 or 21 it reads successfully, ok great, somehow by the grace of god I chose pin 20 on the first try. So then I move on to integrating my next sensor which utilizes the I2C and the Wire library, I should note that I am using this shield so I was able to connect right to the I2C without realizing I was using pins 20 and 21. Now, when I combined the two programs the I2C sensor was initialized second so it ended up getting the pins and the DS18B20 would fail to read, after pulling out my hair for a couple of hours I looked at a Mega pinout and realized it was on the I2C pins and thinking I finally figured it out I went to go and move the DS18B20 to one of the 52 other digital pins, this is when I came to the cold discovery that my DS18B20/OneWire will not work on any pins except pins 20 and 21 which I NEED for I2C. I have not checked every single digital pin but I have checked about half of them and nothing works except pins 20 and 21, I cant figure it out, nothing I can find mentions that OneWire uses or conflicts with the I2C connection.
More Info:

Using latest OneWire
I am not using DallasTemperature and would prefer not to, I could not get it to work whether on pins 20/21 or not
I am using a resistor on the sensor
I am currently only trying to run the code above to debug, no references to I2C sensor or Wire library whatsoever.

Thanks for reading and for any help, I am totally stumped here and thought I was avoiding some of these dumb double use pin issues by using the Mega instead of an Uno...

it is unclear why grace of god was required to choose pin 20 ... the comment in the code listing clearly specifies pin 20

Original code at link did not specify a pin number it only included a function. So I just chose pin 20, which ended up being one of the two working ones.

The difference between pin 20, 21 and the rest of the pins is the pullup resistor on the mega board. I assume that there is something wrong with your pullup resistor for the 1-Wire bus. Its value is far too large or it is not connected.


text:
How to send UDP data packet between two access point?
I am new to arduino programming and nodeMcu boards.I have two ESP8266 bards as access points and one board get some data form WiFi stations and resend that data to other access point. but the problem is second access point didn't receive any data packet from first access point.
This is the code of Access point which collect data and resend it to upper level Access point. This Access point successfully received the data from the WiFi stations.
const char *ssid1 ="SecondAP";
const char *pwd1 = "12345678910";

const char *ssid2 ="FirstAP";
const char *pwd2 = "123456789101";

ESP8266WiFiMulti WiFiMulti;

IPAddress local_IP(192,168,4,10);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);
IPAddress NextAP(192,168,4,9);
StaticJsonDocument<200> doc;
unsigned int locPort1 = 1000;
unsigned int locPort2 = 2000;
WiFiUDP udp1;
WiFiUDP udp2;
char packetBuffer[100];
IPAddress addrs;

void setup() {

  Serial.begin(9600);
  delay(10);
  Serial.println('\n');

  ConnectToAP();
  delay(1000);
  EnableAP();
  delay(1000);

  udp1.begin(locPort1);
  udp2.begin(locPort2);
}

void loop() {

int Icb = 0;

  Icb = udp1.parsePacket();

  if(Icb > 0){
      GetSensorDataPacket();
      Icb = 0;
    }
}

void EnableAP(){

  WiFi.softAPConfig(local_IP, gateway, subnet);
  WiFi.softAP(ssid2 , pwd2);
  delay(1000);

  Serial.print("Access Point \"");
  Serial.print(ssid2);
  Serial.println("\" started");
  Serial.print("IP address:\t");
  Serial.println(WiFi.softAPIP());
}

void ConnectToAP(){

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP(ssid1, pwd1);

  Serial.print("Connecting to ...........");
  Serial.print(ssid1); Serial.println("...");

  int i = 0;
  while (WiFiMulti.run() != WL_CONNECTED) {

   delay(1000);
   Serial.print(++i); Serial.print(' ');
  }

  Serial.println('\n');
  Serial.println("Connection established!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());
}

void GetSensorDataPacket(){

  Serial.println("GetSensorDataPacket Function");
  udp1.read(packetBuffer,100);
  DeserializationError error = deserializeJson(doc, packetBuffer);

  IPAddress ClientAddrs = udp1.remoteIP();

  double SensorData = doc["SensorData"];
  int ClientID = doc["ID"];

  delay(1000);
  Serial.println();
  Serial.print("Sensor reading = ");
  Serial.println(SensorData);
  Serial.print("Client ID = ");
  Serial.println(ClientID);

  SendDataToNextAP(SensorData,ClientID);
}

void SendDataToNextAP(double Sensor_Data,int Client_ID){

  StaticJsonDocument<500> jsonBuffr;
  Serial.println("I'm in SendDataToNextAP Function");

  udp2.beginPacket(NextAP, locPort1); //gateway
  JsonObject Sob1 = jsonBuffr.to<JsonObject>();
  Sob1["SensorData"] = Sensor_Data;
  Sob1["ID"] = Client_ID;
  serializeJson(jsonBuffr, udp2);

  udp2.println();
  udp2.endPacket();

  delay(1000);
}

This is the code of upper Access point which should receive data packet from first access point but didn't receive any data from the first access point.
const char *ssid = "SecondAP";
const char *pwd = "12345678910";
ESP8266WiFiMulti WiFiMulti;

IPAddress local_IP(192,168,4,9); // Ip address of this node
IPAddress gateway(192,168,3,1);
IPAddress subnet(255,255,255,0);

StaticJsonDocument<200> doc;
unsigned int locPort1 = 1000;
WiFiUDP udp1;
char packetBuffer[100];

void setup() {

  Serial.begin(9600);
  delay(10);
  Serial.println('\n');

  EnableAP();
  udp1.begin(locPort1);
  delay(1000);
}

void loop() {

int Icb = 0;

  Icb = udp1.parsePacket();
  if(Icb > 0){
      Serial.println("Got a Udp packet");
      GetSensorDataPacket();
    }
}

void EnableAP(){

  WiFi.softAPConfig(local_IP, gateway, subnet);
  WiFi.softAP(ssid,pwd);
  delay(1000);

  Serial.print("Access Point \"");
  Serial.print(ssid);
  Serial.println("\" started");
  Serial.print("IP address:\t");
  Serial.println(WiFi.softAPIP());
}

void GetSensorDataPacket(){

  Serial.println("GetSensorDataPacket Function");
  udp1.read(packetBuffer,100);
  DeserializationError error = deserializeJson(doc, packetBuffer);

  IPAddress ClientAddrs = udp1.remoteIP();

  double SensorData = doc["SensorData"];
  int ClientID = doc["ID"];

  delay(1000);
  Serial.println();
  Serial.print("Sensor reading = ");
  Serial.println(SensorData);
  Serial.print("Client ID = ");
  Serial.println(ClientID);
}

I couldn't find the reason for that. If anyone knows the solution for that please help me?
Thanks!

you have two networks with the same IP range. and gateway(192,168,3,1); is what?

Sorry It's my mistake. it should be gateway(192,168,4,8).

Thank you very much..It works after change IP address.

The two network interfaces (station and SoftAP) of the middle esp8266 must have different IP address range. If the top AP has 192.168.4.x, set for the AP of the middle IP for example 192.168.5.1. Because with same IP address ranges the esp8266 doesn't know to which network do you want to send the UDP message.


text:
My device doesn't recognize my Arduino
I'm planing to use the ESP8266 to create a web server as a start. My set up is: Arduino nano- Esp8266- Logic level converter  as shown in the diagram.

After I connected everything my device doesn’t recognize the Arudion’s USB serial port, but when I disconnect everything from the breadboard and connect the Arduino alone it show up as COM3 and when I put the circuit back again and hock up the USB to my device it no longer show up.
I’m having the issue on both win 10 and mac.
Whenever I connected the usb cable to my computer the ESP8266 flashes a light for ones.

what is your question?

Why doesn't my device recognize the Arduino when the ESP8266 is connect

The Nano cannot power the ESP8266. It has an absolute maximum limit of about 50mA from the 3.3V pin, since it is provided by the USB interface chip. By drawing too much current (the ESP8266 needs hundreds of mA) the USB chip stops functioning.
You need an external 3.3V regulator to power the ESP8266.

I will try using an external source. but both the 5v and 3v are Connected to the chip doesn't that provide enough?

@Jacob No. You need at least 350mA but you only have 50mA. You need lots lots more power.


text:
Arduino Due Digital Inputs without Response
On two of my Arduino Due, when connecting the pin 3.3V to any digital inputs (37,36,35,34), no serial message nor LED_BUILTIN is thrown as output, only the Test message.
Digital Pins are set as INPUT by default. Blink works.
I have never connected any other thing on those pins, even 5V.
What I am missing?
void setup() {
    Serial.begin(115200);
    while(!Serial);
    pinMode(LED_BUILTIN,OUTPUT);
    Serial.print("Test");
}

void loop() {
    if (digitalRead(37))
        Serial.print("37");
    if (digitalRead(36))
        Serial.print("36");
    if (digitalRead(35))
        Serial.print("35");
    if (digitalRead(34))
        Serial.print("34");
    digitalWrite(LED_BUILTIN,digitalRead(37));
}

No. They are not defined as INPUTs by default (??).

And if you manually set those pins to INPUT, does it start working?

Yes... that was the problem...

I am guessing that, since those pins are also PWM pins, the alternate function was stuck in PWM mode until you manually forced it to change. Possibly from some earlier sketch or something. I don't know the SAM chips well enough to know how the pin functions work.

A good practice is to set the pin mode for all the pins used by the sketch.
void setup() {
    Serial.begin(115200);
    while(!Serial);
    pinMode(34, INPUT);
    pinMode(35, INPUT);
    pinMode(36, INPUT);
    pinMode(37, INPUT);
    pinMode(LED_BUILTIN, OUTPUT);
    Serial.print("Test");
}

The Arduino AVR core does set the pin mode to INPUT by default but the Arduino SAM core does not. The SAM MCU is much more advanced and allows turning on and off the ports, and a lot of other functionality.
Cheers!


text:
How do I properly use the WiFi capabilities of ESP8266?
I am creating a project with an ESP8266 (Arduino IDE) which requires it to serve a webpage to a client. The module will be connected to a WiFi network by default, but when that WiFi network is not available, I need it to turn on its Soft Access Point, so that the user can still access that webpage by connecting to the AP. When the WiFi network becomes available, I want the module to reconnect to the WiFi network and disable the SoftAP.
Here is the chunk of code in my sketch that deals with all the WiFi stuff:
void wifi() {
  if(WiFi.status() != WL_CONNECTED){
    WiFi.mode(WIFI_AP_STA);

    if((unsigned long)(millis() - waitUntil) >= interval){            //this section I used as an alternative to the delay() function, the delay is 3 sec
      WiFi.begin(ssid, password);
      waitUntil = waitUntil + interval;

      if(WiFi.status() == WL_CONNECTED){
        Serial.println("Connection successful! ");
        Serial.print("IP: ");
        Serial.print(WiFi.localIP());
        WiFi.softAPdisconnect(true);
      }
    }
  }

  if(WiFi.status() != WL_CONNECTED && softAPEnabled == false){
    Serial.println("WiFi not connected, enabling SoftAP...");

    WiFi.softAP(softAP_ssid, softAP_password);

    softAPEnabled = true;

    Serial.println("SoftAP ON");
  }
  else if(WiFi.status() == WL_CONNECTED && softAPEnabled == true){
    WiFi.softAPdisconnect(true);
    softAPEnabled = false;
    Serial.println("SoftAP OFF");
  }
}

Here are the problems:

The webpage works fine when the module is connected to WiFi and I go to the IP address from a browser, but when SoftAP mode is enabled, and I connect to the AP and go to 192.168.1.1, it does not work. The next problem may be related to this.
I don't think I'm using WiFi.mode() correctly. I currently have it set to WIFI_AP_STA, but after problem 1 occurred, I tried to change it to WIFI_AP and WIFI_STA individually as I needed each mode, but this still did not work.

192.168.0.1 and 192.168.1.1 are commonly used by commercial routers as their own local address. Could your chosen station-address be colliding with that?

the default SoftAP IP with Arduino core is not 192.168.1.1. Use WiFi.softAPIP(); to print the IP

@Juraj Thanks for this. I will have a look.

@Juraj Also, I have spent way too much time searching for functions of WiFi.h. Do you happen to have a link to a website with the list of all the functions of WiFi.h?

https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/soft-access-point-class.html

https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiAP.h

The following may not solve of your problems, but just in case it helps...
I was using the ESP8266 both in Station mode and AP. Both worked.
In AP mode, it worked but the ESP8266 ignored my instructions to set name and password for the AP , until I realised the following
. The password must at least be 8 characters long, otherwise the instruction is ignored
. in the IDE, you should erase flash AND WiFI settings, otherwise it will be "lazy" and use previous settings


text:
How to read shiftOut function using arduino
(I'm sorry for my bad English, but I will do my best)
I have a Chinese MUC which already programmed. It communicates with a LED driver chip using three wires (STB,CLK,DIN).
(LED driver controls 16 digit 7 Segment display)
After some research, I found that it can be talk to LED driver using shiftout function.
Now the main coal is to connect these
 3 pins(STB,clk,din) to Arduino and read the incoming data and convert the data to numbers.
To test if this idea is working or not,
I came with two arduino (uno to send shiftout function  and mega to read it) after connect pin 2 of uno to pin 2 of mega and same 3 to 3, 4 to 4 and also Gnd of uno to Gnd of mega.
I wrote these codes:
arduino UNO side (to send shiftOut function)

    #define STB  4
#define clockPin  5
#define dataPin  6

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

  pinMode(STB, OUTPUT);
  pinMode(clockPin,  OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
 digitalWrite(STB, LOW);
    shiftOut(dataPin, clockPin, LSBFIRST, 0b10101010 ); // 1st digit
   digitalWrite(STB, HIGH);
}

arduino mega side (to read shiftOut function)

    #define STB 4
#define clockPin  5
#define dataPin  6

 int R_STB[8];
 int R_clockPin ;
 int R_dataPin ;
void setup() {
   Serial.begin(115200);

  pinMode(STB, INPUT);
  pinMode(clockPin,  INPUT);
  pinMode(dataPin, INPUT);
}

void loop() {

 R_STB = digitalRead(STB);
 R_clockPin = digitalRead(clockPin);
 R_dataPin = digitalRead(dataPin);

   for(int i=0 ; i<8;i++){
  Serial.print(R_STB[i]-2);

  Serial.print(" ");
  Serial.print (R_clockPin[i]);

 Serial.print(" ");
  Serial.print(R_dataPin[i]+2);
Serial.println(" ");
   }
 }

But the digital read at arduino mega side can't read all data due to it fast switching between High LOW statement maybe? and I am stuck here.
Please any one has any ideas?

Welcome to Arduino StackExchange. What the Chinenese MUC you have, provide us some the datasheets

You are right that you can't read the data fast enough with your method there. What you really need is the opposite of "shiftOut" - which happens to be called "shiftIn".  You use it just like shiftOut, but instead of you sending it a value to send it instead returns a value that it reads.
You trigger it using the "STB" pin:
if (digitalRead(STB) == LOW) {
    uint8_t val = shiftIn(dataPin, clockPin, LSBFIRST);
    Serial.println(val, HEX);
}

But the protocol you describe is simply SPI.  There is hardware within the Arduino to handle it for you.  A little harder to work with, but it's capable of working at much higher speeds and is more likely to be able to read your incoming data fast enough.
Resources:

https://www.arduino.cc/en/reference/SPI
http://www.gammon.com.au/spi

The latter includes how to configure an SPI "Slave" which is used for receiving data that is sent out from elsewhere.

Majenko thank you vary much . I read about the SPI and i reach to the solution, one question please what if i got just two pin (DIN,CLK) instead of three(STB,CLK,DIN) how or what should i use? thank you in advance.

For SPI there must be a third pin. It may be labelled CS or SS instead of STB. Or it may not be SPI and have a "Latch" pin (it's a shift register in that case).  If there's nothing but CLK and DIN then there must be some other non-standard method for indicating the start of a communication block.

Thank you for your fast reply, The new LED driver (TM1640), it says in it datasheet "Dual-line serial interface (CLK, DIN) " .   datasheet==>> https://datasheetspdf.com/pdf-file/838954/TitanMicro/TM1640/1

It uses a non-standard system: The starting condition of data input is: when CLK is high, the DIN becomes low from high; the ending condition is: when CLK is high, the DIN becomes high from low.

could you suggest any think which by reading it I can handle the data which comes from (MUC) through(CLK, DIN) pins using arduino?please

You already know how to receive the data, and I have highlighted the part of the datasheet that describes the start condition. There's even a picture in there to make it even more obvious.


text:
How to connect SPI device on Etherntet shield on Arduino Uno
In my project I need to connect RFID reader (RC522) on top of the Ethernet shield because of it's capability of reading and editing SD card. When I connect only RFID sensor on Arduino, it works. Same goes to Ethernet shield. But when I use both together, It simply doesn't work. I can compile it and upload it, but I don't get anything in the serial monitor. I think it's because both Ethernet shield and RFID reader use the same pins for SPI like MOSI, MISO and SCK. My question is, if that is the problem, how to connect multiple SPI devices on Arduino, or at least on Ethernet shield.
Here is my code, although I think there's nothing wrong with it. I just merged code for RFID and Ethernet shield with copy-pasting. Sorry for bad formatting, I need it just for test, I'll later make the real code.
#include <SPI.h>
#include <MFRC522.h>
#include <SD.h>

#define RST_PIN         6          // Configurable, see typical pin layout above
#define SS_PIN          7

MFRC522 mfrc522(SS_PIN, RST_PIN);

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
// MKRZero SD: SDCARD_SS_PIN
const int chipSelect = 4;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  while (!Serial);    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin();      // Init SPI bus
  mfrc522.PCD_Init();   // Init MFRC522
  mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
  Serial.println(("Scan PICC to see UID, SAK, type, and data blocks..."));

  Serial.print("\nInitializing SD card...");

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    while (1);
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.println();
  Serial.print("Card type:         ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    while (1);
  }

  Serial.print("Clusters:          ");
  Serial.println(volume.clusterCount());
  Serial.print("Blocks x Cluster:  ");
  Serial.println(volume.blocksPerCluster());

  Serial.print("Total Blocks:      ");
  Serial.println(volume.blocksPerCluster() * volume.clusterCount());
  Serial.println();

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("Volume type is:    FAT");
  Serial.println(volume.fatType(), DEC);

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize /= 2;                           // SD card blocks are always 512 bytes (2 blocks are 1KB)
  Serial.print("Volume size (Kb):  ");
  Serial.println(volumesize);
  Serial.print("Volume size (Mb):  ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Gb):  ");
  Serial.println((float)volumesize / 1024.0);

  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);

  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
  }
}

void loop() {
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  // Dump debug info about the card; PICC_HaltA() is automatically called
  mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

Sorry for being dumb, where is your Ethernet bit code? Also you know that SPI uses Chip select to select device it wants to talk to?

set pin 10 HIGH if you don't use the Ethernet chip

You mean because shields SS is 10? And do you mean that I do pinMode(10, HIGH); ?

yes, set 10 as OUTPUT and HIGH. while it is floating it randomly enables and disables the Wiznet chip on SPI bus

The two devices should share SCK, MISO, and MOSI, but SS (or CS as it's sometimes called) will have to be different and both shields are probably trying to use pin 10 for SS.  Let the ethernet shield have pin 10 for SS.  On the other shield, take that pin and bend it out so it doens't go down into the header when you stack them and then solder a wire to it and take it to another pin.  Go into the code and modify the code for that shield to use the new pin as SS instead of pin 10.

they have pin 7 as SS for RFID reader. and it is not a shield I think

Does CS mean chip select? By the way you are right juraj.

Yes CS is chip select.

OK if they already have the CS lines separated then the next thing to check is SPI modes.  Maybe the two devices use different SPI modes.


text:
My 12V DC Vending Machine motor rotates 1 extra 360 degree rotation sometimes. What could be the reasons?
have main board which has motor control circuit and has row and column to control the row and column of the vending machine.
I have made changes in motor in two ways:
A. I have attached an image for circuit diagram

In this design I have some pros and cons
PROS: 1. It stops at its home position after one rotation
2. It detects row and column of the machine
CONS: 1. Sometime it does not stop at its home position or take more than 1 rotation
B. I have attached an image of other diagram

In this design also I have some pros and cons
PROS: 1. It stops perfectly at its home position after one rotation.
CONS: 1. It does not detect ROW
Please suggest What should I follow and what should I made changes in the circuit.
Here is the video
https://drive.google.com/open?id=1N7ItjeU84JiDAOquAD6SGHkVWufDT40K
https://drive.google.com/open?id=1VX9yncrm6pcr1IBQsNvVZ1yR0UMflJKA

it rotates extra because it is programmed to do so

You've programmed 3.1 sec delays but your comments suggest you intended 2 second delays. Are you seeing ~50% extra rotation?

I have tested it with different time delays. Forgot to clear the comment.

Not 50% extra. It rotates little bit forward like 10% extra with 3.1 sec delay,

Why have you chosen 2 seconds? Won't a shorter delay give the rotation you want?

I have not chosen 2 seconds. It was just written in comments only.

I just want to rotate the motor from the home location to the home location when I give signal one time. But i do not know what time delay should I use?

Have a look on this video
https://drive.google.com/open?id=15CmMVI410zq1Vc2Wl7yseq9n4T8Q1rMm

what are the NO and NC pins used for?

find out ... use an ohmmeter to find out when the limit switch closes or opens

@sugandhasharma, what are the results of the switch testing?

jsotola when switch is not pressed then C is connected to NC and when switch is pressed, C is connected to NO.

"It rotates little bit forward like 10% extra with 3.1 sec delay,"
"I just want to rotate the motor from the home location to the home location when I give signal one time. But i do not know what time delay should I use?"

More than 2.0 and less than 3.1! If 3.1 sec gives 110% rotation, then you need
(100/110)*3.1 = 2.818sec to get 100%.
I realize that your 10% extra is an estimate and not accurate to 3 decimals, but I'd use 2.82 as a starting point and tweak it up or down until you get the amount of rotation you want.
Remember that timing a motor to get distance will inherently be inaccurate due to inconsistencies in the motor acceleration rate and rotation speeds, due to variations in its temperature and the power supply voltage, and load, but this should get you started. For long term accuracy, i.e., if you need it to always come back to a fixed position, you'll need some position feedback, which may be as simple as flag on the motor shaft interrupting a photocell. And even that will have some degree of inconsistency due to coasting speed when you shut the power off, but at least those error won't accumulate.
Update:

2.82, My motor rotates 10% less every time and change its location in every rotation

Right - 2.82 was a first approximation. If that is too small, try splitting the difference between 2.81 and 3.1. If that ends up too small, then split the difference between it and 3.1; or if it was too big, try splitting the difference between 2.1 and it. Do that a few more times until you have an acceptably close value.
Then read what I said about accumulating errors. The Arduino doesn't ever know what the motor position is so it can't correct for any overshoot or undershoot. If you need accuracy and repeatability, you'll have to add some kind of position sensing, or switch to using a stepper motor and drive the number of steps that makes one full rotation (and it would still have to be started from a known position).

What position feedback? Motor has limit switch but I could not control the limit switch. Can you help me in this?

With 2.82, My motor rotates 10% less every time and change its location in every rotation

@sugandhasharma Probably, controlling the motor the way you try only works more or less properly for multiple rotations. Due to the number of coils/magnets the motor has stable positions at specific angles. Stopping at positions between those angles might not work

@Sim Son If you know about it please let me know. I have attached the circuit block diagram and video too.
https://drive.google.com/open?id=15CmMVI410zq1Vc2Wl7yseq9n4T8Q1rMm

I feel you might be building a solution that will only work for a short period of time. The time you calculate will work for the environmental conditions you have right now. As temperature and humidity and age of the motor change, friction will change, this will likely have an impact on the amount of time that the motor needs to be active to get.to a desired position.  You should seriously consider an approach that says "I'm here" when the motor reaches the desired position. This is mentioned @jrobert answer as "position feedback" you should investigate(search) it.

In this motor, there is attached a micro limit switch but it is not working,
Common of switch is connected to Ground through MOSFET module
NO is connected to ground through MOSFET module.
It does run the motor but does not stop on its home location.

If that is the case, then you need to fix it. Either fix the switch on the motor (probably not easy) or build a separate one that works alongside of the motor.

Another problem that I forgot to mention in my comment above (but is mentioned in the answer) is accumulation of error. Let's say you can stop the motor perfectly within 0.1mm of where it is supposed to be using time alone. That's pretty good, but after just 10 cycles it will be 1 cm out of place. After 100 cycles it will be a full 1cm out of place and so on. As jrobert mentioned position feedback can avoid this problem.

Does anybody know the reason? It is really very important for me.

If the switch circuit is not stopping the motor, check the switch circuit itself. Does it actually interrupt the power? If it stops the motor, but lets it coast beyond home, you may need to use a slower motor speed to reduce the coasting.


text:
Why is my Arduino code for running a Bluetooth controlled robot with obstacle sensor not working as it should be?
I have created a Bluetooth based smartphone controlled robot (a 4 wheel car) earlier using Arduino and an obstacle avoidance robot.
Now, I wanted to combine both of them. So, I combined their functions and codes in such a manner that felt right to me. But, it kinda seems wrong to my robot.
My Bluetooth Controlled robot was running smoothly. My obstacle avoiding robot was running flawless. But, when I tried to join them, both of them started crying.
I tried to change orders of the functions, adding some functions twice or thrice removing them from some places that didn't feel right then. Nothing was worthy.
I need to upload whole code because I'm not sure where am I doing it wrong
#include <SoftwareSerial.h>

#include <RemoteXY.h>

// RemoteXY connection settings
#define REMOTEXY_SERIAL_RX A2
#define REMOTEXY_SERIAL_TX A3
#define REMOTEXY_SERIAL_SPEED 9600

// RemoteXY configurate
#pragma pack(push, 1)
uint8_t RemoteXY_CONF[] =
  { 255,8,0,54,0,176,0,8,228,4,
  5,48,44,26,30,30,0,31,8,1,
  6,0,-84,-142,20,20,0,2,26,129,
  0,6,37,23,8,0,64,78,97,118,
  101,100,0,131,3,51,1,20,5,1,
  2,31,82,111,98,111,116,32,67,97,
  114,0,131,0,62,5,19,5,2,2,
  31,67,111,110,116,114,111,108,108,101,
  114,0,129,0,10,45,13,7,0,16,
  84,72,69,0,129,0,5,52,25,8,
  0,136,83,104,101,105,107,104,0,1,
  0,-34,-111,12,12,1,2,31,88,0,
  1,4,79,44,12,12,0,37,151,240,
  159,147,162,0,65,4,87,9,7,7,
  0,65,1,87,17,7,7,0,65,2,
  87,25,7,7,0,67,5,3,3,25,
  14,0,94,24,51,2,0,86,1,11,
  5,0,135,26,31,31,79,78,0,79,
  70,70,0 };

// this structure defines all the variables of your control interface
struct {

    // input variable
  int8_t joystick_1_x; // =-100..100 x-coordinate joystick position
  int8_t joystick_1_y; // =-100..100 y-coordinate joystick position
  uint8_t rgb_1_r; // =0..255 Red color value
  uint8_t rgb_1_g; // =0..255 Green color value
  uint8_t rgb_1_b; // =0..255 Blue color value
  uint8_t button_1; // =1 if button pressed, else =0
  uint8_t button_2; // =1 if button pressed, else =0
  uint8_t switch_1; // =1 if switch ON and =0 if OFF

    // output variable
  uint8_t red_led_r; // =0..255 LED Red brightness
  uint8_t blue_led_b; // =0..255 LED Blue brightness
  uint8_t green_led_g; // =0..255 LED Green brightness
  char text_indicator[51];  // string UTF8 end zero

    // other variable
  uint8_t connect_flag;  // =1 if wire connected, else =0

} RemoteXY;
#pragma pack(pop)

/////////////////////////////////////////////
//           END RemoteXY include          //
/////////////////////////////////////////////

#define PIN_BUTTON_2 A4
#define PIN_SWITCH_1 A5

#include<AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A0
#define ECHO_PIN A1
#define MAX_DISTANCE 250
//#define MAX_SPEED 150 // sets speed of DC  motors
//#define MAX_SPEED_OFFSET 20

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor left_motor_A(1, MOTOR12_64KHZ);
AF_DCMotor left_motor_B(2, MOTOR12_64KHZ);
AF_DCMotor right_motor_A(3, MOTOR34_64KHZ);
AF_DCMotor right_motor_B(4, MOTOR34_64KHZ);
Servo myservo;

int distance = 100;

int right_motor_speed = 0;
int left_motor_speed = 0;
//define two arrays with a list of pins for each motor
AF_DCMotor RightMotor[2] = {right_motor_A, right_motor_B};
AF_DCMotor LeftMotor[2] = {left_motor_A, left_motor_B};

//speed control of motors
void Wheel (AF_DCMotor * motor, int v) // v = motor speed, motor = pointer to an array of pins
{
  if (v > 100) v=100;
  if (v < -100) v=-100;
  if (v > 0){

    motor[0].run(FORWARD);
    motor[1].run(FORWARD);
    motor[0].setSpeed(v * 1.75);
    motor[1].setSpeed(v * 1.75);
  }
  else if ( v<0 ){

    motor[0].run(BACKWARD);
    motor[1].run(BACKWARD);
    motor[0].setSpeed(v * 1.75);
    motor[1].setSpeed(v * 1.75);
/*    //digitalWrite (motor [1], FORWARD);
    analogWrite (motor [2], (v) * 0.75);
    //analogWrite (motor [2], (-v) * 0.75); */
  }
  else{
    motor[0].run(RELEASE);
    motor[1].run(RELEASE);
    motor[0].setSpeed(0);
    motor[1].setSpeed(0);
  }
}

 int lookRight()
 {
    RemoteXY.blue_led_b = 255;
    RemoteXY.red_led_r = 0;
    RemoteXY.green_led_g = 0;
    sprintf(RemoteXY.text_indicator, "CHECKING THE RIGHT SIDE.");
    myservo.write(50);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
 }

 int lookLeft()
 {
    RemoteXY.blue_led_b = 255;
    RemoteXY.red_led_r = 0;
    RemoteXY.green_led_g = 0;
    sprintf(RemoteXY.text_indicator, "CHECKING THE LEFT SIDE.");
    myservo.write(170);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
    delay(100);
 }

 int readPing()
 {
  delay(100);
  int cm = sonar.ping_cm();
   if(cm==0)
  {
    cm = MAX_DISTANCE ;
  }
  return cm;
 }

 void moveStop()
 {
  left_motor_A.run(RELEASE);
  left_motor_B.run(RELEASE);
  right_motor_A.run(RELEASE);
  right_motor_B.run(RELEASE);

 }

void setup()
{
  RemoteXY_Init ();

  pinMode (PIN_BUTTON_2, OUTPUT);
  pinMode (PIN_SWITCH_1, OUTPUT);

  myservo.attach(10);
  myservo.write(115);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);

}

void loop()
{
  RemoteXY_Handler ();

  digitalWrite(PIN_BUTTON_2, (RemoteXY.button_2==0)?LOW:HIGH);
  digitalWrite(PIN_SWITCH_1, (RemoteXY.switch_1==0)?LOW:HIGH);

    int distanceR = 0;
    int distanceL =  0;
    delay(40);

    if(distance<=27)
    {
      moveStop();
      RemoteXY.blue_led_b = 0;
      RemoteXY.red_led_r = 255;
      RemoteXY.green_led_g = 0;
      sprintf(RemoteXY.text_indicator, "AN OBSTACLE HAS COME IN FRONT OF YOUR ROBOT!!!");
      digitalWrite(PIN_BUTTON_2, HIGH);
      delay(1500);
      distanceR = lookRight();
      delay(250);
      distanceL = lookLeft();
      delay(250);

      if(distanceR>=distanceL)
      {
        RemoteXY.blue_led_b = 255;
        RemoteXY.red_led_r = 0;
        RemoteXY.green_led_g = 0;

        sprintf(RemoteXY.text_indicator, "IT IS GOOD TO GO ON THE RIGHT SIDE.");
      }

      else
      {
        sprintf(RemoteXY.text_indicator, "IT IS GOOD TO GO ON THE LEFT SIDE.");
      }
    }
    else
    {
      RemoteXY.blue_led_b = 0;
      RemoteXY.red_led_r = 0;
      RemoteXY.green_led_g = 255;
      //manage the right motor
      Wheel (LeftMotor, RemoteXY.joystick_1_y - RemoteXY.joystick_1_x);
      Wheel (RightMotor, RemoteXY.joystick_1_y + RemoteXY.joystick_1_x);

    }
    distance = readPing();

    //manage the right motor
    //Wheel (LeftMotor, RemoteXY.joystick_1_y - RemoteXY.joystick_1_x);
    //Wheel (RightMotor, RemoteXY.joystick_1_y + RemoteXY.joystick_1_x);

  }

I want my Robot to work on my directions and when he senses something on its front end then he should stop there and tell me through a RemoteXY.text_string and then check for obstacles at the left and right side and tell me on which side it is available to go. After that, it should again take my orders via my mobile phone.
Firstly, it became impossible to connect the robot to the Smartphone using Bluetooth because the robot was very busy in doing some other stuffs (only he knows what was he doing). Then, I applied a "RemoteXY Button" on my code (that is not in the code that I'm posting here) with an "if" block; such that if this switch is pressed via the Smartphone, only then the robot will start moving. So, doing this thing helped me to connect my robot to my smartphone via Bluetooth but, when I was connection then the Servo Motor was regularly spinning (again, I don't know why) after secure connection, when I turned that switch on, then my robot took only my first order (which is usually moving forward) and it performed on my first order for almost first 3 to 5 seconds and then the Robot got his system hanged and my smartphone was automatically disconnected from the robot.
I am unable to figure out where is the filth in my code or my code is itself fully filthy. This is the matter, where I need you guys' help
Other information that you might need for better Support/help, I am using:
1). RemoteXY app for Android to Robot Communication
2). Arduino UNO as Microcontroller
3). Arduino IDE for Programming Arduino
4). One SG 90 Servo Motor.
5). Four Geared DC- Motors.
6). L293D Motor Driver Shield for driving Dc motors and the Servo
7). HC SR-04 ultrasonic sensor for obstacle sensing
8). A 12V battery
9). HC-05 Module for Bluetooth Communication
10). A buzzer for external indicator/horn. At pin A4
11). A filthy code for Arduino Programming .
Any help with the code will be appreciated.
Thank You So Much in advance. ❤

I guess you are using this library. You have some longer delays in there. Can it be, that the RemoteXY_Handler has to be called more often, so that the App won't disconnect bluetooth? Currently the app might think, that the connection is lost, because if the distance is low enough, the Arduino will not be able do send any data to the app. That would resemble the behavior of the yield function on ESP. Try with a code without long delays

@chrisl  Yeah it might be possible. I'll check it out and update you. Btw I tried reducing some delays but that helped robot to take only one order. So, I think it might help me.  One more thing: Is my robot's microcontroller getting hanged because of so many tasks? I mean he is checking for obstacle and stoping in front of it, meanwhile I'm giving it more orders from my smartphone. So, plenty of multitasking might be resulting in the freezing of processing of the robot?  What do you think? And if Yes so, then how could it be modified and improved?

That's not generally too much. But a microcontroller can only do one thing at a time. So to multitask you have to switch between the tasks very fast. To do this, you should use non-blocking code, like in the BlinkWithoutDelay example, that comes with the Arduino IDE. You should look into Finite State Machines (FSM). They are easy to program and a good way to structure your program.

@chrisl Could you please share a link with me about FSM(s), that may help me since I have no idea about Finite State Machines. I tried reading Wikipedia Article but I was unable to understand that.

@chrisl  This tutorial looks interesting. Will it be enough to help me out on this issue?  I'll try implementing it on my code. If it helps me out, I'll give you an update. If I get stuck in some problem, I'll need your help. I urge you to help me then.

My guess is, that the function RemoteXY_Handler() has to be called very regularly (without long pauses in between) to communicate with the app on your smartphone, or the app will think, that the communication is lost, and disconnect from the robot. This means, that you cannot use long delay() calls in your code, since that is just busy waiting. In your code in case of an obstacle in front of the robot, you wait 3.6s in total. That is too much. The robot is doing nothing in this time. Instead you should use a non-blocking coding style. That means, that the code will not block, waiting (and doing nothing) until an event happends (for example a specific amount of time passed), but instead will execute other functions, until the event occurs. That is a generally better way to program a microcontroller, since it enables you to add more functionalities easily without disturbing the program flow.
Here you try to do timed things with delay(). Instead you should use a coding style, like the one found in the BlinkWithoutDelay example, that comes with the Arduino IDE. It is explained various times throughout the internet and this site. Basically it is like regularily looking at your watch (the millis() function here) and only doing things, when the time has come. You should look at the example and maybe go through some of the tutorials about this, so that you really understand, what happens there. Then you can start to rewrite your code and eliminate all delay() calls. That will need some restructuring of the code.

The BlinkWithoutDelay example is an easy structure, since it contains only few logic. Your goal is a bit more complex. So I suggest, that you use a Finite State Machine (FSM). It is rather easy to implement and a powerful tool to structure your code. It's definitely worth learning for every programmer.
A FSM consists of multiple states, that are connected by transitions. In each state there can be code executed. Also there might be code, that is only executed on transitions. First you have to model your project into states. One state here could be REMOTE_CONTROLLED, which would just execute the commands coming from the app. Based on input from sensors and the app you can then transition between the states. If you see, that you might need a delay() inside a state, that might be a hint, that you can further divide the state into substates. For example I would make an extra state, which gives the servo the time to move. I would suggest, that you really draw a graph for your project with all your states (state name in a bubble). Then draw arrows as state transitions between them. This will give you a good overview of the structure to implement.
In code this is often implemented with a switch() case structure and a state variable:
int state=0;
int distance = 100;

void loop(){
    RemoteXY_Handler ();
    distance = readPing();

    switch(state){
        case 0:
            // Do whatever the remote demands here
            if(distance <= 27){
                // Execute code, that should happen once at transition here
                state = 1; // This makes the transition to the next state
            }
        case 1:
            // Code of the next state
    }
}

With this structure at every time only the code of the current state will be executed. The transitions are made simply by setting the state variable to the next desired state. To make the states more speaking in the code, you can use an enum, so that every state can be referenced with an enum name. The remote handler and the reading of the distance is done outside the FSM here, since you always need the input from those. Based on them, you can do state transitions.
To do timed things in an FSM, you can put the millis() code (like in the BlinkWithoutDelay example) into the corresponding state.

Note, that this is only one way to implement a FSM. The video, that you linked, does this a bit different by using functions pointers (the state() function pointer is the state variable here). The principle is the same, only the programming structure is different. You can decide yourself, what works better for you, and what you understand better (pointers can be a bit difficult to understand for beginners).

Thank You So Much @chrisl for guiding me to the right path. I am familiar with Pointers in C Language as I have done a crash course on C Language. But, I am not master of that. So, I'll better use the way that you told me here. I have read your whole answer and after perfectly understanding everything that you've told here, I'll try to implement it on my code and project. Then, I'll leave an update here that how it helped me or what is confusing me while implementing.  Thank You So Much again Sir


text:
Multiple arduino connections problem
I have 2 Arduino Mega 2560 connected via USB to my Ubuntu 18.04 machine. When I boot, one connects to /dev/ttyACM0 and the other connects to /dev/ttyACM1.
Communication works perfectly. However, randomly on boot, the Arduino boards connect to the opposite port of what is coded into the script. I use Python 3.6 to communicate with the boards.
Is there any way to force these boards to always connect to the same port? Or is there a way for Python to detect the board that it's talking to?

https://majenko.co.uk/blog/making-your-boards-unique-linux

Thanks. Simpler solution found here. raspberrypi.org/forums/viewtopic.php?t=216907


text:
Is this Arduino UNO running at 12 MHz?
I am wondering if this Arduino UNO R3 clone is clocked at 12 MHz instead of the standard 16 MHz? On the board, you can see there is 12.000 written on the crystal oscillator.

But maybe it's not the MCU clock speed? I found this other clone, which has 2 crystal oscillators?! One is 12 MHz and the other one is 16 MHz.

I can't figure out what's happening with these boards... Are these sporting faster or slower speeds? The original Arduino UNO R3 has only one 16 MHz crystal oscillator.

look at the leftmost component between C5 and C6

The 12MHz crystal is for the USB interface.
The main MCU uses a very small 16MHz resonator, which you can see between C5 and C6.

The 16 MHz resonator, a 3-pin part, can be seen between C5 and C6 in the first picture.
The 12 MHz is for the CH340 as noted.
So it's not an Uno, but a clone ripoff, as an Uno would have a Atmega16U2 for the USB.


text:
Pro Micro ATMEGA32U4 unable to upload
I have a simple flashing led program that I want to upload on my pro micro (see image) but it doesnt work (see image: no port available, Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.)
I have successfully uploaded this program on my arduino uno.
Ive followed this guide for the drivers and more.
https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/installing-windows
Thanks for help

Your board will only present a serial port if the sketch that is running on it is programmed to present a serial port. The board does not have an actual serial port for communication with the PC - only what the sketch provides.
If the sketch doesn't provide one, or if the sketch isn't running (for example if it was compiled for the wrong board by accident) then you will never see a serial port.
Since the "normal" way of resetting the board to enter the bootloader (which does present its own serial port) is to open the serial port at 1200 baud, since you don't have one to open it's kind of hard to get to the bootloader. However, depending on what bootloader you have installed there are a number of options that can help you:

Briefly connecting RST to GND just before uploading may activate the bootloader for a few seconds.
Doing the above twice in rapid succession may activate the bootloader for longer (depending on the bootloader version)

Erasing the chip and reinstalling the bootloader is the only real way that is guaranteed to work, though. But that said, I have seen boards come out of China without any bootloader at all - so reinstalling the bootloader is always a good first option with cheap boards.  You can use your Arduino UNO as an ISP programmer (using the ArduinoISP sketch and treating it like you're making a breadboard Arduino).

I have also problem with China boards, after 3 days of googling and trying get boards to work, I found out, that chip it self have difference.one chip is for bootloader from arduino micro, and one from lilypad arduino USB, it is about chip ID when arduino IDE is calling for upload sketch, thers are two 4bit id when it cals. And one is chip with cristal 16MHz lilypad arduino USB, and another version 8MHz Arduino micro, but board is it self looks like Arduino pro micro, Chip type have only few letters difference, if I will never find out that solution, if I will not have two chip comparisions .
Last row of numbers makes chip type difference and vendor id depends to what chip type we have. And what clock speed is using. And I see on the veb that many peoples have this problem to not be able to upload simple sketch because of that chip model.


text:
How To Get Data From Arduino Uno Onto My Laptop Through The USB
I want to write a c++ program that does something with the data from one of the input analog pins as the program runs, but I want to know how to get the value from the arduino uno though the USB port (that I am also using to power the uno) and into my laptop for using. IS there any documentation I should read?
My laptop runs Ubuntu 18.04 if that matters.
EDIT: I am not talking about the Serial monitor by the way

Chech the "serial" scetch and open "serial monitor" in the ArduinoIDE. You can write a program that reads data from the serial.

Check out the inbuilt examples. There are many options there. How do you plan to store the data on your computer once it gets there?

The "Serial Monitor" is merely a window to the Arduino's serial port. You don't have to use it to use Serial. It's just a (very simple) built in way of seeing the data.
You can use the Serial interface with your own software, or with third party software. It's not tied to the Serial Monitor in any way at all.
So:

Use Serial.print() etc to send data to the PC
Write your own PC software in your language of choice to process that data, or
Use some third party application to read and process the serial data


text:
5V pin output on arduino
Sorry for the newbie question (just started learning electronics).
I just saw a tutorial that says that the 5V output pin on the Arduino delivers more amps (if needed) when connecting more voltage to the board (connecting to the 9 - 12V instead of 5V).
Does that mean that the 5V pin then delivers more than 5V as well?

Time for a crash course in electronics and power:
The 5V pin only ever provides 5V. That's why it's the "5V" pin. (assuming, of course, that you give the board more than 5V).
In simple linear electronics you have three values:

The voltage
The current
The load

Generally two of the three are either "fixed" or "known" and the third changes depending on the other two. For simple resistive circuits (where the load is a simple resistor) this relationship is Ohm's Law.

If the voltage is fixed, and
If the load changes, then
The current will also change to keep the relationship stable.

A "power supply" (any device which provides power to some other device) generally has two parameters: Voltage and Current.  One of those is always fixed. The other is always variable, and quoted as a maximum that the supply can give.
For the Arduino's 5V pin the parameters are:

Voltage: 5V
Current: 800mA Maximum

That means that the 5V pin has a fixed voltage of 5V, but the current is free to change depending on the load up to a maximum of 800mA (or a lower limit if you are providing the input power from a source with a lower current. There is also heat to consider with the Arduino - see below).
The two values, voltage and current, combine together to give the "power" of the power supply, through simple multiplication. So the Arduino's 5V pin is 5V × 0.8A = 4 watts maximum.
When you provide power to the Arduino through the barrel jack it first goes through a linear voltage regulator.  This is the device which takes the incoming voltage and reduces it to 5V. Since energy can neither be created nor destroyed it does that reduction in energy by converting some of it to heat.
Say you connect something up that needs 100mA and you plug in a 9V power supply to the board. Let's also assume that the Arduino itself needs 50mA (I like nice round numbers).

That's 150mA in total for the "load".
The incoming voltage is 9V
The outgoing voltage is 5V

The power of the input is thus 9V × 0.15A = 1.35W
The power of the output is then 5V × 0.15A = 0.75W
The power difference is 0.6W
That 0.6W is converted from electrical energy to heat energy by the voltage regulator and "thrown away".
So the "heavier" your load (the more current you demand from the 5V pin) the greater the heat that is generated by the voltage regulator.
When the regulator gets too hot one of two things happen:

A good quality regulator will shut down and you will lose power to the board
A cheap Chinese regulator will likely "fail short" and feed your 9V direct into the Arduino causing components to release their Magic Smoke™ and stop working

Thank you so much, made things clear! :)

Don't you mean to say "A cheap Chinese regulator will likely "fail short" and feed your 9V supply voltage directly into the Arduino causing components to release their Magic Smoke™ and stop working?" (I've always loved the idea that electronics contains magic smoke.)

@DuncanC Yep - typo.


text:
My push button code doesn't work properly
I'm using an OLED display connected to a push button.  I am trying to get my display to show two different values independently  by using the push button to switch between them. Here is a snap of my code from the loop function:
    if (buttonState == HIGH) {
    x=x+1;
  }
  if (x == 1) {
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.setTextSize(2);
  display.print(T);
  display.print(" degree");
  display.display();
  display.print(x);

}
    else if (x == 2) {
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.setTextSize(2);
  display.print(perventage);
  display.print(" %");
  display.display();
  display.print(x);
}
    else  {
      x=1;
      }

  delay(10);
}

x is defined as 1 initially out side the loop.
What happens is that when the circuit is turned on, the screen displays the value of T then what should happen is when I push the button it switches to the second value which is percentage, and I push again to go back to T. My issue is that the Arduino doesn't response to the push button all of the time sometimes it takes 1 click and other times it takes 6 or 8 fast clicks to switch between them and it doesn't stick to a specific number of pushes to switch.
What would you suggest me to change to fix it.
Edit: here is pic of my wiring diagram

How is your button wired?

It should switch between the values from 1 push as it's designed from the code, but In reality it rarely switches between values from 1 push, it takes 4,5,6,8 pushes just to get it to switch between values. I don't understand why it behave like that

Yes, that's what you said in your question. But I asked "How is your button wired?", not "Reiterate what you said in your question about how you want it to behave".

Please show a picture of how you have your button connected to the Arduino.

how i the push button connected to the oled display?

the picture shows that the pushbutton is not connected to any data lines

sorry I for got to add a wire from one of the top pins to pin number 2 in the picture, I have it connected on my breadboard circuit

One core problem is that you have a simple "If the button is HIGH then cycle through the numbers". The longer you hold the button the more times it will cycle through the numbers.  It's pure 50/50 chance that you happen to release the button on a different number to the one it started on.
Instead you need to look for a change in the state of the button. Has it changed from LOW to HIGH:
static uint8_t oldState = LOW;

uint8_t buttonState = digitalRead(BUTTON_PIN);
if (buttonState != oldState) {
    oldState = buttonState;

    if (buttonState == HIGH) {
        // This only runs once at the moment of pressing
        // the button - not continuously while you're
        // holding the button in.
        // Cycle through your displays here.
    }
}

You are reading the raw button state without debouncing it, so you may be getting 2 (or 4, or ...) pulses so quickly - off the same button-push - that the display or your eye can't respond that quickly. Here is Nick Gammon's tutorial on switches and buttons, including debouncing.
Also make sure you use a pull-down resistor on the button input-pin. Floating inputs are noise and will give you a lot of false signals.