text:
Teensy freezing when reading ir sensor
I have a teensy that controls a motor and reads from a ir sensor, GP2Y0E02b. The issue i run into is that at random times the teensy seems to freeze, the main code stops printing but the interrupt routine continue to work. It seems to be that when reading the ir sensor it causes the teensy to freeze. The code below is what I'm using to read the ir values.
#include <i2c_t3.h>
//#include <WSWire.h>
#include <Arduino.h>
uint16_t ReadFirstSensor();
uint16_t ReadSecondSensor();

#define ADDRESS       0x80 >> 1  // Arduino uses 7 bit addressing so we shift
address right one bit
#define DISTANCE_REG  0x5E
#define SHIFT         0x35

class GP2Y0E02B {
public:
    int MaxDistance;
   int MinDistance = 27;
float distance = 0;
byte high, low = 0;
float shift = 0;
bool badSensor = false;

GP2Y0E02B(){
  //Serial.println("Sensors Initialized");
};

float GetRawDistance()
{
    //if (!badSensor){
      float FirstDistance = ReadFirstSensor();
      return FirstDistance;
    //}
    //else
    //  return 22000;
}

void StartSensors()
{
    //Serial.println("StartSensors Called");
    Wire.begin(400000);
    delay(50);
    //Serial.println("Wire.begin() has been called");
    Wire.beginTransmission(ADDRESS);
    //Serial.println ("beginTrans done");
    Wire.write(SHIFT);
    //Serial.println ("Shiftwrite done");
    int stat = Wire.endTransmission();
    //Serial.print("endTrans done stat: ");Serial.println(stat);

    int i = 0;
    while (Wire.available() == 0)
    {
        //Serial.println ("Im trying SPI");
        i++;
        delay(5);
        if (i>30) break;
    }
    if (i<30)
    {
        shift = Wire.read();
        Wire.requestFrom(ADDRESS, 1);
        MaxDistance = GetRawDistance();
        badSensor = false;
    }
    else
    {
        //Serial.println ("couldnt initialize the sensors");
        badSensor = true;
    }
 }

 uint16_t ReadFirstSensor()
 {
    static int LastDist = 0;
    //Serial.println ("Read First sensor called");
    Wire.beginTransmission(ADDRESS);
    Wire.write(DISTANCE_REG);
    //Serial.println ("DoneWireWrite");
    int SPIhealth = Wire.endTransmission();
    //Serial.print ("DoneWireEndTransmit: ");Serial.println (SPIhealth);
    if (SPIhealth == 0) Wire.requestFrom(ADDRESS, 2);
    else return LastDist;
    //Serial.println ("DoneWireREquest");

    int EmergBreak = 0;
    while(Wire.available() < 2)
    {
        //Serial.println ("Trying to get sensor reading");
        EmergBreak++;
        delay(1);
        if (EmergBreak > 20) return LastDist;
    }
    if (EmergBreak > 20);//Serial.println ("Couldnt Read Sensor");
    //else Serial.println ("Done Reading Sensor");

    high = Wire.read();
    low = Wire.read();

    uint16_t rawDistance;
    rawDistance = (high * 16 + low)/16/(float)pow(2,shift); // Calculate the range in CM
    //Serial.print("rawDistance: ");Serial.println(rawDistance);
    rawDistance = (uint16_t) low ;
    rawDistance += (uint16_t)high << 8;
    LastDist = rawDistance;

    return rawDistance;
  }

};

I2C code would typically get "stuck" if the peripheral fails to respond and you don't have a reasonable timeout configured.  You should probably figure out how to configure a timeout for the I2C operation.  And maybe see if you can debug the conditions under which it occurs.

ill try that out

I don't know where to start. The StartSensors function calls Wire.available without a Wire.requestfrom and it will never get to the section with Wire.requestFrom and the variable shift will stay 0. That unused section does a Wire.read first which might return -1 and puts that into the float shift, and after that the Wire.requestFrom is called but the requested data is never read. The function ReadFirstSensor has a while statement without meaning and a calculation for rawDistance has bytes, integers, and float. The I2C bus is not a SPI bus, but there are variables with SPI in their name.


text:
Using TFT with hardware SPI and speaker with tone()
I want to make a device with a TFT screen and a speaker that uses the builtin tone() function. However, according to the documentation, using tone() interferes with PWM on pins 3 and 11. On the Arduino Uno, the MOSI pin is default on pin 11, and it seems like defining another pin for MOSI disables hardware SPI, which, according to the module page, slows down the device. As well, the examples are written for hardware SPI and the SD card is only available with hardware SPI. What should I do here? Is there a way to redefine the default MOSI pin without disabling hardware SPI?

It is no problem. The tone function uses timer2 which is the same timer when using pwm for pin 3 and 11. The tone function does not interfere with pin 3 and 11, it only uses timer2 for a software interrupt to create a tone on any pin. The tone function does not use the pwm capabilities of the microcontroller.

short version : "interference with PWM", not with SPI

You are getting your wires crossed in your brain and imagining a problem where there is none.
Both PWM on pins 3 & 11, and tone(), use the Timer2 device. Only one of those can use Timer2 at a time, and they both want to use it in different ways, so there is a conflict between them.
Timer2 has nothing to do with SPI. So tone() has no effect on SPI, and nor does PWM have any effect on SPI (other than the fact that only one can come out of pin 11 at any time), since there is no internal resource conflict.

source: Stack Exchange

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

sort: votes


text:
Strange compiler error (Segmentation Fault)
You're getting a compiler error. It happens in strange parts of code that really shouldn't be having a problem.  The error looks something like:
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino\HardwareSerial.cpp:203:1: internal compiler error: Segmentation fault

}

^

Please submit a full bug report,

with preprocessed source if appropriate.

See http://gcc.gnu.org/bugs.html for instructions.

lto-wrapper.exe: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc returned 1 exit status

compilation terminated.

c:/program files/windowsapps/arduinollc.arduinoide_1.8.15.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe: error: lto-wrapper failed

collect2.exe: error: ld returned 1 exit status

What is it, and how do you fix it?

Restarting the Arduino IDE may be helpful.

This is a known fault with the compiler in Windows.  The annoying thing is that it's the version of the compiler that is included in the Windows Store App version of the Arduino IDE.
It also snuck into the Windows version of the IDE from version 1.8.6 from the Arduino.cc website, with the bundled version of the Arduino AVR core.
There are numerous Github issues open for the problem and navigating the tangled web of them is a bit of a chore, but this one seems to be the most promising for digging into the root cause:

AVR core 1.6.22 (IDE 1.8.6) crashes avr-gcc compiler (5.4.0) when F() string is assigned to a static variable

The simplest fix is to downgrade your compiler to 4.9.2.  This can be done by using the Boards Manager to install version 1.6.21 of the Arduino AVR Boards.  This should give you compiler version 4.9.2-atmel3.5.4-arduino2 which doesn't suffer from the problem.

This is the central issue report for this problem:
https://github.com/arduino/Arduino/issues/7949

and DO NOT press "Update" button before pressing "Close" !!

Works like a charm, thanks. Had this is issue with a Arduino/Genuino Micro with the IRremote library.

I've been having this kind of error off and on lately for no apparent reason. What eliminated it for me was going into the IDE preferences and changing compiler output to verbose and also show all warnings. What??? I know it's crazy. I was just trying to get more information about the error, but I haven't gotten it since. And I was getting it a lot before.

Worked for me too. Thank you

Sometimes it seems like I have to reboot my PC, as exiting from Arduino and rerunning still doesn't always allow me to compile again.

"changing compiler output to verbose and also show all warnings"

This worked for me too.

I put back the settings to its default state again, after a restart and compile. It worked. Not sure whats under this?

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


text:
How to transmit Float sensor values via NRF24L01 module?
I'm trying to figure out a way to transmit four sensor values: Voltage, Current, Power and consumption but I'm unable to do that.
Yet, my syntax is correct... what am I missing?
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include <RF24.h>

#define ACS712 A0

int lastData = 0;
int dataSum = 0;
int Count = 0;

float Voltage;
float Current;
float Power;
float kWh;
float Consumption;
String Data;

float vpc = 4.882813; // approx. voltage per count

RF24 radio(9, 10); // CE, CSN
const byte addresses[][6] = {"00001", "00002"};

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT);
  radio.begin();
  radio.openWritingPipe(addresses[1]); // 00001
  radio.openReadingPipe(1, addresses[0]); // 00002
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {

  radio.stopListening();

  if (millis() > lastData + 1) {
    dataSum += sq(analogRead(ACS712) - 512);
    Count++;

    lastData = millis();
  }
  // If statement to make calculations.
  if (Count == 1000) {

    // To get the RMS of the data.
    float mean = dataSum / Count;
    float value = sqrt(mean);

    // To get the Voltage (in volts) consumed.
    float Voltage = value * vpc;

    // To get the Current (in amps) consumed.
    float Current = Voltage / 66;

    // To get the Power (in watts) consumed.
    float Power = Current * 240;

    float kWh = Power / 1000;
    float Consumption = kWh;

    dataSum = 0;
    Count = 0;

    Data += F("\nVoltage: ");
    Data += String(Voltage, 3);
    Data += F("\nCurrent: ");
    Data += String(Current, 3);
    Data += F("\nPower: ");
    Data += String(Power, 3);
    Data += F("\nConsumption: ");
    Data += String(Consumption, 3);
    //Serial.println(Data);

    radio.write(&Data, sizeof(Data));
    if (radio.write(&Data, sizeof(Data)) && true) {
      Serial.println("Sent!");
    } else {
      Serial.println("Failed!");
    };
    delay(10);
  }
}

