text:
Lost with Nano and i2c
I've been struggling with some code that was failing to "begin()" any devices on my i2c bus. I've uploaded a scanner program from arduino playground which lists the addresses of any i2c modules found.  With a single sensor connected the whole arduino freezes but when I unplug the wires from the a4 and a5 pins it continues. Plug them back on and it locks. I've tried with the SDA / SCL wires reversed as I've seen mention of things being backward.
Anyone know what I'm missing?

Maybe missing pull-ups?

So I've watched a video on pullups and what they do but I can't find anything about specifically what I need to do on the Nano. Am I using internal pullups on the 5v pin connecting the I2C devices or am I changing something on A4 or A5?

I don't know if the nano has internal pullups, just try adding extra 4k7 as it's a simple thing to do

If it still freezes, determine the voltage on scl in a stucked state. If possible, monitor scl with an oscilloskope

Sorry, my electronics knowledge is limited let alone integrating with microcontrollers.So far I've managed to build this device with all my modules plugging straight onto sda/ scl and voltage pins with little theory required. What do I connect with the 4.7k ohm resisotor to, is it between the voltage pin (in this case 3.3v) and SCL?

Yes, you connect one resistor between sda and vcc, the other between scl and vcc

can you please share the code

As I remember, the Arduino Nano runs with 5V, so why do you write about 3.3V. Does the device work with 3.3V? You cannot simply mix different supply voltages

@chrisl I have 5 devices connected to the Uno. One requires a minimum of 5V, the others are on the 3.3V and all are working.

@Vaibhav Any code where I try to run .begin directly on devices type instances fails regardless of which device I have connected. But the current code where I'm trying to scanning for whatever is connected and display the address of the devices is from here https://playground.arduino.cc/Main/I2cScanner/

@StephenYork OK can you share the schematic of your project.

@Vaibhav How will a schematic help? Like I said I had a single sensor connected...I I have the nano plugged into a breadboard with pin terminals off the A4 (SDA) and A5 (SCL) pins and pins terminals off the 3v and gnd pins.  I then plug my TSL2591 onto those terminals, VIN to the 3v, GND to GND, SDA to SDA, SCL to SCL. When I run the scanner it locks up. When I disconnected the SDA and SCL it continues running. This is identical wiring to how it was on the Uno. Why on the Uno do I not need pull up resistors yet on the nano it seems I do? As I understand it they're the same core hardware

@StephenYork actually it doesn't about nano or UNO. Unlike UART or SPI connections, the I2C bus drivers are "open drain", meaning that they can pull the corresponding signal line low, but cannot drive it high. Thus, there can be no bus contention where one device is trying to drive the line high while another tries to pull it low, eliminating the potential for damage to the drivers or excessive power dissipation in the system. They might be internally pulled up in hardware or you need to do it externally.

did you test the pins with digitalWrite?

I give up, people just keep asking bogus questions over and over. This is clearly not a valuable forum to ask anything on. I literally cannot make it any clearer. NO I didn't test digital write, my code works on the uno, not on nano... so why given it's the same chip and everything's connected the same with the same code?


text:
MQ7 Flying Fish output format
I am new to Arduino project. I used MQ7 flying fish sensor to sense the CO.

Ok now I connected everything as mentioned in various tutorials, such as Arduino CO Monitor Using MQ-7 Sensor.
Also wrote this code based on the following tutorial
const int mq7Pin=0;//the AOUT pin of the CO sensor goes into analog pin A0 of the arduino

int mq7value;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);//sets the baud rate
  pinMode(mq7Pin, INPUT);
}

void Heat(){
  Serial.println("Heating sensor");
  analogWrite(mq7Pin,255);
  delay(60000);
  Serial.println("Reducing the voltage");
  analogWrite(mq7Pin,71); //HIGH*1.4v/5v => 255*1400/5000
  delay(90000);
}

void Read(){
  mq7value=analogRead(mq7Pin);
}

void Print(){
  Serial.print("CO : ");
  Serial.println(mq7value);
}

void loop() {
  // put your main code here, to run repeatedly:
  Heat();
  Read();
  Print();
  delay(60000);
}

After this I got the following output:
Heating sensor

Reducing the voltage

CO : 82

Heating sensor

Reducing the voltage

CO : 246

I used the sensor in a hall and I got 82 in clean air.
After that I used smokes from incense sticks, and I got 246 as sensor value.
So my question is in what format did sensor returned these values? Are they in PPM format?
If not, how can I convert it?

Looking at the datasheet, The output is logarithmic to the PPM. But you'd need to calibrate the outputs first, to get a accurate PPM value. I'm also not sure what the potentiometer and opamp(?) on that breakout are doing.

Sir any resources on how to calculate it. Most of the tutorial I saw prints  sensor value as ppm.

The link that you provided demonstrates/explains how to calibrate/adjust the voltage to PPM

I suspect some tutorials just slap a "ppm" after the value, and call it a day.

Thank you guys. I was confused with various tutorial saying the value was ppm. I know it was not that simple. And I also many tutorial with different kind of ppm calculation formula. Thank you for solving this confusion.

source: Stack Exchange

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

sort: votes


text:
Arduino Mega 2560 and servo motor in Proteus
Can I get help to connect Arduino Mega 2560 and servo motor in Proteus 7.8
correctly because I tried this connection, in the image below, with sweep.ino.hex in the Arduino software examples but did not work!

What didn't work exactly?

servo motor didn't work exactly !

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


text:
Can I use WTV020 sound module as SD card reader?
I want to try this example, A Simple Function for Reading CSV Text Files, in order to read a .csv file from an SD card, but I don't have the SD card reader module and can't find it in my country.
What I have found everywhere is this sound module, WTV020-SD, and I wonder if I can use that to read a single .csv file from it, using the SD Arduino library. I checked the module's documentation and there's nothing about it in there.

It seems unlikely, for if you compare the schematic of the WTV020-SD (card reader part only) from the data sheet that you provided:

to the schematic of a bog standard SD card reader:

they are not the same. Instead of interfacing directly to the Arduino, as the standard SD card reader does, the WTV020-SD has additional logic, in the form of a WTV020SD-20S IC.
Therefore the code on the Arduino forums is highly unlikely to work.


text:
My Code turns on my LED even when my switch is not pressed
I am trying to create a circuit that will turn my motor when I clap. When the first limit switch is low, and there is only one clap, a solenoid pin is supposed to be engaged (currently an LED), but when I clap once without pressing the limit switch, my LED turns on.
Also, I can't seem to get my code to work properly with the limit switches, to control my motor.
I am not sure what is wrong, can someone help?
I have an Arduino Uno with the following code:
#define sound_Sensor 2
#define EN1 9
#define IN1 8
#define IN2 7
#define solenoid_pin 6
#define LimSwitch1 4
#define LimSwitch2 3

int lastSoundValue;
int soundValue;
long lastNoiseTime = 0;
long currentNoiseTime = 0;
int solenoidPinStatus = LOW;
int status_motor = LOW;
int clap_interval = 200;
int claps = 0;
int pos1 = 1;
int pos2 = 1;

