text:
Schematic with Atmega32U4 and WS2812 Led (Smiley Shape). Does it work?
I'm new here and I'm a newbie in electronics. Since 1 year I'm playing around with Arduino (different types) and now I want to build my own thing: a smiley with WS2812D-F5 RGB leds. But I'm not sure if I did any misstakes. Is it possible that an expert in electronics can check my schematic? That would be very kind, nice and cool :)
Functions: The switch SW1 is connected on D8 (PB4) and if pushed the smiley changes from sad to happy. pushed again it changes again and so on.
Because the WS2812 leds needs a lot of current, I have added some different possibilities to power the whole thing: 1x DC jack connected on a voltage regulator that output 5V fixed and two pins for a LiPo 3.7V that ist connected too on the voltage regulator. I dont know if it works if the LiPo has only 3.7V.
Well.. then I added a power switch, micro usb, FTDI and SPI connection. If one fails to burn the bootloader or to upload a sketch, I have more possibilities to do that ;)
Yeah I think thats it. If I forgot something, just ask me. Thanks a lot!
Kind regards.
Greetings from Switzerland
delf

Edit 15.5.19 18:00
Ok, I just changed the schematic based upon your great advices :) Thanks a lot to everyone. I changed/added the regulator. Current output=3A (each one). Should  be enough. But I'm not sure if I can divide the current in that way.
What do you think? :)
Greetings to everyone :)

Be sure that every component, that lies between the power supply and the LEDs, is capable of giving the needed current. Also the supply has to provide enough current

A 7805 as a regulator on a circuit that needs about 4A...?!  OUCH. I think not.

Majenko already replied to the most important part (the power management); I'd like to just give a few advice. The LiPo battery connector cannot work that way, since the 7805 needs at least 6-6.5V to work. Moreover you shouldn't connect it in parallel to a 12V supply. The very first time you forget it connected and you also connect the 12V... well, there are a lot of videos of batteries exploding... Finally try to be "cleaner" when drawing the circuit; avoid too many intersecting lines since they are confusing (for instance look at the reset line). Finally SW1 is useless (you cannot control it

Which method and/or programmer are you using to burn the bootloader?

@frarugi87
SW1 has only the function to check if the signal is high to change the shape of the smiley. That should work or did I forgot something? Finally I forgot something important: the max amount of running LED's = ~50. I just add a newer version in a few minutes with the layout of the pcb

@Gerben
I dont know. At the moment I'm in the planing stage. The bootloader task comes later ;)

@swimhive yes, but when SW1 is not pressed it should go to a known state. usually you connect a resistor to either VCC or GND, and the switch to the other, so the node can "go" to the other state when the button is not pressed. These are called respectively pull-up resistors or pull-down. The micro you are using has integrated pull-up resistors, so you can either 1) connect the SW1 to ground, enable the internal pull-up and search for a LOW state or 2) leave the SW1 connected this way, and add a pull-down resistor. Usually people tend to use solution 1 (less components)

On the FTDI header you need to swap the TX and RX pins. The TX of the FTDI should connect the the RX of the Arduino, and vice-versa.
Also, on the FTDI header, the USBVCC pin is connected directly to the 5V pin. I would want to connect my PC to that header if external power is applied to your board. If you're never going to use that pin to power the board, you could leave it disconnected. The same applies to the USB port.
I'd have the LiPo connector bypass the regulator, as all it does is drop the voltage even lower. A LiPo is around 4.2V when full. The 3.7V is only it's nominal voltage.
D1 is in a weird location. If you want to use it to prevent reverse polarity, move it between the jack, and the input of the voltage regulator.

Thanks a lot for your advice :) I just did a few changes. But I'm not sure if I can split the current in that way and how to power the VBus. Is it possible to connect the VBus pin with the output pin from the "regulator2"?
Kind regards

It seems the VBUS pin is an input pin, used to detect if USB is plugged in. So you could wire the 5V from the USB port directly to the VBUS pin. And no connect it to the 5V from the regulator. Leave the Vcc from the FTDI header disconnected.

No. That circuit will not work.
The moment you turn on more than a few of the LEDs the regulator will go into meltdown. No matter how powerful your power supply is, that regulator is the bottleneck and will overheat the moment you try and light your smiley face.
The regulator (a venerable 7805 - I mean, come on, that's from the ark. There's far better modern regulators now...) is rated for a maximum of 1A. That is with very good heatsinking and thermal management, and an input voltage only slightly above 5V + the dropout voltage.  Your circuit can draw up to about 4A. That's 4x what the regulator is rated for when it's at its most optimim - probably 6x to 8x what your arrangement would be able to provide.
For this kind of circuit you need a switching regulator. One that can provide many many times the current of a linear regulator like the 7805 (or the more modern LM1117-5.0).  You need one that will provide at least 4A, and ideally a little more for some extra headroom. So you're looking at 5A.
With a decent efficiency you could then run the whole thing from a 12V input with 2.5A minimum current. Assuming 85% efficiency:

12V @ 2.5A = 30W
85% of 30W = 25.5W
25.5W @ 5V = 5.1A

So a 12V, 2.5A supply being fed into a 5V, 5A switching regulator with at least 85% efficiency will allow your circuit to operate more reliably.
You also need to take care with your PCB layout (assuming you are designing this for building on a PCB). Switching regulators take a certain amount of care when laying them out. You should refer to the recommended PCB layout in the datasheet for your chosen regulator and stick as closely to that as you can.
Also handling larger currents requires more thought put into your traces.  This site has a handy trace width calculator.
As an example: for a 5A trace over a distance of 5cm with (standard) 1oz copper your trace should be at least 2.77mm wide. That will give a 10C temperature rise in the trace at room temperaure (25C to 35C).

Hi :)
Thanks a lot for your help! like I said: I'm a newbie :) can you recommend a voltage regulator? I only find linear voltage regulators that provide 3.3V and 5A. But I need 5V :-/
Thanks a lot for the usefull informations. But.. the rest of the circuit works?
About the traces on the pcb: only the VCC and the GND trace should be ~3mm wide or am I wrong?
Thanks a lot for your kind help :)
Greetings and keep smiling ;)

@swimhive personally I'd go with larger traces, or even planes. I suggest you to try to minimize the amount of current in a single point (for instance use a sort of "tree" connection rather than a sequential one).

Certainly for the ground you want a solid pour rather than traces. Then route the power traces first, and only afterwards worry about the signals.

@swimhive As a newbie I wouldn't suggest designing your own switching regulator circuit just yet. Take a look at external modules, such as UBEC modules for model aircraft etc.

@Majenko
Yes you are right. But I have to :( There is one thing that I dont understand. My Arduino Due can drive 50 pieces WS2812B leds. One single led uses max 60mA (20mA for each color). If every led is white it consumes 60mA each. Total=3000mA. The regulator on the DUE is a LM2734Y and has a max. current output 1A. But it works.. how?

You are probably over-stressing the regulator. How hot is it getting? Is the output voltage dropping?

@Majenko I'm not sure if the output voltage is dropping. It's a shield. I cant access the regulator while running the led, because he's covered.


text:
Speed Control of Brushless DC Motor
I cannot understand the code of controlling the speed of brushless dc motor using ESP8266 WiFi Module.
I found it in- https://ubidots.com/blog/speed-control-for-brushless-motors-with-an-esp8266-2/
The part that I cannot understand is-

float btof(byte * payload, unsigned int length) {

  char * demo = (char *) malloc(sizeof(char) * 10);

  for (int i = 0; i < length; i++) {

    demo[i] = payload[i];

  }

float value = atof(demo);

  free(demo);

  return value;
}

// Callback to handle subscription

void callback(char* topic, byte* payload, unsigned int length)

{

    value = btof(payload, length);

      value = map(value, 0, 1023, 0, 180);

//Map the 0-100 values from the slider to the 0-180 to use the servo lib.

 ESC.write(value);

//Send the value (PWM) to the ESC

}

Please help me with the code!

What aspect of the code cannot you understand?  Without being specific, it is hard to help you.

The entire btof and callback function that have been created. Why have they been created, what is payload and length, why are we creating btof and callback function, what is the logic behind it and how are they related to speed control of brushless dc motor.

Callback function must be data send from server to the ESP.
Payload is the data byte sent from server.
Length is the size of data in bytes.
BTOF is basically byte to float converter which converts all the data byte received into single floating variable and return that floating point value.
ECS.write must be the function that write the value to the servo motor controller H-bridge IC. It belongs to servo library.
Value range that can be mapped into this ECS.write is between 0-180 so map function will use that will convert the floating point data received from btof function.
Basic definition of map() function:

Map function maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.
Does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.
Note that the "lower bounds" of either range may be larger or smaller than the "upper bounds" so the map() function may be used to reverse a range of numbers.
Syntax:
map(value, fromLow, fromHigh, toLow, toHigh)

Then ECS.write(value) will write that mapped value to servor motor controller H-Bridge.

Okay, thanks a lot for clearing most of it. Still I have few doubts- 1)char * demo = (char *) malloc(sizeof(char) * 10); Meaning of this line.   2) Is payload a defined function? Which library does it belong to?  (3) Also I would want to know about the subscribe function and client there in the code- client.begin(callback);   client.ubidotsSubscribe(DEVICE_LABEL, VARIABLE);

In that case you need share your full sketch here. 1. char * demo = (char *) malloc(sizeof(char) * 10); Meaning of this line. You should clear your basic C concepts. In this you are assigning some memory space to this char pointer of 10 bytes size;

The full sketch is here in the link- https://ubidots.com/blog/speed-control-for-brushless-motors-with-an-esp8266-2/

Payload is a array pointer of byte type. It is declared in ESP8266 Library. Rest is features of TCP communication protocol. You should study about how TCp protocol works. Client Sever concept, what is publish and subscribe, and HTTP Post and Get request. Then you will know about these functions better.

Okay, thanks a lot!!

It would be great of your sir if you can also please provide some useful resources for the same if you have any?

this is a simple document that tells about esp8266 and contain reference links to other protocols a well document.

Thanks a lot sir for helping out! :)

source: Stack Exchange

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

sort: votes


