text:
can we make Drone with Dc 180 motor and Arduino?
I want to make a drone as a project for my university, But I am kinda newbie in this, I did many searches about this and I found I should do it with the brushless motors (BLDC) but I can't buy this kind of motors, So I want to do it with DC motors I found in youtube there is motor can be used in the drone it called ( 180 dc motor) but they didn't use them with Arduino.
My question is can I use Dc 180 motor with Arduino and make a drone Or Not?

https://youtu.be/J0x4ChjUS00 not exactly what u wanted but it is also using brushed motor if u want u can give this a try

Yes you could but you will have to use a motor driver or else the motors will not be able to get enough power and try using arduino micro or an esp32 if you want to use it with Bluetooth which will also help you to keep the weight down.

Yes I saw it, but he didn't use Arduino he used transmitter and receiver, I want to connect it with my Arduino and my code and thank you aalot

Sorry your question didn't fully load on my phone I have updated my answer

So if I want connect it with Arduino i need 1. motor driver and micro And Nano will work too right? , and drone will work 100%? Thank you very much

Yes it will work with arduino Nano just try keeping the weight of the drone as less as possible and you can also use transistor insted of a motor driver I suggest watching this video : https://youtu.be/J0x4ChjUS00

maybe this is a dumb question, but what the point of using motor driver and transistor? yes thanks about the video

You have to use a transistor or a motor driver because an Arduino has a maximum output of 5v 40ma on its digital pins which is not enough for these motors. they are used to mainly supply voltage and current to the motors as the current input of the motors can go as high as 0.80amps

Thank you a lot


text:
How to read two byte register address using arduino wire library
I want to read a register 0x012A from the device I2C address 0x0A, the value stored in the register is two bytes, If the register address is one byte i can use Wire.requestFrom and give the register address and how many bytes i want to read since here register address itself 2 bytes i'am bit confused . can any one help in this regard.

Have a look at https://github.com/rodan/ds3231/blob/master/ds3231.cpp#L409-L413 . As far as I can see. You begin a transmition to the device; you write your two registry address bytes; then close the transmission. After that you use requestFrom to read any number of bytes (which happens to be two as well, in your case).

i can use Wire.requestFrom and give the register address and how many bytes i want to read

So you give it 2 to ask for 2 bytes.
Then you combine them. How you do that depends on what the bytes represent.  If the first is the upper byte and the second the lower byte of a 16 bit value then you would:
uint8_t b1 = Wire.read();
uint8_t b2 = Wire.read();

uint16_t val = (b1 << 8) | b2;

If it's the other way around then just swap the variables in the combining section.
However if the values are some other arrangement (I saw something recently that had two registers with a 12 bit value with overlapping bits) you will have to combine it in the way that is required for that specific arrangement.

source: Stack Exchange

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

sort: votes


text:
Communication between two slaves via single SPI bus
I am trying to control both RC522 and lcd st7920 (128x64) via a single SPI bus on the NodeMCU esp8266. I am using Arduino core for my esp8266. Now in this portion of the code, I only want to display the UID of the card on the lcd each time a card is scanned on the RC522. The code is as follows:
#include <SPI.h>
#include <MFRC522.h>
#include <U8g2lib.h>

#define SPI_SCK_pin       14  // Clock pin of SPI
#define SPI_MOSI_pin      13  // MOSI pin of SPI

#define SPI_RST_pin       0   // RST-PIN for RC522 - RFID - SPI - Modul GPIO5
#define SPI_rfid_SS_pin   15  // SDA-PIN for RC522 - RFID - SPI - Modul GPIO4
MFRC522 mfrc522(SPI_rfid_SS_pin, SPI_RST_pin); // Create MFRC522 instance

#define SPI_lcd_SS_pin    5   // Slave Select pin of SPI for lcd<->RS
U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R2, SPI_SCK_pin, SPI_MOSI_pin, SPI_lcd_SS_pin, U8X8_PIN_NONE);

void setup() {
  SPI.begin();           // Init SPI bus
  Serial.begin(115200);    // Initialize serial communications

  u8g2.setFont(u8g2_font_amstrad_cpc_extended_8f);
}

void loop() {

  mfrc522.PCD_Init();    // Init MFRC522
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    delay(50);
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    delay(50);
    return;
  }

  Serial.print(F("Card UID:"));
  String uid = dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println();
  digitalWrite(SPI_rfid_SS_pin, HIGH);   //return rfid slave pin back to normal

  u8g2.begin();
  u8g2.clearBuffer();
  u8g2.setCursor(3,10);
  u8g2.print (uid);
  u8g2.sendBuffer();
  digitalWrite(SPI_lcd_SS_pin, HIGH);   //return lcd slave pin back to normal
//  delay (10);

}

// Helper routine to dump a byte array as hex values to Serial
String dump_byte_array(byte *buffer, byte bufferSize) {
  String userid;
  for (byte i = 0; i < bufferSize; i++) {
      userid += String(buffer[i]);
  }
  Serial.print(userid);
  return userid;
}

I am new to using the esp8266 and this is my first time using multiple slaves on a single SPI bus so I may not know the correct way to using multiple slaves. I tried connecting only the rfid rc522 with esp8266 via SPI and it worked flawlessly with the schematic. Similarly the lcd also works flawlessly individually on the SPI bus with the same schematic.
The issue only exists if I try to connect both via SPI. The problem is that only the first time a card is scanned, is it displayed on the lcd. After that no more cards are scanned and the only the first card scanned is displayed on the lcd.
What I am trying to do is that every time a card is scanned, its UID be displayed on the lcd. I've posted the schematic and my actual setup which you can check.

with the display you use software spi on hardware spi pins. the reader uses the hardware spi. find out how to use the display with hardware spi

@Juraj Fancy making that into a proper answer along with suggestions of how it may be "fixed"?

@Majenko sorry, no. OP didn't give feedback so II would not write an answer without at least compiling the code. and of course I don't have the devices to test it.

@Juraj the lcd uses software spi. There is only one spi bus available on the esp8266

so you think it is a good idea to use software spi on the same pins as hardware spi? spi devices are selected by the CS pin to share the bus, but you can't share the pins for two different SPI libraries

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


text:
Why Windows 10 does not see Nodemcu device?

I am using a Windows 10 laptop. Behind the nodemcu it says that download CH340G driver.
I already had arduino ide and the esp libraries were already
installed because i was using a esp8266 01 device before.
I bought a Nodemcu i downloaded the driver for it CH340G driver.
When i install the driver it says that The drive is successfully
pre-installed in advance!
When I plug my Nodemcu to my computer with a new cable blue lights
come from the board and it stops. And windows doesn't make a sound
which indicates that it sees the device.
I don't think the nodemcu is the problem. How do i fix this?

so are you are not able to see the nodemcu in arduino

In arduino IDE i can see the nodemcu in the cards section but when it is plugged in there are no ports attached to the nodemcu. Windows does not see it

so what's the problem if u can see it in Arduino then you can upload code to the node muc please tell me what you want .

If Windows doesn't make a sound then it doesn't see the device being plugged in. Are you sure you're usb cable has data wires in it?

does your board have a CH340G chip?

you could also try deleting the driver you installed . it may be conflicting with win10 . also windows installs necessary driver for any new device .

I tried this on 3 computers 2 of them are windows 10 and one mac and they did not work either. I bought a new usb-mini cable which says that it has 48bps transfer rate. I think it is a decent cable for nodemcu. I also tried this without installing drivers and also it did not work. But when i plug the card to the computer the cards lights flashes then they stop. So i think it means that the card works right?

Also when i plug the nodemcu to my computer windows does not make a sound of recognition for the device.

it could be a problem with the usb port on ur node mcu  it may be oxidized . because windows doesn't make any sound until a device data pins are connected .

I tried it with multiple devices so usb port should not be an issue. Also cable is okay. :(

I have had nodemcu clones from China where the soldering of the USB socket is bad. You may need to resolder the socket.

This is probably it... I can not find another way for this not working.

Read through https://stackoverflow.com/questions/43007501/nodemcu-not-detected-by-computer#:~:text=I%20had%20to%20install%20the,Afterwards%2C%20it%20worked.&text=For%20future%20people%20with%20this,and%20it%20wouldn't%20detect. and  also search few ways to remove oxidation from pins like using autosol (I have never used it ) . Try uploading code through FTDI modules or just get it replaced.


text:
Minimizing IR Detection Interference
I'll start by saying that the goal here is to have a hand/distance detection device. Basically touch-less button.
I managed to get it working with a simple 2-pin IR emitter and 2-pin IR detector using analog read from the detector to trigger an event. The problem is that I get interference from the sun on bright days.
Is there a way to pulse the emitter at a specific frequency and have the detector activate only on that frequency and keep the 2-pin setup?
One solution I have been leaning towards is changing the IR detector to a IR decoder and basically treat it as a remote control but I can't see a way to detect distance using this method.
I am also open to any other ideas on getting something like this to work, without IR or ultrasonic.
Thanks.

search VL6180X Time of Flight Distance Ranging Sensor

Turn off the IR led. Read the value of the IR-detector. Turn on the IR led. Read the value of the IR-detector. The "subtract" the value without the led on, from the value with the led on. I put the word subtract in quotes, because I doubt it's that simple. You'd have to do some measurements, with different ambient light levels, and plot them in excel and see what their relation is. In short, calibrate your system. But maybe you need a different sensor to get a more accurate distance. Something like those ultrasonic sensors.

This is actually something I have been meaning to try but never got around to it.
My idea is to drive the LED with PWM with a 50% duty cycle. The frequency isn't really that critical, but you don't want it too high for the next part.
Now you sample the receiver at a fixed frequency that is at least 2x the frequency of the PWM into a buffer.
Then you perform FFT on that buffer.
The bucket that contains the frequency of the PWM should have a power value that is proportional to the distance.
Other light sources will be unlikely to affect the same bucket as the PWM frequency - most will only affect the lowest (0Hz+) bucket.
Or that's the theory that I came up with. I have yet to try it in practice.


text:
How can I PWM 4 LEDs from 0 to full brightness using a two axiz resistive joystick?

I am trying to use the Arduino MAP function to allow me to PWM 4 LEDs between 0 and full brightness. I guess the tricky part is that the joystick neutral position is at the venter of the range of the potentiometers so the analog voltage to the inputs is at +2.5V when the joystick at neutral). Ideally I want to make a red LED that is associated with the Y axis to go from 0 to full as the joystick is pushed away. Similarly, I want a blue LED associated with the Y axis to go from 0 to Full on when the joystick is pulled toward me. I want to duplicate that action for the X axis with green and yellow LEDS but I can't seem to be able to figure out how to compensate for the 2.5V offset* I hoped I could just use mapping of the values.

Yes, just map 2.5-5 to 0-255 and analoWrite that value

int x=analogRead(A0);if (x >=512) red=(x-512)/2; etc.