void setup() {
  pinMode(sound_Sensor, INPUT);
  pinMode(EN1, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(solenoid_pin, OUTPUT);
  pinMode(LimSwitch1, INPUT);
  pinMode(LimSwitch2, INPUT);
}

void loop() {

  soundValue = digitalRead(sound_Sensor);
  currentNoiseTime = millis();
  if (soundValue == 1 && lastSoundValue == 0 && (currentNoiseTime > lastNoiseTime + 200))
  {
      if (claps == 0) // allow first to register without much condition
      {
          claps = 1;
          lastNoiseTime = currentNoiseTime;
      }
      else
      {
          if (currentNoiseTime > lastNoiseTime + clap_interval)
          {
              claps++;
              lastNoiseTime = currentNoiseTime;
          }
      }
      Serial.print(claps);
  }
  else
  {
      if (currentNoiseTime > (lastNoiseTime + 3 * clap_interval)) // no claps for a longer duration time to print and/or reset clap
      {
          if (claps > 0)
          {
              while(status_motor == LOW){
                  if (digitalRead(LimSwitch1) == LOW && claps == 1)
                  {
                    solenoidPinStatus = HIGH;
                    digitalWrite(solenoid_pin, HIGH);
                  }

                 if (digitalRead(LimSwitch1) == LOW)
                 {
                    pos1 = 2;
                    status_motor = HIGH;
                    digitalWrite(IN1, HIGH); //Turns on Motor
                    digitalWrite(IN2, LOW);
                    analogWrite(EN1, 200); //Set Speed of Motor
                  }
                 else if (digitalRead(LimSwitch2) == LOW)
                 {
                    pos2 = 2;
                    status_motor = HIGH;
                    digitalWrite(IN1, HIGH); //Turns on Motor99++
                    digitalWrite(IN2, LOW);
                    analogWrite(EN1, 200); //Set Speed of Motor
                 }
              }

              while(status_motor == HIGH){
                if (pos1 == 2 && digitalRead(LimSwitch2) == LOW)
                {
                    status_motor = LOW;
                    digitalWrite(IN1, LOW); //Turns on Motor
                    digitalWrite(IN2, LOW);
                    pos1 = 1;
                }

                else if (pos2 == 2 && digitalRead(LimSwitch1) == LOW)
                {
                    status_motor = LOW;
                    digitalWrite(IN1, LOW); //Turns on Motor
                    digitalWrite(IN2, LOW);
                    pos2 = 1;
                }
              }
          }
             claps = 0; ///reset
      }
  }

// if (solenoidPinStatus == HIGH && status_motor == LOW && digitalRead(LimSwitch1) == LOW)
// {
//   solenoidPinStatus = LOW;
//   digitalWrite(solenoid_pin, LOW);
// }
  lastSoundValue = soundValue;
}

Sorry my wire diagram may not be the easiest to look at...

what is the voltage across Limitsw1 output pin.

how are the switches wired? do you have pull-down resistors?

Where is the diagram?

I think your problem might be connected to wiring.
This is one of the ways you can correctly connect a switch to Pin 8.

In this case you need to configure Pin 8 as INPUT_PULLUP to use internal "pullup" resistor. When switch is not pressed Pin8 is connected to 5V through that resistor and value on the pin is HIGH. When you press the switch it connects Pin 8 to ground (the resistor prevents a short) and that way value on Pin 8 is LOW.
This is code that works correctly with the design above
void setup()
{
  pinMode(8, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop()
{
  if (digitalRead(8) == HIGH)
  {
    Serial.println("It's HIGH");
  }
  else
  {
    Serial.println("It's LOW");
  }

  delay(1000);
}

If you do not configure Pin 8 as INPUT_PULLUP but just normal INPUT (as you did in your code) when the button is not pressed Pin 8 is "floating" (it's not connected to anything) and on a "floating" pin values are random.


text:
Programming the serial description
Is it possible to program a custom description so that my python program can know exactly what USB port to connect to for that specific programming?
It should be able to find any board with that program so the best approach is if a custom description can be programmed with the active program being uploaded.
I want to make sure my setup can handle multiple Arduino boards and always know what USB to use for each specific use.
This finds a general Arduino device:
for port in serial.tools.list_ports.comports():
    if "Arduino" in port.description:
        print "Arduino device!"

But I want something like this:
for port in serial.tools.list_ports.comports():
    if "proximity_sensor" in port.description:
        print "My specific Arduino program!"

Use the serial_number parameter to find a specific board?

Yes, this will find one specific board. What I want is to find a series of boards with a specific programming. I will update my initial question to clarify this.

On a normal Arduino board, no, it's not possible from a sketch POV. With a Leonardo or similar ATMega32U4 based board it may be possible to give it a unique VID/PID combination, and even possibly custom manufacturer and product strings. You may be able to do it by creating a custom board definition in boards.txt (or maybe manipulation of the AVR core) - but I have never tried that sort of thing with Arduino, so I cannot vouch for how easy it would be.
However (shameless self-promotion coming here...) if you were to switch away from Arduino and use a chipKIT board like the Lenny (or any of the other chipKIT boards with a direct USB connection, such as the Fubarino boards) then it is possible to craft a completely custom USB profile from within your sketch, including VID/PID, Manufacturer and Product strings, and even what devices the board implements. For example:
USBFS usbDevice;
USBManager USB(usbDevice, 0xf055, 0x1234, "Espentech", "My Little Widget");
CDCACM USBSerial;

void setup() {
    USB.addDevice(USBSerial);
    USB.begin();
}

void loop() {
    USBSerial.println(millis());
    delay(1000);
}

Which results in:
[  661.328155] usb 2-1.2.7: new full-speed USB device number 10 using ehci-pci
[  661.458613] usb 2-1.2.7: New USB device found, idVendor=f055, idProduct=1234
[  661.458616] usb 2-1.2.7: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[  661.458619] usb 2-1.2.7: Product: My Little Widget
[  661.458621] usb 2-1.2.7: Manufacturer: Espentech
[  661.458623] usb 2-1.2.7: SerialNumber: CK2660A05312F3
[  661.459181] cdc_acm 2-1.2.7:1.0: ttyACM0: USB ACM device


text:
Analog reading with noise - Arduino Uno VS ESP12e
I was testing analog output from a microphone (Max9814) with an Arduino Uno, which came with nice results. The output provided by the microphone is converted into sound and is loud and clear.
Setup: (Max to Uno)

Pin Vdd to 3,3V
Pin GND to GND
Pin Out to A0

However when I tried to set it up with an ESP12e instead of an Uno, I got a lot of 'noise' and no clear sound at all.
Here I used the following setup: (Max to ESP)

Pin Vdd to VCC (VCC is measured at 3.3v with a multimeter)
Pin GND to GND
Pin Out to AD0

A little 'side step'
The problem arised that the analog output from the microphone delivered a voltage of around 1.24, while the ESP12e analog has 1v as max input. This made the analogRead max out all the time. For this reason I put a 10k OHM resistor between the OUT and AD0 combined with a 20k OHM resistor between gnd and AD0. This resulted into nice analog readings (instead of 1024, around 400-500 all the time).
However, like mentioned before, a lot of noise is in between and the sound is not clear. (I also tried to work with 'sample windows', here is the 'filtering mechanism' which can be found on many sites/questions and works perfectly fine):
//(global logic is set to take n samples and than print the line)
//Tried n of 5 to 20
//Also instead of just samples tried the micros variant instead of just samples which is also found on many sites to create a time window to record.
unsigned int sample = analogRead(A0);
if (sample < 1024) {  // toss out spurious readings
  if (sample > signalMax) {
    signalMax = sample;  // save just the max levels
  } else if(sample < signalMin) {
    signalMin = sample;  // save just the min levels
  }
}

unsigned int peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
Serial.println(peakToPeak);

Does somebody have a clue why the Arduino gives such clear and good sound, while the ESP12e does not. (The analog values do not 'seem' to differ much in the levels)

The ESP8266 is an incredibly (electrically) noisy environment.
Because you can't use anything except the internal voltage reference, which is in turn driven from the internal noisy power, you can't get anything even vaguely approaching stable readings.
It is recommended to disable the WiFI completely ("Modem Sleep") when doing ADC readings to reduce noise.
However, the ADC was never intended for this kind of work. Its primary role is for monitoring the battery voltage of your hardware - and as such it really doesn't care that much about noise, since you can average a number of samples for greater accuracy (something you can't really do with audio).

So that means I should chain (somehow?), for example, the Arduino to the ESP and 'pass' the data through the esp to send it away?

Sure, you can do that. You could also attach an external ADC chip with a proper stable voltage reference to the ESP8266.

Ah, that is a very good note. Something like this?:
Analog to Digital Converter - MCP3002

Sure. That's pretty much the same as the ADC in the Arduino.

Thanx for the feedback, very much appreciated!


text:
WiFi Connection With a Enterprise WLAN
I have an ESP32 and want to connect it to the WLAN at my office. Based on my current knowledge of the Arduino, we use the WiFiClass to connect to a WLAN and then use a WiFiClient to use the WiFi for data transfer.
In order to connect to the WLAN at my office, a certificate is needed. I have asked the network guys to issue a x.509 certificate and plan to use the WiFiSecureClient class.
The problem is that my WiFi.begin(ssid) method never leaves the following while loop:
Wifi.begin(ssid); // my office needs a certificate to connect to the wifi at the first place
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}

Note that to connect to my office network, no password is needed. The x.509 certificate is enough for the connection to establish.
Only after a WiFi connection is established, I can set the WiFiSecureClient parameters of the CA. But to connect to the WiFi, I need the certificate.
This is very confusing. Could someone please clarify a way our for me in this situation.

You're confusing WiFi access and a secure connection to a remote server. WiFiClientSecure is for the latter (such as https://) not the former. You only want to use WiFiClientSecure if the remote server you are connecting to uses SSL or TLS. You haven't got that far, so remove WiFiClientSecure from your mind completely.

@Majenko thank you for the tip. My goal is to connect to get WiFi access. But the WiFi access needs a certificate. There is no username or password. I only know the SSID of the WLAN and have a x.509 certificate.

@Roboticsnerd, you could publish here as answer the solution based on Majenko's answer, if it works?

@Juraj I am working on it. Will publish if it works for me.

The Arduino API for ESP32 does not support your desired configuration.
The ESP32 is capable, but there is no easy "Arduino" interface to configure it.
Instead you will have to directly interface with the ESP32 SDK and configure things manually.  That won't be easy.
This example code shows you how it can be done - however that code is not designed to run in the Arduino environment, so you will first need to understand exactly what it is doing and then adapt it to suit.


text:
Problem with LCD
I'm working on this piano project. When I push a button one of the led light is suppose to turn on and a tone comes out of the piezo. The LCD screen is suppose to print out a sentence but I can't get it to work.
Here is a picture of the board ( everything works except the LCD) I think the problems lies in the power supply but I'm not sure. This is the first time I use a big breadboard.
Here is my code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(13,12,11,10,9,8);

int p1 = 1;
int p2 = 2;
int p3 = 3;
int p4 = 4;

int C,D,E,F;
int buzz = 5;

void setup()
{
   lcd.begin(16, 2);

  lcd.print("hello, world!");

  Serial.begin(9600);
  pinMode(p1,INPUT);
  pinMode(p2,INPUT);
  pinMode(p3,INPUT);
  pinMode(p4,INPUT);

}

void loop()
{

  lcd.setCursor(0, 1);

  lcd.print(millis() / 1000);

  C = digitalRead(p1);
  D = digitalRead(p2);
  E = digitalRead(p3);
  F = digitalRead(p4);

  if(C == 1){

    tone(buzz,523);
  }else if(D == 1){
    tone(buzz,587);
  }else if(E == 1){
    tone(buzz,659);
  }else if(F == 1){
    tone(buzz,698);

  }else{
    noTone(buzz);
  }
  delay(50);
}

the power rails are separated in the middle of the breadboard. bridge them with jumper wires

According to the picture, RS and E are connected to pin 8 and 9. According to your sketch, RS and E are connected to 13 and 12.

Did you set the contrast correctly (using the potentiometer)?

The LCD is not powered, there are 2 separated power rails... use a wire to connect both rails.

Where do I put the wires?

You need to use a wire to connect the 2 rails. Right where is the bigger separation.

the power rails are separated in the middle of the breadboard. bridge them with jumper wires


text:
Connect three android to one arduino mega
Android Arduino Mega SerialPort1 SerialPort2 SerialPort3
Is it possible to connect three Android tablets to the Arduino mega through three SerialPort? Rx1 Tx1; Rx2 Tx2; Rx3 Tx3
I managed to connect only one device directly through the cable, but this is only one device.

Sure. Three USB to UART adaptors. Or three serial Bluetooth modules.

may have information how to do this? Link?

If using USB to UART: plug one end into the phone. Plug the other end into the TX/RX pins. Profit. If using bluetooth it's identical to using just one module.

Not every library supports USB-UART, I have already tried five USB-UARTs in the application, there is very little information on the Internet about connecting USB-UART to Android applications.

Then you need to find one that does work.

where is the problem, if you connected one?

@Juraj I guess he connected the Arduino directly through it's built in USB port.

then it is about USB chip drivers for Android?

https://github.com/felHR85/UsbSerial
I found the library, I think I will understand, thanks


text:
Send data string from Arduino UNO to ESP8266-01
Is there anyway to send a string from an Arduino UNO to a ESP8266-01 (one with only 8 pins RX, TX, CH-PD, vcc, ground, reset, GPIO0, GPIO2) without using without using AT commands.  I've looked everywhere and from what I can see UART doesn't work and SoftwareSerial uses only AT commands.  I am at my wits end.  Can anyone help here? please.
I have tried Serial.write but only writes String and Esp8266 only receives ints.
I found some code I thought might work but so far I can see that the arduino is sending <100.00:200:00>, but on the esp8266 all I get is four backwards question marks
this is the code on the Arduino UNO
#include <SoftwareSerial.h>

SoftwareSerial ESPserial(2, 3); // TX | RX
 float water = 100.00;
 float battery = 200.00;
void setup()
{
    Serial.begin(9600);     // communication with the host computer
    //while (!Serial)   { ; }

    // Start the software serial for communication with the ESP8266
    ESPserial.begin(57600);

}

void loop()
{
   ESPserial.print("<");
          ESPserial.print(water,2);
          ESPserial.print(":");
          ESPserial.print(battery,2);
      ESPserial.print(">");
      Serial.print("<");
          Serial.print(water,2);
         Serial.print(":");
          Serial.print(battery,2);
      Serial.print(">");
     delay(10000);
}

and here is the code on the ESP8266
#include <SoftwareSerial.h>
#include <string.h>

SoftwareSerial ESPSerial(2,0);

const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;

String water;
String battery;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  ESPSerial.begin(57600);
  delay(10);

}

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

 water= getValue(receivedChars, ':', 0);
  battery = getValue(receivedChars, ':', 1);
Serial.println(water);
}