text:
Display not showing output - Arduino Wattmeter
I have been playing with this code for some time now, I am able to show the results in an 16X2 LCD display, but I am not able to do it in an OLED.
here is the code
    #include <SPI.h>
    #include <Wire.h>
    #include "U8glib.h"  //Library for display

    U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C interface for OLED

    int index = 0; //size of array
    const int number_of_readings = 200; //total number of readings arduino takes before it averages
    const int current_zero = 510; //initial value of current from arduino with 0 amps
    int current_reading[number_of_readings]; //create array for current_reading
    int voltage_reading[number_of_readings]; //create array for voltage_reading

    float R1=30000; //resistance of R1 in voltage sensor
    float R2=7500; //resistance of R2 in voltage sensor
    float current_average = current_zero; //initial value of current average
    float current_total = 0; //initial value of current_total
    float voltage_average = 0; //initial value of voltage_average
    float voltage_total = 0; //initial value of voltage_total

    int x = 0;
    int row = 0;
    float voltage = 0.1;

      void setup() {
       Serial.begin(9600);
       pinMode(A4,INPUT_PULLUP);
       pinMode(A5, INPUT_PULLUP);
      }

      void draw(void) {
       u8g.setFont(u8g_font_fub14r);
       {

       u8g.drawStr(0, 20, "V: ");
   u8g.drawStr(0, 40, "A: ");
   u8g.drawStr(0, 60, "Watt: ");
   u8g.setPrintPos(58,20);
   u8g.print( Bat_Volt,2);
   u8g.println("V");
   u8g.setPrintPos(58,40);
   u8g.print( current,0);
   u8g.println("mA");
   u8g.setPrintPos(58, 60);
   u8g.print( power ,1);

    }
    }

     void loop() {
      voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
      voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
      current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
      current_total = current_total + current_reading[index]; // add current to current_total
      index = index + 1;

      if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
        current_average=current_total/number_of_readings;
        voltage_average=voltage_total/number_of_readings;
        Serial.print("Current average=");
        Serial.print(current_average);
        Serial.print("   Voltage average=");
        Serial.println(voltage_average);
        current_total=0;
        voltage_total=0;
        index=0;

      }

      float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
      float current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
      float current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
      float power = (voltage*current); //calculate power

     u8g.firstPage();
      do {
        draw();
      } while( u8g.nextPage() );

    }

The function of the code is to read data from a "ACS712 - 30A Range Current Sensor Module" and a "Voltage Detection Sensor Module".
Display is a "0.96 inch 128x64 OLED Display Module - SPI/I2C - 7 Pin    ", it is converted to I2C, and working with other codes.
Board : Arduino Uno
Max input voltage will be 12.8V, DC.
The code is supposed to display the voltage on top, ampere in the middle, and watt usage at the bottom.
But it is not working when edited for OLED display.
Someone please make this a working code.
I am new to C+ and coding , so need detailed help.
Here is the code that worked with 16X2 LCD
#include <LiquidCrystal.h>
#include <Wire.h>

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

/*The circuits
 * LCD RS pin to digital pin 12
 * LCD enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4                                                             21333333
 * LCD D6 pin to digital pin 3
 *
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * 10K resistor
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)
 */

byte lightning[8] = {
  B00001,
  B00110,
  B01100,
  B11000,
  B00011,
  B00110,
  B01100,
  };

int index = 0; //size of array
const int number_of_readings = 200; //total number of readings arduino takes before it averages
const int current_zero = 510; //initial value of current from arduino with 0 amps
int current_reading[number_of_readings]; //create array for current_reading
int voltage_reading[number_of_readings]; //create array for voltage_reading

float R1=30000; //resistance of R1 in voltage sensor
float R2=7500; //resistance of R2 in voltage sensor
float current_average = current_zero; //initial value of current average
float current_total = 0; //initial value of current_total
float voltage_average = 0; //initial value of voltage_average
float voltage_total = 0; //initial value of voltage_total

void setup (){
  Serial.begin (9600);
  lcd.begin(16,2); // size of LCD
  lcd.createChar(6,lightning); //create charecter named lightning

  //STARTUP MESSAGE
  lcd.setCursor (3,0); //set cusror to row 0, column 3
  lcd.print(" "); //lcdprint
  lcd.print("Arduino"); //lcdprint
  lcd.setCursor(1,1); //set cursor to row 1, column 1
  lcd.write(6); //lcd write charecter 6 (lightning bolt)
  lcd.print("Power Meter"); //lcd.print
  lcd.write(6); //lcd write charecter 6 (lightning bolt)
  delay(5000); //delay by 5 seconds
  lcd.clear();  //clear lcd screen
  }

void loop() {
  voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
  voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
  current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
  current_total = current_total + current_reading[index]; // add current to current_total
  index = index + 1;

  if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
    current_average=current_total/number_of_readings;
    voltage_average=voltage_total/number_of_readings;
    Serial.print("Current average=");
    Serial.print(current_average);
    Serial.print("   Voltage average=");
    Serial.println(voltage_average);
    current_total=0;
    voltage_total=0;
    index=0;

  }
  float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
  float current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
  float current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
  float power = (voltage*current); //calculate power

  lcd.clear(); //print voltage, current, and power values to LCD screen
  lcd.setCursor(0,0);
  lcd.print(voltage);
  lcd.print("V");

  lcd.print (" ");
  lcd.print(current);
  lcd.print("A");

  lcd.setCursor(0,1);
  lcd.print(power);
  lcd.print("W");
  delay(1);

}

 it is not working in that way. what do you mean by this?

@Vaibhav, it was a mistake, It is not working, that is what I mean.

In your Sketch
void draw(void)
{
   u8g.setFont(u8g_font_fub14r);
   u8g.drawStr(0, 20, "V: ");
   u8g.drawStr(0, 40, "A: ");
   u8g.drawStr(0, 60, "Watt: ");
   u8g.setPrintPos(58,20);
   u8g.print( Bat_Volt,2);
   u8g.println("V");
   u8g.setPrintPos(58,40);
   u8g.print( current,0);
   u8g.println("mA");
   u8g.setPrintPos(58, 60);
   u8g.print( power ,1);
}

current, power, Bat_Volt are local variables define in loop function. Bat_Volt in not even defined in your sketch that's why they are not printing anything in draw function.
Initialize then as global variable in your sketch and in place if Bat_Volt you had use voltage here float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read in your sketch.
Correct that to.
Your code after edit:
#include <SPI.h>
#include <Wire.h>
#include "U8glib.h"  //Library for display

U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C interface for OLED

int index = 0; //size of array
const int number_of_readings = 200; //total number of readings arduino takes before it averages
const int current_zero = 510; //initial value of current from arduino with 0 amps
int current_reading[number_of_readings]; //create array for current_reading
int voltage_reading[number_of_readings]; //create array for voltage_reading

float R1=30000; //resistance of R1 in voltage sensor
float R2=7500; //resistance of R2 in voltage sensor
float current_average = current_zero; //initial value of current average
float current_total = 0; //initial value of current_total
float voltage_average = 0; //initial value of voltage_average
float voltage_total = 0; //initial value of voltage_total
float voltage = 0.0,current_mV = 0.0,current = 0.0,power = 0.0;

int x = 0;
int row = 0;
float voltage = 0.1;

  void setup() {
   Serial.begin(9600);
   pinMode(A4,INPUT_PULLUP);
   pinMode(A5, INPUT_PULLUP);
  }

  void draw(void) {
   u8g.setFont(u8g_font_fub14r);
   u8g.drawStr(0, 20, "V: ");
   u8g.drawStr(0, 40, "A: ");
   u8g.drawStr(0, 60, "Watt: ");
   u8g.setPrintPos(58,20);
   u8g.print( voltage,2);
   u8g.println("V");
   u8g.setPrintPos(58,40);
   u8g.print( current,0);
   u8g.println("mA");
   u8g.setPrintPos(58, 60);
   u8g.print( power ,1);
}

 void loop() {
  voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
  voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
  current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
  current_total = current_total + current_reading[index]; // add current to current_total
  index = index + 1;

  if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
    current_average=current_total/number_of_readings;
    voltage_average=voltage_total/number_of_readings;
    Serial.print("Current average=");
    Serial.print(current_average);
    Serial.print("   Voltage average=");
    Serial.println(voltage_average);
    current_total=0;
    voltage_total=0;
    index=0;

  }

  voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
  current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
  current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
  power = (voltage*current); //calculate power

 u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );

}

Thank you for the reply, I have corrected the "Bat_Volt" into "voltage", but while saving it is showing error "'current' was not declared in this scope". is possible please edit the code for me.

declare current , power, voltage globally. You will get this error removed.

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


text:
Python script not reading from serial unless teensy is rebooted
I want to send some analog sensor data from a Teensy 3.2 to a mac running a python script (I am using the usual pyserial module and I send data using Serial.print() in the arduino sketch). I am using Teensy but I guess the same would be true for an Arduino Uno.
The teensy is correctly sending on the serial port the data, as I can see it using the serial monitor. However, only the first time that I run the python script the data are handled by the script itself, if I stop the script then no data seem to be read in the serial buffer. To make the script work I necessarily have to re-launch the Arduino IDE and then upload the sketch.
Indeed the second time I run the script (after having stopped it), I can see that the pyserial function serial_port.inWaiting() does not give any data.
if (serial_port.inWaiting() > 0):
   print("serial_port.inWaiting() > 0") # does not print anything the second time I launch the script

I have checked that the second time that I launch the script the serial connection is open (using self.serial_port.isOpen())
What is preventing the python script to get the serial data the second time? Why serial_port.inWaiting() is not seeing that there is data in the input buffer?
In the arduino sketch code I have added the line while(!Serial); in void setup()
EDIT: I post the code. This is the arduino code (I am testing on teensy so no initial handshaking is required as teensy will not reboot)
int sensor = 0;

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

void loop() {

  sensor = analogRead(0);
  Serial.print(sensor);
}

And this is the python code:
#!/usr/bin/env python3

import serial
import time
import signal
import sys

def keyboard_interrupt(signal, frame):
    serial_port.close()
    time.sleep(2)
    exit(0)

serial_port = serial.Serial("/dev/tty.usbmodem1225061", 115200)

signal.signal(signal.SIGINT, keyboard_interrupt)
signal.signal(signal.SIGTERM, keyboard_interrupt)

if serial_port.isOpen():
    print(serial_port.name + ' is open...')

while True:
    if (serial_port.inWaiting() > 0):
        sensor = serial_port.read().decode("utf-8")
        print('sensor: "{}" '.format(sensor))

I discovered so far that in_waiting is returning 0 after the script is launched the second time. I can't figure out why. Any idea?