Thanks to all who have responded. I have tried Sim Son's approach and as unsuccessful. I will have to test the other techniques.I'll report back on progress.

There's a number of steps you need to go through:

Read the ADC to get the joystick position
Subtract 50% of the full range (512) to get a ±512 value
Note the sign to get the direction
Take the absolute value to get the distance
Subtract a small amount to create a "dead zone" in the centre of the joystick
Map the result to 0-255 for the PWM.

The code might look like (note: untested):
int y = analogRead(0);    // Get the current value
y -= 512;                 // Subtract 512

int pin = 2;              // Unless otherwise told, use pin 2
if (y < 0) {              // If it's negative...
    pin = 3;              //    then we'll use pin 3 instead
}

y = abs(y);               // Take the absolute value (discard the sign)
y -= 20;                  // subtract 20 for a dead zone
If (y < 0) y = 0;         // zero any negative
y = map(0, 492, 0, 255);  // map the new full range of 0-492 to 0-255
analogWrite(pin, y);      // light the LED on the pin we chose above.

And do the exact same thing for X with different pins.

If you subtract 20 from y before mapping, won't that cause some negative values of y? (The range would be -20 to 492 instead of 0-512.) What does map do with out-of-range values?

I'd suggest changing  y -= 20; to if y <= 20 y = 0; instead.

Good question. You should do it at 0.


text:
ESP-01S + Fastled
I am trying to control a WS2812B Led Strip with my ESP-01S board.
It works fine with my ESP32 DevKit board, but the ESP-01S won't do anything :/
I couldn't figure out which 2 GPIO the ESP-01S is using (from the pinout), I assume it's GPIO0 (pin 5) and GPUI1 (pin 2).
I modified the sketch and tried several pin settings but the LED won't react.
any ideas what's wrong?

io 0 and io 2 are on every esp-01 header

and io 1 and io 3 as RX and TX. and io 0 has pull-up on esp-01s


text:
Run computation only on request over serial
An Arduino Nano is set up to perform A/D conversions and send results out over Serial. Currently the code structure is like
loop() {
  delayUntilNextTargetTime();
  measure();
  sendMeasurementsToSerial();
}

Though I make already sure that delayUntilNextTargetTime does not blindly delay(MILLIS) but rather subtracts the computation time from the time to sleep to prevent drift, I would rather get the timing from the host computer.
The idea is that the host computer sends a command string over the serial when it wants data, so the loop could look like
loop() {
  if (!Serial.available()) return;
  measure();
  sendMeasurementsToSerial();
}

Now I wonder if there is a way to do this without idle polling, something along the lines of
loop() {
  if(Serial.available()) {
    measure();
    sendMeasurementsToSerial();
  }
  sleepUntilSerialPotentiallyHasData();
}

I read that saving power is hard and likely not worth the effort, in particular when having a USB power supply. It is pure curiosity to see

what it takes to bring the system into, say, IDLE mode, possibly stopping the timers too, because they are not used (I guess)
and what it takes to get out of IDLE mode correctly again such that A/D conversion in measure() works without flaws.

On a Nano you can #include <avr/sleep.h>, then simply call
sleep_mode() from loop(). This will put the device to sleep, by
default in IDLE mode, until the next interrupt fires. The Nano will wake
up at least once every 1,024 µs, to service the timer interrupt
that is used to implement the Arduino timing function(millis(),
delay(), etc.). Most of the time this loop() will do nothing more
than testing Serial.available(), so the MCU will be awake only for a
couple of microseconds every 1,024 µs, which is not much.
If you disable the timer interrupt, all the timing functions will be
off, but the MCU will still be waken by the serial port interrupt as
soon as data is available.


text:
How to swap ground and power for multimeter
I'm trying to create a multimeter that measures resistance and capacitance for a school project and the code must be under 30 lines. I have made both a resistance meter and a capacitance meter but the only problem is that on for my resistance meter, ground is connected to the to the known resistor and the arduino's output goes through the unknown component. Where as my capacitance meter is the opposite (ground to unknown, output to known), just wondering if their is an easy fix or if i need to rethink my entire project. Any help is appreciated, thanks.

You could use an H-bridge to reverse the polarity

Please show your schematic. It is unclear what you mean.

Arduino have a lot of pins, can you use one pin for resistance and other for capacitance?


text:
Unable to use DHT11 with NodeMCU(esp8266)
I am trying to use a NodeMCU like an arduino,trying to read Temperature and Humidity using a DHT11,but when ever I check the serial monitor the it outputs : nan, Can anyone help me find the problem.(The data pin is D4 on NodeMCU)
    #include "DHT.h"

DHT dht2(2,DHT11);

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

    }

void loop()
{

    Serial.println("Temperature: ");
    Serial.println((dht2.readTemperature( )));
    Serial.println("Humidity");
    Serial.println((dht2.readHumidity( )));
    delay(5000);

}

use D1 or D2. D4 has a pullup resistor https://electronics.stackexchange.com/questions/402066/esp8266-free-gpios-for-relay-switching/404845#404845

Thanks manhh, you rock!!

The esp8266 boot configuration pins 0, 2, 15 require a pull-up/pull-down  to ensure the required state at boot. The board (NodeMCU in this case) has pull-up resistor on io0 and io2 and a pull-down resistor on pin 15. The MCU pins io0, io2 and io16 are the NodeMCU pin D3, D4 and D8. You can use this pins in the sketch, but only to attach devices which are not in conflict with the required boot state and are not disturbed by the pull-up/pull-down.
NodeMCU and "Wemos D1 R2 and Mini" esp8266 pins and io overview

Serial
RX io1 RX0
TX io3 TX0

boot config pins with pullup or pulldown on board
D3 io0 PULLUP (LOW for boot to flashing mode)
D4 io2 TX1 PULLUP (Serial1 TX. no RX for Serial1)
D8 io15 PULLDOWN (SS pin if esp8266 is SPI slave)

untroubled GPIOs with optional function for I2C or SPI bus:
D1 io5 default pin for I2C SCL
D2 io4 default pin for I2C SCA
D5 io14 SPI CLK
D6 io12 SPI MISO
D7 io13 SPI MOSI

RTC pin for timed deep sleep wake-up (if connected to reset pin)
D0 io16 - optional internal pulldown, internal pullup not available

not useable: Sx pins io 6 to io 11 connect QIO SPI flash memory (in DIO flash mode the 2 QIO pins can be used as gpio) (in a very special setup the SPI bus can be used with other SPI device)
note: most digital IO start as INPUT_PULLUP


text:
command keeps echoing because web page tries refreshing
I want to execute a action only once when I press web page button but as the page tries refreshing the action gets executed in a loop.
I am using the wifimanualwebserver example for esp8266.
Please suggest what should I do?

Not sure if it possible in your case, but you might send and ID with it which you increase every time the button has been (really) clicked (thus not refreshed). On the receiver side, check if the ID is already received, if yes, do not execute it.


text:
How can I use Methods in digitalWrite(): digitalWrite(int, "methodHere")?
When creating a piece of code to operate a 7-segment display, I ran into a problem:
The seven segment display on TinkerCad (I was using this at the time) requires you to pull down the inputs to turn a segment on, while the one that I have turns on when I pull up the inputs.
Instead of completely rewriting the code for the display that I had, I wanted to make my code more universal for if I need to use it in the future.
I cannot find a way to make the method digitalWrite(int pin, int val) work with a method that returns and int in the place of "int val"
This is the code that will not work:
int F = 11;
int G = 10;
int E = 9;
int D = 8;
int C = 7;
int DP = 6;
int B = 5;
int A = 4;
int type = 1;

 int highLow(int highOrLow)
{

  int digOutput;

  if(type = 1)
  {

    if(highOrLow = 1)
    {

      digOutput = 1;

    }
    if( highOrLow = 0)
    {

      digOutput = 0;

    }

  }
  if(type = 0)
  {

    if(highOrLow = 0)
    {

       digOutput = 0;

    }
    if( highOrLow = 2)
    {

      digOutput = 1;

    }

  }
  return digOutput;
}

void zero()
{
  digitalWrite(F, highLow(0));
  digitalWrite(G, HIGH);
  digitalWrite(E, LOW);
  digitalWrite(D, LOW);
  digitalWrite(C, LOW);
  digitalWrite(DP, HIGH);
  digitalWrite(B, LOW);
  digitalWrite(A, LOW);
}

setup
{
pinMode(F, OUTPUT);
pinMode(G, OUTPUT);
pinMode(E, OUTPUT);
pinMode(D, OUTPUT);
pinMode(C, OUTPUT);
pinMode(DP, OUTPUT);
pinMode(B, OUTPUT);
pinMode(A, OUTPUT);
zero();
}

Note : I am just using pin f to test.
Also, my etiquette is not very well defined or tested, so please keep it rather simple if you can.
If it matters, I am going to be using to using an Arduino Mega2560 produced by Elegoo.
Thanks for any help!!

In this situation it is far more efficient to use #define and conditional compilation.
// Uncomment this for tinkercad
// #define INVERTED

#ifdef INVERTED
#  define ON HIGH
#  define OFF LOW
#else
#  define ON LOW
#  define OFF HIGH
#endif

Then just use ON or OFF in place of HIGH and LOW.
digitalWrite(3, ON);

But the reason you have a problem is not because you are trying to use a function as the value to digtalWrite() - the problem is actually in your basic C syntax.
You are using the assignment operator (=) when you should be using the comparison operator (==). For example here:
if(highOrLow = 0)

you should have:
if(highOrLow == 0)

Thanks a ton! Will try this when i can get access to a computer again!


text:
How can I clear the memory of my Arduino in this case?
I have made a code using involving HID control. But it seems that I messed up, but I can't upload a new sketch(nor edit the wrong code), because my Arduino is constantly doing things like Ctrl+Alt+Delete, Alt+F4... etc.
It seems that the only way is erasing the code in the memory, but how can I do so?

Use a hardware programmer (USBASP, etc, or an Arduino as an ISP).

Do the "button dance" - hold the Arduino in reset, releasing just you see the download start in the IDE. This may (will!) take a little practice to get just the right timing.

or

Use an external programmer connected to the ICSP connector. This could be a commercially made one, a DIY, or another Uno programmed and connected as an ICSP programmer. How-to's abound on the web.

You can't do the "Button dance" on the Leonardo. Holding it in reset will not give you a serial port to start the upload to. Depending on the bootloader version you may get a few seconds after releasing the reset where it presents a COM port before the sketch runs (good luck on Windows - it may take too long to enumerate...), or pressing reset twice rapidly may put it in the bootloader. Best to have a programmer on hand anyway though as a general rule regardless.


text:
Why do I get error "Error compiling for board Arduino Uno" with my mpu6050 video stabilization code?
This is the code I'm working with. I'm using it for video stabilization system. It was working fine but for some reason now it gives me this error? Is it because I deleted the library and installed again? Please help. I'm new to arduino. Hopefully I formatted this correctly.
#include <Servo.h>
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