void recvWithStartEndMarkers() {
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (ESPSerial.available() > 0 && newData == false) {
        rc = ESPSerial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    }

The Arduino sends writes every 10 seconds and the esp prints the ???? every 10 seconds but with a lag.
I am not sure what the pin out to pin in should be.  Right now I have the Arduino 2(TX) attached to the GPIO0 and the Arduino 3(RX) attached to the GPIO2.
Can someone look at my code and see what I am doing wrong.  I thought I would send over two values because eventually I want to show water level and battery level.

Why do you think UART doesn't work? UART is what I would suggest...

How do I do it.  I want to use Arduino IDE to upload but language I found didn't work.  Do I need a separate board.  Sorry

You just have to connect rx->tx/tx->rx and look for an example. There are many tutorials about serial communication between arduino and esp8266.

@user1114881 are you using End of Line and Carraige Return characters at the end of string you are sending?

Arduino 2(TX) attached to the GPIO0 and the Arduino 3(RX) attached to the GPIO2 nope, you have to connect Arduino-TX to Esp-RX and Arduino-RX to Esp-TX. At least the esp8266 has very limited possibilities on gpio0 and gpio2

how do I handle   SoftwareSerial ESPSerial(2,0); on ESP and SoftwareSerial ESPserial(2, 3); // TX | RX on the Arduino.  Do I just leave that part out or how do I assign them

I changed it to SoftwareSerial ESPSerial(1,3); on ESP and Software Serial ESPserial(0,1); on the Arduino and still all I get is ???? on the Serial Monitor 57600 baud

I may have found one glitch.  The code I found has #include <string.h> but there is no library string.h and I cannot find it on line.  Can you point me to a good example of what I want to accomplish.  Thanks for you help and patience.  by the way now under 57600 I get four 0s

I figured this out.
send code is
Arduino Uno side
 f = String('<')+String("Hi")+String(',')+String(waterSensorOutValue)+String(',')+String(sensorBatValue)+String('>');

    Serial.print(f);

ESP side
const byte numChars = 32; char receivedChars[numChars]; char tempChars[numChars];        // temporary array for use when parsing // variables to hold the parsed data char messageFromPC[numChars] = {0}; float floatFromPC = 0; float floatFromPC2 = 0; boolean newData = false; //end stuff ti bring in string String f;  long itt = 500;
    long itt2 = 500;

void loop() {

  //new stuff string recvWithStartEndMarkers();
    if (newData == true) {
        strcpy(tempChars, receivedChars);
            // this temporary copy is necessary to protect the original data
            //   because strtok() used in parseData() replaces the commas with \0
        parseData();
        showParsedData();
        newData = false;
    } }

void recvWithStartEndMarkers() {
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    } }

//============

void parseData() {      // split the data into its parts

    char * strtokIndx; // this is used by strtok() as an index

    strtokIndx = strtok(tempChars,",");      // get the first part - the string
    strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC

    strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
    floatFromPC = atoi(strtokIndx);     // convert this part to an integer

    strtokIndx = strtok(NULL, ",");
    floatFromPC2 = atoi(strtokIndx);     // convert this part to a float

}

//============

void showParsedData() {
    Serial.print("Message ");
    Serial.println(messageFromPC);
    Serial.print("Float ");
    Serial.println(floatFromPC);
    Serial.print("Float ");
    Serial.println(floatFromPC2); } //end new stuff string

Then connect to wifi and upload to ThingSpeak.
I had to get rid of Softwareserial and connect the RX on the Arduino Uno to the TX on the ESP8266-01 and the TX on the Arduino Uno to the RX on the ESP8266-01.
Everything worked great till I changed from an Arduino UNO R3 to an Arduino Pro Mini for size and energy conservation.
With the wiring the same (I think) and the code the same the string (f) doesn't get sent over to the ESP.  I don't see the TX led flashing on the Pro Mini when it should be transferring string(f) and nothing gets uploaded to ThingSpeak.  Not sure why but I will post another question for that one.  Thanks for everyone's help.

It is OK to accept your own answer as the solution.

Sending data between Arduino and NodeMcu (Serial Communication)
youtube link  (in French):
https://youtu.be/0TXmi9EgaCs

When you make a video that is entirely in french, please don't write the title entirely in english.  Use some french, or write "[french]" in the title or something.

hi ..  i make that video to help people to solve the problem.. i forget to ad the language in title .. but the important thing it's the methode (arduino code) using to send the data .. i'm gonna change the title and maybe i will make a video in english  ..  thank you

I appreciate that there are non-english videos out there  =).  It's just good that people know what they're going to get, particularly if they're already frustrated by a problem they're having. Voted you up.


text:
Problem with String& argument of a function
I am trying to send SMSs using a GSM module with Arduino Mega. I have followed a tutorial and downloaded the SIM908IDE100 library. I am using the function
SendSMS(String&, const char [27]);.
It works fine when I type:
sms.SendSMS("1234567890","Text message");
where "1234567890" is the telephone number I want to send the SMS to and "Text message" is the text of the SMS.
If I instead try to pass to the function a String containing the telephone number
String number = "1234567890";
sms.SendSMS(number,"Text message");
I get the following error:
exit status 1
no matching function for call to 'SMSGSM::SendSMS(String&, const char [27]);'
I don't understand what String followed by an ampersand means. What am I supposed to pass the function as its first argument?

are you sure it is not the sms.SendSMS("1234567890","Text message"); giving you "no matching function"?

@Juraj Yes I am sure. The sms.SendSMS("1234567890","Text message");  works fine and the SMS is sent without any problem.

Hint: Try sms.SendSMS(String("1234567890"),"Text message");

The function prototype in sms.h is
char SendSMS(char *number_str, char *message_str);

if number is String, you should have
sms.SendSMS((char*) number.c_str(),"Text message");

c_str() is a function of the Strinng class. It returns a pointer to internal char array of the String object.
The cast to char* is necessary because the author of the library didn't make the parameter constant with const char*. (It is a good practice, to declare pointers and references as constants.)
The error message no matching function for call to 'SMSGSM::SendSMS(String&, const char [27]); shows the arguments you try to use. String& is reference to some instance of the String type

if I use sms.SendSMS(number.c_str(),"Text message");    I get the error: no matching function for call to 'SendSMS(const char*, const char [13])'

sms.SendSMS((char*) number.c_str(),"Text message");

thank you very much, it works now. I still don't fully understand how (char*) works, would you mind to briefly explain it? thanks again

https://www.tutorialspoint.com/cprogramming/c_strings.htm


text:
Is it possible to send a float Array over I2c
I have tried it several times myself but i never could send or receive it properly. I am asking myself if it is possible and if so could someone explain how?
Cheers.

It is possible. You gave to send both bytes of the float and put them back together correctly after it. Please include your code into the question, so that we can help you

Below is a simple rewrite of the Master Writer/Slave Receiver Wire Tutorial, https://www.arduino.cc/en/Tutorial/MasterWriter, for a vector of floating-point numbers.
Master Writer Sketch
#include <Wire.h>

const int DEVICE = 8;

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

void loop() {
  const int VEC_MAX = 6;
  float vec[VEC_MAX];
  uint8_t* vp = (uint8_t*) vec;

  Wire.requestFrom(DEVICE, sizeof(vec));
  while (Wire.available()) {
    *vp++ = Wire.read();
  }

  for (int i = 0; i < VEC_MAX; i++) {
    Serial.println(vec[i]);
  }

  delay(500);
}

Slave Receiver Sketch
#include <Wire.h>

const int DEVICE = 8;
const int VEC_MAX = 6;
float vec[VEC_MAX] = { ... };

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

void loop() {
  delay(100);
}

void requestEvent() {
  Wire.write((uint8_t*) vec, sizeof(vec));
}

Is it possible to send a float Array over I2c

So I would answer - Yes.


text:
Conditions with GSM module SIM900 doesn't execute
I'm executing this code to control a LED with GSM SIM900 message but there are two problems. First, it receives messages sometimes and some times doesn't. The second is that it doesn't execute the if conditions that are on the GSM message when received.
Is there a problem with my GSM module? Can any one help?
#include <SoftwareSerial.h>
SoftwareSerial gsm(9,10);
String msg;
const int LED = 13;

void setup() {
  gsm.begin(9600);
  Serial.begin(9600);
  Serial.println("PUMP CONTROL");
  Serial.println("t : to receive text");
  delay(1000);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
}

void loop() {
  if (Serial.available()>0)
  switch(Serial.read())
  {
    case 't':
    showSMS();
    break;
  }

  while(gsm.available() > 0)
  {
    Serial.write(gsm.read());
  }
  if ( msg == "ON")
  {
    Serial.println("ON");
    digitalWrite(LED, HIGH);
     Serial.println("ON1");
    delay(1000);
  } else if (msg == "OFF")
  {
    digitalWrite(LED, LOW);
    delay(1000);
  }
  if(msg != "") msg = "";
}

void showSMS()
{
 gsm.print("AT+CMGF=1\r");
 gsm.print("AT+CNMI=2,2,0,0,0\r");
 delay(1000);
 msg = "";
 while(gsm.available() > 0)
 {
  msg += gsm.read();
 }
 Serial.println(msg);
}

There are some basic commands that you should run before checking the messages. Like AT\r\n and check network status available or not and there are some more.

I’ve solved the condition problems by making the condition with the ASCII code of ON and OFF.
I replaced:
if ( msg == “ON”)

with
if(msg.indexOf("ON")>=0)

and replaced:
else if (msg == "OFF")

with
if(msg.indexOf("OFF")>=0)


text:
ESP32 bluetooth discovery parse names
I'm running a sample code from ESP32 examples and I'm scanning available BLE devices. I can see device MAC address etc. But for few devices I can't see their names.I am using ESP-WROOM-32 with hardware support checked out directly from their github (some bugs were fixed earlier on github than via lib manager)When I use LightBlue app for discovery of BLE Devices I can see names for more devices that ESP. What can I change to see the names correctly? OR Can how can I parse device name from the data I'm receiving?
This callback code
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
      Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
      Serial.print(" RSSI: ");
      Serial.println(advertisedDevice.getRSSI());
    }
};