Serial communication is always terminated with a specific character (usually \n). The receiving device will accumulate the incoming bytes in a buffer until it receives this terminating character.
To fix the problem simply change the last line of your arduino loop to Serial.println(sensor);
Also note that the arduino might be faster than your python script, meaning that you will get several sensor values per readout. If that's the case you have to add a short delay in the arduino loop.


text:
Reading serial buffer taking newline character instead of user input
I am trying to compare whether the user input matches a user ID or not. When I read the input from serial, the program is taking the last character which is newline char '\n' and moving it into the char data value to compare against the stored user ID and I don't understand why it's taking the '\n' value instead of the actual user input.
int Gled = 7;
int Rled = 8;
int wait = 5000;
char UserID = "12345";
char data;
char incoming;

void setup() {
  Serial.begin(9600);
  pinMode(Gled,OUTPUT);
  pinMode(Rled,OUTPUT);
  Serial.println("Please Enter your username or ID:");
}

void loop() {
  if(Serial.available()>0) {
    while(1) {
      data=Serial.read(); //read user input and move to data char
      if(data !='\n')
        incoming = data; //if data doesn't equal newline data = incoming
      if (data == '\n')
        break; // newline char detected break
      if (data == -1) //continue reading all of user input
        continue;
      Serial.print(data);
      Serial.print(incoming);
    }
    Serial.println(incoming);
    if(incoming == UserID) { //if user input matches run statement
      digitalWrite(Gled, HIGH);
      Serial.println();
      Serial.println("Access Granted");
      Serial.println("Hello User Name");
      delay(wait);
      Serial.println("Login time exceeded, you are now logged out.");
      Serial.println("Reenter your UserID to log back in.");
      digitalWrite(Gled, LOW);
      Serial.end();
      Serial.begin(9600);
    } else if(incoming != UserID){
      //user input doesn't match run statement
      digitalWrite(Rled, HIGH);
      Serial.println();
      Serial.println("Access Denied");
      Serial.end();
      delay(wait);
      Serial.begin(9600);
      digitalWrite(Rled, LOW);
      Serial.println("Please Enter a Valid ID to Continue.");
    }
  }
}

Your whole data reading and user ID storage and comparison is completely wrong.

Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Some parts of this can help too: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

Thanks for those links, I read them and figured out what I was doing wrong.

if(data !='n')

This should be
if(data !='\n')

NEXT.
data=Serial.read();

only reads ONE character. You should add to a buffer, not assign a single character.

Thats my mistake for leaving that in there I had already copied the text before fixing that typo but the program still has the same issue.

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


text:
How to use this Arduino code to control multiple different LEDs?
I am making an Android-controlled LED system over Bluetooth but I need to use 4 LEDs. I have done Android app but I am not able to figure out this Arduino code. Can some please help me get this done?
char command;
String string;
boolean ledon = false;
#define led 5

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    string = "";
  }

  while(Serial.available() > 0) {
    command = ((byte)Serial.read());
    if(command == ':') {
      break;
    } else {
      string += command;
    }
    delay(1);
  }

  if(string == "TO") {
    ledOn();
    ledon = true;
  }

  if(string =="TF") {
    ledOff();
    ledon = false;
    Serial.println(string);
  }

  if ((string.toInt()>=0)&&(string.toInt()<=255)) {
    if (ledon==true) {
      analogWrite(led, string.toInt());
      Serial.println(string);
      delay(10);
    }
  }
}

void ledOn() {
  analogWrite(led, 255);
  delay(10);
}

void ledOff() {
  analogWrite(led, 0);
  delay(10);
}

what is the data format sent for android? what is the results expected?

you only define 1 led but want to control 4?

android application is sends code like TO & TF for on&off respectively the result i want is to switch 4 leds on and off by those commands which are sent by android app over bluetooth

yup i actualy got this code from a website em a total newbie to this so i have no idea

Its better if you use SoftwareSerial for Bluetooth, so the native serial port can be used to debugging. But in case you doesn't need them:
uint8_t led[4] = {5,6,7,8}; // pin for LED 1,2,3,4
char command1,command2;
String string;
  void setup()
  {
    Serial.begin(9600);
    for (int i=0; i<4; i++)
        pinMode(led[i], OUTPUT); //set all LED pin as OUTPUT
  }

  void loop()
  {
    if (Serial.available() > 1) //run if 1 bit or more data received
    {
    string = "";
        command1 = Serial.read();
        command2 = Serial.read();
        switchled(command1-'0',command2-'0');
    string = command1+command2;
    }
    delay(1);
  }
void switchled(char pinLED,char statusLED)
{
    if (statusLED == 0 || statusLED == 1)
    digitalWrite(led[pinLED-1],statusLED);
    else
    digitalWrite(led[pinLED-1],!digitalRead(led[pinLED-1]));

    Serial.print("LED ");
    Serial.print(pinLED);
    Serial.print(" = ");
    Serial.print(digitalRead(pinLED));
}

The code reads 2 byte of data, so if your phone sent "11" the 1st led will turned on, and "10" will turn the 1st led off. The first digit is the LED index (1/2/3/4) and the second digit is the LED state (0/1), other than that, the LED on selected index will be toggled;

the following error comes up when trying to compile ---string was not declared in this scope --- if (Serial.available() > 1) //run if 1 bit or more data received     {     string = ""; // ---string was not declared in this scope ---         command1 = Serial.read();

still unable to compile shows ";" expected before string but adding that gived another error please verify the code

updated answers

still compilation error please check it on the software then upload

There are a million reason of compilation error. I compiles successfully. Please keep in mind that I have no obligation to do this "app" of yours, I am just trying to help. Do some effort, this is not "please-make-me-a-code.com". I'm out of here.

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


text:
Driving numerous chips from 2 separate SPI connectors w/ Arduino Micro
I want to drive numerous chips (L9823, TLC5925, ADG1414, MCP23S08) from an Arduino Micro as well as read input from analog pins connected to momentary buttons, toggles, potentiometers and such. The chips and input controls will be on various boards connected to the Arduino using ribbon cables.
The current idea is to have two sets of 8 pin FFC connectors with the following pins:
FFC digital "bus" conductors:
--
SCLK
VL
SDI
RST
SDO
LE3
LE2
LE1

The clock, VL (5V), SDI and SDO will be shared by both connectors but I still need 6 latches (which can also be commandeered for an interrupt or analog input) and 2 reset pins. This will allow me to run up to 3 types of chips per connector (minus latches used for something else).
I will also have a third 8-conductor FFC connector for 7 analog inputs (the eighth conductor is 5V analog ref).
So my question is, does anyone see any holes in this strategy? I don't think I'm going to try to even breadboard something like this. PCB fab is so easy now (and the first run is always wrong anyway) so I'm just going to make the boards and go from there.
So I just need to settle on what pins to use. Here is a diagram of the Arduino Micro:

So the connectors could use pins:
Connector 1 - Digital I/O:
--
SCLK SCK
VL   5V
SDI  MOSI
RST  11
SDO  MISO
LE3  A8
LE2  A7
LE1  SS

Connector 2 - Digital I/O:
--
SCLK SCK
VL   5V
SDI  MOSI
RST  13
SDO  MISO
LE3  A9
LE2  7 (Arduino INT)
LE1  5

Connector 3 - Analog Inputs:

5V
A0
A1
A2
A3
A4
A5
A6

A10 and A11 are reserved for other purposes as well.
Does this look ok?
UPDATE 1:
I have updated the text of this question to consider many of the great comments. The changes include:

Share MISO and MOSI
between connectors. Not sure why I thought I needed to use separate
ports for the different connectors. SLCK, MISO and MOSI should
indeed be shared by both connectors.
Moved 5V to be in between
SCK and MISO and moved RST to be in between MISO and MOSI. The idea
is that the low impedance of these lines will shield from capacitive
crosstalk described by Majenko. The connectors are 1mm pitch which
isn't terribly small so hopefully this will not be an issue. It does
make routing a little harder since the data pins tend to be next to
each other but the same bus is going to connect to multiple boards
in a daisy chain fashion so capacitive crosstalk could definitely be
an issue. Fortuntely things don't have to run really fast since
everything is ultimately for interfacing with humans who are
relatively slow.

The micro only has one SPI bus. It is SCK/MISO/MOSI. You may want a second one, but you don't have one.  You can't magic one up out of thin air.
You could emulate one in pure software (bit-banging) but it won't be anywhere near as efficient as using a real hardware one.
Why do you feel you need to have two independent buses anyway? What are you wanting to achieve that you can't achieve with a single shared bus? That same bus can quite happily appear on multiple connectors.
One thing to note with your strategy: Ribbon connectors and SPI don't mix well together.  There is a lot of crosstalk and capacitance in a ribbon cable that high speed serial communication really doesn't like.  If I had to use ribbon cable for SPI communication for anything longer than a couple of inches I would use twice as many connections and interleave ground between each signal.  That is what the ribbon cables for later IDE drives in PCs used to get higher speed, more reliable, communication down ribbon cables.

I have a bit-banged SPI library on my page about SPI. For low-ish speeds that could be perfectly acceptable.

The MOSI (Master Out Slave In) and MISO (Master In Slave Out) will be much better for your SPI pins. Your SDI (Slave Digital In iirc) will equate to MOSI and your SDO (Slave Digital Out iirc) will equate to MISO. Those are the hardware SPI pins and will be much better than trying to emulate SPI in software.

But I want 2 buses. Meaning I want 2 channels of SPI so that I can have 2 cables with different latches (2 x 3 = 6 latches). So you can't use other pins for SPI without "emulating"? What about pins 2 and 3. It seems they are used for I2C communication so perhaps they can be jerry rigged for SPI? None of this needs to be terribly fast. Even 125 KHz would be fine I think.

Could you have one bus that splits off on your PCB to both connectors?

You have SDI and SDO backwards there. SDO is Serial Data Out and is the same as MOSI - SDI is Serial Data In and is MISO. It's the flow of serial data as seen from the master.

Thanks. I have updated the question. Yes, I definitely can share MISO and MOSI on both connectors. Not sure why I thought I needed separate pins for that. Also I corrected the reversed MISO and MOSI lines.

@Majenko It depends on what datasheet you're looking at in my experience. For example, the MAX31865 IC datasheet here: https://datasheets.maximintegrated.com/en/ds/MAX31865.pdf has the SDI line as an input to the MAX31865, not as an output to the micro.

Actually SDI and SDO were not backwards. The input of each chip needs to connect to the output of the uC. MOSI sends data to SDI and SDO sends data to MISO.

authors: ณัฐนันท์ กัญจนกาญจน์