MPU6050 mpu;
Servo myServo;   // define servo
int servoPin=9;
float PWM = 0;
float Yaw = 0;

#define OUTPUT_READABLE_YAWPITCHROLL
#define INTERRUPT_PIN 2
#define LED_PIN 13

bool blinkState = false;

// MPU control/status vars
bool dmpReady=false;    // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
//packet structure for InvenSense teapot demo

volatile bool mpuInterrupt=false;
void dmpDataReady(){
  mpuInterrupt=true;
}
// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================
void setup()
{
  // join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000);

#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);

#endif

  Serial.begin(115200);
  while (!Serial);      // wait for Leonardo enumeration, others continue immediately

  // initialize device
  Serial.println(F("Initializing I2C devices..."));
  pinMode(INTERRUPT_PIN, INPUT);
  // testing connection...
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
  // load and configure the DMP
  Serial.println(F("Initializing DMP"));
  devStatus = mpu.dmpInitialize();

  // INPUT CALIBRATED OFFSETS HERE; SPECIFIC FOR EACH UNIT AND EACH MOUNTING CONFIGURATION!!!!
  //fix offsets #s when we use mount
  mpu.setXGyroOffset(0);
  mpu.setYGyroOffset(0);
  mpu.setZGyroOffset(0);
  //mpu.setXAccelOffset(-651); //unneccesary
  //mpu.setYAccelOffset(670);  //also unneccesary
  mpu.setZAccelOffset(17);

  // make sure it worked (returns 0 if so)
  if (devStatus == 0){
    // Calibration Time: generate offsets and calibrate our MPU6050
     // mpu.CalibrateAccel(6);
     // mpu.CalibrateGyro(6);
     // mpu.PrintActiveOffsets();
    // turn on the DMP, now that it's ready
       Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.print(F("Enabling interrupt detection (Arduino external interrupt 0)"));
    Serial.print(digitalPinToInterrupt(INTERRUPT_PIN));
    Serial.println(F(")..."));
    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);

    mpuIntStatus = mpu.getIntStatus();
    Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;
    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
  }else
  {
    // ERROR!
    // 1 = initial memory load failed, 2 = DMP configuration updates failed (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP Initialization failed code = "));
    Serial.println(devStatus);
    Serial.println(F(")"));
  }

  // configure LED for output
  pinMode(LED_PIN, OUTPUT);
  myServo.attach(servoPin);
  PWM=0;
}

//main program loop

void loop()
{
  // if programming failed, don't try to do anything
    if (!dmpReady) return;
    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        if (mpuInterrupt && fifoCount < packetSize) {
          // try to get out of the infinite loop
          fifoCount = mpu.getFIFOCount();
        }
        // other program behavior stuff here
    }

  //reset inerrupt flag Get INT_STATUS byte
  mpuInterrupt=false;
  mpuIntStatus = mpu.getIntStatus();

  // get current FIFO count
  fifoCount = mpu.getFIFOCount();

  // check for overflow (this should never happen unless our code is too inefficient)
  if (fifoCount<packetSize){

    // reset so we can continue cleanly
  }else if ((mpuIntStatus & _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024) {

    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));

  }else if (mpuIntStatus & _BV (MPU6050_INTERRUPT_DMP_INT_BIT)){

   while (fifoCount>=packetSize)
  {
    // check for correct available data length
    //if (fifoCount < packetSize)
    //return; //  fifoCount = mpu.getFIFOCount();

    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);

    // track FIFO count here in case there is > 1 packet available
    fifoCount -= packetSize;
   }
     #ifdef OUTPUT_READABLE_QUATERNION
     //display quaternion values in easty matrix form: w x y x
    mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.print(q.z);

    #endif
    #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif
        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Yaw = ypr[0]*180/M_PI;
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif
        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif
        #ifdef OUTPUT_READABLE_WORLDACCEL
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

    // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
  }
  PWM= map(Yaw, -180, 180, 1860, 1140);
  myServo.write(PWM);
  Serial.println(PWM);
  Serial.println(Yaw);
}

If the error code is needed please let me know. It's too long to attach in the body

Only the first one perhaps two errors in compiler output are normally useful.  The ones that follow are often the result of the first error or the compiler's attempt to recover from it and sometimes end up being more misleading than helpful.  It's probably enough to paste just the top of the output.

Thanks for responding. I had multiples of some libraries. Don't know how that happened. But I uninstalled all the libraries, and manually installed the ones I needed. It works now.


text:
Send commands from cPanel website to client ESP8266
I have a project where I want to remotely turn on and off a relay using an Arduino,(ESP8266) over the internet.

I have a remote web server that hosts my existing hobby website, cPanel hosted by GoDaddy Sites.
An Arduino (ESP8266) connects to this website listening for relay on/off commands.
Open a browser and load the webpage dashboard to sent commands to Arduino.

Yes I could have the Arduino poll the website ever so often to check for a value changed in a database, but I don't want to do that, Just seems unethical to me.
I was looking at WebSockets and thought that might be what I'm looking for but I know too little about it or there's not enough relevant documentation online about it to use it in this type of project.
I am looking forward to your comments and answers, but please do not tell me to host the site on the Arduino, and also using an app or other service is not going to work either, We are working with my own webpage and thats it no thirdparty apps, Thanks.

What is the question?

why is checking a website unethical?

Because it is like a little kid in the back seat asking every km on the road, "are we there yet"? If there could be a way to tell the client when to turn on a relay only when needed, would be much more efficient. there will be millions of checks that are essentially useless, so having it just wait until the command is sent to it would be ideal.

I don't believe you will have the capability to implement a Websocket interface on the GoDaddy cPanel web site.  I think you are limited to just serving up HTML content and associated files.  Websocket requires a server-side resource to talk to which you cannot implement.
I see nothing wrong with having a simple HTML page, that doesn't even need to really contain HTML that your ESP8266 can "GET" and examine and determine to turn your relay on or off.

Thanks, yes that would and will probably work, as per my previous comment, it's just not ideal that way, creates constant internet traffic that's essentially useless.


text:
What's wrong? FastLED and WS2812B simulation works, physical build doesn't
I'm new to Arduino coding and FastLED. When it comes to coding, I'm a complete novice, however, I've been watching YouTube tutorials to help my knowledge. I have successfully run my code on Wokwi, however, when I upload my code to my Arduino, it uploads without error, yet the WS2812B doesn't run the code correctly and appears to freeze after the first pattern.
The LED strip works just run with my Adafruit code, running a very basic set of patterns I created (different than the below code).
Any help would be greatly appreciated! The code below is what I wrote up in Wokwi and the simulation works flawlessly. The only change when uploading to my Arduino is: NUM_LEDS  135
#include <FastLED.h>
#define NUM_LEDS  16
#define LED_PIN   5
#define BRIGHTNESS  255
#define caseCount 7
CRGB source1[NUM_LEDS];
CRGB source2[NUM_LEDS];
CRGB output[NUM_LEDS];

DEFINE_GRADIENT_PALETTE (christmasBlue_gp) {
  0, 0, 0, 255,
  64, 0, 0, 135,
  127, 255, 255, 255,
  191, 0, 0, 135,
  255, 0, 0, 255
};
CRGBPalette16 bluePal = christmasBlue_gp;

uint8_t blendAmount = 0;
uint8_t patternCounter = 0;
uint8_t source1Pattern = 0;
uint8_t source2Pattern = 1;
bool useSource1 = false;

void setup() {
  FastLED.addLeds<WS2812B, LED_PIN, GRB>(output, NUM_LEDS);
  FastLED.setBrightness(BRIGHTNESS);
}

void loop() {

  EVERY_N_MILLISECONDS(5) {
    blend(source1, source2, output, NUM_LEDS, blendAmount);
    if (useSource1) {
      if (blendAmount < 255) blendAmount++;
      } else {
      if (blendAmount > 0) blendAmount--;
      }
  }

  EVERY_N_SECONDS(5) {
    nextPattern();
  }
  runPattern(source1Pattern, source1);
  runPattern(source2Pattern, source2);
  FastLED.show();
}

void nextPattern() {
  patternCounter = (patternCounter + 1) % caseCount;
  if (useSource1) source1Pattern = patternCounter;
  else source2Pattern = patternCounter;
  useSource1 = !useSource1;
  }

void runPattern(uint8_t pattern, CRGB *LEDArray) {
  switch (pattern) {
    case 0:
      movingDots(LEDArray);
      break;
    case 1:
      whiteFill(LEDArray);
      break;
    case 2:
      greenFill(LEDArray);
      break;
    case 3:
      whiteFill(LEDArray);
      break;
    case 4:
      redFill(LEDArray);
      break;
    case 5:
      greenBlueTwinkle(LEDArray);
      break;
    case 6:
      greenRedSplit(LEDArray);
      break;
  }
}

void movingDots(CRGB *LEDarray) {
  uint16_t posBeat = beatsin16(30, 0, NUM_LEDS -1, 0, 0);
  uint16_t posBeat2 = beatsin16(60, 0, NUM_LEDS -1, 0, 0);
  uint16_t posBeat3 = beatsin16(25, 0, NUM_LEDS -1, 0, 127);
  uint16_t posBeat4 = beatsin16(45, 0, NUM_LEDS -1, 0, 127);
  LEDarray[(posBeat + posBeat2) / 2] = CHSV(0, 255, 255);
  LEDarray[(posBeat3 + posBeat4) / 2] = CHSV(120, 255, 255);
  LEDarray[(posBeat3 + posBeat2) / 2] = CHSV(120, 255, 255);
  LEDarray[(posBeat2 + posBeat4) / 2] = CHSV(0, 255, 255);
  LEDarray[(posBeat2 + posBeat4 + posBeat) / 3] = CHSV(0, 0, 255);
  fadeToBlackBy(LEDarray, NUM_LEDS, 1);
}

void whiteFill(CRGB *LEDarray) {
  fill_solid(LEDarray, NUM_LEDS, CRGB::White);
}

void greenFill(CRGB *LEDarray) {
  fill_solid(LEDarray, NUM_LEDS, CRGB::Green);
}

void redFill(CRGB *LEDarray) {
  fill_solid(LEDarray, NUM_LEDS, CRGB::Red);
}

void greenBlueTwinkle(CRGB *LEDarray) {
  EVERY_N_MILLISECONDS(50){
    LEDarray[random8(0, NUM_LEDS-1)] = ColorFromPalette(bluePal, random8(), 255, LINEARBLEND);
    }
  fadeToBlackBy(LEDarray, NUM_LEDS, 1);
  FastLED.show();
}