produces this output:
Advertised Device: Name: , Address: 1d:0c:c7:3a:fb:c6, manufacturer data: 4c0009060378c0a81f12, payload: 1073609632
 RSSI: -75

Bluetooth has two ways of dealing with device names. A device can optionally choose to advertise its device name. It also has to respond to a "get device name" request. The former is passive, and is what you normally see when scanning. The latter is active and requires you to connect to the device and make a request. If the device doesn't advertise the device name then the only way you can get the name is to make a GATT "Name Characteristic" request to the device. The ESP32 doesn't (AFAIK) do that automatically because these things are designed to be "light weight". Your heavier-weight "reference" software can go off and do more things because it's a full-blown application.
You can sometimes see the difference in the devices because your reference application might populate the list of devices with a combination of MAC addresses and names, and then replace the MAC addresses with names in a later step. Also it probably caches names that it has queried in the past.


text:
How can I hook up multiple MMA8451 accelerometers, (I2C protocol) using one Arduino Mega?
How can I hook up four (adafruit) MMA8451 accelerometers (using I2C protocol) using one Arduino Mega? What I'm confused about is I only have one SDA and SCL on the Arduino Mega obviously. So how can I connect these all? Multiplexer? I need four because I have one on each leg of a robot. Or is perhaps this impractical to put an accelerometer on each leg of robot? I'm a little new to electronics so please explain in depth if you could. Thanks.
Note to moderators: I just would really love an answer to this even if this doesn't meet the super strict question guidelines. It seems every time I post here there's always that one person who takes it down for any number of trivial reasons. Please let me get an answer at least. Thank you!

Looking at the datasheet for the MMA8451Q, factory default it has two distinct I2C addresses 0x1C and 0x1D, selectable with the SA0 pin, but if you want more to share a bus, they can factory program other IDs, so you could share 4 on one bus if you could buy a couple non-default chips.  Otherwise you need two busses to differentiate 4 chips.

Brief explanation: When you talk to the slave device through I2C you start with (slave) device address. Then you send the message. It is like calling your colleague in an office with many other people. You say: "John", and when he is aware you continue with message, like "let's go for coffee".
This arrangement allows for adding up to 127 devices on one I2C bus. Each device must have different address (sorry, you cannot have two John's in the office, it will cause conflict). Generally two different type of devices will have different I2C addresses, but it may happen you need to use two (or more) of the same (like in your example). In this case, see below.
Many devices with I2C interface allows for address change. Using this facility you are able to communicate with many of the same devices through the same pair of cables.
You can check if your chosen accelerometer has possibility for address change: On picture below there is one with Address tab. When jumper is not fitted, you will get one address, when is fitted, the address of this device will be different, allowing of two of this accelerometers on one I2C bus. Unfortunately in this example there will be possibility of maximum of two of the same devices.

Of course there are devices with more than two possible addresses, you need to search for them.
And, yes, it is fine to use one Arduino to communicate with many I2C devices.
EDIT:
Looking after some of Adafruit accelerometers, I have found this page: https://learn.adafruit.com/i2c-addresses
And small off topic note: If you struggling on finding I2C with more than 2 addresses, check if it is easier to use SPI protocol. In this case you need (edited to correct bus lines names after user CrossRoads comment) MISO, MOSI, SCK and CS (chip select) wires. Chip select is individually connected to each slave device. This allows selecting particular device without addressing issue.

SPI would also be faster to query all the devices.  SPI uses SCK, MISO, MOSI and a unique chip select per device. Communication with a Mega can be at up 8 MHz clock rate, 20 times faster than the 400 KHz of I2C.

Talking about I2C protocol. The slave Address is of 7 Bits that means one I2c can handle 127 Slave I2C devices of different address. So you can connect 127 devices with Single I2C Port just make sure there slave address is different from each other.
Some I2C devices are provided with the option to select salve address by setting some pins high and low. If you are using some identical sensors you are set their slave address different.

The general technique for addressing multiple I2C devices is:

If the device(s) have only one address: use an I2C bus multiplexer.
If the device(s) have two addresses controlled by an addressing pin: use digital output pins from the Arduino to select which device to address, e.g., set the control pin for the selected device low and others high and use the corresponding address to address the device.

With MMA8451Q, factory default it has two distinct I2C addresses 0x1C and 0x1D, controlled by the SA0 pin, use digital output pins on the Arduino Mega to address the selected device (address 0x1C) by setting the corresponding output pin low for the selected device and the control pin for the others to high (address 0x1D). Use address 0x1C to interact with the selected device.
Cheers!

Simple just connect all SCK and SDL accelerometer lines together and then u just need to get a specific code address in your use to get a data from any of the accelerometers


text:
Looking for software allowing for Arduino-based project "mocking" / "wireframing"
I'd like to be able to import a number of components (e.g Arduinos, MPU6050s, displays, motor drivers, LEDs, etc) into an app of some sort then be able to wire those components to each other for the purpose of being able to refer to this crude schematic at a later point or to share it with others. I tried importing things into Eagle, but that seemed like an absolute overkill (if Eagle can be used for something like this, what would the best approach be?). Does software that solves that particular issue exist? Think of it like wireframing for hobby electronics projects...
Please forgive the absolute layman explanation.

Fritzing is the normal Arduino user's schematic tool.

or https://www.tinkercad.com

@Majenko Absolutely what I was after! Thank you!

tinkercad is nice because it will actually run the sketch and simulate hardware like blinking LEDs.


text:
Modifying a code
I use this code to turn on/off a small 5v dc motor. How can I modify it so that the arduino writes the potentiometer value to the motor when it is in ON state ?
int speed = analogRead(pot) / 4;
ButtonState = !digitalRead(Switch);

if (ButtonState != lastButtonState)
{
     if (ButtonState == 1)
     {
         if (motorstate == 1)
         {
             motorstate = 0;
         }
         else
         {
             motorstate = 1;
         }
     }
     lastButtonState = ButtonState;
}

digitalWrite(enable, motorstate);
delay(20);

It depends on whether enable is a pin capable of PWM or analogWrite(enable,speed).

yes it is. i tried removing the last output statement and replaced it with
if (motorstate == 1) analogWrite ( enable , speed );

but it doesnt work.

(this is not an answer, but just a comment, used to use code alignment).
This sketch (which I aligned in your code) can be rewritten to
int speed = analogRead(pot) / 4;
ButtonState = !digitalRead(Switch);

if (ButtonState != lastButtonState)
{
     if (ButtonState == 1)
     {
         motorstate = (motorstate == 1 ? 0 : 1);
     }

     lastButtonState = ButtonState;
}

digitalWrite(enable, motorstate);
delay(20);

I suggest the best way to proceed is to add print statements and use the serial monitor to check what values you get and see what you expect (which is not fully clear).

oh i just figured it out :D i used this statement analogWrite ( enable , motorstate*speed)


text:
Control motor DC with buttons
i'm new user with Arduino, i want to know if there is a tutorial to control the rotation of a motor like : with 4 buttons, the first to rotate +pi/2 the second to rotate -pi/2 the third to rotate +-pi and the fourth to stop the rotation
thanks a lot !!

there may be such a tutorial, but you do not need it ..... what you are referring to is not one programming action, it is two actions ..... one is the detection of button presses ..... the other is motor rotation control ..... find tutorials that teach you how to read button presses and how to control the motor .... then you put those two together so that the program does what you want it to do

Is the motor a stepper? If not you will have trouble getting it to position reliably.

duncan Thank you for your reply :) ! I do not know yet about the type of engine to choose, I want to run a table with a motor connected to the Arduino board. I think to do it on a stepper motor as you say

jsotola, thanks for you reply :) , i'll try, i know how works the detection of button presses, i'm learning about rotation control


text:
Arduino Light Puzzle Help
This is my first time doing this type of thing and I have no background in coding.
It will compile however the code won't upload and I've been working on this for days.
Any help you can provide would be very much appreciated.
Error messages:
Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Uno"

Sketch uses 1898 bytes (5%) of program storage space. Maximum is 32256 bytes.
Global variables use 13 bytes (0%) of dynamic memory, leaving 2035 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\CHRIST~1\AppData\Local\Temp\arduino_build_870585/sketch_apr18.ino.hex:i

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x9c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x9c

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

Code:
void setup() {
//constants
// set pin numbers:
int buttonPin1 = 6; //pushbutton pins
int buttonPin2 = 7;
int buttonPin3 = 8;
int buttonPin4 = 9;
int buttonPin5 = 10;
int buttonPin6 = 11;

int const led1 = 0;      //led pins
int const led2 = 1;
int const led3 = 2;
int const led4 = 3;
int const led5 = 4;
int const led6 = 5;

  //variables

  //led pins as outputs
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);

  //pushbuttons as inputs
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);
  pinMode(buttonPin4, INPUT);
  pinMode(buttonPin5, INPUT);
  pinMode(buttonPin6, INPUT);

  //activating leds
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);
  digitalWrite(led5, LOW);
  digitalWrite(led6, LOW);

  //selecting leds to begin game

  int ran1 = random(0, 1);
  int ran2 = random(0, 1);
  int ran3 = random(0, 1);
  int ran4 = random(0, 1);
  int ran5 = random(0, 1);
  int ran6 = random(0, 1);

  //ensuring 6 led=LOW does not occur | approximatley .02 percent chance running random code twice
  if (ran1 == 0) {
    if (ran2 == 0) {
      if (ran3 == 0) {
        if (ran4 == 0) {
          if (ran5 == 0) {
            if (ran6 == 0) {
              int ran1 = random(0, 1);
              int ran2 = random(0, 1);
              int ran3 = random(0, 1);
              int ran4 = random(0, 1);
              int ran5 = random(0, 1);
              int ran6 = random(0, 1);
            }
          }
        }
      }
    }
  }

  if (ran1 == 1) {
    digitalWrite(led1, HIGH);
  }
  else {
    digitalWrite(led1, LOW);
  }
  if (ran2 == 1) {
    digitalWrite(led2, HIGH);
  }
  else {
    digitalWrite(led2, LOW);
  }
  if (ran3 == 1) {
    digitalWrite(led3, HIGH);
  }
  else {
    digitalWrite(led3, LOW);
  }
  if (ran4 == 1) {
    digitalWrite(led4, HIGH);
  }
  else {
    digitalWrite(led4, LOW);
  }
  if (ran5 == 1) {
    digitalWrite(led5, HIGH);
  }
  else {
    digitalWrite(led5, LOW);
  }
  if (ran6 == 1) {
    digitalWrite(led6, HIGH);
  }
  else {
    digitalWrite(led6, LOW);
  }

  int buttonState1 = 0;
  int buttonState2 = 0;
  int buttonState3 = 0;
  int buttonState4 = 0;
  int buttonState5 = 0;
  int buttonState6 = 0;

}