text:
Multiple defintion error, Linker error
Trying to create an elf file for two sets of files in different folders.
LIDARBOT.h
-----------
#ifndef LIDARBOT_H_
#define LIDARBOT_H_

#include <avr/io.h>
#include "drivers/motors.h"

#endif

LIDARBOT.C
----------
#include "LIDARBOT.h"
int main(){
  pwmtimersetup();
    while (1) {
    }
}

motors.h
--------
#ifndef MOTORS_H_
#define MOTORS_H_

#include <avr/io.h>

void pwmtimersetup(void);

#endif

motors.c
--------
#include <avr/io.h>
#include "motors.h"

void pwmtimersetup(void){
  // Timer pre-scalar for ~490 Hz is 8
  TCCR0B &= ~((1<<CS02)||(1<<CS00));
  TCCR0B |=  (1<<CS01);
  // Set Compare Output Mode to Toggle PWM
  TCCR0A &= ~(1<<COM0A1);
  TCCR0A |=  (1<<COM0A0);
  // Waveform Generation Mode: WGM02 = 1, WGM01 = 1, WGM00 = 1
  TCCR0B |= (1<<WGM02);
  TCCR0A |= (1<<WGM01)||(1<<WGM00);
  OCR0A = 125;
  DDRD |= (1<<DDD4)||(1<<DDD2);
  PORTD |= (1<<PORTD4);
  PORTD &= (1<<PORTD2);
}

I can make a consolidated object file but not an elf file to load onto my board. Output below:
avr-gcc -g -Os -Wall -Werror -Wextra  -mmcu=atmega328p -DF_CPU=1000000UL -Wa,-ahlmns=LIDARBOT.lst -o objects/LIDARBOT.o \
source/LIDARBOT.c \
source/drivers/motors.c \
-I/home/manu/C/Arduino/LIDARBOT/libraries/

avr-gcc -g -Os -Wall -Werror -Wextra -mmcu=atmega328p -DF_CPU=1000000UL -o elf/LIDARBOT.elf objects/LIDARBOT.o
objects/LIDARBOT.o: In function `__vector_22':
(.text+0x7c): multiple definition of `__bad_interrupt'
/usr/lib/gcc/avr/5.4.0/../../../avr/lib/avr5/crtatmega328p.o:(.text+0x0): first defined here
objects/LIDARBOT.o: In function `__vectors':
(.text+0x0): multiple definition of `__vectors'
/usr/lib/gcc/avr/5.4.0/../../../avr/lib/avr5/crtatmega328p.o:(.vectors+0x0): first defined here
collect2: error: ld returned 1 exit status
make: *** [Makefile:191: elf] Error 1

I am kind of lost. What could be my mistake here? If I see an error like this how do i start to debug?

I realized that i did not need to add #include <avr/io.h> in the motors.c file. I removed that and tried it again. Same error.

What exactly are you trying to do by the first avr-gcc command line? In that command line I see multiple source files, only one output file and no -c? This looks like a full compile and link, but saving the resultant elf as an .o file. But why? What am I missing?

You forgot the -c flag to your first command. That means you have first compiled your program into a full elf file. Then you try to link that elf file with the standard startup libraries again (it already contains them) into another new elf file.
And so you get duplicate entries in it.
Add -c to your first command, which means "compile only, don't link" to create object files not an elf file.

Thank you guys for your input, AnT and Majenko. I realized my issue which was trying to link a .o file into another one. So I corrected my make file by individually compiling but not linking the source files with the -c option. I then made my final elf file using the unlinked .o files.


text:
measure +3V and -3V through resistor divider and switch on/off by digital pins
I've seen that resistor dividers can be used to read negative voltages, but I'ld like if there is a way to accomplish this with less components and having a way to turn this off.
I was thinking if there would be an extreme option of changing from pinMode INPUT to INPUT_PULLUP or INPUT_PULLDOWN to power the circuit and use the 20k pullups to make part of the divider, together with another resistances on the input. Alternatively, switching from INPUT to OUTPUT would be fine.
What I want to measure is an external +3V/GND/-3V power supply (battery pack) that shares the GND with the arduino SAMD21 (3.3V), measuring both +3V and -3V, and avoiding drain when not measuring (hence the pin mode changes)
Currently I'm using this schema to measure the voltage of +5V supply battery (connected through VIN, thus using the internal regulator), by dividing with 2 1Mohm resistances, ground to digital pin and measurement by internal adc. I don't need so much precision, so this is enough here. So I'm looking for the same or better alternatives, but for the -3V I don't know how to properly calculate the 3 resistor divider.

When measuring a voltage that is higher than the maximum rating, the voltage of interest is tied to ground with a voltage divider. When measuring a negative voltage, you instead have to tie the voltage of interest to the positive supply voltage (study the answers to this question).
In theory you can use the internal pullup to spare one resistor, but I would consider this a bad practice and recommend using an external pullup for the following reasons:

a uC's internal pullups/-downs are not accurate and sometimes not specified
especially when measuring negative voltage, chances are that harmful voltage is applied to the adc (consider the default state of a gpio)
a pullup/-down is an uncritical component concerning its value and precision. Therefore they are very cheap

Two 1M resistors for a voltage divider is high. You could add a capacitor (1nF or 10nF) to GND and the analog input.
Could you try to find what the leakage current or the self-discharge current of the battery itself is? Then take a percentage of that, for example 20%, then calculate what resistor value the voltage divider should be.
It does not have to be 20%, it can be any current that you are willing to give up to be able to measure the voltage.
For example, when the battery has a self-discharge current of 10µA, then 20% is 2µA, which is two resistors of 825kΩ. That happens to be close to the 1M resistors that you already use.

Yes, 1M resistor were high, but I tried with 10k ones and behaviour was bad. Later, I deduced that the reason was that I was switching the digital pin (low) from output to input to avoid consumption, and when left floating, the analog pin was receiving 5V (for a 3.3V MCU...). Probably it works with 1M due to very low current, but I've also to change that.

@avelo there will be no relevant consumption. Why do you switch "to input"? When using the adc the corresponding gpio is an input allready. The adc only sinks a very small current to charge its sample-and-hold circuitry (small capacity).

@SimSon i was using an analog (A1) pin in the middle of the divider, and a digital one (6) at the end to connect to ground digitalWrite(6,LOW); pinMode(6,OUTPUT); when measuring (disconnecting by changing it to INPUT). Just as a way to save the 5/20k power waste. With 2*1Mohm the consumption drop to irrelevant as you said, so no reason to use the digital pin for that (and I'll have the +5V problem if let it floating), I agree!


text:
Run a loop for only 60 secondes
How do run a code on arduino for only 60 secondes and than shut it down? I know I have to use the millis() function, but I do not know how to it in my code. Sorry if it looks unclear, but I only need to know how to program the millis() function. This is my first code so I have no experience.
int main(void)
{
pin_mode(A13,INPUT);
pin_mode(A12,INPUT);
pin_mode(A11,INPUT);
pin_mode(A10,INPUT);
pin_mode(A15,INPUT);
pin_mode(D0,OUTPUT);
pin_mode(D1,OUTPUT);
pin_mode(D2,OUTPUT);
pin_mode(D3,OUTPUT);

while (1)
{
    int potmeter1 = read_analog_pin(A13);
    if (potmeter1 >= 1000 && potmeter1 < 1100){
    gen_pwm(D0, 1000, 100);

        int potmeter2 = read_analog_pin(A12);
        if (potmeter2 >= 2000 && potmeter2 < 2050){
        gen_pwm(D1, 1000, 100);

            int potmeter3 = read_analog_pin(A11);
            if (potmeter3 >= 500 && potmeter3 < 525){
                gen_pwm(D2, 1000, 100);

                    int potmeter4 = read_analog_pin(A10);
                    if (potmeter4 >= 3500 && potmeter4 < 3510){
                        gen_pwm(D3, 1000, 100);

    {
        int lichtsensor = read_analog_pin(A15);
        if (lichtsensor >= 2000 && lichtsensor < 3500 && potmeter1 >= 1000 && potmeter1 < 1100 && potmeter2 >= 2000 && potmeter2 < 2050 && potmeter3 >= 500 && potmeter3 < 525 && potmeter4 >= 3500 && potmeter4 < 3510){
            gen_pwm(D0, 1000, 100);
            gen_pwm(D1, 1000, 100);
            gen_pwm(D2, 1000, 100);
            gen_pwm(D3, 1000, 100);
            _delay_ms(250);
            gen_pwm(D0, 1000, 0);
            gen_pwm(D1, 1000, 0);
            gen_pwm(D2, 1000, 0);
            gen_pwm(D3, 1000, 0);
            _delay_ms(250);

        }
    }
                }else{
                gen_pwm(D3, 1000, 0);
                }
            }else{
            gen_pwm(D3, 1000, 0);
            gen_pwm(D2, 1000, 0);
            }
        }else{
        gen_pwm(D3, 1000, 0);
        gen_pwm(D2, 1000, 0);
        gen_pwm(D1, 1000, 0);
        }
    }else{
    gen_pwm(D3, 1000, 0);
    gen_pwm(D2, 1000, 0);
    gen_pwm(D1, 1000, 0);
    gen_pwm(D0, 1000, 0);
    }

                }
            }

I have merged my program with your program and I have added the #include "Arduino.h". The millis() function is colored now and works. My code still won't stop at 60 secondes, did I do something wrong?
#include "hva-xmega.h"
#include "Arduino.h"

unsigned long EndTime;

void setup()
{
    pin_mode(A13,INPUT);
    pin_mode(A12,INPUT);
    pin_mode(A11,INPUT);
    pin_mode(A10,INPUT);
    pin_mode(A15,INPUT);
    pin_mode(D0,OUTPUT);
    pin_mode(D1,OUTPUT);
    pin_mode(D2,OUTPUT);
    pin_mode(D3,OUTPUT);

    EndTime = millis() + (60*1000L);
}

void loop() {
    if( millis() < EndTime ){

while (1)
{
    int potmeter1 = read_analog_pin(A13);
    if (potmeter1 >= 1000 && potmeter1 < 1100){
        gen_pwm(D0, 1000, 100);

        int potmeter2 = read_analog_pin(A12);
        if (potmeter2 >= 2000 && potmeter2 < 2050){
            gen_pwm(D1, 1000, 100);

            int potmeter3 = read_analog_pin(A11);
            if (potmeter3 >= 500 && potmeter3 < 525){
                gen_pwm(D2, 1000, 100);

                int potmeter4 = read_analog_pin(A10);
                if (potmeter4 >= 3500 && potmeter4 < 3510){
                    gen_pwm(D3, 1000, 100);

                    {
                        int lichtsensor = read_analog_pin(A15);
                        if (lichtsensor >= 2000 && lichtsensor < 3500 && potmeter1 >= 1000 && potmeter1 < 1100 && potmeter2 >= 2000 && potmeter2 < 2050 && potmeter3 >= 500 && potmeter3 < 525 && potmeter4 >= 3500 && potmeter4 < 3510){
                            gen_pwm(D0, 1000, 100);
                            gen_pwm(D1, 1000, 100);
                            gen_pwm(D2, 1000, 100);
                            gen_pwm(D3, 1000, 100);
                            _delay_ms(250);
                            gen_pwm(D0, 1000, 0);
                            gen_pwm(D1, 1000, 0);
                            gen_pwm(D2, 1000, 0);
                            gen_pwm(D3, 1000, 0);
                            _delay_ms(250);

                        }
                    }
                    }else{
                    gen_pwm(D3, 1000, 0);
                }
                }else{
                gen_pwm(D3, 1000, 0);
                gen_pwm(D2, 1000, 0);
            }
            }else{
            gen_pwm(D3, 1000, 0);
            gen_pwm(D2, 1000, 0);
            gen_pwm(D1, 1000, 0);
        }
        }else{
        gen_pwm(D3, 1000, 0);
        gen_pwm(D2, 1000, 0);
        gen_pwm(D1, 1000, 0);
        gen_pwm(D0, 1000, 0);
            }
        }
    }
}
 else {
     // Time is up! Hang here
     for(;;)
     ;      // infinite loop here stops further processing
    }
 }