void greenRedSplit(CRGB *LEDarray) {
  for(int i = 0; i < NUM_LEDS; i++) {
    LEDarray[i] = CHSV(0, 255, 255);
    LEDarray[(NUM_LEDS-1-i)] = CHSV(120, 255, 255);
    FastLED.show();
    delay(100);
    LEDarray[i] = CHSV(0, 255, 255);
  }

  for(int i = NUM_LEDS - 1; i >= 0; i--) {
    LEDarray[i] = CHSV(120, 255, 255);
    LEDarray[(NUM_LEDS-1-i)] = CHSV(0, 255, 255);
    FastLED.show();
    delay(100);
    LEDarray[i] = CHSV(120, 255, 255);
  }
}

Does it work with, say, NUM_LEDS 15? Could well be a memory problem.

Good question and suggestion. I'll have to try it when I get home, I'm at work and my Chromebook doesn't support Arduino's IDE.

It might also be that your power supply is not powerful enough (see @st2000's answer). You could try reducing the brightness to reduce power consumption and see if that makes it work more reliably.

I reduced brightness to 100, which didn't solve the issue. However, I broke the code down more.
Ocrdu's suggestion of a memory issue might have been the issue. I removed 3 parts from the blend, so their is only 4 cases running on all 135 LEDs.
My "void greenRedSplit(CRGB *LEDarray)" code appears to have been freezing the Arduino anytime it "ran".

Consider what would happen if your power supply is not powerful enough.  Depending on the number of WS2812B you are lighting at the same time you may be exceeding the current rating of your power source.  Using the following quote from this source:

... consider how much current your LED strip is going to pull. With every
single LED on at full brightness, each breakout board can pull about
60mA (20mA per color channel).

We can calculate for a string of 15 WS2812 set to full brightness it would take 15 x 60mA or almost 1 Amp of power.  People commonly source power supply which can handle twice the expected high current load.  So, in this case you would need a supply which can source at least 2 Amps
Also consider not using the Arduino's linear voltage regulator for large current loads.  Not only does it have current limitations but it is also not as effective as a switching power supply. Instead use a power supply of the correct voltage and capable current rating for large current loads.
Try lighting only 1 LED at a time in the strip and stick to one color at a time.  If this works it is likely your power supply is not capable of supplying the necessary current to operate your project as expected.

Great thought since I would have overlooked this, had it not been for the videos I watched. I made sure I had enough power to run the strip on full bright white prior to the coding.

Another thought - you should avoid usig the Arduino's linear power regulator to power large loads.  Not only does it have current limitations but it is also not as effective as a switching power supply.

It would be very telling if you performed the test described in this answer.  Either result would be interesting.  If it works or if it does not work.


text:
STM32 as keyboard
I would like to use a STM32F105xx to build my own computer keyboard.
That MCU has support to USB OTG (FS).
So, I have 2 questions:

Can I flash microcontroller with usb or I need a external
programer?
How to do the computer recognize stm32 as a keyboard?

https://arduino.stackexchange.com/tour

The STM32F105xx series is not yet supported by either Arduino core (STM32 core or maple core) and neither mbed-os.
The chip is still usable with the STM32 provided framework, the STM32HAL, (e.g. through STM32CubeMX). There you can select your chip and generate a template project. The program lets you easily configure the chip for "USB Device" role and HID (Human-Interface-Device) class.

Note that from a hardware side, you must provide the chip with an external crystal oscilator (usually 8MHz) so that the HSE+PLL can generate the 48MHz USB clock. This will not work on the internal HSI clock due to low precision. Activate the HSE Crystal in the RCC section of CubeMX and see the clock configuration tab.
From there on you'll have to read the STM32F1 HAL documentation to figure out how to send keystrokes. There are also external resources here and here.
Programming the board via USB is possible. Just set the BOOT0 and BOOT1 pins accordingly and reset the board to get into bootloader mode. It will then appear as a USB device which is flashable by given tools. See e.g. here. The more direct way is to buy a cheap STLinkv2 and program it via the SWD pins (SWDIO + SWCLK), which also enables debugging, which USB flashing does not.


text:
Arduino and DAC
this might be more general electronics question, forgive me if this is not the correct place to ask.
I am atempting to use the arduino and MCP4725 breakout board to inject 4 different voltages into an existing line that comes from V1.
V1 is the analog signal from an existing unit and varies between 2v, 3v and 4v. VM1 responds to those voltages and switches to a different working modes. 2v == Mode A, 3v == Mode B, 4v == Mode C.
My plan is to have MCP4725(represented as V2 below)hooked up to Arduino to simulate Modes A, B, C when needed.
MBR0540 D2 is there to prevent sending the voltage back to the sending unit, MBR0540 D1 is to do the same for DAC.
I am worried that if the D2 fails for whatever reason, I might loose the sending unit functionality.. is there a better way to do it?

simulate this circuit – Schematic created using CircuitLab
Thanks for any help/comments you might have.

VM1 will receive the higher voltage of the two sources. If V1 is set to 4V then V2 will not be able to do anything - it will be ignored. Is that really what you want?

yes, thats what I would like, to occasionally send higher voltage and change the Mode on the receiving end ignoring 2v in this case

Here is a video about reverse voltage protection. It's my favorite one. High current is not your problem. But Afrotechmods shows more ;-).  https://www.youtube.com/watch?v=IrB-FPcv1Dc . With the MOSFet solution you have nearly 0 voltage drop. Then you can make the protector more safe by using more stages.

You can also use two OpAmp Buffers https://en.wikipedia.org/wiki/Buffer_amplifier to separate the two outputs from each other. That has also the avantage of being able to drive more load, if you would need it.

There is also a solution I would like the most. As you ask for security, a complete separation of the two lines would be the best way. I would measure the output voltage of V1 with the arduino and if the arduino should overwrite it with a higher voltage it generates it with the MCP4725. Both outputs the V1 and V2 are connected to a 2 channel analog multiplexer. The arduino is able to toggle it for its needs. It depends on the security level you needs, whether you should use such a complicated solution. But I would do it, just for the fun ;-).

thanks @Peter Paul Kiefer I will investigate the MOSFET solution, is there a safe(fallback) solution using analog multiplexer so that if it fails it fails back to V1 voltage all the time?

There is always a risk that the multiplexer fails. You could use two of them to lower the risk. you have also the risk of a failing MCU. If you use two multiplexer in parallel, you could lower the risk that the multiplexing will be disturbed. But it's more complex to handle MCU failures. You could build a watchdog circuit with a capacitor that is loaded over a time interval and that is discharged from an permanently triggered impulse by the MCU. If the MCU fails the cap. is charged to the maximum voltage. You can use the voltage to switch the muxer to the V1 channel. (Just an idea!)

Unless you are really stressing it, it is highly unlikely that D2 would fail.
You could, though, replace both diodes with a simple SPDT switch to select between the two voltage sources.
Whatever you do, though, it probably has about the same chance (or more so) of failing (and the same end result) as having the diodes.
You could always add an "emergency override" switch that both bypasses D2 and isolates V2 in case of failure.

thanks for this, what would stress it? would giving it permanent 4v be considered stressing it?

The MBR0540 supports up to 40V, so you're not even close to stressing it.


text:
op amp circuit single sourced from arduino power
Getting an audio signal from a 3.5mm jack amplified (non-inverted) and fed into analog in pin on a Mega 2560. I am having problems using a potentiometer as a variable resistor to adjust gain. I'm also getting a lot of noise (+/-10 units on the 0-1023 scale)
Circuit:
- The audio is from a mono 3.5mm jack, playing from my laptop (with audio split to my speakers).
- Audio goes through an op amp TL071, single sourced shared with arduino 5V
- The potentiometer is wired with 2 pins as a variable resistor. The pins are connected to ground and the inverting input (VCC-)
- Output signal from the op-amp is biased by 2.5V and seems to work fine.

I'm closely following the instructions here (https://www.instructables.com/id/Arduino-Audio-Input/) but with a TL071 op amp as a single sourced from the Arduino 5V power supply.
The potentiometer doesn't seem to make much difference; I can even unplug it and I still get some readings on A0. I'm misunderstanding how to 'rewire' the op-amp for a single supply, but I can't figure out what else I can do.

I've also tried moving the variable resistor to bridge the output and inverting input (swap with the 100k resistor)

In case anyone is looking for a solution, I followed the TL071 manual (texas instruments) for an op-amp instead of using the diagram posted above. That signal then links into a bias.
The noise was coming from having 5V shared with the LED lights (WS2812B). Once I put them on a different circuit (shared ground) it was ok.

The TLO series don't work with 5v supply. They have also a reversal phase : that meens, when used in follower, it's output will go high when intut is lower than 3v...
One can use an old LM324 or LM358, but output is not going up to VCC...
OPA140 is a correct choice.
Also, may be a link capacitor of 100µF between input and potentiometer is necessary : this avoids amplification of DC, gives a centered output, and will reduce noise due to DC paht in potentiometer.

What I read from other posts was that the TL0 series is ok to use with 5V because I'm only trying to amplify a very small audio input.


text:
Why do I get different results when compiling the same code with different ide?
I have a basic code about reading true rms.I compiled the same code with arduino ide and atmel studio, then ran it in a proteus simulation.I'm trying to measure how long the read_rms() function takes.
My mcu:attiny84
1.experiment)I have added board to arduino ide with board manager.And I chose attiny84 and internal 1Mhz from tools menu in arduino menu.
The result was that the read_rms() function took 23.25 milliseconds.
2.experiment)I compiled the same code without any changes in Atmel Studio.Device,attiny84 selected.
The result was that the read_rms() function took 44 milliseconds.
44 miliseconds vs 23.25 miliseconds. Why?
Note:The following settings are selected in the proteus.Internal RC Osc. 8 Mhz,and CKDIV8=Programmed.
My code:
#define F_CPU 1000000UL
#include <avr/io.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stdint.h>
const uint8_t muxbits = 1<<MUX3 | 1<<MUX2 | 1<<MUX1 | 1<<MUX0;

void adc_init()
{
    ADMUX = 0;    //Vcc_ref_
    ADCSRA = (1<<ADEN)|(1<<ADPS1)|(1<<ADPS0); //adc_enable_and_prescaler_8_ 125000 Hz (1000000/8)
    //first_try
    ADCSRA |= (1<<ADSC);
    while ((ADCSRA & (1<<ADSC)) != 0);
}

uint16_t adc_read(uint8_t channel)
{
    ADMUX = (ADMUX & ~muxbits) | channel;
    // start_single_convertion
    ADCSRA |= (1<<ADSC);

    // wait for conversion to complete
    while ((ADCSRA & (1<<ADSC)) != 0);

    return (ADC);
}

double read_rms()
{
    uint16_t i=0;
    uint16_t a_data=0;
    uint32_t sum=0;
    float avarage=0;
    double rms=0;
    for(i=0;i<200;i++)
    {
        a_data=adc_read(1);

        sum=sum+(a_data*a_data);
    }
    avarage=(float)sum/200;
    rms=sqrt((double)avarage);

    return rms;

}