I'm unable to do that is meaningless ..... clear description of observed results is meaningful

Hint: What is the payload max size? And what would be transmitted for radio.write(&Data, sizeof(Data)), the String object or its value?

Have you tried sending command values instead of string values? For example, send 0x01 for Voltage, 0x02 for Current etc. That way you don't send Strings (which in embedded programming you really shouldn't be using!!) and will reduce the data transferred.

Why not just send the voltage, and do all those calculations on the receiver, as there are just basic division/multiplication with set constants. Also, first try a more basic program to get the radio working. Were you able to run one of the example sketches, and get the radios working?

Simple float transmission:
For TX use
float payload = 0.12345;
radio.write(&payload, sizeof(payload));

For RX use
float payload = 0;
radio.read(&payload, sizeof(payload));

here he wants to transmit the complete string, not a single float value your answer will be applicable if it is a single float but here the question deals with how he can transmit a complete string.


text:
library mixing log4Esp & Syslog for esp8266
has someone finaly made a new lib combining log4esp and syslog
cf :
SyslogAppender for log4esp
thanks:!

I did a rather dirty (but efficient for my purpose) job : While creating a new logger I declared and attached to it a log4esp formatter in which I sent ... syslog messages
dirty dirty dirty
my config constants are : SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME

My logger.h:
#ifndef Logging_H
#define Logging_H
#include <Log4Esp.h>
namespace Logging
{
void setup() ;
log4Esp::Logger Logger(const char *name);
}
#endif

my logger.cpp:
#include <Log4Esp.h>
#include <Syslog.h>
#include <WiFiUdp.h>
#include <ESP8266WiFi.h>
#include "Logger.h"
#include "config.h"
namespace Logging
{
// A UDP instance to let us send and receive packets over UDP
WiFiUDP udpClient;
// Create a new syslog instance with LOG_KERN facility
Syslog syslog(udpClient, SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME, LOG_KERN);
//new logger
log4Esp::Logger Logger(const char *name)
{
  //new instance
  log4Esp::Logger logger = log4Esp::Logger(name);
  //minimal level
  logger.addLevelToAll(log4Esp::Appender::LOG_LEVEL);
  // formatting for serial logging
  logger.addFormatterToAll([name](Print & output, log4Esp::Appender::Level level, const char *msg, va_list * args) {
    ////////////////////////////////////////
    // serial log format
    // output uptime of this program in milliseconds
    output.printf("%10d", millis());
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // output free heap space
    output.printf("(%d)", ESP.getFreeHeap());
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // output logger name
    output.printf("%-4s", name);
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // output log level
    output.print(log4Esp::Appender::toString(level, true));
    if (level <= log4Esp::Appender::Level::ERROR) {
      output.print("***");
    } else {
      output.print("   ");
    }
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // determine buffer length for formatted data
    size_t length = vsnprintf(NULL, 0, msg, *args) + 1;
    char buffer[length];
    // output formatted data
    vsnprintf(buffer, length, msg, *args);
    output.print(buffer);
    ////////////////////////////////////////
    // Stop here if wifi is down
    if (WiFi.status() != WL_CONNECTED)
      return;
    ////////////////////////////////////////
    // format for syslog
    uint16_t slevel;
    switch (level) {
      case log4Esp::Appender::Level::FATAL    :
        slevel = LOG_CRIT;
        break;
      case log4Esp::Appender::Level::ERROR    :
        slevel = LOG_ERR;
        break;
      case log4Esp::Appender::Level::WARNING  :
        slevel = LOG_WARNING;
        break;
      case log4Esp::Appender::Level::VERBOSE  :
        slevel = LOG_INFO;
        break;
      case log4Esp::Appender::Level::TRACE    :
      default:
        slevel = LOG_DEBUG;
        break;
    }
    syslog.logf(slevel, "%10d|(%d)|%-4s|%s", millis(), ESP.getFreeHeap(), name, buffer);
  });
  return logger;
}
void setup() {

}
}

Yes:)  i understood now the other thread!  That s also perfect for me, you should GitHub it:)


text:
Which board's bootloader is on the microcontroller?
Currently I'm doing a project that needs an Atmega2560 standalone MCU. After I burned the bootloader with this method: http://www.gammon.com.au/bootloader . I set the Board as "Arduino/Genuino Mega or Mega 2560" and the Processor as "ATmega2560 (Mega 2560)". But, it just stuck at "uploading" and this message pop up: "avrdude: stk500v2_ReceiveMessage(): timeout". So, I'm guessing I'm choosing a wrong board. Is there a way to check which board to select in the Tool tab?

Do you have DTR connected via 0.1uF cap to create a Reset and start the bootloader code looking for a serial download?

It depends on which bootloader you loaded, when you write your bootloader with AVRDude you specify the hex file, Which Hex file did you specify?

I burned through this method: http://www.gammon.com.au/bootloader and I haven't use any Hex File with this method.

Nick Gammon's sketch for loading a bootloader holds 10 different bootloaders. The actual bootloader that is burned depends on the detected signature of the board being programmed. If this went well the following bootloader should have been programmed "Atmega2560 with fixes for watchdog timer problem (8192 bytes)". With Nick Gammon's sketch you can also verify the existing bootloader. Dit you try that?


text:
Question about browsing the web using arduino
I have got an arduino, a TFT touch screen and a WIFI module. The question is can i visit a specific web site and display it on that screen and interact with it.

no. you would need a html rendering engine like Gecko oe WebKit

yes, but you'd have to use an opera-mini style pre-render process on a middle-man.

As already pointed out in @Kwasmich's answer, you are vastly overestimating the capability of an arduino. Another more powerful board (Such as a Raspberri-PI) could possibly handle those tasks. But Arduino's + your Wifi module are much better suited for allowing remote monitoring and control of simple processes. The coding and hardware that go into displaying a web page with graphics may seem easy these days, but there are some mountains you'll need to climb to understand why its much harder than it seems. Don't let that discourage you though! Mountains can be climbed!

You just have to install Chromium and call the desired page.
No, just kidding. I don't think you will ever fit a parsing and rendering engine on an arduino. Chromium for example takes about 150MiB of storage and depending on the opened page hundreds of MiB of RAM. Both of which is multiple orders of magnitude larger than the Arduino has to offer.
You might want to consider going to use a SBC like the Raspberry Pi for such usecase.
Alternatively you can query the data over network and write your own rendering code for the TFT display.


text:
Arduino button-controlled LED with AVR Assembly
I am trying to make a simple button-controlled LED, but I cannot seem to get any input from the button that would change the state of the LED. In other words, the program keeps branching to lighton, keeping the LED always on, regardless of the button state. I am using an Elegoo Uno R3.
Schematic:

Code:

.text
.global setup
.global loop

setup:
  ser r16
  sts DDRB, r16
  ldi r16, 0b00000000
  sts DDRD, r16
  ldi r16, 0b00100000
  sts PORTB, r16
  clr r16
  sts PORTD, r16

loop:
  lds r20, PORTD
  cpi r20, 0x00 ; PORTD always equal to 0x00 ?
  breq lighton
  clr r16
  sts PORTB, r16
  rjmp loop
lighton:
  ldi r16, 0b00100000
  sts PORTB, r16
  rjmp loop

Edit: I also implemented the method in https://stackoverflow.com/questions/39361410/creating-a-toggle-switch-in-avr-assembly to create a short delay with r18 instead of del, but it didn't help; see revised loop method below:

loop:
  cpi r18, 0
  brne dec_jmp
  lds r20, PORTD
  cpi r20, 0x00 ; PORTD always equal to 0x00 ?
  breq lighton
  clr r16
  sts PORTB, r16
  ldi r18, 250
  rjmp loop
lighton:
  ldi r16, 0b00100000
  sts PORTB, r16
  ldi r18, 250
  rjmp loop

dec_jmp:
  dec r18
  rjmp loop

With delay:

lighton:
  ldi r16, 0b00100000
  sts PORTB, r16
  call delay150
  ldi r16, 0b00000000
  sts PORTB, r16
  call delay150
  rjmp loop

Duplicate: https://stackoverflow.com/questions/39361410/creating-a-toggle-switch-in-avr-assembly

See edit in post

You have two potential problems in he setup: 1. You test not only PortB-bit2 (=Arduino pin 2), but all the pins of PortB. As these are floating your test (cpi r20 0x00) will never come true and the branch to lighton will never happen. 2. Your button will suffer from bouncing (google on this). Because of the 1st problem the LED should stay OFF. But it stays ON, so there is something else wrong. Break he program in small(er) parts and test each part on it's own. Did you try to switch the LED on and of by software alone (with a delay in between and not looking at the state of the switch)?

PORTB-bit2 corresponds to Pin13, which is the output pin that I am using. From what I understand, the branch to lighton is always happening and that's the problem. For example, I removed the line that sets PORTB in the setup method, and the LED remains on. So, Pin13 is constantly being set at lighton. Also, I did try the LED by itself with a delay and it works normally.

are you sure that the button is wired correctly? is the voltage on pin3 changing when you press the button?

Why did you connect a second LED to pin 13? You can as well used the LED that's already there (on the Arduino). Change the test to only test bit2 and not all the bytes from PortD (mask them out bij AND with 0x04). Even if you do that you still have the bouncing problem. Put a delay of a couple of seconds in so that you can see what happens in every loop. What happens when you replace the button with a piece of wire (like the button always closed), or when you take the button out (like button always open)?

See answer below

Just for the record: If you work with an Arduino Uno then Pin13 is on-board connected to a yellow LED via a non-inverting opamp and a resistor. Because of the opamp the load on the pin is negligible. - The setup of the other pins of PORTD is not so important. What is important is that you only test the status of pin2: lds r20 PORTD / andi r20 0b00000100 / breq lighton (the andi instruction sets the other bits to zero, so that the breq is based on the value of Pin2 only).