void loop() {

//constants
// set pin numbers:
int buttonPin1 = 6; //pushbutton pins
int buttonPin2 = 7;
int buttonPin3 = 8;
int buttonPin4 = 9;
int buttonPin5 = 10;
int buttonPin6 = 11;

int const led1 = 0;      //led pins
int const led2 = 1;
int const led3 = 2;
int const led4 = 3;
int const led5 = 4;
int const led6 = 5;

  int buttonState1 = 0;
  int buttonState2 = 0;
  int buttonState3 = 0;
  int buttonState4 = 0;
  int buttonState5 = 0;
  int buttonState6 = 0;

  //read each pushbutton
  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);
  buttonState3 = digitalRead(buttonPin3);
  buttonState4 = digitalRead(buttonPin4);
  buttonState5 = digitalRead(buttonPin5);
  buttonState6 = digitalRead(buttonPin6);

  // check if the pushbutton is pressed
  //button for leds 3 and 6
  if (buttonState1 == HIGH) {
    if (led3 == HIGH) {
      digitalWrite(led3, LOW);
    }
    else {
      digitalWrite(led3, HIGH);
    }
    if (led5 == HIGH) {
      digitalWrite(led6, LOW);
    }
    else {
      digitalWrite(led6, HIGH);

    }
  }
  //button for leds 1 and 4
  if (buttonState2 == HIGH) {
    if (led1 == HIGH) {
      digitalWrite(led1, LOW);
    }
    else {
      digitalWrite(led1, HIGH);
    }
    if (led4 == HIGH) {
      digitalWrite(led4, LOW);
    }
    else {
      digitalWrite(led4, HIGH);
    }
  }
  //button for leds 2 and 5
  if (buttonState3 == HIGH) {
    if (led2 == HIGH) {
      digitalWrite(led2, LOW);
    }
    else {
      digitalWrite(led2, HIGH);
    }
    if (led5 == HIGH) {
      digitalWrite(led5, LOW);
    }
    else {
      digitalWrite(led5, HIGH);
    }
  }
  //button for leds 2 and 6
  if (buttonState4 == HIGH) {
    if (led2 == HIGH) {
      digitalWrite(led2, LOW);
    }
    else {
      digitalWrite(led2, HIGH);
    }
    if (led6 == HIGH) {
      digitalWrite(led6, LOW);
    }
    else {
      digitalWrite(led6, HIGH);
    }
  }
  //button for leds 1 and 5
  if (buttonState5 == HIGH) {
    if (led1 == HIGH) {
      digitalWrite(led1, LOW);
    }
    else {
      digitalWrite(led1, HIGH);
    }
    if (led5 == HIGH) {
      digitalWrite(led5, LOW);
    }
    else {
      digitalWrite(led5, HIGH);
    }
  }
  //button for leds 3 and 4
  if (buttonState6 == HIGH) {
    if (led3 == HIGH) {
      digitalWrite(led3, LOW);
    }
    else {
      digitalWrite(led3, HIGH);
    }
    if (led4 == HIGH) {
      digitalWrite(led4, LOW);
    }
    else {
      digitalWrite(led4, HIGH);
    }
  }
  //flash all lights once for winning
  if (led1 == LOW) {
    if (led2 == LOW) {
      if (led3 == LOW) {
        if (led4 == LOW) {
          if (led5 == LOW) {
            if (led6 == LOW) {
              digitalWrite(led1, HIGH);
              delay(1500);
              digitalWrite(led1, LOW);
              digitalWrite(led2, HIGH);
              delay(1500);
              digitalWrite(led2, LOW);
              digitalWrite(led3, HIGH);
              delay(1500);
              digitalWrite(led3, LOW);
              digitalWrite(led4, HIGH);
              delay(1500);
              digitalWrite(led4, LOW);
              digitalWrite(led5, HIGH);
              delay(1500);
              digitalWrite(led5, LOW);
              digitalWrite(led6, HIGH);
              delay(1500);
              digitalWrite(led6, LOW);
            }
          }
        }
      }
    }
  }
}

I could compile your code just fine. No compiler errors. Though it's not that useful to define the pins as constants inside setup and loop. Just use global variables.

So the problem is not compilation but uploading. Have you chosen the correct COM port?

I believe so. It only lists one port "COM4(Arduino/Genuino Uno".

You also have logic errors in your code. You have if (led5 == HIGH), which will NOT check the state of the LEDs pin, but will compare the LEDs pin number, which is constant 4 here, to HIGH, which is defined as 1. This is always false. You have to do a digitalRead(led5)

Thank you for your help. I went through and changed all the logical errors.
l5=digitalRead(led5);
if (l1 == HIGH) {
digitalWrite(led1, LOW);           It doesn't have any issues from what I can tell other than it not uploading so I believe it is an issue with my computer now. Again thank you so much.


text:
D1 mini / esp8266 WifiManager
So i have a D1 mini that I want to connect to the wifi.
I found the following code on the internet that is supposed to start a web server, that you can visit and then connect to the chosen wifi through the website. It will then remember the settings and try to connect to that wifi next time before it starts a web server - which is just what I need!
The problem is that when I connect to the wifi the d1 mini thinks it did just than - but when I visit my router and check it is not connected.
I cannot figure out why it thinks it's connected but is not, can anyone help me?
#include <FS.h>                   //this needs to be first, or it all crashes and burns...
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

void setup() {

  Serial.begin(115200);
  Serial.println();

  //WiFiManager

  WiFiManager wifiManager;

  //reset settings - for testing
  wifiManager.resetSettings();

  IPAddress _ip = IPAddress(192, 168, 0, 35);
  IPAddress _gw = IPAddress(192, 168, 0, 1);
  IPAddress _sn = IPAddress(255, 255, 255, 0);

  wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);
  if (!wifiManager.autoConnect("WemosAP", "ConfigureMe")) {
    Serial.println("failed to connect, we should reset as see if it connects");
    delay(3000);
    ESP.reset();
    delay(5000);
  }
  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");
  Serial.println("local ip");
  Serial.println(WiFi.localIP());
}
void loop() {
}

btw: the ip 192.168.0.35 is free, and I have checked both the gateway and the subnet mask from my laptop by running ipconfig in cmd.

remove resetSettings()

So it seems like the code is just broken. I found an example from the WifiManager library that is called "autoconnect". This just seems to do the exact same thing, just by also working:
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  //reset settings - for testing
  //wifiManager.resetSettings();

  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wifiManager.setAPCallback(configModeCallback);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if(!wifiManager.autoConnect()) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  }

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");

}

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

}


text:
cannot convert 'bool' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus) on Arduino Uno Rev 2 Wifi not working
I am a newbie to micro controllers and struggling to figure out how to fix this issue. When using an older Arduino micro controller it works fine, but when I use a new board (Arduino Uno Rev 2 Wifi) it gives me this error:
cannot convert 'bool' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus)'

At this line :
digitalWrite(pin_enable_line, !digitalRead(pin_enable_line));

Library I am using is: ReceiveOnlySoftwareSerial.

Can you show us the sketch you are using?

nice. the MegaAVR core use the new common Arduino API and it has enum for pin status. use HIGH and LOW, not bool. so digitalWrite(pin_enable_line, (digitalRead(pin_enable_line) == HIGH) ? LOW : HIGH); (value is still LOW 0 and HIGH 1)

The digitalRead method doesn't return a Boolean value. It returns an Integer.
From what I remember inside Arduino.h values of LOW and HIGH are defined as being simply Integer 0 and 1.
#define HIGH 0x1
#define LOW 0x0

I think that was changed to an Enum called PinStatus but Enum can be treated as an Integer.
This means that you have to store results of digitalRead inside Integer variable.
int value = digitalRead(8);

It was designed that way to easily cast values between Integer and Boolean. By (very smart) design choice Integer value of 0 (LOW) will be cast to false and every other value (for example 1 or HIGH) will be cast to true.
The operator ! (Boolean NOT) can be used only with Boolean variables so the compiler needs to perform several "implicit casts". When it's smart enough it will assume you are know what you are doing and it will add the cast by itself.
By reading the error I see that the issue is happening when compiler tries to convert Boolean value into Integer. So this is implicitly evaluated correctly as a Boolean value
!digitalRead(pin_enable_line)

But when you try to put it inside a place for PinStatus you get the exception
cannot convert 'bool' to 'PinStatus'

Try adding an "explicit cast" to PinStatus:
digitalWrite(pin_enable_line, (PinStatus)!digitalRead(pin_enable_line));

It should fix the issue.
But I suggest splitting the code into several lines and adding a temporary variable. It makes debugging much easier. Trust the code optimizer that's built into the compiler. It will understand what you want to do and actual machine code will be the same.

if you write an answer, why you don't try it? the cast to int doesn't compile

@Juraj Strange. Line digitalWrite(9, (int)!digitalRead(8)); works perfectly in Tinkercad.

for megaAVR core (Uno WiFi 2) with PinStatus enum?

@Juraj You got me. I was reading wrong source code, and tested it on wrong simulator. Post answer about using ternary operator and I will delete mine.

cast to PinStatus could work. it compiles, but I would like to know if it works. but I don't have a board which would use the updated Arduino API. but the enum could be tested on it's own.

I did a little simulation and Serial.println((TestEnum)false); prints 0 and Serial.println((TestEnum)true); prints 1 so cast looks good. I will adjust my answer. If it will fail on OPs board I will delete it.


text:
How to filter the power supply for an Arduino in a vehicle (car, motorcycle)?
I want to use an Arduino (maybe Nano, maybe MEGA) in my motorcycle (a new KTM with lots of electronics).
I checked my test circuit (with the MEGA) and it uses about 100mA (with 5V connected to the 5V pin).
Edit: the bike has a 12v battery and when it's on the generator pushes this up to about 14.3v.
For my first tests I used a 3 terminals DC/DC Regulator with output 5V for the Arduino power supply. If the ignition is on the Arduino works. As soon as I start the bike the Arduino restarts every couple of seconds.
Currently I used the BP5293 DC/DC Regulator because it has 2% precision. Currently I don't have any capacitors on the input or output terminals of that regulator.
I guess I have the following options:
a) Use the BP5293 and add capacitors on the input and/or output terminals. In the datasheet an output capacitor of about 10-330uF is recommended. For the input it recommends a capacitor but without any value given.
b) Use another regulator to 5V
c) Use a regulator to i.e. 7V and then connect that to the Arduino power input and let the Arduino do the filtering of the input.
What is the proper solution and what are suitable values for the capacitors?
I have 100nF ceramic capacitors and Low ESR electrolyte capacitors with 6.3V, 16V and 35V from 68uF up to 3300uF in stock. Obviously I could just try but I prefer to know how it should be done.