int main(void)
{

    DDRA|=(1<<7);
    PORTA &=~ (1<<7);
    adc_init();

    while(1)
    {

    read_rms();
    PORTA ^= (1<<7);// TOOGLE_PA7   for_measure_time_of_read_rms()_with_oscilloscope

    }
}

Impossible to tell. Maybe Atmel studio is using actual double-precision values for double whereas Arduino uses only float (single precision).

It's not impossible to tell. You could compare the assembler generated by both. I'm not very familiar with AVR assembler, so I wouldn't be the best choice to do that analysis, but  I'm sure somebody on this board could suss it out.

You could also get something of a fuzzy confirmation on whether float vs double is responsible by just altering your code to make use of float types everywhere.  This includes using sqrtf rather than sqrt.  As said, there may still be other differences, so the timing results may not completely converge.

Different compilers produce different machine code.
As Majenko pointed out, the Arduino IDE's compiler, which happens to be GCC, uses float even when you write double.
The Atmel Studio creates double for double, using twice as much bits.
Calculating with more bits takes longer.

I did float.the result is the same again.And I did sqrtf instead of sqrt.

Did you look into the generated assembly? There might be some implicit conversions to double, or Atmel's compiler uses the standard sqrt() even for sqrtf().

no I haven't examined.But,Why would there be such a thing?Instead of sqrt I typed sqrtf because I didn't want to use double numbers unnecessarily. As for the main problem, I think it's related to compiler configurations. But I haven't figured it out yet.


text:
How to read an analog value on ESP32-CAM with the SD card reader enabled?
I use an ESP32-Cam module for a project for which I need both the SD card and the cam. According to this page, the only pins that are not in use by either the camera or the SD card reader are GPIO0, GPIO2 and GPIO16. However, I need to read an analog value, which is only possible with the pins 12-15, 2 and 4, as the Arduino forums state, which are all in use by the SD card reader.
However, I came across a way to make the SD reader leave the GPIO4 pin out, namely by initializing it with
SD_MMC.begin("/sdcard", true);

Now the flashlight does not light up anymore when accessing the SD card, which means that there is no output anymore to GPIO4. However, it still does not allow me to read the pin after the SD card has been initialized. I also tried "converting" the pin to a GPIO through
pinMode(4, FUNCTION_3);

but it did not make a difference.
So my question is: How can pin 4 be used to read analog values while still keeping the SD card reader functional? And if this is not possible, is there any other way to read an analog value into the ESP32-CAM?

According to the schematic and pin notes, I don't think you can use GPIO4 as an ADC input (it can be used as a GPIO pin and technically it can be configured as an ADC pin), but it has a 47k pull-up resistor on it, making it not possible to be used as an ADC input.
Depend on your hardware wiring skill, one alternative is to use an external ADC chip with i2c interface (such as an MCP3221) and connect it to TWI_SCL and TWI_SDA, but those pins are only available on cam-connector, not on the header pins.

Thank you. I ended up using FTP instead of the SD-Card, which gave me "a lot" of digital pins. Then I connected an ADC-i2c-chip - as suggested - to two of them.


text:
detecting signal coming from another motion sensor that triggers camera's shutter
I have a motion sensor (used for camera trapping) that sends a signal to the camera to trigger the shutter. I am trying to use Arduino to turn on lights for 10 seconds by getting the signal from the motion sensor. I know there are ways to use motion sensor that can be used with Arduino. However, I need to know how I can detect a signal coming from the sensor to feed it to Arduino. I have tried connecting the cable from the sensor to A0, wrote a simple code to print the value of A0 but the serial monitor of Arduino shows nothing.

what motion sensor?

I guess the motion sensor is some third party product, which is not designed for the use with Arduinos. In that case you need to find out, what voltage levels and signal type the sensor uses. For the Uno the voltage has to be in the range of 5V. The type is most probable a digital signal. You need to find out, if it is active low or active high (active meaning the state, where the sensor is triggered). Amd whem the serial monitor doesm't show anything, then either your code or the setting of the serial monitor is wrong. Please look into this and then give more information in your question

What motion sensor? What code?