look at the BlinkWithoutDelay example code in the Arduino IDE

It doesn't look like you are using an Arduino core. What framework are you using? Does it provide something similar to millis()?

note: the long if statement is unnecessarily long ... you are testing values that were tested already

My university designed his own board, but it uses a atxmega256a3u microcontroller. I do not know if it provide something similar as millis().

@DennisdeKruijf, it is not Arduino. it is a proprietary board and library. we can't help you

I can use the same libraries as arduino so I think it's about the same idea. But maybe I am wrong. I am using C to program with the program Atmel Studio and it look like the same environment as arduino.

Your indentation is completely messed up, and it would seem you have unbalanced braces.

Note that in an Arduino environment, main() is already provided for you. It calls your function void setup(void){ ... } once, then loops forever, calling your function void loop(void){ ... }. Either function may be empty but both must be present.
Without going into the specifics of your code, here is a program that fits the Arduino conventions, and will execute some procedure for 60 seconds, then hang, doing nothing:
unsigned long EndTime;

void setup()
{
   // Any setup code you need goes here.

   EndTime = millis() + (60*1000L);
}

void loop() {
   if( millis() < EndTime ){
      // Do your processing here
   }
   else {
      // Time is up! Hang here
      for(;;)
         ;      // infinite loop here stops further processing
   }
}

My setup codes are the pin_modes right? and everything below is my
  processing?

Update:
Correct - Put pin modes and anything else that needs to be done once, at the beginning of the run in setup(). Everything else goes in loop().
Or if you're more comfortable writing your entire program starting with main() (as we do in other environments than Arduino), you can use the setup() function exactly as you would use main(), and leave loop() empty. The idea of a loop function is that embedded programs are typically not meant to end as long as the device has power. There are instances when this isn't strictly true and you seem to have one example.

I have
  to remove the int main(void) from my code when I use your code right?