Connect ceramic capacitor, recommended 10μF from the datasheet. I'd start with the input side, as the Arduino boards already have some capacitors on the board itself. Low ESR electrolytic, instead of ceramic, is most likely fine. Just make sure you have the correct polarity. I'd go for the 35V rating, just to be sure.

Your motorcycle battery is 6V, correct? You're probably having voltage drop problems. A capacitor on the input side of your power supply might help. You might also need a buck/boost power supply, which is able to increase or decrease the output voltage, since 6V too close to 5V for a linear regulator to handle.

@DuncanC: I edited the question to show the bike has 12v. I didn't mention that because I think by now all bikes, even the smallest, use 12v. But if it would use 6v then you are obviously right about the consequences. Thanks

The solution depend on what causes the reset.
It might be EMI interference on the RESET, in this case a stronger pull-up might help. The standard pull-up for nano is 1kohm which should be enough but if you use a clone the value might be higher.
If the reset comes from power drops then only a higher capacitor on the regulator input would not be enough since you also have other consumers on the 12V line that will suck the energy stored in the input capacitor.
Feed the capacitor and the regulator input through a diode, anode to 12v, cathode to capacitor/regulator. This will stop the energy stored in the capacitor to go back to the 12V line.


text:
Triggering an ultrasonic sensor
I made a smart blind stick for my class project. It uses an ultrasonic sensor to detect obstacles and I was asked this question in VIVA...
Why is it necessary for giving a digital high for 10 μS on the trigger (Trig) pin of an ultrasonic sensor ?
Why 10 μS only?
I changed it to 5 μS then to 20 μS and to 50 μS and it still works fine! Why so?

obviously i googled for an explanation but couldn't find my answer for "Why 10u" and neither could i find it in your answer

The specification1 says (emphasis is mine):

using IO trigger distance, the high signal to at least 10us.

So, longer than 10 μS is not a problem.
With respect to less than 10 μS, well 5 μS may also work, but it is out-of-spec and therefore not guaranteed to work and so may not always work correctly, or as expected.
From Source 1:

From Source 2:

As to why must it be 10 μS, well that is probably (at a guess) down to the design of the logic upon the silicon and the resultant propagation delay through the logic gates. Most, if not all, logic ICs specify a minimum amount of time required for a signal level, in order to allow the signal to propagate through the transistors that make up the logic, so that they switch correctly. PN junctions require a finite time for the electrons and holes to move, and when there are a number of them in sequential stages, that time is multiplied by the number of stages that the signal needs to propagate through. That is a very simplified way of looking at it.
To confirm this, you would need to speak to either the designers, or take a look at the mask used to fabricate the IC. Test simulations were probably run during the design phase, and they suggested a minimum trigger pulse of 10 μS. The figure could also be arrived at by simply looking at the design and counting the number of stages and multiplying that by the propagation delay per stage.
However, as Valbhav points out, the HC-SR04 is controlled by a STM8 (actually it is a STC11F), and after having looked at the STM8 programming manual, it is more related to instruction cycles. The Trig pin is, I assume, an interrupt, and from section 3.2 CPU registers

When an interrupt occurs, the CPU registers (CC, X, Y, A, PC) are pushed onto the stack.
This operation takes 9 CPU cycles and uses 9 bytes in RAM

So, 9 CPU cycles just begin to to service the interrupt, and then however many needed to actually do the rest. I can't find any timing diagrams in the Programming Manual which would show the minimum interrupt signal length.  This information, is however in the Reference Manual
The length of a CPU cycle will obviously depend upon the clock frequency., which according to this schematic, from An Ultrasonic Shortcut – Getting the HC-SR04 Transducer Up and Running Fast!, is 4 MHz:

So, 10 μS is 40 CPU cycles.

1 Sources for downloading HC-SR04 pdf datasheet:

Source 1
Source 2

HC-SR04 Specifications

Working Voltage: DC 5V
Working Current: 15mA
Working Frequency: 40Hz
Max Range: 4m
Min Range: 2cm
Measuring Angle: 15 degree
Trigger Input Signal: 10µS TTL pulse
Echo Output Signal Input TTL lever signal and the range in proportion
Dimension 45 * 20 * 15mm

But it is still a question why > 10us. Its like the logic that internally lies in ULTRASONIC SENSOR has something like it checks the TRIG pin status for 10us or more if he gets it high it will generate the 8 pulse of 40Khz.

Propagation delay through the logic gates? Most, if not all, logic ICs specify a minimum amount of time required for a signal level, in order to allow the signal to propagate through the transistors that make up the logic, so that they switch correctly. PN junctions require a finite time for the electrons and holes to move, and when there are a number of them in sequential stages, that time is multiplied by the number of stages that the signal needs to propagate through. That is a very simplified way of looking at it.

It contains an STM8 Controller

@Vaibhav - Ok, so then, in that case. it is more to do with instruction cycles rather than propagation delays. STM8 Programming manual

@Vaibhav - I think it is actually a STC11F

It might vary, in some datasheet I had seen STM8.


text:
ESP8266 BearSSL performance
I am playing with a minimal https server on an ESP01S, using BearSSL::ESP8266WebServerSecure.

With 2048bit RSA keys it takes ~5 seconds to serve a "hello" request.
Using 256bit EC keys it takes ~2 seconds.

I wonder whether it is possible to make key exchange faster without giving up on reasonable security level.
I am struggling with trying to set ec_all_m15 implementation (see Key Exchange) to make it faster without any luck - I have actually no idea how to do it properly .
I tried something like
...
BearSSL::X509List *cert = new BearSSL::X509List(serverCert.c_str());
BearSSL::PrivateKey *key = new BearSSL::PrivateKey(serverKey.c_str());
server.setECCert(cert, BR_KEYTYPE_EC, key);
server.begin();
br_ssl_server_context sc;
br_ssl_server_init_full_ec(&sc, cert->getX509Certs(), 1, BR_KEYTYPE_EC, key->getEC());
br_ssl_engine_set_ec(&sc.eng, &br_ec_all_m15);
br_ssl_server_reset(&sc);

Could someone help pls?

it always going to be slow. what have you tried?

@dandavis I have added to the post.


text:
Trying to use an Arduino Uno together with an ISM330DLC communicating through SPI
I am trying to get a MEMS-module (ISM330DLC) to work together with an Arduino Uno but I can't get it to work. I am using the ism330dlc drivers.
ISM330dlc Drivers: https://github.com/STMicroelectronics/STMems_Standard_C_drivers/tree/master/ism330dlc_STdC
ISM330dlc Datasheet: http://www.farnell.com/datasheets/2339632.pdf
ISM330dlc Application Notes: https://www.st.com/content/ccc/resource/technical/document/application_note/group0/68/eb/a3/cd/2c/78/45/41/DM00468454/files/DM00468454.pdf/jcr:content/translations/en.DM00468454.pdf
I have switched out the voltage regulator to a 3.3V on the Arduino following this guide: https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion
I am using the STEVAL-MKI182V2 board for easier wiring.
This is the current wiring:
Arduino Pin<------------->STEVAL Pin
Pin 10 (SS)<------------->CS
Pin 11 (MOSI)<------------->SDA
Pin 12 (MISO)<------------->SDO
Pin 13 (SCK)<------------->SCL
SDx is connected to ground, SCx is connected to VddIO. The board is also connected to ground on the Arduino as well as Vin 3.3V.
Here is the code:
/* SPI Pin config (There are other pins dedicated to SPI I think) */
#define SSpin 10
#define MOSIpin 11
#define MISOpin 12
#define SCKpin 13

/* Variables used to store data */
static axis3bit16_t data_raw_acceleration;
static axis3bit16_t data_raw_angular_rate;
static float acceleration_mg[3];
static float angular_rate_mdps[3];

static int32_t platform_write(void *handle, uint8_t Reg, uint8_t *Bufp, uint16_t len) {
  SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE3));
  digitalWrite(SSpin, LOW);
  SPI.transfer(Reg);
  SPI.transfer(Bufp);
  digitalWrite(SSpin, HIGH);
  SPI.endTransaction();
  return 0;
}
static int32_t platform_read(void *handle, uint8_t Reg, uint8_t     *Bufp, uint16_t len) {
  Reg |= 0x80; //Set bit 0 (MSB) in order to read
  SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE3));
  digitalWrite(SSpin, LOW);
  SPI.transfer(Reg);
  *Bufp = SPI.transfer(0x00); //Dummy send to get value from module
  digitalWrite(SSpin, HIGH);
  SPI.endTransaction();
  return 0;
}

/* Init mems driver interface */
ism330dlc_ctx_t dev_ctx = {platform_write, platform_read, 0};
//dev_ctx.write_reg = platform_write;
//dev_ctx.read_reg = platform_read;
//dev_ctx.handle = 0; //No handler needed