Thanks for the information. Here is the sensor:
Scout Trail Monitor
This a very advanced motion sensor which uses modulated IR beam and the only way for me to detect any signal (without taking the expensive equipment in parts) is to see what is coming from 3.5 mm shutter cable.
The very basic code to print:
    Serial.begin(9600);}

 void loop() {
  Serial.print("Value: ");
  Serial.println(analogRead(0));
  delay(1000);
}```

Please no code in the comments. You need to add all this information to your question by editing it. Also: you are trying to read from pin 0, which is the Serial interface. You need to read from A0

That's correct. I used A0.

Also, with multimeter set to 20k resistance, I can see some increase to about 16k

If you use the HC-SR501 motion sensor, see this tutorial

Almost all camera shutter cables are simple switches. They are an open circuit until you want to press the shutter, and then the switch closes. There is no voltage out of the shutter release, and so nothing for an analog pin to detect.
Many cameras have a shutter half-press switch that activates the light meter/auto-focus, and then a second switch that closes the shutter.
For a simple RCA plug shutter release or mono 3.5 mm plug shutter release, it's probably just a simple single pole switch. Wire one wire from the shutter release to a digital pin, and the other wire to ground. Set the pin to INPUT_PULLUP, and wait for it to go LOW. When it goes LOW the shutter is being pressed.
Be aware that a modulated IR shutter trap will be a little slow. It probably won't catch subjects like birds flying at high speed until the bird has moved past the point where the trap is pointed. For that you would want a laser beam and a fast phototransistor. Those can be fast enough and accurate enough to measure the speed of a bullet. (Although you need to read port registers directly in order to get fast enough response for that. DigitalRead() is too slow.)

Thanks for the great advise which helped me to detect the signal. Now I can see the output changes from 1 to 0 when. That's exactly what I needed.

If I've answered your question then you should accept my answer. (click the check mark.)

Sorry I am typing this here coz I don't have enough rep to comment. Anywho, most of the motion sensors involve PIR tech, so the best way is to connect your PIR Signal pin from your sensor to any analog pin of your arduino and test the kind of signal you're getting when the environment is idle and when movement is detected, Keep in mind of the region that the sensor covers too (ROI). That will tell you some things,

If the sensor works or not.
If the sensor value is analog or digital
If the sensor is active high or low
Trial and error on the actual ROI

After all that you can write your code around it.


text:
Line Following Robot using PID control not working
I'm currently making a line following robot using PID control. My robot uses an Arduino Uno board, a L298N motor, 1 9V battery, 2 motors, 5 TCRT 5000 infrared light sensors to detect a black line on a white surface. I uploaded the code successfully but my robot didn't do anything:

Both of my motors didn't run at all
the sensors couldn't detect the line. The sensors somehow could only detect the distance between it and the ground when i lift the robot above the ground.
The wire connections are fine.
When i used a multimeter to measure the voltage, I found out that there was no voltage from the L298N to both motors. The circuit diagram that i'm using:
[![enter image description here][6]][6]

And this is my code:
float Kp = 1;
float Ki = 1;
float Kd = 1;

//setup speed of the motors
#define ENAspeed 200
#define ENBspeed 200

#define ENB 5 // Enable pin PWM of the Left motor
#define IN4 6 // pin of left motor
#define IN3 7 // pin of left motor
#define IN2 8 // pin of right motor
#define IN1 9 // pin of right motor
#define ENA 10 // Enable pin PWM of the Right motor

int Sensor[] = {A1, A2, A3, A4, A5};
float P = 0;
float I = 0;
float D = 0;
int Error = 0;

int Previous_Error, Previous_I;
int PID_value;
int Left_Speed, Right_Speed;

void setup(){

     pinMode(9, OUTPUT);
     pinMode(8, OUTPUT);
     pinMode(7, OUTPUT);
     pinMode(6, OUTPUT);
     pinMode(5, OUTPUT);
     pinMode(10, OUTPUT);

     pinMode(A1, INPUT);
     pinMode(A2, INPUT);
     pinMode(A3, INPUT);
     pinMode(A4, INPUT);
     pinMode(A5, INPUT);

     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);

     analogWrite(ENB, Left_Speed);
     analogWrite(ENA, Right_Speed);

     for (int i = 1; i <= 5; i++)
      {Sensor[i];}
     // reading the sensor if HIGH (Black line) or LOW (White line) line
     Sensor[1] = digitalRead(A1);
     Sensor[2] = digitalRead(A2);
     Sensor[3] = digitalRead(A3);
     Sensor[4] = digitalRead(A4);
     Sensor[5] = digitalRead(A5);
}

    void loop() {
    //use analogwrite to run motor at adjusted speed
     CalculateError();
     Calculate_PID();
     motor_control();
}

  void CalculateError(){
  if ((Sensor[1] == 1) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 4;}
  else if ((Sensor[1] == 1) && (Sensor[2] == 1) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 3;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 1) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 2;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 1) && (Sensor[3] == 1) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 1;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 1) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 0;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 1) && (Sensor[4] == 1) && (Sensor[5] == 0))
  {Error = -1;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 1) && (Sensor[5] == 0))
  {Error = -2;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 1) && (Sensor[5] == 1))
  {Error = -3;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 1))
  {Error = -4;}
  //Special case
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {if (Previous_Error = -4) {Error = -5;}
  else if (Previous_Error = 4) {Error = 5;}}
  else if ((Sensor[1] == 1) && (Sensor[2] == 1) && (Sensor[3] == 1) && (Sensor[4] == 1) && (Sensor[5] == 1))
  {Error = 0;}
}

  void Calculate_PID() {
    P = Error;
    I += Error;
    //I = I + Previous_I;
    D = Error - Previous_Error;

    PID_value = (Kp * P) + (Ki * I) + (Kd * D);

    I += Error;
    Previous_I = I;
    Previous_Error = Error;
}

  void motor_control() {

     //define new speed limitation for the engine
     Left_Speed  = constrain (Left_Speed, 0, 255);
     Right_Speed = constrain(Right_Speed, 0, 255);

     //calculating the effective motor speed:
          if ((-5 < Error) and (Error < 0)){
              Left_Speed  = ENBspeed - PID_value;
              Right_Speed = ENAspeed + PID_value;
          }

          if ((0 < Error) and (Error < 5)){
              Left_Speed  = ENBspeed + PID_value;
              Right_Speed = ENAspeed - PID_value;
          }

          if (Error == 0){
              Left_Speed  = ENBspeed;
              Right_Speed = ENAspeed;
          }
     }

Sorry for my bad English if there is any mistake. I'm quite new to Arduino and thanks in advance for your help.

9V battery ... if this is a regular block battery, then it is only good in very low current applications, such as smoke alarms

so should i use a 4 AA battery instead? Thanks for your recommmadation.

Both of my motors didn't run at all ... it is pointless to even look at your code ... first, make sure that you can control one motor ... write a simple sketch to run one motor, in one direction, for one second, pause one second, then repeat .... then run opposite direction .... then run two motors .... each time use a simple sketch that does only one thing ........ then move to sensors .... light up an LED to indicate that the sensor is detecting a line, nothing more ... when all components work, then move to combining the components

what voltage do 4 AA cells produce?

Yes, maybe i should slow down and try to do it step by step. 4AA cells if connected in series then it'll produce a 6V output. Is that the answer you're looking for?

i am not saying that you need to slow down ... i am saying that you need to test the hardware first ... at this point, you do not know if the problem is caused by hardware, or by software ... about the AA cells, i just qanted to make sure that you were aware of the voltage, because you said that you ate using a 9 V battery .... anyway, since you probably have everything connected, try replacing the battery before you start testing motors and sensors ... you may actually have everything already working, only power starved

LOL I guess problem solved. I did like what you'd suggested and turns out, the hardware, software, wire connections are fine. The robot doesn't move due to the 9V battery. The motors did spin but didn't provide enough force to move the robot. Thanks for your help, i'll use 4AA cells instead.


text:
What processor can I replace on behalf of ATMEGA328P, to get more processing power for machine learning in UNO
I wanted to do a machine learning project in Arduino UNO R3. But I came to know that the processor(ATMEGA328P) isn't capable of supporting the processing power needed for machine learning. So is there any other processor that is better than ATMEGA328P for machine learning that is supported in UNO? If not any other way that I can do it?

if you replace the ATMEGA328P with something else, then you no longer have an Arduino UNO

The UNO part of this question is almost certainly a dead end.  If the "it" in "If not any other way that I can do it?" refers to machine on an Arduino(ish) board, then more details on the sort of thing you want to do are needed, that "processing power" you spoke of.  You may find that none of them are really up to the task, but it depends on the task.

@jsotola Thanks a lot

@timemage Thanks for your help

You can't just replace the processor on the UNO with something better. The 328P is pretty much the best MCU there is in the pinout for that board.
Instead you can replace the whole UNO with something more powerful.
My board of choice for AI work would have to be one based on the Kendryte K210 chip, such as the Maixduino (which is helpfully in an UNO footprint).  The K210 is a dual-core 64-bit 400MHz RISC-V CPU with embedded neural network co-processor. On the Maixduino it's also coupled with an ESP32 for WiFi/Bluetooth.  That's 2x 400MHz 64-bit cores, 2x 32-bit 240MHz cores, one low-power FSM core, and a neural network core all on one board.

I fully agree. Putting a machine-learning processor on an UNO shield is like strapping a get engine onto a Ford Pinto

@Majenko Thank you

@DuncanC +1 for the image of a Ford Pinto with a jet engine ... lol ... of course I added screaming passengers to that picture

The Arduino blog recommends this: https://store.arduino.cc/nano-33-ble-sense.
See: https://blog.arduino.cc/2019/10/15/get-started-with-machine-learning-on-arduino/
I know Arduino has been talking about machine learning for about a year or so. Here's the Google search I used to find this: Arduino machine learning.
Here's a kit you can buy too: https://store.arduino.cc/usa/tiny-machine-learning-kit.


text:
Confusion regarding PID library?
PID library is available(built in) in standard installation  of arduino IDE or do we have to download it additionaly after installing our IDE?
How can i check which of libraries are available in my standard installation?

Open the Library Manager and search for the library you want. You will
see a list of libraries matching your query. Under the name of each of
those libraries, you will see a line showing the author and the version
number.

if this lines stats with “Built-in”, then it is a library that comes
with the standard installation of the IDE

if the line ends with “INSTALLED”, then this library is installed in
your system.

Can you please name any famoous/common library which is "installed" and also any "library" that is built in?


text:
l298n voltage loss when motor attached
Im trying to power a brushless DC Motor (Tamiya 300054358) through the l298n attached to an Arduino.
The l298n is powered by an external 9V source and the logic of the l298n is powered by the Arduinos 5V, wich is also powered by the 9v.
Both components using the same ground.
The code looks good and i can successfully adjust the power-output for the motor between 6-9V.
As soon as is attach the Motor, the volage drops do somewhere around 0-1V and the motor isnt turning.
When i attach the motor directly to the power source, it runs fine, so the power should be enough. (in the original RC car its powered by an 7V battery).
I tried some smaller motors just to be sure and the problem is similar. The motor is turning, but very slowly.
I also tried to connect the batterypack instead of the extern power source just ending up with the same result.
Do you have any ideas, where the problem could be at?
Thanks in advance

The problem is in the H driver. You lose about 1.4 volts on each leg so your loss from the battery is about 2.8 volts. The internal driver transistors are in a darlington configuration. If the bridge were Power MOS instead of bipolar transistors your voltage would be dependent on the resistance of the MOSFETs. Typically a few tenths of a volt in total. If your 9V source is a battery you probably are not getting the 9V you are expecting.

From an L298N datasheet:

TOTAL DC CURRENT UP TO 4 A

From motor's "datasheet":

I'm no expert in electric motors and driving them, not even sure I'm novice level, but I just don't see you driving a motor anything near this current draw with this part.  If by some miracle you can, it will be horribly inefficient owing to the losses associated with the voltage drops that Gil mentions.
For a motor that operates with this much current I would expect a practical h-bridge setup to have discrete mosfets, perhaps mounted to a heatsink.

ah okay. So if im getting this right, i need a Mosfet witch is capable of handling 150A.
So something like this?
https://www.reichelt.de/mosfet-n-ch-150v-150a-680w-0-011r-sot223b-ixfn180n15p-p257219.html
As you can see im quite new to this and im just not sure with these numbers.
Thanks for your help!

I would like to address some of this, but I really can't answer it well, less so in a comment.  Probably the best thing to do is to ask about appropriate driving circuity for that motor on the electronics SE.  If you want to try to ask here, it would probably be similar, but less open ended, e.g. "is there an Arduino-friendly shield/module that can handle this motor's current requirements?"; I don't know how well that will go though.

I will just caution you that there's a lot more to it than picking a FET by datasheet where the large current shown in the datasheet is greater or equal to your motor current.  That number is often a maximum current for some pulse usage scenario which may not match how you're actually trying to use the FET.  And I'm sure there are other factors to consider.

thanks for your advice! I really should try to get into these things deeper first.


text:
Piezo buzzer with PWM on arduino uno with atmega328p in C on registers + analogRead on registers
I have a little project at the university where I have to use the timers to generate a pwm signal and get it into a piezo buzzer when something else turns over a certain value by using the registers, the thing is that we have worked on some other microcontrollers so I don't really know the libraries for arduino uno with atmega328p and I would require some help on that. Also I have to use the registers instead of the function analogRead() that is reading from a temperature sensor.
Having the following code that works for my setup:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //Digital pins to which you connect the LCD
const int inPin = 0;
const int buzzer=9;// A0 is the sensor
void setup()
{
  pinMode(buzzer,OUTPUT); // DDRA=0b00000001;
  lcd.begin(16,2);
}
void loop()
{
  int value = analogRead(inPin); // read the value from the sensor <= to be written on registers
  lcd.setCursor(0,1);
  float millivolts = (value / 1024.0) * 5;
  float celsius = (millivolts-0.5)*100;
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(celsius);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print((celsius * 9)/5 + 32); //turning the celsius into fahrehait
  lcd.print("F");
  delay(1000);
  if(celsius>30.0){tone(buzzer,1000);delay(1000);noTone(buzzer);delay(1000);} //<= on registers
}

Step one: read the ATMega328P datasheet. That has all the information you need.

So is your question; how to convert the above code to use registers instead?

In fact all the mentioned function calls are using the Special Function Registers (SFR) and thus the hardware peripherals of the Arduino in the background to work. But I guess this is an exercise to learn how to configure and use these peripherals yourself. Doing this for the whole code is a rather big task for a single question on this site. So I will give you hints and will point you to the corresponding registers. Then the datasheet of the Atmega328P (the microcontroller on the Arduino Uno) is a must read for you. It contains detailed descriptions for almost every function and SFR of the microcontroller.

PWM: I think you want to use PWM for creating a tone from your buzzer. This is not the classical PWM use case (as you don't need to change the duty cycle but the frequency to get different tones). Nonetheless you reach it with the same hardware. For hardware PWM you need to configure a Timer. The Uno has 3 Timers, where Timer0 is already configured by the Arduino IDE for functions like delay(), millis() and such. So I suggest you use Timer1. It has 3 control registers called TCCR1A to TCCR1C. You want the timer to be in CTC Mode (Clear Timer on Compare Match)(Waveform Generation Mode Bits set to 4, CTC mode for OCR1A). The timer will count up with the set frequency (will describe this later) until it gets to the value, that you wrote into the OCR1A register (Compare Match). Then it will reset. If you have set the COM1Ax bits in the TCCR1A register to the correct values, you can set it up to toggle the OC1A pin on a Compare Match).
So in this mode, the timer will reset at a counter value that you set and will toggle the OC1A output pin for you. Thus it generates a square wave with variable frequency, that you can control by writing different values to the OCR1A register.
But we also need to configure the frequency with which the timer will count up. This is done by the clock selection bits CS10 to CS12 in the TCCR1B register. A value of 0 for all bits means the timer is stopped. Look at the corresponding table in the Timer1 register descriptions in the datasheet. You want to connect the timer to the internal system clock. With these bits you can set the prescaler. This determines how many clock pulses it needs to let the timer count 1 up. With no prescaler the timer will count at every clock pulse. With the bit values 0 1 1 you will get a prescaler of 64, so the timer will count up 1 every 64 clock pulses. This sets the frequency range, that you have with the counter. The internal system clock runs at 16MHz on the Uno (you can do the math with the prescaler to calculate for the wanted frequency).
analogRead aka ADC: For reading an analog voltage the ADC (Analog Digital Converter) is used. It has the SFRs ADMUX, ADCSRA, the convertion result registers ADCL and ADCH, and ADCSRB. First we want to set the reference voltage for our conversion. When we set the REFS1 and REFS0 bits in the ADMUX register to 01 we use Vcc as voltage reference, which is sufficient most of the time. The bits MUX3 to MUX0 in the same register select one of the ADC pins for AD Conversion (We have only 1 ADC in the Atmega328P, but we can connect it to multiple ADC pins one after another). Now on the ADCSRA register: The ADEN bit will enable the ADC, with ADSC we can start a conversion. With the bits ADPS2 to ADPS0 we can select a clock prescaler for the ADC. This determines how fast the ADC runs. For maximum resolution you should keep the frequency between 50 and 200kHz.
You can start a conversion by writing 1 to the ADSC. Then you can poll the ADIF bit in the same register. It will be set to 1, when the ADC has completed the conversion. Then you can read the conversion result from the ADCL and ADCH registers (for the Low byte and the High byte of the 10bit result). You should reset the ADIF bit after that by writing a 1 to it.
LCD: I don't know, if you also need to replace the LiquidCrystal library by your own code, since it does not use special peripherals (just digital pins). Digital pins are controlled via the DDRx, PORTx and PINx registers. Google "arduino port manipulation" for more information. And then you can resemble the functions from the library with it.


text:
10 DOF gyro and accelerometer to x,y,z displacement
I have a 10 DOF sensor with wire outputs labeled "VIN", "GND", "SCL", and "SDA".  I would like to wire these into my arduino and ultimately obtain x, y, and z displacement.  This might sound like a simple problem for a veteran but I have gotten lost in the literature and code.  Where can I learn how to do this or is there a library that I can use?

Google "10 DOF IMU" should give you plenty of information. Here is a learning resource based on Adafruit products https://learn.adafruit.com/products/1604/guides

When asking a question here it is always appreciated if you include part numbers.  Or vendor web pages.  Guessing, SCL is a serial clock line and SDA is the serial data line.  So it sounds like you have a chip which talks over an I2C serial bus.  So you need the I2C Arduino library.  But, the real problem - what does the chip look like inside?  How many registers?  What do the bits mean in those registers?  How do you control this chip?  That's why you need a part number.

Step one: Read the number(s) on the chip(s). Step two: find libraries and tutorials for those chips.

I think this is it.  https://www.dfrobot.com/product-818.html

The link to the datasheets is at the bottom of this page, https://wiki.dfrobot.com/10_DOF_Mems_IMU_Sensor_V2.0_SKU__SEN0140, but I don't know what is relevant in my case.


text:
HC-06 Arduino UNO not working
Trying to get my HC-06 to work. The idea is to control a addressable RBG LED strip in the future. Currently I'm using a Arduino UNO, some wires and a HC-06. I connect the VCC pin to 5V, GND to GND, RXD to TX and TXD to RX. The module has a red light flashing for a second and after that nothing happens. Any idea what I should do next?

What have you tried to connect to the HC-06 over bluetooth? Is your phone (or whatever you are using) actually connected to the HC-06? How do you know, that it is not working? What do you think should happen? What are you doing with the HC-06 (you didn't include your code)

I can't see the HC-06 on my phone, so I can't connect to it. I also found out that the RX pin can only accept 3.3V (previously I only used jumper wires and connected HC-06 directly to Arduino, luckily I have 1k and 2k Ohm resistors if they are needed).The RXD pin on HC is connected to TX (1) on Arduino, TXD is connected to RX (0) on Arduino. For the code I used this: https://i.imgur.com/MhUev3R.png

Probably need to get a breadboard and watch a video if I need to connect the resistors. Maybe if you could help me with a code? Later on I'll have 28 LED's connected to pin ~6 and I'd like to control it via bluetooth on my phone.

2 things: 1. Please copy&paste the code as text into your question. 2. Where did you get that code? It uses pin 0 and 1 for software serial, which cannot work, since hardware serial is on these pins. Also I don't see, why the delay should be needed

Is it required to use resisistors since RX pin needs 3.3V, I'm using USB atm but will use a 5V power bank in the future?

This question might be helpful for this. Your specific module might be 5V tolerant, but I think most HC-06 modules aren't. Look at what your seller says and then decide, if you wanna trust him with this. Or just add the voltage divider, since it doesn't hurt.

Voltage divider didin't work. So I'm connecting HC-06 to Arduino, the module flashes like 10 times and then stops (the light turns off). Isn't it supposed to keep flashing until a device gets connected to it? Currently just want my phone to be able to see this BT module. Any ideas what I should do?

Starting to think that the module is not working. Literally following Youtube guides, they are able to see the HC-06 bluetooth right after connecting the wires. Also their module keeps flashing...

https://i.imgur.com/mTlJ7fK.png This is what it currently looks like, using 1k and 2k resistors (followed this video https://www.youtube.com/watch?v=F6E5mP70jaw&t=1s). Do I need to give the Arduino a code for the module to start working? Currently is still just flashes and then the light turns off.

I don't know, how your module is set up. You should first implement the communication between Arduino and HC-06 (and the communication to the PC for forwarding). Then you can test, if the HC-06 is still alive at the point, that it stops flashing. You can communicate with the HC-06 with AT commands like described at this site. But for that, first fix your wiring. In your photo you are using hardware RX and TX pins, whereas the video tutorial uses different pins. Thats essential

I ordered a new module (also HC-06), this one is working. Guess the old one was sold to me in a broken state...

But thank you all so much for the help, can continue with the project now.


text:
How to connect ESP32 to HC-06?
I am making a small project (BT controlled "tank") and need to connect ESP32 with HC-06 (ESP32 will be in controller and HC-06 in the vehicle). Android phone communication with both ESP and HC-06 works prefectly, I can not just figure out, how to pair/connect these two modules. Any ideas?
EDIT: Just to clarify, I can not connect them, because the HC-06 has PIN and I can not figure out how to remove that PIN or connect to it with PIN from ESP32...

The HC-06 can just communicate over the SPP protocol (UART/Serial). Your phone (it isn't an iPhone, as it is not able to use this protocol) can search for this service. So, you have to set a GATT server or client and search for a characteristics with the SPP GUID (you can find something here: https://www.oreilly.com/library/view/getting-started-with/9781491900550/ch04.html). It isn't so easy and you are very limited. Why not use directly 2 ESP32 with ESP NOW for example?

You can either use a breadboard Or Female to Female Jumber wires.
Ofoucrse you can always solder yourself the two modules together with wires.
PS. Too low reputation to comment, so i insert this as answer

Yeah, I know that my question was a bit unclear, I meant connect / pair WITH BLUETOOTH, but thanks anyways.. :)


text:
EthernetClient not initializing properly
I am trying to make a connection with the EthernetClient, but it always fails with code 0. I decided to write a small code just to test if the client ever becomes ready, and as I suspected it does not.
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {0x2A, 0x27, 0x55, 0x08, 0x1E, 0x6A};
IPAddress ip(172, 16, 48, 133);
EthernetClient client;

void setup() {
  Ethernet.init(10);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
  while (!Serial) {;}

  for (auto link = Ethernet.linkStatus(); link != LinkON; link = Ethernet.linkStatus()) {;}
  Serial.println("Link ON");

  while(!client){
    Serial.println("Client not ready");
    delay(1000);
  }

  Serial.println("Client ready!");
}

void loop() {}

If I try to run the code above, it gets stuck at the "Client not ready" loop, and I can't figure it out what I'm missing for it to work.
Obs.: I have already configured a web server with success with my shield, so I'm guessing the problem is not with it.

I'm not sure why you're evaluating !client. This maps to the boolean operator which tells you if it has a connected socket (https://github.com/arduino-libraries/Ethernet/blob/6e9dffa64f6b0eb89607dbb5293dc33be82cc39e/src/Ethernet.h#L232). Since you have not called connect() on the client, this will always return false. What actual error do you have in your full sketch?

Connect returns 0. I've looked the source and found multiple points where it might return 0, so it's hard to diagnose.

@Maximilian the reference says only that it "Indicates if the specified Ethernet client is ready."

An EthernetClient expects to connect to a remote socket. At no point do you instruct it to connect to a socket, so it never succeeds.
At some point before checking for a connection you need to initiate that connection:
// arduino.cc is 100.24.172.113
IPAddress server(100, 24, 172, 113);
client.connect(server, 80);

The if (client) operation relies on sockindex having been assigned a valid value, and that is only ever done either by EthernetClient::connect() or by being explicitly set by EthernetServer::available().

in this example this is done to check if the client is available

@LucasNoetzold That example makes no sense. Like many on the Arduino website it's complete nonsense. You should only check if (client) to confirm a connection has been established. Normally only when using it as an incoming connection to a server.

As it states in the source code: // the next function allows us to use the client returned by // EthernetServer::available() as the condition in an if-statement.

I'll have to find why connect is returning 0 then. Thanks.

0 indicates DNS name resolve failure. https://github.com/arduino-libraries/Ethernet/blob/6e9dffa64f6b0eb89607dbb5293dc33be82cc39e/src/EthernetClient.cpp#L38 @LucasNoetzold


text:
A bug with multiple IR detectors
I have a device power by arduino nano atmega328.
The idea of this HW is to detects dropped seed (corn, oil bean etc.) and to count it.
I wrote initial code, but id does not work in an expected way. it increments one count "channel" (I have 8 pairs of IR diodes 3mm) automatically, and passing it does not detect.
Here is the code maybe, someone has some similar experience and maybe help me to refactor the code.
#include<wire.h>
#include<Adafruit_SSD1306.h>

int irPin1 = 1;
int irPin2 = 2;
int irPin3 = 3;
int irPin4 = 4;
int irPin5 = 5;
int irPin6 = 6;
int irPin7 = 7;
int irPin8 = 8;

int count1,count2,count3,count4,count5,count6,count7,count8, count = 0;
boolean state = true;

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

void loop(){
if(!digitalRead(irPin1) && state)
 {
   count1++;
   state = false;
   Serial.print("count1: ");
   Serial.println(count1);
   delay(200);
 }

if(digitalRead(irPin1))
  {
    state=true;
    delay(100);
  }

if(!digitalRead(irPin2) && state)
 {
   count2++;
   state = false;
   Serial.print("count2: ");
   Serial.println(count2);
   delay(200);
 }

if(digitalRead(irPin2))
  {
    state=true;
    delay(100);
  }

  if(!digitalRead(irPin3) && state)
 {
   count3++;
   state = false;
   Serial.print("count3: ");
   Serial.println(count3);
   delay(200);
 }

if(digitalRead(irPin3))
  {
    state=true;
    delay(100);
  }

    if(!digitalRead(irPin4) && state)
 {
   count4++;
   state = false;
   Serial.print("count4: ");
   Serial.println(count4);
   delay(200);
 }

if(digitalRead(irPin4))
  {
    state=true;
    delay(100);
  }

 if(!digitalRead(irPin5) && state)
 {
   count5++;
   state = false;
   Serial.print("count5: ");
   Serial.println(count5);
   delay(200);
 }

if(digitalRead(irPin5))
  {
    state=true;
    delay(100);
  }
 if(!digitalRead(irPin6) && state)
 {
   count6++;
   state = false;
   Serial.print("count6: ");
   Serial.println(count6);
   delay(200);
 }

if(digitalRead(irPin6))
  {
    state=true;
    delay(100);
  }
 if(!digitalRead(irPin7) && state)
 {
   count7++;
   state = false;
   Serial.print("count7: ");
   Serial.println(count7);
   delay(200);
 }

if(digitalRead(irPin7))
  {
    state=true;
    delay(100);
  }

 if(!digitalRead(irPin8) && state)
 {
   count8++;
   state = false;
   Serial.print("count8: ");
   Serial.println(count8);
   delay(200);
 }

if(digitalRead(irPin8))
  {
    state=true;
    delay(100);
  }
count= count1+count2+count3+count4+count5+count6+count7+count8;
}

I work in platformIO.

One of the the things that stands out immediately is that you're using the serial TX pin for an IR sensor but also using Serial to send. The way you've asked the question, this isn't exactly an answer though.

When the delays are active nothing else is. Try using the millies instead.

@Gil can you elaborate more or give me an example? what are the milies are?

@timemage do you have another solution? which I should use instead TX and serial?Im also into that shorten the code to create some kind event to subscribe on it, and then to check which ir is triggered..

See the blinkWithoutDelay example for using millis() instead of delay(). This is also referred to as non-blocking code.

Digital pin 1 is used for serial TX. Avoid using it for any other purpose if you need it for serial. Allocate a different free pin for sensor 1.

you are trying to run before you can walk ... get this to work with only one sensor ... then try two sensors ... it is a waste of everyone's time, including yours, by asking about eight sensors if you can't get one to work

@jsotola One is working. but strange, only digitalRead(6), others shows that there is some obstacle beetween although is not any.

one working is good ... since the others are failing, work on each one separately

use the working sensor for testing each of the other pins

Use arrays instead of a copy/paste coding style.
Use millis() instead of delay() statements to eliminate blocking code.
Explicitly configure input pins.
compiles, but untested:
uint8_t irPin[ 8 ] = { 2, 3, 4, 5, 6, 7, 8, 9 } ; // set the sensor pins here . Avoid 0 and 1.
uint16_t seedCount[ 8 ] = { 0 } ;
uint32_t lastSeedAtMs[ 8 ] = { 0 } ;
const uint32_t lockOutTimeMs = 200UL ; // milliseconds - prevent 1 seed generating multiple counts

void setup() {
  Serial.begin(9600);
    for ( uint8_t channel = 0; channel < 8 ; channel++ ) {
      pinMode( irPin[ channel ] , INPUT_PULLUP ) ;  // configure all input pins
    }
}

void loop() {
  for ( uint8_t channel = 0; channel < 8 ; channel++ ) {
    if ( digitalRead( irPin[ channel ] ) == LOW ) {  // sensor active low
      if ( millis() - lastSeedAtMs[ channel ] > lockOutTimeMs )  {  // if X ms passed since last detection on this channel
        seedCount[ channel ] ++ ;
        lastSeedAtMs[channel ] = millis() ;
        Serial.print("count");
        Serial.print(channel);
        Serial.print(": ");
        Serial.println( seedCount[ channel ] );
      }
    }
  }
}


text:
trigger a function of a Arduino Uno from signal received by LoRa module
I have two sx1278 Lora transceivers where both are connected to two Arduino Uno boards. I want to trigger a function in the Arduino Uno board where receiver side of LoRa connected using the signal received by Lora receiver.

Do you have a specific question? Have you looked at the examples of whatever LoRa library you’re using?

"LoRa by sandeepmistry" is the library I am using. I was able to send hello packets between two LoRa modules. Now what I want is trigger a function of receiver side of Arduino from a message get from LoRa module

what is preventing you from doing that? ... you still have not asked a question

I suggest writing code for that.

I'm assuming you have read the datasheet for the SX1278.  If not, please refer to it at:
SX1278 Datasheet
On page 69 you will see a couple of tables regarding the functions possible on the digital I/O (i.e. DIO) pins:

I'm not clear what exactly you are looking for or which mode you are operating in (you have provided almost no information about your project) but all the information you might need is available on these DIO pins.
You can connect the appropriate pin or pins to some of the edge sensitive lines on your Arduino and define and enable an INTERRUPT in your code.  So when the event you are waiting for happens, an interrupt will occur, you can go and read the data and do whatever with it.


text:
Arduino Mega 2560 + BLE HM-10 - I cannot execute AT commands
I have an Arduino Mega 2560 and a HM10 Bluetooth module (this one)
I have connected the Bluetooth according to the manufacturer's specifications:
VCC -> 5v
GND -> GND
TXD and RXD of the Bluetooth, I have tried to put them in pins of Arduino, in Serial1, in Serial2, in Serial3, with the same result.
The code I use for my tests is this:
#define BTserial Serial1

int LED_BOARD = 13;
int LED_RED = 2;
int LED_GREEN = 3;

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

    pinMode(LED_BOARD,OUTPUT);
    pinMode(LED_RED,OUTPUT);
    pinMode(LED_GREEN,OUTPUT);
}

void loop() {
    if (Serial1.available()) {
        dato = Serial1.readStringUntil('\n');

        Serial.println("DATA RECEIVED: [" + String(dato) + "]");

        if (dato.equals("1")) {
            digitalWrite(LED_BOARD, HIGH);
        }
        if (dato.equals("0")) {
            digitalWrite(LED_BOARD, LOW);
        }

        if (dato.equals("RED_ON")) {
            digitalWrite(LED_RED, HIGH);
        }
        if (dato.equals("RED_OFF")) {
            digitalWrite(LED_RED, LOW);
        }

        if (dato.equals("GREEN_ON")) {
            digitalWrite(LED_GREEN, HIGH);
        }
        if (dato.equals("GREEN_OFF")) {
            digitalWrite(LED_GREEN, LOW);
        }
    }
}

I have an Android phone, and I use the Arduino Bluetooth Controller (HM-10 Module) app.

I send the text 1, and the led of the Arduino board (pin 13) turns on.
I send the text 0, and the led of the Arduino board (pin 13) turns off.
I send RED_ON, and the led of my breadboard, connected to pin 2, turns on
I send RED_OFF, and the led of my breadboard, connected to pin 2, turns off
I send GREEN_ON, and the led of my breadboard, connected to pin 3, turns on
I send GREEN_OFF, and the led of my breadboard, connected to pin 3, turns off

So the Bluetooth works.
My problem is trying to see the list of Bluetooth commands (AT+HELP command).
I have a method that is responsible for sending AT+HELP to bluetooth, but I have no response.
This is the method, which I run in the main:
String str_ii = "";
int ii_0 = 0;
void ble_help(){
    Serial.println("ble_help");

    BTserial.println("AT+HELP"); // list all AT+ commands
    while (true){ // loop to print all AT+ commands
        char in_char = BTserial.read();
        if (int(in_char)==-1 or int(in_char)==42){
            continue;
        }
        str_ii+=in_char;
        if (in_char=='\n'){
            if (str_ii==String('\r')+String('\n')){
                if (ii_0 == 0){
                    ii_0 = 1;
                    continue;
                }
                break; // break after more than 1 empty carriage return and newline
            }
            Serial.print(str_ii);
            str_ii = "";
        }
    }
}

When executing this method, in application Arduino Bluetooth Controller (HM-10 Module) app i see the text AT+HELP, but there is no reaction / response from the bluetooh. Neither in the Arduino Bluetooth Controller (HM-10 Module) application nor in the Arduino serial monitor
What am I doing wrong?
Thank you.

First thing first you can see all AT commands available from the data sheet available from datasheet
Second to get strings from Serial to BTserial you can just use c = Serial.readStringUntil('\n'); like here
#define BT_RX           0
#define BT_TX           1
#define BT_Serial       Serial1
#define BT_Timeout      100

String c, c2;

void setup() {
  BT_Serial.setTX(BT_TX);
  BT_Serial.setRX(BT_RX);
  BT_Serial.begin(9600);//baudrate
  BT_Serial.setTimeout(BT_Timeout); //set bluetooth read/write timeout

  Serial.begin(9600);
  Serial.setTimeout(100);
  delay(100);
}

void loop()
{
  if (Serial.available()) {
    c = Serial.readStringUntil('\n');
    Serial.println(c);
    BT_Transmit_AT(c);
  }
  if (BT_Serial.available()) {
    c2 = BT_Serial.readStringUntil('\n');
    Serial.println(c2);
  }
  delay(20);
}

void BT_Transmit_AT(String data) { //send AT commands
  unsigned long current_time = millis();
  while (BT_Serial.available() > 0) {
    if (millis() - current_time > 100){ //timer to get out incase not receiving anything
      Serial.println("Timeout");
      break;
    }
  }
  BT_Serial.print(data);
}

And lastly you need to make sure your HM-10 is genuine/has genuine firmware installed or it's a clone. Check if it respond to "AT" with "OK" at all. If it does then it's genuine and you can continue. If it doesn't then you need to flash genuine firmware onto it, then upgrade from there if you. Here is a good tutorial on flashing the genuine firmware onto the module.
After that you can follow a tutorial here on upgrading the firmware from an older genuine firmware. You can get the latest genuine firmware from the Manufacture's website.


text:
Cannot program ATMEGA328PU after burning bootloader with internal clock
I have build a couple of boards that have an ATMEGA328P-AU (the 32 pin MLF, as used on the Arduino Pro Mini). If I burn a bootloader via SPI to use an external 8MHz clock, I can then use the Arduino IDE to write a program via the serial port. If I burn a bootloader to use an internal 8MHz clock, burning the bootloader is still successful but programming with the Arduino IDE does not work.
The current boards do have crystals, but I want to build the rest of the boards without a crystal, so I need to get internal clock working.
The internal (non-working) script looks like this:
avrdude -Cavrdude.conf -v -patmega328p -B4 -cusbasp -Pusb -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xE2:m
avrdude -Cavrdude.conf -c usbasp -p atmega328p -e -Uflash:w:ATmegaBOOT_168_atmega328_pro_8MHz.hex

The external (working) script looks like this:
avrdude -Cavrdude.conf -v -patmega328p -B4 -cusbasp -Pusb -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m
avrdude -Cavrdude.conf -c usbasp -p atmega328p -e -Uflash:w:ATmegaBOOT_168_atmega328_pro_8MHz.hex

By my reckoning, lfuse=0xE2 should be CKDIV8=1, CKOUT=1, SUT=10 and CKSEL=0010.
Any suggestions how to make the internal clock work?

Except for the clock division bit I never set any fuses and it works for me. For a test you could try without setting any fuses, the atmegas are set to run with the internal clock by default from my experience.

Use ISP programmer, file menu >> Sketch >> Upload using programmer, to upload the sketch instead of via UART (arduino bootloader) and completely ignore the bootloader thing. You have to choose correct programmer, file menu >> Tools >> Programmer. I suppose you spin your own pcb then pop out an ISP port is no problem. Just be aware that timing stuffs, like delay and all, would not work correctly. also you would run into trouble with UART as well. But I think add a small resonator like CSTNE16M0V51Z000R0 on PCB wouldn't be a problem since it's quite darn small and not that expensive.

Are you trying to program over serial? Serial requires a somewhat accurate clock. Maybe the RC-oscilator is to far of 8Mhz for serial to work. Can you upload a blink sketch over ISP, and have it blink with those fuse settings?