Fixed it with the below code for the loop:

loop:
  sbic PIND, 2
  call nopressb
  ; button pressed
  ldi r16, 0b00100000
  out PORTB, r16
  rjmp loop
nopressb:
  ldi r16, 0b00000000
  out PORTB, r16
  rjmp loop

Why do you use a call to jump to nopressb? call is ment to call a subroutine and stores the return address on the stack. Because you never return from a subroutine the stack will overflow.


text:
Arduino Voice recognition
Is it possible to use only arduino to do voice recognition? or maybe with esp32 no internet.
I found speech recognition chip but that's not what i want
I got esp32 esp8266 and arduino board.
I would like to know if somebody could do it

No. It's as simple as that. No. Voice Recognition is a very very complex task. To do it fast and well in a "general" way takes a neural network, or a very powerful PC (note: all common ones now use online resources to do all the work).
A voice recognition chip generally is pre-programmed to respond to specific words.

Correction: You don't actually need a cloud-based service. It might take a little while, but Mozilla's Deepspeech (https://github.com/mozilla/DeepSpeech/) is capable of doing it on-device. IIRC Raspberry Pi's are capable enough to do it, but only just.

And how does that relate to doing it on an Arduino?

True. Just wanted to point out that it's technically possible to do locally, given the right equipment :P

Maybe if we were on the Pi SE site your comment might be taken a little more seriously. But we're not. Anything can be done if you have the right equipment.

The answer to can it be done is inherently yes at some point, making this answer wrong... it's as simple as that.

@user2305193 No, it's not. I challenge you to do it. Do voice recognition with just an Arduino, and maybe an ESP32 with no internet connection. Go on. Show us how. No extra hardware. No VR3 module. No Kendryte K210. No connection to a PC. Nothing. Just an Arduino. 9 times out of 10 when someone says "An Arduino" they mean "An UNO". I'll be nice. You can use a Mega2560.

A simple speech (word) recognition can be done. I made one in 1998. Chip was atmega16. Now there are ready to use sound detectors and you just use digital out. https://s.click.aliexpress.com/e/cn6IwDhI
From that digital signal you get frequencies, durations and delays. First output results to serial and then get key features, ranges of voice command or a word. Put those boundaries to table and there you have it. It works like a charm with few words but then you have to make indexed database or something to keep it reasonable fast. I had only 8 commands and recognition was about 85% There were only 2 times when it "hear" some other word as a listed word. Language was finnish. I assume that it might lower those false positive occurrencies. As you see this is nothing compared to real systems but can be easily used in non critical solutions. ESP32 can do so much more that I think this might be interesting..
You may also want to look -> https://github.com/MhageGH/esp32_CloudSpeech

Marmenmu, Form my understanding. Only you can speak to the microphone right? It use your frequency or tone. or only you that can make the robot understand.

Also what do i need to know to make frequencies recognition with atmega16

This method cannot handle high noise levels. First use the trimmer that it only activates when command is spoken at close distance of microphone. Then make "capture program" that only passes word parameters to pc. Speak desired word several times and you get key values of frequencies, delays and order of those. You have to just watch one pin and find minimum value how long the frequency alias tone must be same. Write those packets to array and then compare predefined commands that tells order and min and max lengths of frequencies and delays. https://forum.arduino.cc/index.php?topic=105289.0

Yes it is possible - see here for ESP32 example:
https://github.com/espressif/esp-adf/tree/master/examples/speech_recognition/asr


text:
Trouble understanding connection diagram

The image shows a way of connecting an optocoupler.
My problem comes from how the emitter (Q1 in the image) is connected. The emmiter goes to a resistance going to ground and to v_out. When i try to add this to my circuit the pin that is suppost to be receiving data, the v_out pin goes silent. If i remove the resistance going from the emitter to ground and just have vout to the emitter everything works fine.

Is the optocoupler connected to an arduino board? What is your circuit?

My first reaction is "YIKES- That's 18Volts going into the arduino input pin?". If the Ardiono in question is the kind that has an on-board 5V regulator, use that in place of the 18V at Q1's collector, put the resistor back in, and try again. Obvious, but don't forget to configure your input pin and an INPUT. You also might want to try a different input pin because as much as I hate to say it, you're first experiment could have destroyed the input circuit for the first pin.

please explain what this means .... pin goes silent

pin that is suppost to be receiving data .... which pin are you talking about?

Normally you would connect the ground (0V) side of resistor R2 to the ground of the Arduino and the other side of R2 (which is also connected to the emitter of Q1) to an input pin of the Arduino. When the LED is energized by pressing the button it sends light to the fototransistor. Because of this the phototransistor starts conducting current (I1) which causes a voltage drop I1xR2 over R2. When this voltage is high enough the input pin will show a "1" (or HIGH) when read out.  "High enough" means >= 0.7 x Vcc, where Vcc is the voltage of the powerline to the Arduino.
The website from which the picture in your question originates (here) has an extensive article about the working and implementation of optocouplers. It also shows examples of alternative circuits.

maybe i'm misunderstanding here, but something like this? https://imgur.com/6xZE5gx Here the red wire goes to the collector. the emitter goes to ground via resistor and sends signal to the Arduino via the gray cable

I would leave away the resistor in the collector line. Are the resistors from the picture the real ones you use (how did you get a non standard resistor of 250 Ohm?). Personally I have more faith in the circuit of fig. 14 in the datasheet: https://www.vishay.com/docs/81181/4n35.pdf


text:
SD card initialization failed
i use the example sketch of SD card presented in Arduino IDE.
It runs well, but when i reboot my Adruino Mega by the reset button, the SD card initialization fails.
To fix it, i need to remove the SD card, insert it in his socket and reboot the board again. Then, SD card initialization is OK.
How can i update my code to try initialize the SD card until initialization is OK?
Also, can you explain me where come this bug ?
See the example SD card setup on the Arduino Mega:
Serial.print("Initializing SD card...");

  if (!SD.begin(53)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

It is probably not a bug, not all sd cards are compatible with the sd library. Are you resetting the arduino while the sd card is busy? Perhaps the socket on its module is not suitable for 5v. Perhaps you use a breadboard. Perhaps the wires are too long Perhaps the arduino mega has not enough voltage due to a cheap usb cable. There are many more things that can be wrong.

is some other SPI device attached?

No other SPI device attached. I use usb cable and 20cm wires to link sd card to the arduino. I will try the work with an external 9V power supply and maybe see you soon...

After using an external power supply, initialization works well after 10 reboots !!! You're write Jot, using only the usb cable, voltage on the CS pin of SD card device is about 4.5V. With an external voltage high 5V for the arduino, CS pin of SD card device is 4.99V. I think that the problem came from here. Thanks !

A sd card is 3.3v (or at least compatible with 3.3v). Can you show a photo of the module with the socket? Is there a chip on the module to convert the 3.3v signals from the sd card to the 5v signals of the arduino?

I don't known how to post pictures here, but there is a regulator on the device. I can measure 4.99V on one of pins and 3.29V on the other on.

The spi signals for the sd card should be converted to 3.3v signals. On this module is a hc4050 to convert the signals: https://www.adafruit.com/product/254

My board is equipped with the SN74LVC125A, a 3.3V buffer. Find the board model here: https://www.amazon.fr/SKYNET-Lecteur-Reader-ARDUINO-RASPBERRY/dp/B01DNXWVES

I just add an external 9V power supply to my Arduino Mega. The SD device is power by arduino 5V pinout.


text:
Count fuel liters with Arduino
We have created a fuel sensor in our lab with Arduino in order to get fuel data from vehicles. Regarding the code below, I receive an error

PARSE ERROR: 'attachInterrupt': this function needs to be defined.

Could you please advice?
int pin = 2;
volatile unsigned int pulse;
float volume = 0;
float flow_rate =0;
const int pulses_per_litre = 2000;
int count_pulse;

void setup()
{
    Serial.begin(9600);
    pinMode(pin, INPUT);
    attachInterrupt(0, count_pulse, RISING);

}

void loop()
{
    pulse=0;
    interrupts();
    delay(1000);
    noInterrupts();

    Serial.print("Pulses per second: ");
    Serial.println(pulse);

    flow_rate = pulse * 1000/pulses_per_litre; //

    Serial.print("FUEL FLOW rate: ");
    Serial.print(flow_rate);
    Serial.println(" milliliters per second");

    volume = volume + flow_rate * 0.1; //Time Interval is 0.1 second

    Serial.print("Volume: ");
    Serial.print(volume);
    Serial.println(" milliliters");
}

void count_pulse()
{
pulse++;}

You have a int count_pulse and a function count_pulse, that confuses the compiler.

and add forward declaration line void count_pulse(); before setup()

@Juraj Doesn't the Arduino IDE do that for you?

there is some problem for function as parameter

You have declared count_pulse as a variable and NOT as function prototype.
int pin = 2;
volatile unsigned int pulse;
float volume = 0;
float flow_rate =0;
const int pulses_per_litre = 2000;

void count_pulse(); \\ <--- Function prototype

void setup()
{
    Serial.begin(9600);
    pinMode(pin, INPUT);
    attachInterrupt(0, count_pulse, RISING);
}

Just initialize pulse to zero in its definition at line 2.
The message "'pulse': used without being explicitly initialized" is due to the count_pulse() function: The compiler can't analyze the run-time behavior of the code, nor your intentions. Some interrupts could arrive before loop() runs, so in fact, pulse could very well get incremented without having been initialized. You may not care about and can discard the first few readings, but the compiler doesn't (and shouldn't!) guess that.


text:
Arduino MEGA Timer Help
Nick Gammon posted some code to setup a counter on an Arduino UNO using timer2 to generate a 38KHZ signal, and I've used it on several IR projects.
On my current project, I'm using FreeRTOS for the Arduino, and the source says it uses timers 0-3 for its own kernel operation, so the timer code obviously will interfere with the RTOS.
I'm using an Arduino MEGA for this project, and AFAICT it also has a timer4 and timer5. Unfortunately, my programming ability for the ATMel products is lacking at that level, so I'm looking for some help to create a timer that will generate a 38KHZ output using timer4 or timer5 of the MEGA 2560 on any output pin. Interrupts shouldn't be used because it would also probably cause issues with RTOS.
BTW, on the Arduino MEGA, you can do a context switch between tasks in less that 200usec, and be able to determine what task YOU want to execute next.

Can you show me where I can read that freertos uses timers 0-3? In my opinion it does not use any of those timers.

For the life of me, I can't find what I found before.....I did find some example code that setup the watchdog timer to generate the basic tick function time, and the code allows using almost any of the HW timers. I did see that some of the docs posted say that the RTOS timers don't depend on any HW, but it also says that the SW timers don't use any processor time?? That doesn't make sense. The lack of documentation in this area may show that no HW is indeed used, especially because the RTOS will run on almost any Arduino, and the timers are quite different in capability.

The file that has the timer stuff is; \avrfreertos-master\avrfreertos-master\freeRTOS10xx\include\FreeRTOSBoardDefs.h

The watchdog timer is recommended, but I see that for the arduino mega 2560 the timer3 is used in this one: https://github.com/feilipu/avrfreertos/blob/master/freeRTOS10xx/include/FreeRTOSBoardDefs.h That is okay, since timer0, timer1 and timer2 are not used by freertos. The library manager in the arduino ide uses a mini version of freertos, and that one uses the watchdog timer: https://github.com/feilipu/Arduino_FreeRTOS_Library/blob/596a743509309121afcf7fa95c4d17d6d7fdd7ce/src/FreeRTOSVariant.h Why did you choose the larger version of freertos?

I just downloaded the version that the IDE showed. I didn't know there was another, smalled version. The size of the code isn't important to the project, as there will be only 3 tasks running that are all process dependant, but just scan while running in a state machine. They'll all run at the same priority, and at each exit from each state in the loop they're in, they will yield to the next task. ALL of them will always be in the ready state. Originally, I setup the code to chage their own priority to match all the rest, and then raise the priority of the next task to run.

Then that task lowers its prority and then raises the priorty of the next task to run. I set this up with dummy tasks to measure the context switch times, and couldn't tell any difference between the two techniques. As I stated above, the context switch time was less than 200usec. I need to do this because the original code ran in separate Arduino modules, and monitors IR detectors setup in a quadrature configuration with less than 0.030" separating them.

So, the state machines need to be very responsive, and the 200usec context switch will minimize any latency in the detection because the state machine stays in a switch statement loop, and the execution time is very fast, actually many times faster than needed for detection. So, the code should function with minimal changes. AFAICT, the only real difference would be just to do the context switch right before the break statement for each case.

I installed the "FreeRTOS by Richard Barry" from the library manager and I got the mini version. I think you don't need a rtos, you can put three finite state machines in the loop and remove all delays and use interrupts for the ir detectors. An interrupt itself uses a few microseconds in a avr microcontroller: https://gammon.com.au/interrupts The code inside an interrupt takes often more microseconds, because a single digitalread uses about 4 microseconds.

The state machine is complex, and with 2 running in each task, having 6 total machines interacting would be a ZOO trying to troubkeshoot. I really don't want to start all over. Currently the code works fine, but if I run into performance issues, I'll reconsider. BTW, the code that Nick wrote for the 38KHZ output works just fine in the RTOS, but it outpouts on data pin 10 on the MEGA instead of data pin 11 on the UNO. So, the project continues to its next phase.

I think we both learned from this. I have created an answer (with my opinion). I have used freertos, and it is working well. However, I think that the disadvantages are larger than the benefits.

Using a pre-emptive Real Time Operating System on a Arduino board with a AVR microcontroller (Arduino Uno, Leonardo, Mega 2560) is an academic exercise.
The FreeRTOS is reliable, and for someone that is used to write multitasking code, it can be useful.
In my opinion, the FreeRTOS does not match with the simple AVR Arduino boards:

Not enough ram memory.
Every task gets its own stack.
The ram memory is limited on a AVR board. That means that every
task should be written very careful to limit the stack usage.
Not enough ram when the fun is about to start.
When there are a few tasks and perhaps a few interrupt routines,
then a number of buffers and message queues are needed.
There is not enough ram memory for that.
The Arduino was not developed with a multitasking system in mind.
The Arduino libraries are not suitable for that.
Some functions wait
for something (Serial.parseInt, Wire.requestFrom,
Wire.endTransmission)
and that makes a RTOS work worse than expected.
The FreeRTOS is large, it requires memory and cpu time.

Without FreeRTOS, some known techniques are very efficient for the AVR Arduino boards:

A Finite State Machine uses very little ram memory.
A Finite State Machine without delay()
that uses millis() can be very responsive.
Avoiding interrupt routines.
It is often possible to avoid interrupt routines.
Reading buttons can often be done by polling the buttons
in the loop().
Avoiding the String object and moving text into PROGMEM
can be used
to have enough memory for a more complex and reliable sketch.

At this moment the "FreeRTOS by Richard Barry" is in the Library Manager. It is a smaller version of FreeRTOS and it only uses the WatchDog timer. It has no conflict with Arduino libraries.
A larger FreeRTOS version and many examples can be found at https://github.com/feilipu/avrfreertos
Not every version of FreeRTOS uses the WatchDog timer. Look for the file FreeRTOSBoardDefs.h to see which timer is used for your specific Arduino board.
crusader27529, I don't see a problem to remove the FreeRTOS and call the three tasks sequencially.
void loop() {
  task1();
  task2();
  task3();
}

The nature of the tasks is that they never terminate, but continuously monitor multiple IR sensors that are time critical, all run in multiple state machines. Using RTOS, I can use the YIELD function to force the running task into a state that allows the next task to run. Since all the tasks are the same priority, it results is a cooperative task switching operation with extremely low context switching overhead. AAMOF, I can switch sequentially among 4 tasks in sequence in less than 200usec. That actually works out tf about 50usec per task context switch, with minimal changes to the old code.

@crusader27529 I understand now, you stay in the finite state machine and perform a yield to the other ones. Without a RTOS, the loop() runs over and over again and rushes through the finite state machines. That is a different approach.


text:
Confusion between switch and if?
Following code is to control two LEDs for on and off by two dedicated push buttons. I have used if() for each condition and I was not comfortable writing this code, as I could feel, it can be better with switch...case, because if we increase more buttons, it will be a messy solution for that. However, I couldn't get optimized switch...case for it. Can some one suggest the nice switch transformation for this if().
int buttonState1 = 0; // variale for reading pushbutton1 status
int buttonState2 = 0;  // variable to reading push button2 status
//set pin numbers
int button1 = 2; // push button no. 1
int button2 =3;  // push button no. 2
int Led1 = 4; // led 1
int Led2 =5;  // led 2

void setup() {
  Serial.begin(9600); // serial begins at 9600
  // defining pin modes for led and buttons
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode (Led1, OUTPUT);
  pinMode (Led2, OUTPUT);
};

void loop() {
 buttonState1 = digitalRead(button1); // reading pushbutton 1 in the variable buttonstate1
 buttonState2 = digitalRead(button2); // reading pushbutton 2 in the variable buttonstate2
 // condintion for led 1 ON, if pushbutton1 is pressed
 if (buttonState1 == HIGH) {
  digitalWrite(Led1, HIGH);
  }
  // condition for led2 ON, if pushbutton2 is pressed.
 if (buttonState2 ==HIGH){

  digitalWrite(Led2, HIGH);

  }
  // both led are off if no push button is pressed
  else{
    digitalWrite(Led1, LOW);
    digitalWrite(Led2, LOW);
  }

};

Sidenote. The else only applies to the second if statement. So if you release button 1 while button 2 is still pressed, led 2 won't go off.

You could also do replace the entire code with, digitalWrite(Led1, digitalRead(button1)); digitalWrite(Led2, digitalRead(button2)); . Could you expand a bit on what you want to achieve, as that would limit the numerous different approaches you could take. If you want to read a  large number of buttons, and change their accompanying leds, you could use an array for the button pin numbers, and an array. Then use a for loop to read each of the buttons one by one, and run some code. That would reduce the amount of "duplicate" code.

A switch case does not seem like it would be an effective way of controlling your LEDs. It would make more sense (and would probably be easier) to create a function instead to control the LEDs.
void buttonToggle(int buttonPin, int ledPin) {
  int buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

You would then need to replace your if statement with calls to the function (EX buttonToggle(Button1, Led1);

If you want to use a dedicated push button for every led, then it is not handy to use a switch .. case statement. This is because first you have to construct the switch-variable based on the readings of the switches before you can use it (the switch variable) for de case statements.
When you combine the reading of the switches with the setting of the leds you get a nice Loop-section:
    void loop() {
      digitalWrite(Led1, digitalRead(button1));
      digitalWrite(Led2, digitalRead(button2));
      digitalWrite(Led3, digitalRead(button3));
      digitalWrite(Led4, digitalRead(button4));
      digitalWrite(Led5, digitalRead(button5));
      // and so on
    }


text:
ATMEGA 328P Standalone on 3.3v controlling a servo
I'd like to use an ATMEGA 328P on standalone mode powered by a 3.3V supply source to control a servo (which is powered by 4 AA batteries, resulting in 6V). My question is: do I have to convert the PWM signal's peak amplitude to 5V for it to work? Or will the servo work just fine with a 3.3V amplitude signal? My servo's datasheet says its operation voltage ranges from 4.8V to 6V, but I'm not sure if that applies only to its power source or if it has implications on the control signal as well.
Servo's datasheet:
https://www.donkeyhoute.com/UploadFiles/2014916134245511.pdf
Also, since I will be using an 8 MHz external clock, do I have to change anything in my Arduino sketch regarding the PWM signal frequency, or do I just set the board to the 'Lilypad' option when burning the bootloader and keep the sketch the way it is now?

It's impossible to tell. There's no real data in that datasheet. You'll have to try it and see.

do I have to convert the PWM signal's peak amplitude to 5V for it to work?

There is insufficient information to determine that.  It may, or it may not. You'll have to try it and see.

since I will be using an 8 MHz external clock, do I have to change anything in my Arduino sketch regarding the PWM signal frequency

If the board you select is 8MHz then no, you don't need to change anything. The fact you have selected the right frequency for the board means that all the timing calculations the Arduino API does will be correct.


text:
Addressable RGB LED Strip
I am looking to create an addressable RGB LED strip circuit with my NodeMCU v3 Wi-Fi. I am looking at a strip of 150 RGB LEDs, 5 meters long, so 30 LED/m. But I am only going to use about 50 LEDs for the backlight on my desk. My understanding is that if each RGB LED pulls 60 mA on full white, and I'm running 50 LEDs, then I will need at least 60 mA x 50 LEDs = 3000 ms (3 A) of power to sufficiently light all of them. I am thinking about upgrading this in the future, and so I am thinking about going with a 5V 10A power supply. Am I okay to go with a 5 V 10 A power supply? Or will this be too much current for the system.

In your case I would use ledstrips with SPI protocol (like APA102). Using SPI, you can have your resources free (not having to bit bang), transmission speed is higher (no fixed delay) and you can allow more time for calculating the next pixel, so you don't have to store them all in memory. Also, the nodeMCU may not always be "atomic" or do every instruction in order (and has to yield every now and then) so the hard timed bit banging of neopixels may not be glitch free/doesn't seem correct for this application.

I generally double my current needs when looking for supplies and wiring.  So if you think your load is 3A then I would get a 6A power supply.    I'm thinking like @Paul.  You may have problems generating the timing of older addressable LEDs as the ESP8266 is also concerned with WiFi communications.  The more complex the processor's responsibilities, the worse the real time response.   That's why it's difficult to drive these LEDs from a Raspberry Pi.

the current rating of a power supply is how much current you can draw before the power supply overloads ..... the current rating is not how much current is forced into a connected load .... think about 100W light bulb compared to 5W nightlight .... both connected to a 15A 110V AC circuit ..... 100W bulb draws almost 1A .... 5W bulb draws about 50mA .... neither one has 15A forced through it

Each will only draw as much current as they normally would from a 5 volt supply. If you had a 5 volt 100 amp supply they still would not draw any more.
The amount of excess current a power supply can deliver doesn't change what the load will take from that supply.
For example, if you had a 5 volt supply with a 1 ohm resistor as a load the current would be 5 amps. 5 volts / 1 ohm = 5 amps. And if you had a 5 volt 10 amp supply the current would still be 5 amps. Same with a 20 amp supply. As long as the voltage is the same, going up in current capacity is safe.
(LEDs are not resistors but with this application it is much the same)
When you do wire up the LED strips make sure you are using thick enough wires.


text:
Maze solving robot turning failure due to sensor distance to the corner increasing during the turn
At my school we have a project where we have to make a robot that can solve a 3D-maze using an arduino controlled robot that uses ultrasonic sensors to determine how to turn. The robot may not be pre-programmed and must work on all simple mazes with 90d turns.
I have figured out most of the code I think, however my problem is that when the robot needs to turn. Since how much and which direction the robot should turn is determined by distance sensors, the distance to the corners increase, making it longer than what is required to turn. This makes the robot want to turn back into the corner and then it gets stuck in a loop of turning in and out of the corner (see image attached).
Note: we don't want to program a 90d turn as it could mess up later and we believe it better to try make how long the robot should turn be determined by the value of the different sensors.
The robot is made up of three ultrasonic sensors, front, right, and left. The robot has tracks which lets it turn on the spot. The arduino is an arduino mega, so it is fast at updating and measuring values (unless the time needed for measuring the distance is long).
Files:

Pictures describing the turning problem:

Images of the robot:

If any other information is needed that is left out, I will try to obtain it (such as images, dimensions, exact component names, etc.)
The entire code:
enum robState {
  robInit,
  robInitForward,
  robInitRotL,
  robInitRotR,
  robStop,
  //robWaitCrystals,
  robInitBack,
  robReset,
  robFindWay
};

struct LFR {
  int L;
  int F;
  int R;
};

struct robMotor {
  byte pwm;
  byte dir_1;
  byte dir_2;
};

robState robStatus;
//const int robTurnSpeed = 255;
robMotor motorL = {2, 4, 3};
robMotor motorR = {5, 6, 7};

int dirInt = 1;
LFR echoPin = {12, 11, 13};
LFR trigPin = {24, 26, 22};
LFR distance;
const int robStartStopPin;

void setup() {
  // put your setup code here, to run once:

  //init pinModes
  initPins();

  Serial.begin(9600);
  robStatus = robInit;
}

void loop() {
  int disWall = 12;
  // put your main code here, to run repeatedly:
  distance.L = distanceUpdater(trigPin.L, echoPin.L);
  distance.F = distanceUpdater(trigPin.F, echoPin.F);
  distance.R = distanceUpdater(trigPin.R, echoPin.R);
  Serial.print("/n distance.L= ");
  Serial.println(distance.L);
  Serial.print("/n distance.F= ");
  Serial.println(distance.F);
  Serial.print("/n distance.R= ");
  Serial.println(distance.R);
  //delayMicroseconds(50);

  switch (robStatus) {

    case robInit:
      //init motors and shit
      motor(0, 0);
      motor(1, 0);
      //wait for start/stop
      //while (digitalRead(robStartStopPin) == LOW);
      Serial.print("/n robInit");
      robStatus = robFindWay;
      break;

    case robInitForward:
      motor(0, 1);
      motor(1, 1);
      Serial.print("/n robInitForward");
      robStatus = robFindWay;
      break;

    case robFindWay:

      Serial.print("/n robFindWay");
      if (distance.R > disWall) {
        //if open to right, turn right.
        robStatus = robInitRotR;
      }
      else if ((distance.R < disWall) && (distance.F > disWall)) {
        //go forward if you can't go right
        robStatus = robInitForward;
      }

      else if ((distance.R < disWall) && (distance.F < disWall) && (distance.L > disWall)) {
        //if nothing else works, turn left.
        robStatus = robInitRotL;
      }
      else if ((distance.R < disWall) && (distance.F < disWall) && (distance.L < disWall)) {
        //found the end, must turn. turns left.
        robStatus = robInitRotL;
      }
      else {
        Serial.print("shit somethings wrong with path finding");
      }
      break;

    case robInitRotL:
      Serial.print("robInitRotL");
      //forward direction of motorR
      motor(1, 1);
      //reverse direction of motorL
      motor(0, -1);
      //send the correct motor speed*/
      robStatus = robFindWay;
      /*analogWrite(motorR.pwm, robTurnSpeed);
        analogWrite(motorL.pwm, robTurnSpeed);*/
      break;

    case robInitRotR:
      Serial.print("robInitRotR");
      //reverse direction of motorR
      motor(1, -1);
      //forward direction of motorL
      motor(0, 1);
      //send right motor speed
      robStatus = robFindWay;
      /*analogWrite(motorR.pwm, robTurnSpeed);
        analogWrite(motorL.pwm, robTurnSpeed);*/
      break;

    case robStop:
      motor(0, 0);
      motor(1, 0);
      //while (digitalRead(robStartStopPin) == LOW);
      robStatus = robInit;
      break;

    case robInitBack:
      //reverse both motors
      motor(0, -1);
      motor(1, -1);
      break;
  }

}

void initPins() {
  //init motors
  pinMode(motorL.pwm, OUTPUT);
  pinMode(motorL.dir_1, OUTPUT);
  pinMode(motorL.dir_2, OUTPUT);

  pinMode(motorR.pwm, OUTPUT);
  pinMode(motorR.dir_1, OUTPUT);
  pinMode(motorR.dir_2, OUTPUT);
  //init sensors
  pinMode(trigPin.L, OUTPUT);
  pinMode(trigPin.F, OUTPUT);
  pinMode(trigPin.R, OUTPUT);

  pinMode(echoPin.L, INPUT);
  pinMode(echoPin.F, INPUT);
  pinMode(echoPin.R, INPUT);
  //init button
  pinMode(robStartStopPin, INPUT);
  //init power sources
  /*pinMode(VCCPin1, OUTPUT);
  digitalWrite(VCCPin1, HIGH);
  pinMode(GNDPin1, OUTPUT);
  digitalWrite(GNDPin1, LOW);*/
}

void motor(int side, int action) {
  //side 0=L 1=R
  //action -1=reverse 0=still 1=forward
  int normalSpeed = 255;
  if ((side == 0) && (action == -1)) {
    //reverse left
    digitalWrite(motorL.dir_1, LOW);
    digitalWrite(motorL.dir_2, HIGH);
    analogWrite(motorL.pwm, normalSpeed);
  }
  else if ((side == 0) && (action == 0)) {
    //still left
    digitalWrite(motorL.dir_1, HIGH);
    digitalWrite(motorL.dir_2, LOW);
    analogWrite(motorL.pwm, 0);
  }
  else if ((side == 0) && (action == 1)) {
    //forward left
    digitalWrite(motorL.dir_1, HIGH);
    digitalWrite(motorL.dir_2, LOW);
    analogWrite(motorL.pwm, normalSpeed);
  }
  else if ((side == 1) && (action == -1)) {
    //reverse right
    digitalWrite(motorR.dir_1, LOW);
    digitalWrite(motorR.dir_2, HIGH);
    analogWrite(motorR.pwm, normalSpeed);
  }
  else if ((side == 1) && (action == 0)) {
    //still right
    digitalWrite(motorR.dir_1, HIGH);
    digitalWrite(motorR.dir_2, LOW);
    analogWrite(motorR.pwm, 0);
  }
  else if ((side == 1) && (action == 1)) {
    //forward right
    digitalWrite(motorR.dir_1, HIGH);
    digitalWrite(motorR.dir_2, LOW);
    analogWrite(motorR.pwm, normalSpeed);
  }
  else {
    Serial.print("monkaS wrong motor inputs");
  }
}

int distanceUpdater(int trigPin, int echoPin) {
  long duration;
  int distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration * 0.034 / 2);
  return distance;
}

The pathfinding and turning:
switch (robStatus) {

    case robInit:
      //init motors and shit
      motor(0, 0);
      motor(1, 0);
      //wait for start/stop
      //while (digitalRead(robStartStopPin) == LOW);
      Serial.print("/n robInit");
      robStatus = robFindWay;
      break;

    case robInitForward:
      motor(0, 1);
      motor(1, 1);
      Serial.print("/n robInitForward");
      robStatus = robFindWay;
      break;

    case robFindWay:

      Serial.print("/n robFindWay");
      if (distance.R > disWall) {
        //if open to right, turn right.
        robStatus = robInitRotR;
      }
      else if ((distance.R < disWall) && (distance.F > disWall)) {
        //go forward if you can't go right
        robStatus = robInitForward;
      }

      else if ((distance.R < disWall) && (distance.F < disWall) && (distance.L > disWall)) {
        //if nothing else works, turn left.
        robStatus = robInitRotL;
      }
      else if ((distance.R < disWall) && (distance.F < disWall) && (distance.L < disWall)) {
        //found the end, must turn. turns left.
        robStatus = robInitRotL;
      }
      else {
        Serial.print("shit somethings wrong with path finding");
      }
      break;

    case robInitRotL:
      Serial.print("robInitRotL");
      //forward direction of motorR
      motor(1, 1);
      //reverse direction of motorL
      motor(0, -1);
      //send the correct motor speed*/
      robStatus = robFindWay;
      /*analogWrite(motorR.pwm, robTurnSpeed);
        analogWrite(motorL.pwm, robTurnSpeed);*/
      break;

    case robInitRotR:
      Serial.print("robInitRotR");
      //reverse direction of motorR
      motor(1, -1);
      //forward direction of motorL
      motor(0, 1);
      //send right motor speed
      robStatus = robFindWay;
      /*analogWrite(motorR.pwm, robTurnSpeed);
        analogWrite(motorL.pwm, robTurnSpeed);*/
      break;

    case robStop:
      motor(0, 0);
      motor(1, 0);
      //while (digitalRead(robStartStopPin) == LOW);
      robStatus = robInit;
      break;

    case robInitBack:
      //reverse both motors
      motor(0, -1);
      motor(1, -1);
      break;
  }

Your main loop (loop()) is powering through the whole code continuously. It wouldn't be a bad idea to put some "breaks" between each sensor scan cycle. For example:
long timerCounter = 0;

void setup()
{
    // Do your setup here

    timerCounter = millis();
}

void loop()
{
    // Only do some code every 1 second (1000ms)
    if (millis() - timerCounter >= 1000)
    {
        ScanSensor1();
        ScanSensor2();
        ScanSensor3();

        robState state = DetermineStateFromSensorReadings();

        DoActionForState(state);
    }
}

What this does is break the cycle down to 1Hz (change as you wish). When you are using ultrasonics (as per your images), it's always a good idea to reduce the intervals between each reading, as it allows residual noise to quieten down. Imagine the beeping sound from the sonar on a submarine.
You've got the right idea by using a state machine in your code. Each cycle can determine which state it should be in after reading the sensor data. Good job on that!
Just some additional information about ultrasonics regarding your project:

Sonar has an emission angle of 30 degrees (not a straight line!). Imagine a code pointing out with an angle of 30 degrees. This means anything inside this range could be picked up by the sensor. Looking at your turning problem image 2, I'd expect a lot of erroneous data from that sensor pointing towards the corner.
Multiple sensors working at the same frequency (40kHz?) may interfere with each other.

The problem you are seeing is mainly caused by the fact that you are checking the walls around you as you are turning. I would suggest you use either the forward facing sensor or the opposite sensor to that in turning problem image 2 to significantly reduce erroneous data.
If your budget (and time) allows, you may benefit from using a cheap Lidar (like this one for example) to more accurately determine your surrounding. Lidar doesn't have an emission angle, which means that it's measurement point is in a straight line from the source.

Autonomous robots are a lot of fun (and hard!)  Right now your robot is doing exactly what you told it to do - follow the wall.  One way or another you are going to have to 'program in a 90-deg turn'.  The hard way to do this is to model the corner, in terms of the expected distance profile vs time, and constantly adjust the robot's offset target to smoothly navigate the turn.  The easy way would be to let the robot recognize that a turn is required, execute the turn, and then reassess the situation.  FMI, see the 'robots' category at  https://www.fpaynter.com/

You need two states. Making a turn and not making a turn.
Once you start making a turn, ignore the side sensors, and continue turning until the front sensor distance has reached its peak.


text:
Remotely uploading code to an Arduino board over the internet
I recently used Particle Photon that allows me to upload firmware (.bin file) remotely over the internet.
I would like to use something like this for my Arduino but I cannot find anything like that. Does anyone know any possible way to upload firmware to my Arduino board remotely connected to internet via Ethernet shield of any WiFi module?

you want to use Ethernet shield/module?

@Juraj yes I have ethernet shield.

You can upload to your Arduino board over Ethernet if you flash it with a special bootloader named Ariadne.
You will need an Ethernet module or shield that uses the W5100, W5200, or W5500 Ethernet controller chip. You can not use the ENC28J60 Ethernet controller with Ariadne.
You will need an ISP programmer to burn the Ariadne bootloader to your Arduino board. If you don't own an ISP programmer, you can use a spare Arduino board as an "Arduino as ISP" programmer. If you're going to purchase an ISP programmer, I recommend the 6 pin USBasp. The USBasp works well with the Arduino IDE and is very reasonably priced. You can buy them on eBay.
A description of how the Ariadne upload over Ethernet process works:

Compile the sketch you want to upload.
Use avr-objcopy to convert the .hex file of the sketch generated from the Arduino IDE compilation into a binary (.bin) file.
Reset the Arduino board to activate the bootloader code. You could do this by pressing the reset button on the board but the need to have physical access to the board negates much of the advantages of uploading over Ethernet. For this reason, the upload will typically be accomplished by sending a command to your Arduino board which triggers the application to reset the microcontroller by activating the watchdog timer and then allowing it to time out. There is a library named EthernetReset bundled with the Ariadne hardware package for this purpose, but you can easily implement your own solution if you have other needs.
Start a TFTP upload of the .bin file to the IP address of your Arduino board within the 10 seconds that the bootloader is activated after the reset. The upload doesn't need to finish within the 10 second window, it only needs to start.

You can get the Ariadne bootloader, as well as detailed instructions, here:
https://github.com/loathingKernel/ariadne-bootloader

some of the links on https://github.com/codebndr/Ariadne-Bootloader are not working ! but is it possible to link me up with some of ISP programmer

I want to know how can a bootloader can flash new firmware from the internet ?

"some of the links on github.com/codebndr/Ariadne-Bootloader are not working" The project has been moved to https://github.com/loathingKernel/ariadne-bootloader. If you find any broken links in that repository, please let me know and I'll get them fixed.

"is it possible to link me up with some of ISP programmer" What do you mean by that? Are you asking for a link to buy an ISP programmer? If so, here you go: www.ebay.com/itm/232327462892

"I want to know how can a bootloader can flash new firmware from the internet ?" I've added a summary description of the upload process to my answer. After reading that, if you have any specific questions let me know and I'll try to improve my answer. I don't want to reproduce the full Ariadne documentation here. The idea behind the answer was only to explain that this is an option for uploading firmware over the Internet, with a short description in order to make it more than just a link.

can you explain the point 3, after I press the reset button on my uno then what command to run to upload the ariadne bootloader

http://loathingkernel.github.io/ariadne-bootloader/#using-a-tftp-client-to-upload-the-sketch

This will do it. ESP8266 as wireless AVR (arduino) ISP programmer.
https://github.com/rene-win/esp_avr_programmer
or
https://github.com/jeelabs/esp-link
The ESP8266 can be programmed with the Arduino IDE. So it can be used for a lot of Arduino projects. And it can be OTA (Over The Air) programmed as well.
https://arduino-esp8266.readthedocs.io/en/latest/ota_updates/readme.html

sounds  great I also came across ArduRF1 by tindie that has onboard capability to upload firmware remotely over internet with lipo battery support onboard.


text:
how to compile arduino sketch from termnial without using arduino ide
I want to know how can I compile and upload the arduino sketch from my terminal instead of using Arduino IDE. I want to use a different IDE for writing code.

https://blog.arduino.cc/2018/08/24/announcing-the-arduino-command-line-interface-cli/

there's also platformio

https://www.sparkfun.com/news/2833

As a contributor to Sloeber, an Eclipse Plugin dedicated to Arduino and other micro controllers, I can tell you it's all a matter of using the correct version of gcc and provide the correct options.
Even if that might seem simple, it's not like that, so my advice is to download Sloeber and look at the build console output where we print all the statements used to fulfill the build task: you can infer a lot from that.
As Sloeber is also open source, you can also inspect how we create those build commands for the different boards and tool chains.

I have been using PlatformIO for about 2 years now I think. It’s simply amazing.
https://platformio.org
You can use it standalone just for the CLI compile or bundled with VisualCode Studio for a complete IDE solution.


text:
Defining array in switch case
I’m completely new to arduino, so be polite. I’m trying to program my esp32 to drive neopixels as seven segment display. So I take a digit and pass it to switch case and in switch case I mention which led number should be lit.
`
function showDigits(digit){

switch(digit){

 case 1:
   int a[]={1,3,4,.....};
  break;

 case 2:
    int a[]={1,3,4,6,8,...};
   break;
  .
  .
  .
default:
   int a[]={1,2,3,4,5,6,7,8,9,....};
  }
}

Now this is throwing multiple errors including redeclare of array a in same scope. Is there any better way to code this?

If you want to declare multiple variables with the same name inside different case statements, you can enclose the code inside each of them inside curly braces:
case 1:{
    Code...
break;}
case 2:
...

The curly braces will set the limits for the variables scope to just this case.

While I don't discourage you from doing it yourself. I would go the easy route and use an available library. As is, or if need be, after modifying it. For me, it is the better way as I'm not that good at programming.
https://learn.adafruit.com/adafruit-neopixel-uberguide/neomatrix-library
And this looks good.
FastLED NeoMatrix

Better support for ESP32 than Adafruit::Neopixel

https://github.com/marcmerlin/FastLED_NeoMatrix

I see several issues with your code.
First one is the issue of "scope". If you define the int a[] inside the switch it will be destroyed as soon as the switch will finish and no code that runs outside of its brackets will be able to access it.
I also think that array of integers is the wrong choice here. It would be much less memory consuming to use array of boolean that mean if each LED should be lit or not. You can use it later like that:
if (a[4]) { digitalWrite(LED4, HIGH); } else { digitalWrite(LED4, LOW); }

or even better using "ternary operator":
digitalWrite(LED4, (a[4] ? HIGH : LOW));

Third problem is that your function is incorrectly defined and it does not contain any type information. This is C and not Python so the types are EXTREAMLY important! The correct definition of your function should be:
void showDigits(int digit)

Take a look at this example that compiled correctly:
void showDigits(int digit)
{
  bool a[6] = {false, false, false, false, false, false};
  switch (digit)
  {
    case 1:
      a[0] = true;
      a[1] = false;
      break;
    case 2:
      a[1] = false;
      break;
    default:
      a[0] = true;
  }

  if (a[4]) {
    digitalWrite(4, HIGH);
  } else {
    digitalWrite(4, LOW);
  }
};

The switch..case is a very particular syntax. If you don't use the break; at the end of a case the execution will actually continue to next case definition, and compiler told you that you tried to define int a[] several times in the same scope. (which is a no-no)


text:
Unexpected behavior of ++myCount
I'm new to Arduino and C.
This behavior is not what I'd expect:
Serial.begin(9600);
while ( ! Serial );

int myCount = 0;

for (int i=0; i<10; i++) {
    myCount = min( ++myCount, 8 );
    Serial.print( myCount );
    Serial.print( "  " );
}

I would expect:
1  2  3  4  5  6  7  8  8  8

But I get:
2  4  6  8  8  8  8  8  8  8

Why is my code counting by 2?

Because of the way the min() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results: https://www.arduino.cc/reference/en/language/functions/math/min/

if min is a macro such as #define min(a,b) ((a)<(b)?(a):(b)) think about what happens when you expand min( ++myCount, 8 ) .... you get ((++myCount)<(8)?(++myCount):(8)) - however, I didn't think it was a macro, so that's odd

Jaromanda X is indeed correct - min() is defined on line 92 of Arduino.h, thusly:
#define min(a,b) ((a)<(b)?(a):(b))

Therefore when the ++mycount is substituted for the a, it is in fact substituted twice, in both the (a)<(b) and the (a):(b), leading to the increment by 2, each time min(++mycount,8) is executed.
As VE7JRO mentions, as it is defined in this way, the reference for min(x,y) states:

Warning
Because of the way the min() function is implemented, avoid using
  other functions inside the brackets, it may lead to incorrect results
min(a++, 100);   // avoid this - yields incorrect results

min(a, 100);
a++;            // use this instead - keep other math outside the function

As the second example states, keep any incrementing outside of the min() macro.
Alternatively, I think that you could use the inline function to workaround this issue:
#undef min
inline int min(int a,int b) {return ((a)<(b)?(a):(b)); }

Because inline provides a real function call (with parameters) it avoids the use of macros and substitution, which gives rise to the issue that you encountered.
inline is a much better (safer) way to implement the functionality provided by macros, in many cases. For more information, see Inline functions in C++ or read a C++ reference.

The advantage of using a macro is it is type agnostic. You can use it with float, double, char, int, long, signed or unsigned, and it doesn't care.

esp8266 has min() as template function.


text:
Idenitifying pins in my code. which pin is which?
I'm new to arduino and knnow nothing about electronics.
How do I idenitify which pin is which in the coding?
eg- I have a pin on my esp8266 "D3"... how would I reference that in the code?

You could try google search ...

You could either call it as just D3 in your code, or you could use the GPIO number which in this case is 0, do not get used to calling it Dx most boards are not capable of doing this

If you select the right board in Tools menu, you can use constants corresponding to labels.
pinMode(D3, OUTPUT);
digitalWrite(D3, LOW);

and of course, you can google "nodemcu pinout" and you will find nice pictures with all pins specs


text:
Control I2C relay board from two Arduino Uno
how can I make multi master Arduino device to work with single I2C device?
As both the master device are 20 m away from Slave device,
I am using the I2C relay board to connect with 2 Arduino boards and need to connect I2C device and create the two way switching technique from this.
Any suggestions here will be a great help.

Why would you want to use a highly priced device with an unsuitable interface with no support when there are hundreds of relay modules which use simple logical levels?

Yes there are TTL relay modules with almost identical form factor and you can buy them for <10% of the price of the OP's board.  What is the reason you need I2C, because of the long distance between master and slave?

Hi MichaelT, Actually I am looking for the solution to use I2C relays for longer distance and setting the priority of master device (Arduinos) to work as per the requirement.

What you want is to operate in multi-master mode.  This is a supported configuration of I2C - however the Arduino API has no support for it.
It involves each master identifying if a collision has occurred and stopping transmission if it has - to then retry transmission later on.
The Arduino hardware can do it, but the software can't. You would have to bypass the software and control the I2C interface yourself (or locate a better library than the Wire library that supports multi-master).

Hey, What if instead of using Arduino, I 'll use ESP8266 or ESP32?
Also If I 'll go with Arduino then any IC package will be useful to achieve this kind of mode?

The answers by Majenko and chrisl are far too optimistic in my opinion.
A distance of 20 meters is not possible. The I2C bus can be 20 cm or 50 cm.
There is no library that supports a multi-master bus for the Arduino Uno.
You have to change your project. Make one Arduino board the Master, and let the Master retrieve data from the other board and the Master writes to the relay board. You need a bus capable of such a distance or use wireless. The RS-485 bus has no problems with 20 meters. Adafruit has a number of RFM69 modules, those should have no problem with 20 meters.

There are chips that translate the I2C bus signals into differential signals that can be used with a twisted pair cable (for example a cheap Cat5 ethernet cable). The SparkFun Differential I2C Breakout makes it easy to put a I2C device at a longer distance.
(Thanks to @PimV for this addition).

Sparkfun has a "Differential I2C Breakout Board" that enables distances of 100 ft (link.

@PimV yes, those are nice modules. They create a rs-485 alike signal over twisted pair wires. When a ethernet cable is used and connected properly then it should have no problem with 20 meters.

Hi, The Differential I2C Breakout board seems better Idea.
But Could it be possible that instead of using Ethernet Port, I can use 2 cables at longer distances also?

An simple Cat5 ethernet cable is cheap and is according to certain specifications for a twisted pair cable. The PCA9615 chip on the Sparkfun chips works best with a ethernet cable. Using just any two cables (of two wires each plus GND) is doubtful. When that cable is not shielded, it might pick up too much electric noise. When that cable is shielded, the capacitance to GND might be too high. A lot can happen in a cable of 20 meters.

The Wire library has no complete multi-master support (as I remember). You can join the bus as slave and becoming master by using the master functions for the time of these transmissions (on execution of endTransmission() the master style I2C transmission is started. When it's finished the library will change to slave again). But you will run into problems, when the two masters send at the same time.
The I2C protocol incorporates a technique named bus arbitration. When two masters write to the bus at the same time, the first one to write a 1 on the bus, must retreat from transmission and become slave again. Unfortunately it seems, that the Wire library doesn't implement this.
So you might not run into problems, until the master are sending simultaneously. Depending on what the Arduinos also have to do, you may be able to recover from such a condition by using the Watchdog Timer to reset both masters, when they are stuck there.
Or you try to find a good I2C/TwoWire library, that works for Arduino and has Bus arbitration implemented.

Sidenote: 20m is quite a long distance for I2C. It is designed for short distances, mostly on the same PCB (hence it is called Inter Integrated Circuit, short IIC or I2C). You may not run into issues, but you should keep this in mind. The bus will have a greater capacitance and you may need strong pullup resistors.


text:
4 digit 7 segments display wrong number
I'm an Arduino newbie having problems with 4 digit 7 segments display.
I want to display some thousands to 4 digit 7 segments display but it display only 0000.
I want to receive data from serial with string. And display the data to 4 digit 7 segments display... So test make String = '2575'... but it's not work.
What's wrong in my codes?
Any suggestions here will be a great help. thanks
int segments[] = {A0, A1, A2, A3};

byte digits[10][7] =
{
  { 1,1,1,1,1,1,0 }, // 0
  { 0,1,1,0,0,0,0 }, // 1
  { 1,1,0,1,1,0,1 }, // 2
  { 1,1,1,1,0,0,1 }, // 3
  { 0,1,1,0,0,1,1 }, // 4
  { 1,0,1,1,0,1,1 }, // 5
  { 1,0,1,1,1,1,1 }, // 6
  { 1,1,1,0,0,0,0 }, // 7
  { 1,1,1,1,1,1,1 }, // 8
  { 1,1,1,0,0,1,1 }  // 9
};

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

  for(int i=2;i<10; i++) {
    pinMode(i, OUTPUT);
  }

  for(int i=0; i<4; i++) {
    pinMode(segments[i], OUTPUT);
  }
}

void loop() {
  String IncomingData = "2575";

  for(int i=0; i<4; i++) {
    digitalWrite(segments[i], LOW);
    int digit = atoi(IncomingData[i]);
    displayDigit(digit);
    delay(5);
    digitalWrite(segments[i], HIGH);
  }
}

void displayDigit(int num){
  int pin = 2;
  for(int i=0;i<7;i++){
    digitalWrite(pin+i, digits[num][i]);
  }
}

Are  you sure you  have a common cathode display? Do you have current limit resistors on each segment pin?   Also, why do you have int for everything, when byte is all that is needed for a 0,1 or 0 to 9?  Try adding a Serial.print after this line int digit = atoi(IncomingData[i]); to see that digit is breaking out what you think it is.

use common anode display.  and int number display very well like displayDigit(5) but the code did not work... thanks

Code is setup for common cathode; low on the cathode to select the digit, high on the segments to turn them on.  If you are using common anode, then reverse the logic; high on the digit to select one, low on the segments to turn them on.

I use common cathode, sorry... and how can i fix it? Serial.print shows 00000000... I think use int for function displayDigit(int num)...

Fix it by reversing the logic:  High to turn on a digit, Low to turn it off. Flip all the 0s to 1s, the 1s to 0s in the digits array.

Change displayDigit(digit); to displayDigit(3); to see if the problem is in the string parsing, or in the led-displaying part.

displayDigit(3); works... string parsing problem... thanks

You call atoi() with a char. Parameter of atoi is const char*. To convert ASCII code of digit to the digit use
int digit = IncomingData[i] - '0'

i can't understand that... anyway apply IncomingData[i] - '0' ... it's not works... thanks

@김태정, int digit = IncomingData[i] - '0'

you do not know what is ASCII code? how characters are encoded? or you don't know why IncomingData[i] is char and can't be used with itoa?

woww@.@ it works! thanks a lot! How can I understand the theory...! Have a nice day!

how can i accept the answer?...


text:
How to add if condition in RFID example?
Using an Arduino Mega 2560 and PN532 NFC/RFID module, I want to be able to scan a card and see if its value is (0xF0, 0x21, 0x5D, 0xA7). It should print "accepted" in the serial monitor.
However during compilation it keeps telling me:
iso14443a_uid:99:11: error: expected primary-expression before ']' token

if (uid[] = {0xF0, 0x21, 0x5D, 0xA7}){
        ^

exit status 1 expected primary-expression before ']' token

This is my code:
/**************************************************************************/
    /*!
        This example will attempt to connect to an ISO14443A
        card or tag and retrieve some basic information about it
        that can be used to determine what type of card it is.
    Note that you need the baud rate to be 115200 because we need to print
    out the data and read from the card at the same time!

    To enable debug message, define DEBUG in PN532/PN532_debug.h

*/
/**************************************************************************/

/* When the number after #if set as 1, it will be switch to SPI Mode*/
#if 0
  #include <SPI.h>
  #include <PN532_SPI.h>
  #include "PN532.h"

  PN532_SPI pn532spi(SPI, 10);
  PN532 nfc(pn532spi);

/* When the number after #elif set as 1, it will be switch to HSU Mode*/
#elif 0
  #include <PN532_HSU.h>
  #include <PN532.h>

  PN532_HSU pn532hsu(Serial1);
  PN532 nfc(pn532hsu);

/* When the number after #if & #elif set as 0, it will be switch to I2C Mode*/
#else
  #include <Wire.h>
  #include <PN532_I2C.h>
  #include <PN532.h>
  #include <NfcAdapter.h>

  PN532_I2C pn532i2c(Wire);
  PN532 nfc(pn532i2c);
#endif

void setup(void) {
  Serial.begin(115200);
  Serial.println("Hello!");

  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }

  // Got ok data, print it out!
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

  // Set the max number of retry attempts to read from a card
  // This prevents us from waiting forever for a card, which is
  // the default behaviour of the PN532.
  nfc.setPassiveActivationRetries(0xFF);

  // configure board to read RFID tags
  nfc.SAMConfig();

  Serial.println("Waiting for an ISO14443A card");
}

void loop(void) {
  boolean success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

  // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
  // 'uid' will be populated with the UID, and uidLength will indicate
  // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);

  if (success) {
    Serial.println("Found a card!");
    Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print("UID Value: ");
    for (uint8_t i=0; i < uidLength; i++)
    {
      Serial.print(" 0x");Serial.print(uid[i], HEX);
    }
    Serial.println("");
    // Wait 1 second before continuing
    delay(1000);
  }
  else
  {
    // PN532 probably timed out waiting for a card
    Serial.println("Timed out waiting for a card");
  }
  if (uid[] = {0xF0, 0x21, 0x5D, 0xA7}){
    Serial.println("Success");
    }
}

= is assignment operator. you can't use constant initialization to assign a value to a variable. In if condition usually a comparison operator is '==' is used and it can't be used to compare arrays

well, it same if i use == and if i can't compare arrays so what is the right way to make that happens like if the card serial / uid is what i want to give access and print success is there a way to do that?

You have to compare each value in the array once at a time. Like if( uid[0]== 0xF0 && uid[1]==0x21 && ...)

Can you recommend a course for me that can get me to that as fast as i can, I've less than 3 months to get that project done, I've no idea about arduino or c++ my college put me in this situation i didn't even studied anything about electronics or even c++

@AbdalrahmanGamal, lol, i am very curious .... you used the statement I wanna in your post .... i have seen a lot of people use it .... i am wondering, how did you learn the word wanna? .... it not a word in the English language, by the way ... the statement should be I want to

As has been noted in the comments you can't compare arrays like that. Instead you have to iterate through each entry and compare the individual elements.
If it's just a few entries, then you can do it manually:
if ((uid[0] == 0xF0) && (uid[1] == 0x21) && (uid[2] == 0x5D) && uid[3] == 0xA7) {
    // ...
}

If your values are both in arrays then you can use the memcmp() function to compare them:
uint8_t compare[] = {0xf0, 0x21, 0x5d, 0xa7};

if (memcmp(uid, compare, 4) == 0) {
    // ...
}

memcmp returns 0 if the two arrays match up to the number of bytes given (4 in this case), or a negative or positive number if the one is "less than" or "more than" the other.


text:
Programming a switching AC current?
I tried using this code to output AC power from one H-bridge and then another, switching every second, but when I connected a motor to it, it just seemed to output direct current. This is the code I was using (by the way, the motor controller I'm using has a max frequency of 20 kHz, so that's not the problem as far as I know):
int EnablePin = 8;
int duty;
int PWMPinA;
int PWMPinB;

const byte CPin = 0;  // analog input channel
int CRaw;      // raw A/D value
float CVal;    // adjusted Amps value

void setup() {
  pinMode(EnablePin, OUTPUT);
  pinMode(PWMPinA, OUTPUT);
  pinMode(PWMPinB, OUTPUT);
}

void loop() {

  digitalWrite(EnablePin, HIGH);

  for(duty = 0; duty <= 20000; duty += 1){

    PWMPinA=11;  // Timer2
    PWMPinB=3;
    analogWrite(PWMPinA, 255);
    analogWrite(PWMPinB, 0);
    delayMicroseconds(50);

    if(PWMPinA == 11) {
      PWMPinA = 3;
      PWMPinB = 11;
    } else {
      PWMPinA = 11;
      PWMPinB = 3;
    }

  }
  for(duty = 20000; duty>=0; duty -= 1){

    PWMPinA=6;  // Timer2
    PWMPinB=5;
    analogWrite(PWMPinA, 255);
    analogWrite(PWMPinB, 0);
    delayMicroseconds(50);

    if(PWMPinA == 6) {
      PWMPinA = 5;
      PWMPinB = 6;
    } else {
      PWMPinA = 6;
      PWMPinB = 5;
    }
  }
}

..... Your outputing PWM signals to 4 difference pins? its very confusing to be changing the pin assigned to a variable rather then having them all defined and changing which one you are using.    Need to post a schematic of what you have done if you want any help

I tried that and it seems to work.  Don't know why I didn't think of that considering it's simpler, but thank you!

Sounds like you have it sorted already but the first major problem with your original code is that you use PwmPinA and PwmPinB in setup(), before they are assigned any values.
I'd be surprised if the compiler didn't warn about that. Never ignore compiler warnings! :-)