void setup() {
  delay(100);
  Serial.begin(9600);
  pinMode(SSpin, OUTPUT);
  digitalWrite(SSpin, HIGH);

  /* Initialize SPI */
  SPI.begin();
  //SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));     //MSBFIRST, SPI_MODE3

  /* Needed for setup */
  static uint8_t whoamI, rst;

  /* Check if device ID is correct */
  whoamI = 0;
  ism330dlc_device_id_get(&dev_ctx, &whoamI);
  while (whoamI != ISM330DLC_ID) {
    Serial.print("Wrong device ID!! \n"); Serial.print("whoamI: ");     Serial.print(whoamI); Serial.print("\n\n"); delay(50);     ism330dlc_device_id_get(&dev_ctx, &whoamI);
  }

  /*Restore default config */
  ism330dlc_reset_set(&dev_ctx, PROPERTY_ENABLE);
  do {
    Serial.print("reset:"); Serial.print(rst); Serial.print("\n\n");
    ism330dlc_reset_get(&dev_ctx, &rst);
  } while (rst);

The problem is that whenever I run this code I get DeviceID 255 no matter what (ism330dlc device id is 106). One thing I noticed is that if I reset the Arduino and quickly insert the USB cable and upload the code (in the time interval of a second) I can get the right device ID, but then I can't restore the default configuration (i.e not read or write again). Any tips what might cause this? I have tried SPI.setClockDivider() as well as different SPI Modes.
UPDATE: Removing ground from GND, SCx and SDx makes me get the correct deviceID but I still get stuck on trying to restore default configurations.

You are powering the STEVAL board from the VIN pin of the Arduino, while powering the Arduino through USB?

No sorry about that, I am powering the STEVAL-board using the 3.3v output on the Arduino. Edit: I have also tried powering it using an extern source at 2.8V.

Sorry there was a time limit on editing comments more than once. The Arduino is powered through USB and the STEVAL board is powered through the 3.3v output.

I realize now that I have not added any coupling capacitors to Vdd and Vdd_IO, could that affect the data?

Unlikely. The STEVAL board will have plenty of decoupling built in.

When I measure the CS pin it alternates between 2.4V and 2.6V when doing reads, is the difference too small? Vdd_IO is at 3.25V (same as Vdd).
SDO (MISO) is always 3.15V, SDA (MOSI) is switching between 0.3V and 1.3V, SCK is always 3.25. These values doesn't seem to be correct, right?


text:
Fan regulator control from Arduino
I'm trying to control my ~230 V fan from the Arduino.
Can anyone say the best possible ways to design a fan regulator that can be controlled by the Arduino using a low cost design.

Use TRIAC Circut. In this you can control the current flow to the FAN

How many relays needed to make 5 level regulator? I think it is not effective design.

Do you want a variable speed controller or single-speed? And is this a 3 phase motor?

Single phase motor and variable speed controller for my home automation.

Relay don't control current that's why is suggested TRIAC

I use Kemo module to regulate a heater. They can regulate an inductive load too. For MCU control they have a digital pot module M150 controlled by PWM. https://www.kemo-electronic.de/en/Light-Sound/Effects/Modules/M012-Power-Control-110-240-V-AC-1200-VA.php

@Juraj Thanks. That's more cost design than the 5 relay circuit which is nearly 250 INR. From Amazon lower cost of this module is 3,800 INR.

I enhanced my answer

To control AC power for inductive load (motor) a Triac is used. The concept is called phase cutting. It works for a resistive load (heater) too.
This module is designed for phase cutting. It contains a zero crossing detector and a Triac. The control is done in MCU. The zero crossing detector is wired to an interrupt pin. The control signal for the Triac is wired to an output pin. In external interrupt function you set a timer interrupt to send a pulse to the Triac after some microseconds. Longer off time results in less power for the motor.

At 50 Hz AC, one pulse is 10 milliseconds. To cut a part of AC wave out, activate the Triac gate for 20 microseconds after 0 to 10 milliseconds. Triac turns self off the AC line at next zero crossing.
Robotdyn has a library for the module.
EDIT:
I bought the Robotdyn AC dimmer module to use it in my AC heater regulation project and I tested it with a incandescent light bulb and a fan. (video on youtube)
The library by Robotdyn works, but it is designed to control many dimmers and uses a timer interrupt every 12 microseconds (yes, micros). The library sets the interrupts over MCU registers.
I wrote an arduino fade-in/out sketch using TimerOne library to demonstrate phase cutting with this module.
#include <TimerOne.h>

const byte INTERRUPT_PIN = 2;
const byte TRIAC_PIN = 4;
const byte TRIAC_PULSE_MICROS = 30;

const int FADE_MAX = 9800;
const int FADE_MIN = 2000;

volatile bool triacOn;
volatile int period = FADE_MIN; // microseconds cut out from AC pulse

int fadeAmount = 10;

void zeroCrossing() {
  triacOn = false; // triac tuns off self at zero crossing
  Timer1.setPeriod(period); // to call triacPulse() after off period
}

void triacPulse() {
  if (triacOn) { // stop pulse
    digitalWrite(TRIAC_PIN, LOW);
    Timer1.stop();
  } else { // start pulse
    digitalWrite(TRIAC_PIN, HIGH);
    triacOn = true;
    Timer1.setPeriod(TRIAC_PULSE_MICROS);
  }
}

void setup() {
  pinMode(TRIAC_PIN, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), zeroCrossing, RISING);
  Timer1.initialize();
  Timer1.attachInterrupt(triacPulse);
}

void loop() {
  period = period + fadeAmount;
  if (period <= FADE_MIN || period >= FADE_MAX) {
    fadeAmount = -fadeAmount;
  }
  delay(25);
}

EDIT 2 version with triac activated by 'pwm' pin
const byte TRIAC_PIN = 9;
const byte ZC_EI_PIN = 2;

unsigned long topMicroseconds = 9700; // 10000 micros is between zero crossings
int prescaler = 8;
byte prescalerBits = _BV(CS11); // 8

void zeroCrossing() {
  TCNT1 = 0; // reset the timer counter
}

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

  attachInterrupt(digitalPinToInterrupt(ZC_EI_PIN), zeroCrossing, RISING);

  pinMode(TRIAC_PIN, OUTPUT);
  uint32_t topPeriod = ((F_CPU / 1000000)* topMicroseconds) / prescaler ;
  ICR1 = topPeriod;
  OCR1A = topPeriod + 1; // full off
  // WGM mode 14 - Fast PWM w/TOP=ICR1
  TCCR1A = _BV(WGM11) | _BV(COM1A0) | _BV(COM1A1);
  TCCR1B = _BV(WGM13) | _BV(WGM12) | prescalerBits;
}

void loop() {
  if (Serial.available()) {
    unsigned long microseconds = Serial.parseInt();
    Serial.find("\n");
    uint32_t period = ((F_CPU / 1000000)* microseconds) / prescaler ;
    OCR1A = period;
  }
}

on SAMD it is possible to setup this to start the timer on external interrupt over event, without an interrupt function. then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals
EDIT 3:
The TriacDimmer library version 1.1.0 for AVR Arduinos available in Library Manager works good with this dimmer. Fun fact: It uses timer1's input capture on pin 8 instead of external interrupt on pin 2 or 3.

the modules and component I linked in comments use this method. they work as 'pwm to phase cutting adapters'

The animated graphic is of rectified AC, does it really get down to a zero crossing to do a shut-off?

@DaveX, not to exact zero crossing but in the scale the animation is right

The waveform in the animation isn't right for AC--there's a sharp 'V' at length/2, it looks rectified, so instead of 50Hz 230Vrms AC, it's showing 100Hz (10ms) pulsed DC.   The robotdyn module uses a triac that won't rectify like that diagram.  It should have the second half of the top diagram flipped around it's X axis and twice the height.

@DaveX, the negative part is mirrored up. I didn't find a better one. I linked the animation from Wikipedia page about phase cutting. now I see SE copied the animation

@juray You properly say that the RobotDyn library raise an interrupt every 12us to control multiple dimmers. But this is just an unoptimized implementation since I have implemented this library https://github.com/fabianoriccardi/dimmable-light which triggers only 2 interrupts per semi-period.

Its not exactly what you are looking for but it will help Arduino-controlled-light-dimmer-The-circuit.
Here is the sample project in which TRIAC is used with arduino for controlling the flow of current to the light. In your case Light or better we can say load is FAN. This will help you in controlling the FAN Speed. Relay only act as switch and it won't control FAN Speed.

Link only answer? We are looking for comprehensive answers that provide some explanation and context. Very short answers cannot do this, so please [edit] your answer to explain why it is right. Additionally, we prefer answers to be self contained where possible. link only answers are frowned upon (as links tend to rot) & will be rendered useless if the linked-to content disappears. If you add more context and detail from the link, it is more likely that people will find your answer useful.

Thanks Vaibhav, My thought is TRIAC's AC phase may affect arduino board which will affect my analog sensor readings in arduino and their is chance to death too :-/.

Now I think I am better clear about what I want to say.

Finally i found it as a product available here
with the thyristor circuit and electrical-contactless servo (PWM or ANALOG input) motor ( to drive the input) will helps to drive the output from 0 to 220V. smooth fan regulator can also do this with servo motor and without any external electrical component requirement . If it is not efficient way with low cost design command or answer your way.  :-).

If your design is more efficient than mine your design is considered as answer. :-). Thanks in advance.

this is for manual regulation. you want to turn that pot with a motor?

@Juraj Thank you. That can be done by arduino PWM input. So we don't need to work for that.

the board I linked in my aliexpress comment looks better. labels and description swapped input/output (like you do: PWM input ?!), but the electronics should work

You are correct Juraj. That will perfectly match to this circuit ♥. But in question I asked to bring it in low cost design. Your answer is highly acceptable rather than cost.  That's why I'm not mentioned my design also correct.

@SivamaniV : If the pot is controlled manually, what is the purpose of arduino here.

@Learner pot is not manually controlled here. Servo motor controls the pot. Arduino triggers servo motor.

@SivamaniV, read my answer, if you visit Stack Exchange again

There is also the issue of isolation here, to keep the controller side from being connected to the mains for reasons of noise and safety.  The previous posters' comments about doing this with triacs or mosfets, and phase angle control are all true.  It is nearly impossible to control the speed of a single phase induction motor.   Anyway, the most elegant solution is to get a 3 phase fan motor and a variable frequency drive with low-voltage DC control input.  Run the pwm output from the Arduino through an opto-isolator (drive the internal led).  Use the DC reference on the speed control to power the output of the opto-isolator.  Run that through an rc lowpass filter to the speed control voltage input.  I think you could get out of this for around 200$US. Check surpluscenter.com.  there are many motors and drives out there.
-Hugh

It depends on the motor.
To quote MarkT from this post:

The simple advice is you can't.  Standard induction motors in domestic appliances cannot
safely be speed-controlled (some can be a little, but its not easy to find out by how much).
Get a DC fan

To quote dc42, from this post:

What sort of motors do the fans have? If they use induction motors,
then you won't be able to control the speed much using phase angle
switching - the speed is tied to the supply frequency. If they are
series-wound motors with brushes, then phase angle switching should
work.
The results you reported when you tried to use the velleman kit
suggests to me that the fans may have induction motors.

For more information, read:

How to control AC 220V fan speed with arduino's PWM output..?? and;
Changes in Dimming Circuitry! and;
Learn about zero-crossing. This might help How stuff works - dimmer switch.
AC Fan Speed Control with Arduino

Thanks Greenonline. But how fan regulators do this. From the blog, if I done with PWM signal with normal fan regulator circuit, the output pulse signal will affect the 50 Hz (Indian standard AC frequency) both home main supply box and connected devices.

Blog? What blog? Link?

that's arduino forum https://forum.arduino.cc/index.php?topic=100899.0 from the joy reply

As this reply to Joy's post states, you need to use zero-crossing detection, which Juraj's answer correctly demonstrates.