Correct - the Arduino environment provides a main() function, so writing your own - within that environment - would result in a multiple-definition error.
Update 2:
"WProgram.h" is obsolete. Instead, use: #include <Arduino.h>. There is no function called elapsedMillis(), just millis(). You won't need an include statement for it, or any of the other standard or common stuff: Serial I/O, digital I/O, analog I/O, pin definitions for specific boards, etc. 'Arduino.h' pulls in all that stuff. Your university should have add a description of the proprietary board to the Arduino's board description file.
(But if you/they are not using standard Arduino libraries, board descriptions, etc., then there is a lot of behind-the-scenes "housekeeping" you may be responsible for. That isn't something we can know; you may have to ask those kinds of questions of others more familiar with your university's programming environment. I think it is unlikely they would abandon the existing/working resources, but it's something to keep in mind.)

Alternatively, if (millis() >= 60000) exit(0);.

My setup codes are the pin_modes right? and everything below is my processing? I don't have much knowledge about programming ^^ . I have to remove the int main(void) from my code when I use your code right? @JRobert

problem is, it is not Arduino, so the answer is not applicable

I have done exactly what you said and my program still works fine, except the millis() function. I have added the #include "elapsedMillis.h" library, but the millis() function stays as a normal text, so my program doesn't stop after the 60 secondes. Furthermore it can't find the WProgram.h: file or directory. Do you maybe know how to fix that? @JRobert


text:
Are my stepper motors being burnt out? What is the issue here?
I am building a mini-cnc laser engraver as shown in this intructable and this youtube video.
I have built the circuit (minus the jst connector and two male pins at the top left of the board) and have attached a stepper motor from a dvd drive. It worked like a charm, but made a loud ringing noise (like tinnitus.) I proceeded to test it with laser GRBL, and it moved great, but gradually started missing steps, at first only in one direction and eventually in both. After a couple hours of being connected, it wouldn't budge at all. I switched the motor for another motor, and tested it again. This time the motor was much shorter-lived. It made 5 steps perfectly and then just shut off. You could hear the motor try to turn, but it was like it didn't have any torque at all. What could be the issue? (I also tried it on the other axis with the other motor driver, no change.)
It's also worth noting that at one point both the positive and negative (ground) cables from my power supply made contact with metal at once, throwing a spark. However, the steps were already beginning to be lost before that happened.
As per your request, I have attached the circuit layout I am attempting (it's identical to the one in the tutorial) as well as a picture of my physical circuit board. (sorry, a link was my only option as the pics were to big for upload) I know the soldering is pretty bad- I have a giant soldering iron. I don't see any shorts though.

At what voltage did you run those steppers?

@Gerben im going to be completely honest, ive never attempted anything with circuit boards or arduino before. I followed the instructables, which tells me to use a 12v power supply on the screw terminal after everything is hooked up. – Drake Ford just now    Edit    Delete

Your steppers might be 5V instead of 12V. Or his are 5Volt to, but has set the A4988 Motor Drivers to limit the current (with the small potentiometer on the board).

To progress this further I think you'd need to edit your answer to add the part number(s) of your components (preferably along with with their specifications) and along with the schematic / circuit layout you have implemented (rather than the one from the tutorial).

@AJP I have done as you suggested

You can upload images as part of your question, you know. That is far preferable to sending people off-site to some link that might go down in a year, making the question hard to follow. I also don't see the part numbers that were requested.

Sorry my suggestion of a circuit layout was only partially useful as this is what you hope you've wired up @DrakeFord but it's always good to see the actual wiring up.  And as Nick's suggested a picture of your circuit plus a picture of the intended circuit layout would be good.  There might be a simple mistake here.
And secondly again, what are the motors you are using (their part numbers) and their resistance and amperage. You'll need these to know if they'll work with your A4988 drivers: https://learn.adafruit.com/all-about-stepper-motors/matching-the-driver-to-the-stepper

@AJP I had to link my pictures of my circuit- they were too large for upload. I do not have my stepper motor part number, since they were harvested from a DVD drive. My DVD drive model number is LITE-ON SOHW-1633S

You can scale the pictures down.
There should be some part numbers on it somewhere.  Is there no writing on it?  Not a stuck on paper label.  No dot matrix printed numbers.  Nothing?  If you can't find out exactly what the motors are and are capable of I'd go back to experimenting (though you may fry your driver if the motors draw too much current).  Try measuring the voltage and current and see if it's acceptable for your A4988 drivers.  If so try reducing the speed of driving the motors.  Also try with them disconnected from any physical load... maybe they're just stalling.

@AJP the only number i see is E232171 which is printed onto the flexible pcb where the 4 solder joints are on the motor. other than that, nothing. The motors have no physial load.

You seen this @DrakeFord? https://www.eevblog.com/forum/projects/dvd-rw-(liteon)-teardown-stuff-details-(motors-laser-diodes-ir-red-visual-etc)/msg706604/?PHPSESSID=o815ofg9mgsifeduvk0akvpsa0#msg706604

@AJP yes I have. I am suspecting that I might have a bad voltage regulator on the board and that it is feeding 12V into the 5V Stepper. Maybe replace the voltage regulator?

@DrakeFord if you think the voltage regulator is at fault then isolate that first.  If it's producing 12V you'll likely be damaging other components.  If you have a DVM (Digital Volt Meter) then measure it's output and see if it's behaving as intended before just replacing it.  If you don't have a DVM, then borrow or buy one... it's an essential (and cheap) bit of kit of hobby electronics.  When debugging all these problems following this guidance is very powerful: https://stackoverflow.com/help/minimal-reproducible-example  As you reduce the size of your problem it becomes easier to solve it.

So the problem was that somehow the potentiometer had reset its own vref output. I couldn't adjust it after it did this. I replaced both drivers and it works like a charm now.


text:
ESP32 cam board and waking from deep sleep
I am getting an error that the sd card cant be mounted when the ESP32 comes out of deep sleep. The board is coded to wake up on a timer from deep sleep and mount the sd card and take a picture. My question is how can I get the SD card to mount properly? I am providing 3volts to the board and I think the same error happens when 5volts is applied. Here is the code:
/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-cam-take-photo-save-microsd-card

  IMPORTANT!!!
   - Select Board "ESP32 Wrover Module"
   - Select the Partion Scheme "Huge APP (3MB No OTA)
   - GPIO 0 must be connected to GND to upload a sketch
   - After connecting GPIO 0 to GND, press the ESP32-CAM on-board RESET button to put your board in flashing mode

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

#include "esp_camera.h"
#include "esp_timer.h"
#include "img_converters.h"
#include "Arduino.h"
#include "fb_gfx.h"
#include "fd_forward.h"
#include "fr_forward.h"
#include "FS.h"                // SD Card ESP32
#include "SD_MMC.h"            // SD Card ESP32
#include "soc/soc.h"           // Disable brownour problems
#include "soc/rtc_cntl_reg.h"  // Disable brownour problems
#include "dl_lib.h"
#include "driver/rtc_io.h"
#include <EEPROM.h>            // read and write from flash memo
// define the number of bytes you want to access
#define EEPROM_SIZE 1

RTC_DATA_ATTR int bootCount = 0;
// Pin definition for CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27

#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22

int pictureNumber = 0;

#define uS_TO_S_FACTOR 1000000

#define TIME_TO_SLEEP  60

void setup() {

  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector

  Serial.begin(115200);

  Serial.setDebugOutput(true);
  //Serial.println();

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  //pinMode(4, INPUT);
  //digitalWrite(4, LOW);

  if(psramFound()){
    config.frame_size = FRAMESIZE_UXGA; // FRAMESIZE_ + QVGA|CIF|VGA|SVGA|XGA|SXGA|UXGA
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }

  // Init Camera
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  Serial.println("Starting SD Card");
  delay(2000);
  if(!SD_MMC.begin()){
    Serial.println("SD Card Mount Failed");
    //return;
  }

  uint8_t cardType = SD_MMC.cardType();
  if(cardType == CARD_NONE){
    Serial.println("No SD Card attached");
    return;
  }

  camera_fb_t * fb = NULL;

  // Take Picture with Camera
  fb = esp_camera_fb_get();
  if(!fb) {
    Serial.println("Camera capture failed");
    return;
  }
  // initialize EEPROM with predefined size
  EEPROM.begin(EEPROM_SIZE);
  pictureNumber = EEPROM.read(0) + 1;

  // Path where new picture will be saved in SD Card
  String path = "/picture" + String(pictureNumber) +".jpg";

  fs::FS &fs = SD_MMC;
  Serial.printf("Picture file name: %s\n", path.c_str());

  File file = fs.open(path.c_str(), FILE_WRITE);
  if(!file){
    Serial.println("Failed to open file in writing mode");
  }
  else {
    file.write(fb->buf, fb->len); // payload (image), payload length
    Serial.printf("Saved file to path: %s\n", path.c_str());
    EEPROM.write(0, pictureNumber);
    EEPROM.commit();
  }
  file.close();
  delay(2000);
  // Turns off the ESP32-CAM white on-board LED (flash) connected to GPIO 4
  pinMode(4, OUTPUT);
  digitalWrite(4, LOW);
  rtc_gpio_hold_en(GPIO_NUM_4);

  esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);

  Serial.println("Going to sleep now");

  delay(2000);
  esp_deep_sleep_start();
  Serial.println("This will never be printed");
}

void loop() {

}

also here is the board I am using
Here is output of the error:
rst:0x5 (DEEPSLEEP_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1100
load:0x40078000,len:9232
load:0x40080400,len:6400
entry 0x400806a8
Starting SD Card
E (4147) sdmmc_sd: sdmmc_check_scr: send_scr returned 0xffffffff
SD Card Mount Failed
No SD Card attached

Here is a diagram of the pins used by the SD card and Camera. Although I have nothing hooked up to them currently

try SD_MMC.end() before deep sleep

Still fails. @Juraj. I had actually tried stop, quit, exit.. and a few others. But yes, it still fails when I use SD_MMC.end() before deep sleep begins. I will try it now with 5 volts though. EDIT: it also fails on 5 volts

You need to initialize SD_MMC to 1 bit mode (by default 4 bit mode) this way the microsd is slow, but you free up 3 pins, GPIO4 too. I had this problem to write on SD when used GPIO4 to switch on/off the flash led.

if (!SD_MMC.begin("/sdcard", true)) {  // 1 bit mode
    Serial.println("SD Card Mount Failed !!!");
    return;
}
YOUR CODE HERE ...

After this I can use GPIO12 as pullup input (tested on my sketch), when it goes to GND the camera will take the frame and save it to microsd (and even send it over TCP socket to Android device and my PC that save to storage memory and show it :D).
GPIO16 don't worked here, it work just one time, then remains LOW and can't be reused.
Note that I do not use sleep function, just check in the loop() the state of GPIO12 to trigger a camera shot.

The code I posted forces GPIO4 to hold its value in this line:
rtc_gpio_hold_en(GPIO_NUM_4);
This pin is used for SD card interface. I needed to un-hold it after deep sleep wakeup if I wanted to use the pin again.

why do you use for SD card the same pin as used for cam flash LED?

I think it is part of the configuration of the camera. I.E. the LED is part of the camera config? I am not positive. I could use help understanding the pins because I want to use one of them to trigger a reset from code. I am not sure which pin to use however. Here is the tutorial I am following. I am trying to add a PIR sensor to this and reset the board. https://randomnerdtutorials.com/esp32-cam-take-photo-save-microsd-card/?unapproved=383075&moderation-hash=09b851163bbdb63c7d8f69240de09a06#comment-383075

Nevermind I was able to get it working using a pull down circuit to pin 13


text:
esp32 cam and PIR sensor
I have tried all the GPIO pins listed here:I am following this tutorial to save a picture using the ESP32 cam board. I am trying to add a PIR sensor.
https://randomnerdtutorials.com/esp32-cam-take-photo-save-microsd-card/
whenever I try to use any pins to enable wake on external pin high, there is an error either because of interruption with the camera initiation or sd card.
here is my PIR sensor
https://www.robotshop.com/en/wide-angle-pir-motion-sensor.html?gclid=EAIaIQobChMI0Y7QuaOA4wIVl_5kCh3zYA4OEAQYASABEgJFPvD_BwE
here is the code I am using
    /*********
      Rui Santos
      Complete project details at https://RandomNerdTutorials.com/esp32-cam-    take-photo-save-microsd-card

      IMPORTANT!!!
       - Select Board "ESP32 Wrover Module"
      - Select the Partion Scheme "Huge APP (3MB No OTA)
    - GPIO 0 must be connected to GND to upload a sketch
    - After connecting GPIO 0 to GND, press the ESP32-CAM on-board RESET  button to put your board in flashing mode

   Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

 #include "esp_camera.h"
 #include "esp_timer.h"
 #include "img_converters.h"
 #include "Arduino.h"
 #include "fb_gfx.h"
 #include "fd_forward.h"
 #include "fr_forward.h"
 #include "FS.h"                // SD Card ESP32
 #include "SD_MMC.h"            // SD Card ESP32
 #include "soc/soc.h"           // Disable brownour problems
 #include "soc/rtc_cntl_reg.h"  // Disable brownour problems
 #include "dl_lib.h"
 #include "driver/rtc_io.h"
 #include <EEPROM.h>            // read and write from flash memory

    // define the number of bytes you want to access
     #define EEPROM_SIZE 1

     // Pin definition for CAMERA_MODEL_AI_THINKER
     #define PWDN_GPIO_NUM     32
     #define RESET_GPIO_NUM    -1
     #define XCLK_GPIO_NUM      0
     #define SIOD_GPIO_NUM     26
     #define SIOC_GPIO_NUM     27

     #define Y9_GPIO_NUM       35
     #define Y8_GPIO_NUM       34
     #define Y7_GPIO_NUM       39
     #define Y6_GPIO_NUM       36
     #define Y5_GPIO_NUM       21
     #define Y4_GPIO_NUM       19
     #define Y3_GPIO_NUM       18
     #define Y2_GPIO_NUM        5
     #define VSYNC_GPIO_NUM    25
     #define HREF_GPIO_NUM     23
     #define PCLK_GPIO_NUM     22

     int pictureNumber = 0;

     void setup() {
       WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector

       Serial.begin(115200);
       //Serial.setDebugOutput(true);
       //Serial.println();

       camera_config_t config;
       config.ledc_channel = LEDC_CHANNEL_0;
       config.ledc_timer = LEDC_TIMER_0;
       config.pin_d0 = Y2_GPIO_NUM;
       config.pin_d1 = Y3_GPIO_NUM;
       config.pin_d2 = Y4_GPIO_NUM;
       config.pin_d3 = Y5_GPIO_NUM;
       config.pin_d4 = Y6_GPIO_NUM;
       config.pin_d5 = Y7_GPIO_NUM;
       config.pin_d6 = Y8_GPIO_NUM;
       config.pin_d7 = Y9_GPIO_NUM;
       config.pin_xclk = XCLK_GPIO_NUM;
       config.pin_pclk = PCLK_GPIO_NUM;
       config.pin_vsync = VSYNC_GPIO_NUM;
       config.pin_href = HREF_GPIO_NUM;
       config.pin_sscb_sda = SIOD_GPIO_NUM;
       config.pin_sscb_scl = SIOC_GPIO_NUM;
       config.pin_pwdn = PWDN_GPIO_NUM;
       config.pin_reset = RESET_GPIO_NUM;
       config.xclk_freq_hz = 20000000;
       config.pixel_format = PIXFORMAT_JPEG;

       if(psramFound()){
         config.frame_size = FRAMESIZE_UXGA; // FRAMESIZE_ +  QVGA|CIF|VGA|SVGA|XGA|SXGA|UXGA
        config.jpeg_quality = 10;
        config.fb_count = 2;
      } else {
        config.frame_size = FRAMESIZE_SVGA;
        config.jpeg_quality = 12;
        config.fb_count = 1;
      }

      // Init Camera
      esp_err_t err = esp_camera_init(&config);
      if (err != ESP_OK) {
        Serial.printf("Camera init failed with error 0x%x", err);
        return;
      }

      //Serial.println("Starting SD Card");
      if(!SD_MMC.begin()){
        Serial.println("SD Card Mount Failed");
        return;
      }

      uint8_t cardType = SD_MMC.cardType();
      if(cardType == CARD_NONE){
        Serial.println("No SD Card attached");
        return;
      }

      camera_fb_t * fb = NULL;

      // Take Picture with Camera
      fb = esp_camera_fb_get();
      if(!fb) {
        Serial.println("Camera capture failed");
        return;
      }
      // initialize EEPROM with predefined size
      EEPROM.begin(EEPROM_SIZE);
      pictureNumber = EEPROM.read(0) + 1;

      // Path where new picture will be saved in SD Card
      String path = "/picture" + String(pictureNumber) +".jpg";

      fs::FS &fs = SD_MMC;
      Serial.printf("Picture file name: %s\n", path.c_str());

      File file = fs.open(path.c_str(), FILE_WRITE);
      if(!file){
        Serial.println("Failed to open file in writing mode");
      }
      else {
        file.write(fb->buf, fb->len); // payload (image), payload length
        Serial.printf("Saved file to path: %s\n", path.c_str());
        EEPROM.write(0, pictureNumber);
        EEPROM.commit();
      }
      file.close();

      // Turns off the ESP32-CAM white on-board LED (flash) connected to GPIO 4
      pinMode(4, OUTPUT);
      digitalWrite(4, LOW);
      rtc_gpio_hold_en(GPIO_NUM_4);

      delay(2000);
      Serial.println("Going to sleep now");
      delay(2000);
      esp_deep_sleep_start();
      Serial.println("This will never be printed");
    }

    void loop() {

    }

This is the thing I am trying to add. but no matter which pins i chose there are errors. I can add the error if that would be helpful.
esp_sleep_enable_ext0_wakeup(GPIO_NUM_X, level)

A schematic of how you are hooking up the PIR to the esp32 cam board would help.

@st2000 I added some more info to the OP.

So, you are using pins other than pin 3 (E32_RST)?  Guessing, most embedded processors generate different vectors (places they go to and start code execution) based on which pins are generating interrupts.  It may be that the libraries you are using only setup an interrupt for pin 3.  As this is all guess work - I'm resisting the temptation to change this comment into an answer.

I am not seeing a pin 3 (esp32 rst) on this board. Could you point it out. Then you can change this to can answer.

I am looking at this schematic.  Assuming this is the board you have.  I see a reset switch connected to net ES32_RST.  Which appears at pin 3 of the ESP-32S chip.  Guessing, if  your PIR uses an open collector to ground type output, you might try soldering to the open side of the reset switch.

Ok I think I see now. I would need to solder it to the esp32-s chip itself. I will provide a high signal to the rst pin 3 via the PIR sensor and it will reset the board? I added an edit to include the schematic of my PIR sensor.

I don't think that is going to work.  The PIR spec says it will output a high when activated.  And the ESP32 Cam schematic, if accurate, shows K1 making a connection to ground when pushed.  So the PIR is doing the opposite of what you need.  Also, the ESP chip is probably a QFN package is is extremely difficult to solder directly to.  Likely it would be much easier to solder to the push button switch lead.

Ok I will give it a shot

Let us continue this discussion in chat.

Software:
It may be that one of the included libraries (software) you are using depends on pin 3 (E32_RST) of the ESP32 going low in order to operate as expected (wake up and take a picture).  Using an alternate pin may wake up the ESP32 but may not behave as expected.
Hardware:
This schematic of the ESP32 Camera shows how switch K1 is connected to pin 3 of the ESP32.  There is a capacitor C7 and resistor R6 likely used to mitigate K1 switch bouncing and to pull pin 3 high when switch K1 is not pressed.  When switch K1 is pushed it pulls pin 3 to ground waking up the ESP32 to take a picture.
The PIR specified changes its output to high when activated according to its data sheet.  This is opposite of what the ESP32 needs to see at pin 3 in order to take a picture.  It appears an inverter is needed between the PIR and pin 3 of the ESP32.  An open collector type of inverter would be best as this type of driving circuit can be attached where K1, C7 & R6 come together with out interfering with the their (the existing components') operation.  This is the subject of this stackexchange question / answer.


text:
PIR sensor and hex inverter open collector
the M7404 Hex inverter is used to send an active low signal from a PIR sensor to a microcntroller pin
However the reset is being constantly sent some signal keeping it set to on. You can tell because the reset light is on in the picture
Thanks to ST2000 I was able to figure out I need a hex inverter open collector to change the high signal from high to low because the reset pin on the microcontroller is active low. However, Whenever I use the active low reset pin (number 3 on the esp32) it goes into a state of holding down the reset button. Or constantly being high. Here is the thread where ST2000 was able to provide me the solution I am working on: esp32 cam and PIR sensor

My question is: how do i get the pir sensor to send an active low signal to the microcontroller?
here is a schematic of the esp32 board
https://i.redd.it/yv050peu22p21.png

Ok i tried my best to make a schematic and updated to include a question sry. @jsotola

That schematic makes no sense.

The data line from the pir sensor goes through the inverter and then into the microcontroller that is supposed to accept an active low to trigger reset on the board. I know it doesnt make sense but please bear with me or provide another site that is easier to make schematics.

Edit your question then press the schematic button.

Your inverter is backwards in that schematic. Is it backwards in reality?

No its not. I am not at home atm but if you look closely at the camera picture it appears with the text and output oriented right. At least when I was wiring it up I was looking at a tutorial. Also I have updated my schematic to hopefully make more sense.

If you want to turn your active high output into an active low one all you need is a transistor and a resistor. The transistor makes it active low and open collector, and the resistor pulls it up to 3.3V.

it needs to be .7v active low to activate reset. But in my case it seems to be inactive all the time. regardless of the PIR state even w/o the inverter

Let us continue this discussion in chat.

See my edit. ...

@DavidGraff, thanks for adding the schematic .... now it makes sense .... why are you connecting the PIR to the reset pin? .... use one of the other data pins instead .... use a pullup resistor

I wouldn't have chosen a hex inverter for this job. I'd have just used a transistor and a resistor:

simulate this circuit – Schematic created using CircuitLab
When OUT is HIGH, M1 is ON, which connects D3 to GND.  When OUT is LOW, M1 is OFF, which allows R1 to pull D3 up to 3.3V.

As to why you have a boot loop, now you have shown a slightly (though still confusing) clearer schematic I can tell you that it is because you are using pin D3.
Don't use pin D3.
D3 is the RX pin and is held HIGH at boot. That means that when the board resets D3 goes HIGH which then pulls reset LOW through your inverter, which then lets D3 float, so RESET goes HIGH, and that makes D3 then go HIGH which means the RESET is pulled LOW... ad infinitum.
You should read this page and choose a different GPIO pin that isn't going be doing things at bootup.


text:
Stuck with bad sketch
How can I get my programmer board/windows computer to recognize my board again. I am using the esp32 cam and have put two boards in a state where I am unable to flash them anymore. here is the error:
serial.serialutil.SerialException: could not open port 'COM5'WindowsError(2,'The system cannot find the file specified.')Failed to execute script esptoolthe selected serial port Failed to execute script esptool

I tried reinstalling the drivers and understand that the com port is a separate chip
https://gist.github.com/wybiral/2a96c1d1605af7efa11b690586c4b13e
Here is the sketch I used. I uploaded it using the dev module board setting as well as with 80mhz and 112500 speed. I uploaded with 3v and then provided 5v to the board to run the sketch. The sketch runs but prints out gibberish.
Edit:
Here is a schematic of the board
https://github.com/SeeedDocument/forum_doc/raw/master/reg/ESP32_CAM_V1.6.pdf

You can't "put them in a state" where the COM port can't be found. The COM port is a completely separate chip. Check your USB cable. Reinstall the drivers.

And check if the boards still have COM5. Sometimes the numbers change

thanks fellas for the quick replies. I tried reinstalling the drivers for the USB device in question. holding down the reset button before doing so. However, while the com port is still there, it says the drivers are up to date.

Is there a way to reinstall the drivers other than uninstalling > unplugging the usb > plugging the usb back in > and hitting update drivers and browsing to the file where the drivers are?

@majenko I tried reinstalling the drivers before I came here. I just figured there was a quick fix to fixing a broken sketch. I wrote my OP hastily and can update it if needed

The sketch can only affect reflashing on boards that provide a native USB interface, like the Micro and Leonardo. All others that use a USB bridge chip of some form are completely independent of the sketch.

This very much looks like the Serial-over-USB-Driver has chosen another port than COM5 on reconnecting the board. Assuming you are using the Arduino IDE, check whether COM5 still shows up in the Board -> Port menu -- or, in other words, go there and select the port that is listed there while the board is plugged in.
Usually, I'd expect this port to be COM3 on Windows, but that may change when you...

physically disconnect and reconnect the board too fast (i.e. the driver has not yet shut down the old COM port when a "new device on USB!" event comes in)
still have the Serial Monitor open when disconnecting and reconnecting (because the driver cannot remove the virtual COM port device while the Serial Monitor has it opened, in which case the driver creates another virtual COM port device on a different number)
disconnect and reconnect while the esptool process is still working (same reason as above).

It also might help to enable verbose output for compiling and uploading (see preferences dialog in Arduino IDE).

thank you for this throrough reply. The com5 port (the one i have always used) shows up when i plug in the programmer board without the esp32 cam board attached. However if I attach the esp32 cam board to the programmer (the same way i had it wired all times before) the com port disappears and the USB is not recognized by windows. Could it be that the programmer is stuck trying to program and needs to be reset somehow?

Hi, what do you think is going on?

"the programmer is stuck trying to program" - if you power cycle (i.e. disconnect from power) the "programmer" has no memory of what it was doing before. At a guess, you've "fried" and probably permanently destroyed something

@DavidGraff This sounds more like that the cam board produces a short, rendering the programmer inoperable. Either you have created a solder bridge or something like that (e.g. between Vcc and GND) on the cam board, or your esp32 is fried (did it come into contact with 5V?) and shorts internally. (On a completely different note: your name sounds familiar. Does TUDO tell you anything?)

@orithena no that doesnt ring a bell. So it is likely I fired both boards when uploading the sketch and then providing 5v via the 5v input on the esp32 cam board? I have tried all options to reset the board.

I cannot answer that without seeing the schematics (can't find them online), but it seems unlikely that applying 5V to the 5V pin fries the chip, as the board seems to have a voltage regulator onboard. It's more likely that you fried the chip by applying 5V to any input/output pin (a.k.a. GPIO pin), e.g. by using a programmer or external component that outputs a 5V signal level without inserting a level shifter into the signal line. Have you been able to flash the chip exactly once? Then I'd say your programmer outputs a signal level of 5V and the esp32 fried during flashing.

That last hunch comes from: a chip does not fry immediately when exposed to a slightly higher voltage. It needs some time to get hot enough to fry. So the initial handshake to flash it worked, but the actual flashing process after that is: just shove the bytes over the line. So when the chip fries during programming, the next handshake in order to flash it will not work anymore.

thank you for the replies. I don't have the two boards with me to check today but maybe I will later today... I have fried two esp32 cam boards it seems. Both of which were fried when I uploaded a sketch and then applied 5v to the 5v pin. I provided 3v each time while uploading the sketch, however. Could changing any of the settings in the configuration cause the boards not to like the 5v?

I added the sketch I used and a schematic to the OP @orithena

@DavidGraff Interesting schematics. There is an AMS1117 low-dropout voltage regulator to pull the 5V input voltage down to 3.3V. But: did you change anything on the "solder jumpers" marked "5V" and "3V3"? (follow the white line from VCC). If they are both connected, you're effectively bridging the voltage regulator out of the schematics, which means: if they're both connected and you apply 5V to the 5V pin, the chip will be driven with 5V instead of 3.3V, which will fry it (see circuit around U2 and P1 in the schematics; R1 and R2 are the solder jumpers, only one of them may be closed).

Let us continue this discussion in chat.


text:
Person (phone) detector that trigger an event esp32 cam
So me and my dad are trying to catch would be thieves and also someone leaving behind alcohol bottles. At his storage business the cameras don't reach to these spots.
Without being too invasive I want to sense bluetooth and/or wifi signals of relatively close phones sort of like a pax counter. This is in lue of using a pir sensor which I have always found finicky and I want to make use of the esp32' cam's wifi/ble chip.
So to start I researched for the past few days or week. I found that most phones don't use ble so maybe that is out. I also found that the esp32 cam is a bit finicky and I'm not sure if it is compatible with other code I have found.
One time I was able to get the light to come on when my phone was near using code I found for the esp32.
Any help or direction would be nice
Edit: I understand this sounds weird but mostly I would just like to get proximity of bluetooth or wifi to trigger an event. The device is powered by battery and I understand not everyone carrys phones.

Sniffing for wifi request probes could be an option. Knowing the networks a person was connected to can even be sufficient to identify or at least recognise different persons. I have absolutely no idea if that's possible on an esp32. The most difficult thing when doing this on a raspberry pi is finding a network adapter that supports monitor mode and I don't actually know whether the esp's interface supports that or not.

"I was able to get the light to come on when my phone was near" - how did you do this? Was your phone somehoe connected before or was it incognito like a stranger's would be?

incognito. but looking back it is possible it was responding to other BLE devices near by. I would bring the phone close sometimes the light would change. sometimes it wouldnt. It was very strange. The esp32 supports monitor mode its just I havent found any code that would compare RSSI strength of nearby devices. Or if thats even possible?

Detecting a phone could be easily done by capturing WiFi probe requests which are sent by phones having at least one saved WiFi network. Note that such requests alone are often enough to identify the person, if their home WiFi SSID is set to something like "Davids_wifi".
Software-wise, this would be much easier to do on Linux (think Raspberry Pi or a similar device) which already have all the network sniffing software like tcpdump, which you would otherwise have to find or implement on ESP32.
I'm leaving out the legal implications of what you're trying to do as I don't know what country you are in, but bear in mind that hidden surveillance may be illegal in some cases.


text:
Arduino open door (outdoor) tonemelody
My problem lies in the fact that I can not stop the "void loop" function and more accurately "StatInDoor". I have to make sure that the "ButtonOpenDoor" works independently of "ButtonCall". If someone presses the "ButtonCall" button then the "ButtonOpenDoor" button must work in progress, and if the "ButtonCall" button is pressed, the "ButtonOpenDoor" button must stop playing the melody.
My idea for this this:
int StatOutDoor = digitalRead(ButtonCall && ButtonOpenDoor);

or:
if(StatOutDoor == LOW && StatInDoor = LOW){
   PlayMelody();
}

But it does not work :(
Full code:
#include "pitches.h"

int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};
int ButtonCall = 4;
int buzzer = 8;
int ButtonOpenDoor = 7;
int RelayModule = 12;

void PlayMelody() {
  for (int thisNote = 0; thisNote < 8; thisNote++) {
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(buzzer, melody[thisNote], noteDuration);
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    noTone(buzzer);
  }
}

void setup(){
  pinMode(ButtonCall, INPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(ButtonOpenDoor,INPUT);
  pinMode(RelayModule,OUTPUT);
}

void loop() {
  int StatOutDoor = digitalRead(ButtonCall);
  if(StatOutDoor == LOW){
    PlayMelody();
  }
  int StatInDoor = digitalRead(ButtonOpenDoor);
  if (StatInDoor == HIGH) {
    digitalWrite(RelayModule, HIGH);
  } else {
    digitalWrite(RelayModule, LOW);
    delay(3300);
  }
}

Can someone help with this? (Sorry for my bad English).

&& is logical AND. & is Bitwise AND. Use the right one, it might help.

Unfortunately both methods do not work

Unfortunately I don't speak your language, and I find those variable names almost impossible to read. Please use English (or English-like) variable names (and function names) and ideally something to break up the words within them, such as camelCase.

przyciskzadzwon=ButtonOutDoor ; przyciskotworz=ButtonInDoor ; przekaznik=RelayModule ; muzyczka=PlayMelody ; stanwew=StateInDoor ; stanzew=StateOutDoor

That doesn't help me decipher a string of seemingly random consonants in my head...

I can send again full code with translation, just tell where. I really need help ;/

Up there, where the existing code is. Press edit.

Sorry. Edit done

I'm not quite sure I understand the logic of what you're asking. Your description is a little vague. Maybe if you provided more information about what the signals are, what they mean, and where they come from, it may help.
However - if you want the melody to play when both inputs are LOW you should change:
if(StatOutDoor == LOW && StatInDoor = LOW){
      PlayMelody();
}

to:
if(StatOutDoor == LOW && StatInDoor == LOW){
      PlayMelody();
}

Note the use of == not = to denote equality (= is assignment).
Also the use of a 3.3 second delay in your else will show everything down to a crawl when StatInDoor is HIGH.

I want to make an intercom. There are two buttons - one to ring from the outside, the other to open from the inside. If outside someone pushed the call button and play the melody I want to open the door, for this moment problem is that I can only open when the melody is over.
if(StatOutDoor == LOW && StatInDoor == LOW){
PlayMelody();
}  not working too...

Ah, I see. Well for that you need to rethink your entire program. You need to learn how to write non-blocking code. Start with the BlinkWithoutDelay example in the IDE.

ohh... sure. How to transform it?

State machine(s) and using millis() instead of delay().

The Arduino doesn't multitask. So when you execute PlayMelody() the loop() function can't do anything else until the song ends.
You could use interrupts to play the song, but to keep things simple, here's a way to do it without interrupts.
// Struct to hold the song data (simpler than 2 arrays)
struct note {
    int pitch;
    int duration;
};

// Class to play songs
class song_player {
protected:
    note *melody;   // Array of all the notes
    int note_count;  // How many notes in song
    int current_note;
    bool am_playing;  // Playing song?
    unsigned long last_event;  // Time of last note
    unsigned long next_event;  // Time to play next note
    byte speaker_pin;

    // is it time to play the next note?
    bool elapsed()
    {
        unsigned long m = millis();
        if (m >= next_event) {
            last_event = m;
            return true;
        }
        return false;
    }

    // play one note
    void play_next_note() {
        if (elapsed()) {
            // Play next note unless at end of song
            if (current_note < note_count) {
                unsigned long duration = 1000 / melody[current_note].duration;
                tone(speaker_pin, melody[current_note].pitch, duration);
                next_event = millis() +  1.3 * duration;
                current_note += 1;
            }
            else {
                // Finished...
                noTone(speaker_pin);
                am_playing = false;
            }
        }
    }
public:
    // ctor
    song_player(byte speaker_pin, note *melody, int note_count) :
        am_playing(false),
        speaker_pin(speaker_pin),
        note_count(note_count),
        melody(melody)
    {
        // Note: does not make local copy, so array should be
        // valid for lifetime of this object
    }

    // Start the song
    void start() {
        // Initialize
        current_note = 0;
        am_playing = true;
        last_event = millis();
    }

    // Call this every loop()
    void loop() {
        if (am_playing) {
            play_next_note();
        }
    }
};

Then you would change the rest of the program to something like:
// Song data
note the_song[] = {
  {NOTE_C4, 4},
  {NOTE_G3, 8},
  {NOTE_G3, 8},
  {NOTE_A3, 4},
  {NOTE_G3, 4},
  {0, 4},
  {NOTE_B3, 4},
  {NOTE_C4, 4}
};
// Create a player object
song_player player(9, the_song, sizeof(the_song) / sizeof(the_song[0]));

//....

void loop()
{
    // other stuff .....

    if(StatOutDoor == LOW && StatInDoor == LOW) {
        // Start the song
        player.start();
    }
    // Important: Call this every time
    player.loop();

    // Other stuff here....
}


text:
I have to make an LED with an ultrasonic distance sensor, where the LED blinks faster when getting closer than a specific distance
I already have this code, but I do not know how to make the LED blink.
CODE:
const int ledPin = 6; // The pin of your LED, D06
const int trigPin = 5; // The pin to which the TRIG is connected, D05
const int echoPin = 4; // The pin to which the ECHO is connected, D04
const int ledOnTime = 1000;
// The time that the LED stays on, after detecting the motion (in milliseconds, 1000ms = 1s)
const int trigDistance = 40;
// The distance (and lower than it) at which the sensor is triggered (in centimeters)
//
int duration;
int distance;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  digitalWrite(trigPin, HIGH);
  delay(1);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;
  if (distance <= trigDistance) {
    digitalWrite(ledPin, HIGH);
    delay(ledOnTime);
    digitalWrite(ledPin, LOW);
  }
  delay(100);
}

I corrected the formatting and also added indention. You should really use indention. It makes the code way more readable. The Arduino IDE even has an autoformatting function to introduce correct indention

I would say the way to go is using non-blocking code with millis(). Look into the BlinkWithoutDelay example, that comes with the Arduino IDE. It doesn't use delay(), which is considered bad coding practice, since it is just busy waiting. Nothing else can happen during a delay, except for interrupts. Instead of waiting it is better to regularily check the clock, if it is time to do something (much like you would do in real life for example for baking a pizza).
The clock is provided by millis(), which returns the number of milliseconds since startup. Below you see the BlinkWithoutDelayexample. The variable interval controls the blink frequency. If you remove the const keyword before it and change it according to the measurements from the ultrasonic sensor, you will get a changing blinking frequency with changing distance.
Try to combine the codes into one. Remove all delay() calls, except for the delay(1) (it is needed to trigger the ultrasonic sensor and it is small enough to not matter greatly).
const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

The rest is up to you. If you need more information about the BlinkWithoutDelay example, you should google it. There are tons of tutorials. This is a great coding excerise, so have fun :)

step 1: define your MIN_DISTANCE, MAX_DISTANCE
step 2: get distance from sensor
step 3: rescale the distance value to a value in between 0 and 255
step 4: fade led according to the rescaled value.
Note that: you should not use delay() to blink LED. Use analogWrite() instead. See  the example. We can change frequency of PWM to make LED from fading to blinking by using setPwmFrequency() function