text:
Is there a way to have the LED switch on after 10 readings or say a minute?
I am using Arduino for a RFID project where the LED must switch on after either 12 readings of the tag or 2 minute, the tag reading happen every 10 seconds. I can't seem to figure out a way to have the LED switch on only after the above mentioned conditions.
I have tried doing various if loop much to my failure, below is the code I am currently using:
#include <RFID.h>
#include <SPI.h>
#define SS_PIN 10
#define RST_PIN 9
#define LED_PIN A0

RFID rfid(SS_PIN, RST_PIN);
int serNum[5];
String cardno;
int interval = 15000; // millisec
long now = 0;
long lasttime = millis();
// change Reader ID to your name
String readerID = "Reader_001";

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
  pinMode(A0, OUTPUT);
}

void loop() {
  now = millis();
  if (now > lasttime + interval) {
    lasttime = now;
    Serial.print(readerID);
    Serial.print(":");
    Serial.println("I am alive");
  }
  if (rfid.isCard()) {
    if (rfid.readCardSerial()) {
      lasttime = now;
      cardno = String(rfid.serNum[0]) +
               String(rfid.serNum[1]) +
               String(rfid.serNum[2]) +
               String(rfid.serNum[3]) +
               String(rfid.serNum[4]);

      Serial.print(readerID);
      Serial.print(":");
      Serial.println(cardno);
    }
  }
  rfid.halt();
  delay(10000);
}

The expected outcome is the LED switching on after 2 minutes of contact between the tag and the reader.

first thing to do is to correct the indentation of your code so that the code blocks are clearly visible ...... that will help in determining where to place the code that counts the number of repetitions

Ditch the delay() and work only with millis(). Use a counter variable, that is incremented on every read. In the loop you can check for it being >=12 and turn on the LED.

since I am a beginner would it be too much to ask for an example?

You want to light the LED, when the same chip was read 12 consecutive times. So I would suggest something like this:
Inside your void loop() function you use the millis() coding style (refer to the BlinkWithoutDelay example, that comes with the Arduino IDE) to scan every 10s for a chip. Then you add a counter variable to count, how often the same chip was scanned. If this counter variable is >=12, you turn on the LED. If a different chip was scanned, you set the counter to 1 (since this chip was now scanned 1 time). This leads to a code something like this:
#define READ_INTERVAL 10000
int read_counter = 0;
unsigned long read_timestamp=0;
String last_identifier="";
void loop(){
    if(millis()-read_timestamp>READ_INTERVAL){
        // Read the chip
        if(card_identifier == last_identifier)
            read_counter++;
        else
            read_counter = 1;
        if(read_counter>=12){
            digitalWrite(LED_PIN, HIGH);
        }
    }
}

Be sure to use unsigned long with the millis() function, to prevent it from overflowing to a negative value.

Do you also have any suggestions for connecting two arduinos? both my arduino projects are rfid access control, this being the first one the second one is simple rfid but the access on that needs to depend on the output of the first rfid

i am thinking of doing a SPI master and slave? would you recommend that

Yes, that should be possible. This also depends on the distance between the Arduinos


text:
invalid type argument of unary '*' (have 'uint8_t {aka unsigned char}')
New to Arduino and was hoping to figure this out. I am working with a bill acceptor and getting the value once you insert the money. The code works fine with an older Arduino, but I am using Arduino Uno Wifi Rev2 and getting some major issues. I finally go it down to just this error and i cant figure this one out (Help Please!):
invalid type argument of unary '*' (have 'uint8_t {aka unsigned char}')

On line:
*digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));

Library that is giving the issue:
ReceiveOnlySoftwareSerial

You have to familiarise yourself with pointers if you want to use '*'. Also, edit your post and add more of your code.

What are you trying to do with this? Please provide more of your code and an explanation about your indents with it.

@chrisl this is code that already exists out there, i am just trying to use it on a newer board. The library ReceiveOnlySoftwareSerial is producing this error. I dont want to post the whole code in here but you can find the code here http://gammon.com.au/Arduino/ReceiveOnlySoftwareSerial.zip


text:
Optimizing for speed using const, static, constexpr etc in a function
In an ISR I want to keep things quick. At the same time I want to limit variable scope. Storage space is not a factor.
I have this line:
const char trigs[] = "aAbBcCdDeEfFgGhHiIjJ";

When this is global, the resulting compile stats show:
Sketch uses 3418 bytes (10%) of program storage space.
Global variables use 431 bytes (21%) of dynamic memory.

When it's inside the function (to limit scope) I get:
Sketch uses 3470 bytes (10%) of program storage space.
Global variables use 431 bytes (21%) of dynamic memory.

The extra program space is 52 bytes, which is more than the size of the variables, so there must be extra code in there. That might be something to do with initialization checks... but why? Isn't a const already known? If there's a difference in where it's stored, why doesn't global variable space change?
If I prefix this as static const I'm back to the first behavior (3418 / 431).
So the immediate answer is just to use static const, I suppose. But I'm still curious what's going on. Can someone elucidate?

Can you show us your entire sketch?

@VE7JRO - I don't think that's practical. If it's important to see more context I could try to create a minimal sketch that illustrates this, but it seems pretty straightforward now. Is more context really needed?

with const char* trigs = "aAbBcCdDeEfFgGhHiIjJ"; the size of sketch is always the same for global or local with static or without static. if I call the function twice, the local version without static is better

To optimize for speed, add this in the top of your sketch: #pragma GCC optimize("-O3")

const char trigs[] is an auto - it's allocated on the stack at function entry time - and must be initialized at each invocation. The literal used to do that is stored in globals space, which is why the globals allocation doesn't change.
static const char trigs[] is allocated in globals space and used in place. The symbols' scope is still local, though, so trigs[] isn't visible outside the function.
So why does code space increase by 52 bytes? That seems a lot for copying a string from place to another. So I'll take a guess that the need to copy a string loads a library module that includes it and a few other functions as well.

OK, good info. I get that the stack allocation has to occur for variables, but what I guess I missed is that a const would be considered a variable in that sense. On reflection I guess it couldn't be done any other way.

this is not an answer. the question was: why, if it is const and the value is known at compile time, it is not optimized like static?

@Juraj - That was my real question, but with more reading I learned that const here doesn't mean what I naively thought. Here trigs[] is a variable like any other -- the const attribute simply makes it read-only. That's not intuitive to someone coming from a language that has 'true' constants, but it's how the spec is written.


text:
Why can't I switch off the LED immediately using this sketch?
I hope the LED can fade out a period of time. Also, I hope I can switch off the LED immediately when it is fading, but I only can fade out.
const int buttonPin = 2;
const int ledPin = 9;
const int fadingDelay = 20000;
int buttonState = 0;
boolean fadingState = false;
void setup() {

// initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}
void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check whether the button was pressed
  if (buttonState == HIGH) {
    buttonState = LOW;
    // check the current LED status (on/off)
    if (fadingState == false) {
      // turn on the LED
        for (int i = 255; i >= 0; i -= 5) {
          if (buttonState == HIGH && fadingState == true) {
          analogWrite(ledPin, 0); //immediately off
          i=-1;
          }
        analogWrite(ledPin, i);
             delay(fadingDelay);

    }
    fadingState = false;  // save the current LED state (on/off)
  }
}
}

see the BlinkWithouDelay example. now your sketch stops for 20 seconds.

Your code is a mess, and won't work properly. You need to clearly define what you want to do before we can help you.

I can't see anywhere where you are assigning fadingState as true.I can't understand this part
if (fadingState == false) {
      // turn on the LED
        for (int i = 255; i >= 0; i -= 5) {
          if (buttonState == HIGH && fadingState == true) {
          analogWrite(ledPin, 0); //immediately off
          i=-1;
          }
    analogWrite(ledPin, i);
    delay(fadingDelay);
    }

If you are entering in a if condition with statement fadingState as false. Then in for loop you are having a if condition in which statement is fadingState == true.If you are entering in as a False then why are you looking for True Condition.
Then if you manage to sort that add break; in that if condition so that when LED turns OFF you will exit that for Loop.
And Here you are setting the button state as low buttonState = LOW if first If condition, then in that nested if without reading the buttonState you still looking for it as HIGH.


text:
ArduinoJSON v6 - Passing buffer as function parameter
I'm new to ArduinoJSON - so perhaps it is a newbie's question.... but I wish to pass a StaticJsonDocument into a function as a parameter ( later on it should be implemented in a library ).
exmaple below shows test_1 what I wish to obtain, but by duplicating StaticJsonDocument, which I don't want to do.
How can test_1 should be written (as I tried in test_2)?
#include <ArduinoJson.h>

StaticJsonDocument<200> doc;

void createJSON() {
        doc["sensor"] = "gps";
        doc["time"] = 1351824120;

        JsonArray data = doc.createNestedArray("data");
        data.add(48.756080);
        data.add(2.302038);

        // Generate the minified JSON and send it to the Serial port.
        serializeJson(doc, Serial);
        Serial.println("JSON is created:");

        // Generate the prettified JSON and send it to the Serial port.
        serializeJsonPretty(doc, Serial);

}

bool test_1(StaticJsonDocument<100> _doc){
        serializeJson(_doc, Serial);
        return true;
}

bool test2(const JsonObject& _doc){
        Serial.println("HI");
        serializeJson(_doc, Serial);
}

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

        createJSON();
        test_1(doc);

}

void loop() {
        // not used in this example
}

bool test_1(StaticJsonDocument<DOC_SIZE>& _doc) { use a define or const for the size. it must be the same

@Juraj - why not posting it as an answer ? it works OK

it is not about Arduino, but OK. I even found a better solution. (I know it is working, I tested it)

The StaticJsonDocument is a template class. The template value in <> is here only the size of the internal buffer, but every size used generates a different class. (memory usage!)
To have the parameter of the function take an StaticJsonDocument version instance, it must be the same version or a common base class. In this case the base class is JsonDocument.
If you don't use the reference symbol & the parameter is copied. In this case StaticJsonDocument<200> _doc or JsonDocument _doc would create a copy and that copy would be modified in the function. The object used as parameter value would be unchanged - empty.
So use
void test2(const JsonDocument& _doc) {
  Serial.println("HI");
  serializeJson(_doc, Serial);
}

Hey @Juraj, thanks for this answer. I'm trying to do exactly the same thing as @Guy .D, except when implementing your solution I'm getting a compiler error:
no known conversion for argument 2 from ArduinoJson6101_000::StaticJsonDocument<168u>' to 'const JsonObject& {aka const ArduinoJson6101_000::ObjectRef&}  Any advice would be great and I can post a code snippet if required.

yes I'm using ArduinoJSON V6.

sorry, the code snippet was from Guy's code, not from my test. corrected