text:
Servo doesn't move if I detach it AFER the write?
So this is a bit weird, and I don't understand anything.
Basically, I'm just playing with my servo. I wrote a small program, which can be found at this link: https://pastebin.pl/view/8e9c9573 (Note: It's three files, I left some comments there, and the idk function is just my last resort, trying to separate myself from loop, I really don't know :/ ).
So I run controller.Setup() in the setup function, and then in loop I just move it to 180 and detach it, then I run into an infinite loop. Note: I know it's not very good code, but that's not what concerns me right now.
The problem is, when I add the call to detach (line 22), the previous move doesn't run! I think I'm going crazy, cause as soon as I remove the line and recompile, it actually moves.
I tried to remove the lock(Controller::m_Attached), and it still doesn't work. Please let me know if I didn't notice something, but I really don't understand.
Notes:

I'm using arduino-cli, here's my not-very-perfect Makefile: https://pastebin.pl/view/daa852ff
I use the Servo library: https://www.arduino.cc/reference/en/libraries/servo/
I'm using an Arduino Uno

EDIT:
Someone told me to post the code in the question, so here I go:
//Main.ino
#include <Servo.h>
#include "Controller.h"

Controller controller(3);

void idk();

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

void loop() {
    idk();
    while(true);
}

void idk() {
    controller.Move(180);
    controller.Unlock();
}

// Controller.h
#pragma once
#include <Servo.h>

class Controller
{
public:
    Controller(int servoPin)
        : m_ServoPin(servoPin), m_Attached(false) {}

    void Setup();
    void Move(int angle);

    void Lock();
    void Unlock();

private:
    Servo m_Servo;
    bool m_Attached;
    const int m_ServoPin = 3;
};

// Controller.ino
#include "Controller.h"

void Controller::Setup()
{
    m_Servo.attach(m_ServoPin);
    m_Attached = true;
    Serial.print("[CONTROLLER] Attached Servo\n");
}

void Controller::Move(int angle)
{
    if (m_Attached)
        m_Servo.write(angle);
}

void Controller::Lock() {
    m_Servo.attach(m_ServoPin);
    m_Attached = true;
}

void Controller::Unlock() {
    m_Servo.detach();
    m_Attached = false;
}

the detach() function probably stops the data pin from outputting the servo control signal ... you are disabling the control signal a few microseconds after you enable it, so it is never generated ... furthermore, a servo requires the signal to be present at all times

@jsotola Thank you sooo much. When I add a delay in between the function calls it works. You should make it an answer so that I can accept it

The detach() function probably stops the data pin from outputting the servo control signal.
Your code disables the control signal a few microseconds after it is enabled.
The cotrol signal is never generated.
Furthermore, a servo requires the signal to be present at all times for it to keep its position.
When your programming includes real-world events, you have to think about the time frame of the events, and about the time frame of the running program.
Think in the terms that the program can loop 100,000 times before the servo has finished moving.


text:
How to make 16 coin vibration motors and 5 servos work at the same time on a Arduino Mega?
I saw in Arduino Mega's datasheet that the sum of currents out of all input/output pins combined should be maximum 200mA. But I want to make 16 vibration motors and 5 servos work together on the same time. I made the circuit(NMOS, flyback diode, etc.) for every coin vibration motor.Also I'm thinking to power the servos with an external power source.Are the circuits enough so i dont pass the 200mA limit? How can I make the whole thing work together?
im using the following components:

NMOS
coin vibration motor
servo motor

You never power motors with an IO pin. All you ever do is send a tiny signal to the controller for the motor, whatever that is for the type of motor you are controlling.

I'm sorry for my english if i didn't put it down correctly. I'm actually using this circuit link. Do you mean that if i do that for all 16 motors i will be ok with this? Thanks for the response.

Yes, that is the standard motor circuit (except there should be some snubber circuit across the motor). Like I said - you don't power the motors with the IO pin. You just send a tiny signal. The current of the motors is irrelevant, and the current of the signal is minuscule. You'd be lucky to total 1mA.

But how is 1mA even possible?

Sorry? What do you mean, how is it "possible"?

I think its too low. Isn't it? I saw that every IO pin draw 35mA.

Do you understand the meaning of the word "limit"?

I tried with a multimeter to measure the IO current draw and it seems that i draw 35mA. Maybe I'm measuring the wrong way. Where should i put the probes to measure correctly?

Current is drawn by a device. The probes should be in series with the device drawing the current.

Thank you for your help!

source: Stack Exchange

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

sort: votes


text:
ESP8266 WiFi Not Connecting to Internet Without Static IP
I am seeing some very strange behavior with my ESP8266. When I connect it to the WiFi for the first couple of times I am not seeing any issues and the ESP8266 connects just fine.
But after an arbitrary amount of times (like when I restart the unit) it tries to connect for AGES (like multiple minutes). Eventually it says "Connected" but the IP is completely wrong and it is not connected to the internet (GET request fails).
Here are the odd things:

If I assign a static IP then it ALWAYS works and connects within seconds
If I factory reset my router then it works again for a few times
I have not seen this with any other device (like laptops or cellphones)

It is almost as if the DHCP is failing to assign an IP and then returns some random default.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

// Replace these with your WiFi network settings
const char* ssid = "MYSSID"; //replace this with your WiFi network name
const char* password = "MYPASSWORD"; //replace this with your WiFi network password

void setup() {
  Serial.begin(115200);
  delay(1000);

  IPAddress ip(192,168,1,77);
  IPAddress gateway(192,168,1,1);
  IPAddress subnet(255,255,255,0);

// If I uncomment this line then it works fine
//  WiFi.config(ip, gateway, subnet);

  WiFi.begin(ssid, password);

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

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("success!");
  Serial.print("IP Address is: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  HTTPClient http;

  String serverPath = "http://www.google.com";
  http.begin(serverPath.c_str());

  // Send HTTP GET request
  int httpResponseCode = http.GET();
  Serial.print("HTTP Response code: ");
  Serial.println(httpResponseCode);
  String payload = http.getString();
  Serial.println(payload);
  // Free resources
  http.end();

  delay(1000);
}

When DHCP magically works it assigns: 192.168.1.159
When DHCP does not work I get: 169.254.104.241
When I use a static IP then the static IP is assigned.
So the question is: Has anyone seen this behavior and maybe give some hints about how I can get the internet connection to be consistent without needing a static IP?
Update:
If I run a ping to 169.254.104.241 I get a reply. But if I try to get anything from the internet I get HTTP Response Code = -1.

Does the esp connect to wifi either case? That ip 169.254.104.241 is not valid, I guess, but does it actually get this ip (did you scan the network in that case)?

@SimSon I just ran a ping to that IP and it is responding and if I do "arp -a" then the IP shows up.
I did another test and it seems like the device doesn't have an internet connection (I think... I get HTTP Response Code -1). I updated the question.

Finally I figured out a solution. I downgraded the ESP8266 board version in Arduino Studio to 2.5.2 and it worked.

That is interesting. Is there any particular reason why you went to version 2.5.2 (the current version is 2.7.4)? What version was causing the problem? Did you try other versions?

This is normal behavior. well not really, that address is called a apipa address.
It's normal behavior for alot of O.S's to give itself an address in the 169.254.x.x range when they fail to get DHCP responses.
My guess is your library is doing this for you.
It's kind of like the ad-hoc of addressing, if all devices fail to get a dhcp response they will all be assigned to the same subnet, and can communicate with those apipa addresses.
My suspicion is that it may be your router.
You can verify this by downloading a free DHCP server application for your OS. Plug in via Ethernet for the PC that's running the DHCP App, Turn off DHCP in the router. If it stops happening you know it's the router.
Edit: Also, this may be a firmware caveat in the router. Check the router manufacturers website and see if any firmware updates are available. if it hangs with DHCP, most likely every customer with that firmware revision has had this problem. This sort of thing usually gets patched very quickly.

This was very useful information. Thanks! After your comment I just left the ESP to keep trying to GET a page from the internet and eventually like after 10 minutes it got a successful connection. I still have no idea why this is happening but for the sake of what I need I am good to leave it like this.
I will test that DHCP tool you mentioned when I get a break from work and see what happens.

Thanks for posting the question and the solution. I spent hours on google and reading message boards before coming across this. I am not sure if my root cause was the same, but to me the "strange" IP for my ESP8266 (nodemcu) came from them connecting through the Guest Network of my Asus router. This resulted in an identical problem to OP with complete random connecting and long duration of no connections to WiFi, Internet and Blynk
Reverting back to ESP8266 2.5.2 in Arduino Studio seems to have magically solved the issue. Someone should alert the makers of the library.

Glad I am not the only one that saw this issue! Spent so many hours on this. I thought I was alone. Haha.

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


text:
PCA on ESP32 - libraries and recommendations?
it would seem that this would be a commonly sought-after topic, however I cannot find straightforward libraries for this and it's taking too long, so please allow me the question:
Is there a good library for Arduino/ESP32 to run principal component analysis (PCA) on a 3D matrix? Any links etc welcome, EigenArduino is the 'only' library I could find but it's not exactly straight forward (no example code etc). I want to extract the first component of some data sized 3x3000.
Thanks

this looks like example code https://eigen.tuxfamily.org/dox/GettingStarted.html#title1


text:
Wire Halloween Wolf to howl with Arduino motion detector
I bought one of those Home Depot halloween wolves that howl. You can control it with a push-button to be on, or off. It has its own power source via 3 AA batteries that power the howl sound, red eyes and move the jaw.
I'd like to make it motion sensing using the Arduino motion detector.
I thought that I could just cut and splice the wires connecting the button to the wolf to Arduino leads, then use digitalWrite to turn it on/off based on distance detection but it's not working.
The motion detection is working fine, as I set it up like the motion alarm demo. A red LED lights up at the correct distance as well.
Arduino Setup:
pin 10 to J14
J16 to negative
E14 to wolf
E16 to wolf
I'm not sure which wolf wire is +/- so I've tried both
Code:
const int trigPin = 11;           //connects to the trigger pin on the distance sensor
const int echoPin = 12;           //connects to the echo pin on the distance sensor

const int redPin = 3;             //pin to control the red LED inside the RGB LED
const int wolfPin = 10;         //pin that will turn on the wolf

float distance = 0;               //stores the distance measured by the distance sensor

void setup()
{
  Serial.begin (9600);        //set up a serial connection with the computer

  pinMode(trigPin, OUTPUT);   //the trigger pin will output pulses of electricity
  pinMode(echoPin, INPUT);    //the echo pin will measure the duration of pulses coming back from the distance sensor

  pinMode(redPin, OUTPUT);
  pinMode(wolfPin, OUTPUT);
}

void loop() {
  distance = getDistance();   //variable to store the distance measured by the sensor

  if (distance <= 24) {

    analogWrite(3, 255);
    digitalWrite(wolfPin, HIGH);
    delay(5000);

    digitalWrite(wolfPin, LOW);
    delay(1000);
  } else {
    analogWrite(3, 0);
  }

  delay(50);
}

I know there's possibility one/both of my spliced wires aren't working, but I don't think so - I'm new, so it's most likely I have so lack of understanding on something.
Please help, Halloween is approaching...

You need to reverse engineer how the button is wired in the wolf to some degree. Controlling the wolf is certainly possible with the arduino, but you can't randomly connect  wires and buttons and axpect it to work.

bridge the button with relay contacts

I agree with @jsotola. I think you can also use a small signal transistor for this. Like the 2n2222a, and wire the base pin of the transistor to your gpio "wolfPin".

@SimSon I agree with you, please do a electrical schemat of the wolf so you can make right decision for how to control it. To just randomly connect wires is often the cause for fires and smoke ;-)

By the way, cool project, check in on Arduino "touch sensor" feature, then you can add other cool effects.


text:
4WD Robot keeps freezing
I have been working on a 4WD robot for a while now. The parts I'm using are Arduino v4 shield, l298N driver motor, Hc 05 ultrasonic sensor, DHT 11, mq2, Bluetooth module, servo motor, ir transmitter and receiver module and an uno all powered by 2 18650 Li ion batteries and a power bank. when i tried using the Ir sensors only, ultrasonic only or both for obstacle detection and avoidance the code freezes and nothing works anymore until i move the obstacle away then the robot makes the decision it wanted to make. it also used to reset occasionally while frozen but i fixed that issue by powering the Arduino separately. i noticed this problem mostly occurs when all the IRs give a low signal. i think the problem is with my code but i don't really see what i typed wrong.
#include <dht.h>
#include <Servo.h>

#define servoPin 11

// Create a servo object
Servo Servo1;

//Ultrasonic Sensor
#define trigPin 9
#define echoPin 10
// defines variables
long duration;
int distance;

//sensor pins
#define gasSens A4
dht DHT;

#define DHT11_PIN 2

//motor driver pins
#define in1 8
#define in2 7
#define in3 6
#define in4 5

//infared pins
#define lftIr 12
#define ctrIr 4
#define rghIr 3

#define buzzer 13

int dist=1000;
int lastVal=0;
int degVal;
int leftDist;
int rightDist;
int gasVal;
int logicVal=49;
int buzzerTrig=0;
unsigned long curTime;

void setup() {
  // put your setup code here, to run once:
  Servo1.attach(servoPin);
  Servo1.write(100);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);

  pinMode(lftIr,INPUT);
  pinMode(ctrIr,INPUT);
  pinMode(rghIr,INPUT);

  pinMode(buzzer, OUTPUT);

  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);

  curTime=millis();

  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0){ // Checks whether data is comming from the serial port
      logicVal = Serial.read(); // Reads the data from the serial port
   }

 if(millis()-curTime>=10000){
    int chk = DHT.read11(DHT11_PIN);
    gasVal=analogRead(gasSens);
    Serial.print(DHT.temperature);
    Serial.print(" C");
    Serial.print("|");
    Serial.print(DHT.humidity);
    Serial.print("%");
    Serial.print("|");
    Serial.print(gasVal);
    Serial.print("|");
    if(gasVal>500){Serial.println("Dangerous gas levels");buzzerTrig=1;}
    else{Serial.println("normal");buzzerTrig=0;}
    curTime=millis();
  }

 if(buzzerTrig==1){
  buzzerCall();
  logicVal==48;
  }

 if(logicVal=='1'){
      dist=distanceCall();

      int leftIr=digitalRead(lftIr);
      int centerIr=digitalRead(ctrIr);
      int rightIr=digitalRead(rghIr);

      if (leftIr==LOW && rightIr==HIGH){
        stopAll();
        while(leftIr==LOW){
          rightMov();
          leftIr=digitalRead(lftIr);
        }
        stopAll();
       }
       else if (leftIr==HIGH && rightIr==LOW){
        stopAll();
          while(rightIr==LOW){
            leftMov();
            rightIr=digitalRead(rghIr);
          }
        stopAll();
      }
      else if (leftIr==LOW && centerIr==LOW && rightIr==LOW){
          stopAll();
              while(leftIr==LOW || centerIr==LOW || rightIr==LOW){
                backMov;
                leftIr=digitalRead(lftIr);
                centerIr=digitalRead(ctrIr);
                rightIr=digitalRead(rghIr);
                }
                stopAll();
          }

      else if (leftIr==HIGH && centerIr==LOW && rightIr==HIGH){
          stopAll();
          while(centerIr==LOW){
            backMov;
            centerIr=digitalRead(ctrIr);
          }
          stopAll();
          delay(10);
          leftMov();
          delay(500);
          stopAll();
        }
      else{
        fowardMov();
      }
    }
}

int distanceCall(){
  // Clears the trigPin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);
    // Calculating the distance
    distance= duration*0.034/2;
    return distance;
}

void fowardMov(){
  digitalWrite(in2,HIGH);
  digitalWrite(in4,HIGH);
  digitalWrite(in1, LOW);
  digitalWrite(in3, LOW);
}

void backMov(){
  digitalWrite(in1,HIGH);
  digitalWrite(in3,HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in4, LOW);
}

void rightMov(){
  digitalWrite(in1, HIGH);
  digitalWrite(in4, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
}

void leftMov(){
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in1, LOW);
  digitalWrite(in4, LOW);
}

void stopAll(){
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}

void buzzerCall(){
    tone(buzzer, 5000);
    delay(500);
    noTone(buzzer);
    tone(buzzer, 1000);
    delay(500);
    noTone(buzzer);
 }

The goal is for the robot to avoid obstacles and move autonomously using only the IR sensors.
I used to power everything with the batteries but sometimes it shakes and moves slowly so i decided to power them seperately.
Do you think the problem is with my code or it's a hardware problem? Thank you

this seems to be an error logicVal==48; ... what is the purpose of logicVal? ... a more descriptive name would be useful ... assigning a numerical value and testing a character value tends to be confusing

i move the obstacle away then the robot makes the decision it wanted to make and, what decision would that be? .. you did not say anything about how you expect the robot to behave, and how it should react ... there is no way to know if parts of code actually are meant to do what they do

Without a bit more information it will be difficult to give you much help.  At a minimum, we need a wiring diagram and some more specifics about the DHT library you are using, as there are several.  Also, it appears you have code for a single ultrasonic sensor  that is not used at all.  I have some fairly extensive experience with the HC-04/05 ultrasonic sensors and may be able to help you sort out the problems, but not if we don't have some idea about what you are trying to accomplish

@jsotola i'm sorry if i confused you but i forgot to mention i made an app with MIT app builder to send data to switch the robot on or off and also to display sensor data. what i expected to happen is depending on which Ir goes on first .the robot should move away until that Ir reads high. it works for the left and right Ir but for the center it freezes. it also freezes when all the sensors read low or when the  center and another read low. when i remove the obstacle in front of it then the robot turns left right or even turns around. Thank you for helping i hope you understand my problem now

@user3765883 i'm sorry i will add my schematic to the post I don't know who the dht library i'm using was created by i just downloaded it from the tutorial by circuit basics on how to use a dht (https://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-arduino/) Initially i used an ultrasonic sensor but it didn't really work well especially when it faced fabric so i decided to combine it with Ir but after a test my robot hit something then my servo stopped working it's hard and expensive to get parts in my country so i decided to use only IR thats why the variables are there

I'm not surprised that you are having trouble, as you have a very complicated system.  When troubleshooting complicated systems it is important to break it down into very simple 'chunks' and make sure each simple piece works separately.
I would remove everything but the code for the three IR sensors from your system, and use a random number generator to generate a random number between 0 & 7. Then I would use the binary representation of that number to generate the return values for the digitalRead() calls to the sensors, with appropriate printouts to show you what values were generated and what effect those values produced.  I think you'll find that one or more of the 8 possible values causes problems, as you only have IF clauses for 4 (or 6 if you count the two 2-valued systems twice).

Thank you for helping. I took your advice and removed everything except the code for the IR. i also generated random values between 0 and 1 to see what causes the code to freeze. The code doesn't freeze anymore everything works fine for some reason now. maybe the problem was from another part of my code. What do you think? Thank you.

I decided to modify the robot a bit. i'm now using 3 li ion batteries to power both the Arduino and the motors. I tried the script again with only Ir. instead of generating random numbers i decided to see how it'll work with obstacles.  it didn't work.The robot froze immediately it got to a wall so i used the serial monitor to check it out. The problem is with the center IR anytime it reads low first although on the serial monitor the message prints the robot freezes.  Do you think i should use PWM to make the robot slower? Would that improve obstacle detection or it won't matter

Congratulations on making progress!  I'm not sure that going slower will solve your problem, but I doubt it will.  You probably have an issue with your program logic that, if  left unsolved, will continue to make your robot unreliable.  The good news is, now that  you know you have a problem, you should be able to figure it out.  Maybe some more print statements at different points so that you can build a more complete picture of what is actually happening with your logic?  The Mega is undoubtedly executing the programmed logic correctly, but it's also probably not doing what you think ;-).

Thank you very much for your help i have seen the problem. The issue was when the center IR reads low and it enters the while loop it does not move because i did not call the function properly i typed backMov; instead of backMov(); now it works a lot better but i noticed that the UNO resets every time its faces an obstacle. It still avoids the obstacle despite the reset but i don't know why it resets Could it be because the batteries are low? I don't even get a lot of use time with it and i feel it might be due to the fact that i made my own battery holder with easy materials what do you think

If the Mega is resetting it is almost certain it is due to something drawing more current and causing the Mega's internal voltage to drop below 5V.  If you are using the barrel connector or Vin for supplying  power to the Mega, there is about a 2V drop across the internal voltage regulator.

Thank you for your help. The issue was because my batteries were low although it still hits obstacles before making its decision but it still overall works better. do you have any advice on how to fix this i noticed aside from the couch made of fabric and the curtains the robots hits all obstacles before making its decision i feel my problem is the center IR isn't reading low quick enough what do you think?

I am also having problems in getting my two arduinos to communicate using the HC05 Bluetooth module (https://arduino.stackexchange.com/questions/78714/bluetooth-modulehc-05-issues) can you please check it out and tell me what you think? Thank you


text:
2 stepper drivers speed control
I'm using two tb6600 to control two step motors. It's for letter writing cnc machine.
Moving single axis works fine.
I want to push 2 steppers in the same time along a diagonal.
I tried to calculate ratio x:y, so if x is making more steps than y for 1 y do n x steps. This worked, but machine was shaking no mater how i adjusted delays between step high and low. When i use PWM there is no shaking, but i can't figure out how to make it follow diagonal.
Second try was to use PWM with analogWrite.
if(delayX > delayY){
      analogWrite(stepPinX, 128);
      analogWrite(stepPinY, 128);

      delay(delayY);
      analogWrite(stepPinY, 0);
      delay(delayX - delayY);
      analogWrite(stepPinX, 0);

    }else if(delayX <= delayY){
      analogWrite(stepPinX, 128);
      analogWrite(stepPinY, 128);

      delay(delayX);
      analogWrite(stepPinX, 0);
      delay(delayY - delayX);
      analogWrite(stepPinY, 0);
    }

This doesn't works obviously. It reaches end point, but it doesn't follow diagonal.
If i set duty cycle to 2 or 128 it doesn't matter.
Isn't duty cycle supposed to change speed of stepper motor?
What am i missing here and how can this be done?

No, PWM won't change the speed - you're pulsing the STEP input of your stepper drivers, where each signal edge will create a movement. PWM only changes the duration of the HIGH and LOW sections of that movement, not the frequency (which would change the speed).
You'll probably want to use a library designed to handle stepper motors / drivers.

Changing the duty cycle does not change the frequency of the PWM signal.
The tb6000 needs a pulse to trigger a step of the motor. If the frequency does not change the pulses per second do not change too and thus the speed is constant.
If you control just one motor the method of using delays to control the frequency works.
But in the case of two motors with different speed you need counter variables to immetate two frequencies (speeds) you need to control each speed of the motors.
First you caculate the ration of the speeds (you said y=1 and x=n steps. Then, the ratio is n:1, i.e the X Motor is faster then the Y Motor by factor n).
The following is just an incomplete example to explain my idea.
int cntX = 0;
int cntY = 0;

// I don't know you value n
// Let's say n=5
int ratioX = 5;
int ratioY = 1;

// One step per second at max speeed
// choose whatever fits your needs
int delayForMaxSpeed = 1000;

const int stepPinX = 5;
const int dirPinX = 2;
const int stepPinY = 6;
const int dirPinY = 3;
const int enPin = 8;

void setup()
{

  pinMode(stepPinX,OUTPUT);
  pinMode(dirPinX,OUTPUT);
  pinMode( stepPinY, OUTPUT );
  pinMode( dirPinY, OUTPUT );

  pinMode( enPin, OUTPUT );
  digitalWrite( enPin, LOW );

}

void loop()
{
  // Enables the motor to move in a particular direction
  digitalWrite( dirPin, HIGH );

  countx++;
  county++;

  if ( countX >= ratioX )
  {
     countX = 0;
     digitalWrite( stepPinX, HIGH );
  }

  if ( countY >= ratioY )
  {
    countY = 0;
    digitalWrite( stepPinY, HIGH );
  }

  delayMicroseconds( 500 );

  digitalWrite( stepPinX, LOW );
  digitalWrite( stepPinY, LOW );

  delay( delayForMaxSpeed );
}


text:
Is it possible to gather data while the Arduino is being powered with a battery, connect to comp, and then read off the values in Serial Monitor?
I want to do a project where I gather data such as sunlight hours per day, as well as temperature highs/lows. Once I have gathered 24 hours worth of data, I want to hook it up to the computer to read off the values in Serial monitor.
When I try and open the Serial monitor, it restarts the program wiping all the memory.
I tried doing something with PROGMEM, but that didn't seem to help as it is only for constants.
I want to avoid using an LCD to display data if possible.

Are you going to cut power before connecting to the pc? How much data do ypu expect to accumulate within those 24h?  Is there just one value each for sunlight hours, temperature max and temperature min?

It will be powered by the 9V port, so it will not lose power. I am just storing 5 variables. Hours of sunlight, temperature high, temperature low,  humidity high, and humidity low.

The reason you lose your data at the moment is because opening the serial port resets the Arduino. That's how it gets the bootloader going for programming. You will have to disable that to prevent the reset. There's a trace inside a jumper "RESET EN" which you can cut to disable the reset, then bridge the jumper again when you want to reprogram. Or you can add a large capacitor (100uF for example) between RESET and GND to try and negate the reset pulse.

Yes, this is perfectly possible. You will need to write a routine that you can trigger via Serial. For example you will listen on Serial until you get the dump command. Then run a function that spits your variables out to Serial.
You just have to be careful where you save your 5 variables.
If stored in memory (RAM), you should avoid power loss. Therefore I'd suggest a FTDI USB-to-Serial adapter. There you just connect the TX, RX and GND wires and proceed with the Arduino IDE's Serial Monitor.
If stored in EEPROM, you can use the regular USB connector of Arduino.

I will not have any power loss as I am using the 9V barrel jack. Maybe there is a brief power loss once I connect it to the computer and then it switches power sources? EEPROM might be a good option. I am just worried that it will fill up too quickly after awhile.

You should not attempt to power Arduino from Barrel Jack AND USB at once.

Good to know, thank you.

@AustinJohnLippincott it's my understanding that Arduinos include protection circuitry so that you CAN connect both the USB and barrel jack at the same time


text:
Trouble streaming audio from amazon s3 servers
I am experimenting with streaming audio from servers using an ESP32 and this library. I have been able to stream audio from every http server which i have tried but have had mixed success with https servers. I had originally wanted to stream audio from an amazon S3 server but could not get this to work. I have managed to get it to work using the google cloud servers (Both of these are https servers). Any thoughts on what might be the problem would be much appreciated. thanks.
I'm not sure if this is an appropriate forum but im not qute sure where else to post my question. thanks.

SSL decryption takes a lot of CPU power, that could be the culprit. And all streaming and ESP32 application I have seen has been just HTTP.

Hmm...ive actually now managed to get it streaming from my google cloud storage which is an https address. i was originally hoping to retrieve files from amazon aws since i am already using this for various other things but i get an error when trying to retreive files form these servers. Since the google cloud service works it can't be to do with the https protocol which i had originally thought.

Please change your question with that info.

hi, have updated question.


text:
Using several Arduinos simultaneously
I'm working on a project where I need to control the light of 5 buttons as well as listen when each button is switched on/off by the user. I would furthermore like to provide feedback on an OLED display. It looks like I'm running out of pins. This https://arduino.stackexchange.com/a/22689/69029 provides several options for that. I would specifically like to explore the option to have several arduinos connected to each other in a master/slave configuration. Where can I learn more about my option to build stuff using several Arduinos connected to each other? I can also forsee scenarios where I could use 3.3V devices as well as 5V devices.

you can find projects on the internet .... this may be useful ... https://www.pjon.org/SoftwareBitBang.php

Thx @jsotola. Those resources make for an interesting read

Among all the options mentioned, using a master/slave should be the last resort, especially when you are new to embedded programming or Arduino, it is not only more complicate but also more expensive to implement.
One potential solution that could free up the precious digital i/o pins that were used by the 5 buttons is using analog input to detect the status of the buttons.

simulate this circuit – Schematic created using CircuitLab
When sw1 is pressed, the voltage at the A0 will be around 0.83v, and when sw5 is pressed, the voltage at the A0 will be 2.5v. You can write a simple switch...case to determine which switch has been pressed.
The only problem of this circuit is that it can't handle more than one button been pressed simultaneously, but that could be solved by double the value of each resistor like 10k, 20k, 30k...
This will free-up 5 digital pins that can be used for control (such as servo, relay, etc.).

Interesting solution @hcheung. At least I'm going to experiment with it just to explore how it it works

Re “When sw5 is pressed, the voltage at the A0 will be around 0.83v, and when sw1 is pressed, the voltage at the A0 will be 2.5v.”: I think you got the switch labels backwards.

@EdgarBonet, oh, yes, you are right. Thanks for pointing out. I have made the correction.

Instead of trying to use multiple Arduino boards, which would be hard, I'd suggest using a bigger Arduino. The mega 2560, for example, has tons of GPIO lines.

I've since learned about the 74HC595. That seems like a handy solution to free up some pins. I gues in combination with the mega 2560 you would have plenty of pins.

Sure, you can use a shift register to set multiple output pins using a single serial line. A shift register wouldn't let you increase the number of input pins however. There are also CMOS multiplexer chips you could use to share a single pin to take multiple digital inputs (or outputs, since CMOS MUX chips allow bidirectional data flow)

I haven't seen this being done much. But that's probably because it isn't the best option in almost all cases.
Having multiple pieces of code, for different boards, that you have to work together. Constantly having to upload to different boards. This sound like a nightmare.
The only use-case I could see is to have each Arduino have a single function that shouldn't change (much) over time, and having it act like just any another sensor IC, or led driver IC.
The best example of this would be some of the SparkFun Qwiic Twist, Quad Relay, and Button board. For these they use an Arduino compatible ATTiny84 IC with custom firmware to expose it's functionality over I2C.
But most of their Qwiic boards use custom ICs, since they are either cheaper, or less work to get working.

I'm currently learning so my experiments are fairly modest right now. However,  I'd like to build my own RC boat with a lot of sensors supporting it and also many servor to make navigable. Since that would be a huge project considering my current experience with the Arduino platform I can already sense that a single microcontroller would not be enough. Perhaps I'm trying to approach this idea from the wrong angle?

I don't feel that's the best solution. I'd probably look into an IC that does the Servo pulse generation for you. That would give you a few extra free pins, and reduce the CPU load on the Arduino.

@Johan-Sundström: About that boat: if you use sensors that have I2C you can use many with just two wires. You can also replace a display and physical buttons with a web interface on your telephone if you use an Arduino with a WiFi module on it. I've done that with a Nano 33 IoT with the WiFi in AP mode and it works.

Hmm interesting, it seems that I have underestimated the power of I2C Thanks for that recommendation @ocrdu


text:
Serial doesent work when calling function from timer
You can try the code on your arduino UNO to better understand what is hapening in serial monitor!
I want to calculate jacobian matrix from rotation matrix!
float jakMATB[3][3] = {
{0, 0, 0},
{0, 0, 0},
{0, 0, 0}
     };
float POKUS = 0;
float k = 0.000001;
float dt = 0.001;
float b = 90 * (PI / 180);
float vnB[3] = {0, 1, 0}, vpB[3] = {0, 1, 1};
float nB[3] = {0, 1, 0};
float nBplus[3] = {0 , 1, 0};
float nBminus[3] = {0, 1, 0};
void setup() {
Serial.begin(9600);
Serial.print("init ok");
cli();//stop interrupts
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1  = 0;//initialize counter value to 0
// set compare match register for 1hz increments
OCR1A = (16000000) / ((1 / dt) * 1024) - 1; // 15624 = (16*10^6) / ((1)*1024) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12 and CS10 bits for 1024 prescaler
TCCR1B |= (1 << CS12) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei();//allow interrupts
}

when I call the function in loop everithing works fine and I get  1 2 1 in serial monitor
 void loop() {
 izracunJAKOB();
 for (int j = 0; j <= 2; j++) {
for (int i = 0; i <= 2; i++) {
  Serial.print(jakMATB[j][i]);
  Serial.print(" ");
}
Serial.println("");
}
}

when I call izracunJAKOB() with timer interupt Serial monitor
stops working and doesent event write "init ok"
ISR(TIMER1_COMPA_vect) {
  //izracunJAKOB();
 }
void izracunJAKOB() {
for (int j = 0; j <= 2; j++) {
for (int i = 0; i <= 2; i++) {
  nBplus[j] = nB[j] + k;
  nBminus[j] = nB[j] - k;
  float matricaBplus[3][3] = {
    {cos(b) + nBplus[0]*nBplus[0]*(1 - cos(b)), nBplus[1]*nBplus[0]*(1 - cos(b)) - nBplus[2]*sin(b), nBplus[0]*nBplus[2]*(1 - cos(b)) + nBplus[1]*sin(b)},
    {nBplus[1]*nBplus[0]*(1 - cos(b)) + nBplus[2]*sin(b), cos(b) + nBplus[1]*nBplus[1]*(1 - cos(b)), nBplus[1]*nBplus[2]*(1 - cos(b)) - nBplus[0]*sin(b)},
    {nBplus[0]*nBplus[2]*(1 - cos(b)) - nBplus[1]*sin(b), nBplus[1]*nBplus[2]*(1 - cos(b)) + nBplus[0]*sin(b), nBplus[2]*nBplus[2]*(1 - cos(b)) + cos(b)}
  };
  float matricaBminus[3][3] = {
    {cos(b) + nBminus[0]*nBminus[0]*(1 - cos(b)), nBminus[1]*nBminus[0]*(1 - cos(b)) - nBminus[2]*sin(b), nBminus[0]*nBminus[2]*(1 - cos(b)) + nBminus[1]*sin(b)},
    {nBminus[1]*nBminus[0]*(1 - cos(b)) + nBminus[2]*sin(b), cos(b) + nBminus[1]*nBminus[1]*(1 - cos(b)), nBminus[1]*nBminus[2]*(1 - cos(b)) - nBminus[0]*sin(b)},
    {nBminus[0]*nBminus[2]*(1 - cos(b)) - nBminus[1]*sin(b), nBminus[1]*nBminus[2]*(1 - cos(b)) + nBminus[0]*sin(b), nBminus[2]*nBminus[2]*(1 - cos(b)) + cos(b)}
  };
  jakMATB[i][j] = (matricaBplus[i][j] - matricaBminus[i][j]) / (2 * k);
  nBplus[0] = 0;
  nBplus[1] = 1;
  nBplus[2] = 0;
  nBminus[0] = 0;
  nBminus[1] = 1;
  nBminus[2] = 0;
}
}
}

//////////////////////////////
when I comennt out
   nBplus[j] = nB[j] + k;
   nBminus[j] = nB[j] - k;

and
   nBplus[0] = 0;
   nBplus[1] = 1;
   nBplus[2] = 0;
   nBminus[0] = 0;
   nBminus[1] = 1;
   nBminus[2] = 0;

Serial works just fine
when I coment out only  matricaBminus and  matricaBplus serial works fine
Please help! It surely is a stupid solution!

I only get hello world in Serial. Did I get overflow on MCU?

Though that might not be the cause of your problem, do you put the printing of the matrix in loop() into a critical section (with interrupts turned off)? If not, the interrupt might happen in the middle of printing. Please show a complete example sketch for the interrupt version of the code.

@chrisl Timer was to fast! When I decreased frequency everithing worked fine.

It generally not advised to use serial inside an interrupt.

It is even impossible to use Serial in an interrupt, if you risk to overflow the output buffer. You cannot write more than 63 characters (to normal arduinos) from an ISR.

Timer was to fast! When I decreased frequency everithing worked fine.

Increasing the baudrate to something higher that 9600 also helps.

This may seems to solve your problem, however, it is not a best practise for the way you using interrupt. You should read interrupt by Nick Gammon.


text:
How to program Esp8266 remotly via wifi?
I hope it's not a sci-fi for arduino. But I saw that dual system with two MCU can program each other via radio connection. It has been done in experimental space cube projects.
It is theoretically possible? I'm thinking about two arduino MCU first of them will be main MCU and second will be like programming device via serial link.I want to program mcu via wifi without cable connection. Somehow send hex file via wifi to eeprom and upload to second device flash memory.
How do you see this issue? Is that a big nonsense?

Sure, no reason why this cannot be done. Every ESP8266 with enough flash memory has the ability to reflash itself over a wireless link (OTA), downloading a binary file containing its new flash contents from a web server. You can easily run such a web server on another ESP8266. You just have to code it.

The firmware update over WiFi is called OTA update. OTA stands for "over the air".
The esp8266 can OTA update itself. The Arduino library for this is called ArduinoOTA and it is bundled with the ESP8266 Arduino boards support package.
See the example for ArduinoOTA library in IDE Examples menu.
Other MCU have the self update option too. ESP32 has it of course, then for SAMD boards Arduino made WiFi101OTA library. For ATmega I made the ArduinoOTA library based on the WiFi101OTA library so it supports SAMD too. And it doesn't have to be WiFi. Cable works too.
The OTA update stores the uploaded firmware in free part of the flash and after successful upload it moves the firmware to target location and resets the MCU.
For any Arduino with SD bootloader OTA update is possible, because the library only has to store the uploaded firmware to the SD card and reset the MCU.
For small ATmega ftp bootloaders exists. Here the bootloader waits for network upload.
Update over a second MCU solutions are for MCU with less flash, mostly for the ATmega328p. The ESPLink firmware and the WiFiLink firmware for ESP8266 can flash attached ATmega328p over RX/TX. The ESP8266AVRISP can flash ATmega wired over SPI.
ArduinoIDE supports OTA upload. It creates a network port based on MDNS record propagated by the ArduinoOTA library or firmware with OTA support.

Other update way is to download the new firmware from a server or upload it over a web page. ESP8266 has for this ESP8266httpUpdate and ESP8266HTTPUpdateServer libraries. For SAMD, ATmega and other boards my ArduinoOTA library has examples on how to store and apply the update received as download or upload.

Thank you, I'll try it when I came home

I got it, It's pretty cool... Thanks :)


text:
AMIS30543 | Data-Sheet understanding Status register
I was reading the data Sheet of AMIS-30543 stepper motor driver and I was not able to understand how to combine the result of the Micro step position status register MSP[8:0]. I know that its a 9 bit value . Help me understand how to get the value.
In the data sheet it is given like

in SR3 -> MSP[8:2], and in SR4 -> MSP[6:0]. How I am I suppose to get the 9 bit out of these.

In the library I have seen that , (sr3<<2) | (sr4 & 3)  . I don't understand why they are doing and & here.
Please explain . also If there was no library how am I suppose to know how to combine these registers from the dataSheet .
Link to DataSheet

Most of the data is duplicated between the registers. Both registers contain MSP[6:2].
If MSP contains 111001001 the registers (ignoring the MSB "PAR" bit) would look like:
SR3: 1110010
SR4: 1001001

If we line those up it's then like:
SR3: 1110010
SR4    1001001

You can now see the overlap.
So taking SR3 and shifting it left two places (sr3 << 2) gives you:
SR3:   1110010
<<2: 111001000

Taking the lowest two bits of SR4 with & 3 gives you:
SR4:   1001001
& 3:   0000001

Then ORing the two results together:
SR3<<2: 111001000
SR4 &3: 000000001
-----------------
MSP   : 111001001

How can I understand this from data sheet like from sr3 and sr4

The 8:2 and 6:0 refer to the range of bits stored in that register. It's a little unusual to have overlap like that.

So is it okay to do like :: ‘(sr3 << 2 | sr4)’

No, because of the PAR bit that's in the MSB that will corrupt SR3.

Ohh ok. I understand now .

Again one more doubt this overlapping of bits you came to know by practice and experience or you read some where ?

Practice and experience. It's the first time I have seen overlapping bits like that, but the code snippet you showed and the 8:2 and 6:0 in the datasheet allowed me to infer it. It's really not clear at all in the datasheet, so it's not surprising you were struggling with it.


text:
Relay starts trigger about 6 times when connecting arduino to laptop
I have a fairly simple code to turn a relay on-off every 2 seconds
When i attach the USB of the arduino Uno to the laptop, it goes into a frenzy and the relay triggers on off for 6 times within 3-4 seconds and then it settles down.
This however doesnt happen when connecting directly to the power output.
Is there something that needs to be wired to stop this happening ?
I am using an arduino Uno with a relay JQC-3FF-S-Z connected directly to the arduino pins.
const int ONOFF_TRIGGER_PIN = 2;

void setup() {
  // put your setup code here, to run once:
  pinMode(ONOFF_TRIGGER_PIN, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(ONOFF_TRIGGER_PIN, LOW);
  delay(2000);
  digitalWrite(ONOFF_TRIGGER_PIN, HIGH);
  delay(2000);
}

The code is so simple, this has to be a hardware problem. Please add a schematic or  a wiring diagram to your question.

Thanks @Jrobert ive added a fritzing image. Couldnt find the the exact same relay component i have JQC-3FF-S-Z

Put a voltmeter on the pin and to ground while the Uno is starting up with the relay detached. Note any fluctuations. Now, connect the relay with the voltmeter still attached, and restart the Uno. Do you see any difference with the voltage behaviour of the pin?

Are you sure your relay works on 3V supply? JQC-3FF-S-Z operates on 5VDC.

@stevieb - i dont have a voltmeter :(
So this issue only happens when connecting it to the computer. Not when its connected to just a power supply. Means that i have to connect pin 2 after the arduino has "booted"

@hcheung - Ive tried it on both 5v and 3v. it works on both.

The thing is that if you see your relay flicking on and off, it suggesting that you are not having enough power or current supply. So if it is 5V, uses 5V. The 3V on Arduino Uno is weak and not support to be used for supplying a relay....

@hcheung but after the first 3-4 seconds (which i assume is the arduino booting up or something), it starts to work as per the program, So its just the initial phase.
Also, when hooking the arduno to a powersupply, the relay pins are still connected to the arduino. So maybe the arduino i have is corrupted somehow

Well, this is all "poking in the fog" as we say over here. Without measuring the supply voltage, you can't be sure. -- If you can't afford a multimeter (a simple one will do), you might try to use an LED and a series resistor and give it just enough current to be dimmed. You might be able to see fluctuations.

The markings on your relay suggest the coil is for 5VDC. But you have the coil supply wired to 3V3. Move the coil supply to 5V, and try again.

I agree with @Seamus. We don't know what might be going on with the 3v supply during boot up, but going to be marginal for a 5v even at steady state. At least try this and find out.


text:
AMIS30543 | DataSheet Understanding CIRCULAR TRANSLATOR TABLE
I was reading the data sheet of AMIS-30543 stepper motor and I didn't understand fully what does this Circular Translator Table means, I have a couple of doubts

What does Circular Translator table Stands for.? How to read it .? pg:13
What does the current pairs can be projected approximately on a circle in Ix, Iy plane means.? pg:25

In the data Sheet it is given that Changes on the NXT input will move the motor current one step up/down in the translator table (even when the motor is disabled:  = 0). So the changes happened in the table while the motor was disabled will reflect as soon as the motor become active.? Like if I give say 5 step input while the motor was disabled and when I make the motor enable , will the motor will move by itself to reach that position in the translator table.? pg:25

Link to datasheet

It describes the current going through the two coils of the stepper motor at each step.

I'm not quite sure, as I would think the last two diagrams should actually be squares. But for example, in the first image, you can see that the current in the X coil will steadily increase, while the current in the Y coil will steadily decrease. This will make the stepper rotate more slowly.
In the second image, you can see that only the Y coil driver is at 100% in step 0. In step 1 both coils are at 100%. In step 2 coil Y is turned off. I think this is profile produces more torque, but is less smooth.

No. I you are, for example using full step mode, and the motor is in step 0. If you give it 3 steps forward  (while the motor is disabled) it would drive the coils (once you re-enable to motors) as described in the lookup table for step 3. Which in practice would mean the motor would rotate backward one step (instead of 3 steps forward).

In other cases, it could result in undefined behavior. Going from step 0 to step 2 could mean it would rotate clockwise, anticlockwise, or even not rotate at all.
Though in practice I don't think this would even be an issue, and disabling the motor, but still sending it step pulses is kind of silly.


text:
How do I reset to servo position everytime I excecute a particular sequence
I'm trying to make a prosthetic hand that can play rock, paper, scissors with a human. It is based on the premise that you push a button and it randomly selects a move to play. After each move, I'd like for it to return to a normal state after a few seconds delay, the human can then decide whom is victorious.
Code I have so far. It doesn't even stop after the degrees I've set, it just keeps turning. I have a cardboard prototype and it has come close to breaking because the servos just keep turning.
#include <Servo.h> //servo library

//Define servos
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;

int pos = 0;

void setup()
//define servo signal inputs [digital PWM 2, 3, 4, 5]
{
  servo1.attach(2);
  servo2.attach(3);
  servo3.attach(4);
  servo4.attach(5);

}

void loop()
{
  void rEADY();
  //void rock();
  //void scissors();
  //void paper();
}

void rEADY()
{
  servo1.write(20);
  servo2.write(20);
  servo3.write(20);
  servo4.write(20);
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);

}

void rock()
{
  servo1.write(180);
  servo2.write(180);
  servo3.write(180);
  servo4.write(180);
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);
}

void scissors()
{
  servo1.write(180);
  servo2.write(180);
  servo3.write(0);
  servo4.write(0);
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);
}

void paper()
{
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);
  servo1.write(20);
  servo2.write(20);
  servo3.write(20);
  servo4.write(20);

}

do you realize that loop() repeats several thousand times every second? .... think about what your code is doing each iteration of loop()

@jsotola Thanks for replying :) I was working on it today and I did realise that I shouldn’t loop it. But i’m still a bit stuck on how to execute one off moves. Not sure if I’m looking at it the right way.

looping is ok ... look for blinkWithoutDelay sketch in the examples in the arduino IDE ... you can run a subroutine in the loop() block only once quite easily ... in setup(), set a flag ... in loop(), if flag is set, then run code and clear flag ... that's it ... the program will continue looping, but it will run the code only the first time through, because the second time through, the flag is no longer set .... you can easily add code that sets the flag every 10 seconds ... that will make the flag set at the begining of loop() again for a single repeat of the code once every 10 seconds


text:
Selection of module for person following shopping cart
I'm building a person following shopping cart with Arduino for my final year project. The cart is supposed to be able to follow its user while shopping use of Bluetooth module or wifi module will be feasible or not?or I should use IR sensors ?

It seems like this is a big/complicated project. Probably you need a multitude of modules (like WIFI or BlueTooth for the communication between the person and the cart, not sure what is best), an IR sensors to make sure the cart is not hitting something, and since safety is an issue (not bumping into people) you might need also probably one or more cameras, with vision intelligence, making an Arduino Uno not the best choice. But maybe I'm too pessimistic.

I agree with @MichelKeijzers ... perhaps the shopper could wear a vest with IR emitters ... each vest would transmit a unique code ..

@jsotola that could work, although much depends on the way the person with the vest walks (not too fast, not abrupt changes of direction/turning).

Bluetooth beacon. Use "bluetooth positioning arduino" as search terms.
Bluetooth beacon is a way to achieve the same as a GPS can do outdoor. By placing beacons around the room you can find your position in 3D space.
So a beacon locator on the shopping cart (Arduino with BLE module or a ESP32) and one on you (mobile phone) and then some central unit that can coordinate the two positions.
Just as a concept it would be feasible.


text:
Can the atmega328 return remainder during integer division?
When I write code like this:
int a = 7
int b = 2
int c = a/b
int r = a%b

Does the chip use the remainder while calculating c or does it redo the entire calculation?

The Atmega328 does not have an intrinsic divide instruction so one has to be implemented by a sequence of other instructions. So the chip doesn't even know about a divide instruction.

Ah, so the division itself is done by a series of assembly instructions, not just one :) Then I would hope the compiler is smart enough to save the remainder :)

Why do you need to know this? To divide by 2 the compiler merely has to shift right one, and the remainder is simply the low-order bit. These are very fast things to do. The "chip" does what it is told to do.

@NickGammon I'm solving Differential equations in real time with integers to predict the behaviour of a system and I need to know if it's worth to keep track of the remainders to account for them or not, so far it's looking like it's not worth it though, but I want to explore my options to increase accuracy :)

If using optimization, the compiler is smart enough to recognize this.
Since your example is so short, it could be optimized away entirely.
To ensure that doesn't happen, the results in c and r have to be used in some way.
Also, if a and b could never change, the values of c and r would be calculated during compilation.
Therefore, I put the calculation in its own function.
From godbolt.com, using AVR-GCC 9.2.0:
#include<stdint.h>
#include<stdio.h>

uint8_t a = 0;
uint8_t b = 2;
uint8_t c = 0;
uint8_t r = 0;

void calculate() {
    c = a / b;
    r = a % b;
}

int main() {
    a = 7;
    b = 2;

    calculate();

    printf("%d %d", c, r);
}

compiles the calculate() function into
calculate():
        lds r24,a
        lds r22,b
        rcall __udivmodqi4
        sts c,r24
        sts r,r25
        ret

The results, stored in r24 and r25 respectively, are re-used from the same division operation.

By having optimizations turned off, you are asking the compiler to not be smart. And it dutifully obeys. No one would ever compile Arduino code this way. The standard Arduino optimization level is -Os, and at this level the compiler is smart enough to optimize your code to the equivalent of return 0;.

You're right. Though even when making sure the results are used (even by the same statement), and the variables a and b are not constant, it doesn't seem to remember the remainder of the first operation directly: https://godbolt.org/z/Edzq54

Your new test is flawed again. By having a and b volatile, you tell the compiler that it should not assume their values to be stable. Thus a/b and a%b are two different divisions.

Ugh, I'm crap at this. You're right, optimization does use only one division if you make sure the variables can't change and also prevent it from calculating it all during compilation.
https://godbolt.org/z/bG4cG6

Using volatile was not a bad idea: it's a convenient way to simulate side-effects, like I/O. You just have to make sure the numbers you are dividing are not themselves volatile. See for example: https://godbolt.org/z/zGefj9

The compiler is only as smart as you provide it the necessary information.

It is good to examine code on godbolt.com. But use it wisely.
Noone should ever compile without optimizations. In the example above the code is not optimized and thus would never been used as such on a board.
The example is so artificial that the compiler optimizes it away into just 2 instructions. So the code should be representative for the intended usage.
A better godbolt would be:

#include<stdint.h>
#include<stdlib.h>

void myDiv(uint8_t * c, uint8_t * r, const uint8_t a, const uint8_t b) {
    *c = a/b;
    *r = a%b;
}

So the input is not predetermined and also the resulting numbers are returned and not thrown away. Which translates with -Os to:
myDiv(unsigned char*, unsigned char*, unsigned char, unsigned char):
        mov r27,r25
        mov r26,r24
        mov r31,r23
        mov r30,r22
        mov r24,r20
        mov r22,r18
        rcall __udivmodqi4
        st X,r24
        st Z,r25
        ret

There is the div(numerator, denominator) function in stdlib.h. This function performs a division and returns both the dividend and the remainder. It is optimized for each platform and uses the best available method to get both. In Godbolt it would look like this:

#include<stdint.h>
#include<stdlib.h>

void myDiv2(uint8_t * c, uint8_t * r, const uint8_t a, const uint8_t b) {
    div_t d = div(a, b);
    *c = d.quot;
    *r = d.rem;
}

But what surprise, with -Os the resulting assembly looks exactly the same! (I leave it to the reader to try it on godbolt).
That means, the compiler is smart enough to:
a. recognise the intention when calling division and modulo an the same operands successively.
b. will use the best available method to achieve the intended calculation for you.

EDIT after Edgar Bonet's comment:
While playing around in godbolt I made a copy-paste mistake. div only applies to int values. That makes the resulting assembly code larger as there has twice the data to be shoveld around. After changing both examples to int they look almost similar. The only difference is:
The result is stored in d first and then copied to c and r.
So the division/modulo code is more efficient in that regard as the resulting values are copied directly from the registers used in the calling convention.
https://godbolt.org/z/61exz7

Very interesting, +1
Declaring an optimization in my code gets rid of almost all the code, but declaring the variables as volatile prevents that. Even when "volatile", it still does not recognize the potential savings as such, and calculated the division twice.

if you read the assembler code carefuly you will see that it is not the case.

Sorry, I was still talking about my (close to the question) code: https://godbolt.org/z/jWqdv4

I take the code in question as a sample that shows the intention and not the question to be answered. Making everything voaltile forbids optimizations by the compiler. So there is no point in doing so and having -Os. If we stick to the exact code in question then the result would be just two instructions because the input is known at compile time, it does not change and the results of the computations are discarded.

+1. In the second example, you mean *c = d.quot; *r = d.rem;.

@EdgarBonet thank you for pointing that out.


text:
Servos jitter when powered by power module
I need 48 sg90 servos to move to a specific position each minute. Now I am using two arduino mega boards to power everything through 6 bread boards but it seems I need more power because some servos are ticking and are delayed. I cant get the external power supply to work independently of the computer. Once I unplug from my computer the servos jitter. Any help would be greatly appreciated.

...Schematic...?

make sure you have connected all the grounds together, i mean from both the Arduino boards, i had similar issue when using ESP8266 module and Arduino UNO together! check this first and also make sure the power supply is regulated and sufficient for your needs.

Most servos use an analog signal (width of a pulse) for positioning.  Any perturbation in that signal will cause unexpected behavior.  Activating 48 servos simultaneously will likely indirectly or directly affect the analog signal.

The unexpected behavior might be mitigated through changes in software or hardware.  These mitigation efforts may include:

Staggering the servo changes so that only 1 servo moves at a time.
Perhaps less effective but worth trying, staggering the servo changes so only 1 servo starts moving at a time.  In this scenario more than 1 servos may be moving at a time.
Using a power supply which maintains the expected voltage even during events such as all servos starting simultaneously.

These are only 3 options to consider.  Many more exist but may not be pertinent to your situation.  More information is needed.

For 3: A short power surge could also be handled with a big capacitor between Vcc and ground. Those could provide the current needed for the spike and prevent the voltage from dropping


text:
Please help with my tinkercad code. Debouncing stopwatch with lcd
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int ssPin = 8;
int resetPin = 9;

bool cntrRunning = false;

int sec = 0;
int min = 0;
double currentMillis;

void setup()
{
    Serial.begin(9600);
    lcd.begin(16, 2);
    lcd.print("00:00");
    pinMode(ssPin, INPUT);
    pinMode(resetPin, INPUT);
}

void loop()
{
    if (digitalRead(ssPin) == HIGH)
    {
        if (cntrRunning)
        {
            stop();
        }
        else
        {
            start();
        }
    }
    else
    {
        if (cntrRunning)
        {
            keepRunning();
        }
        else
        {
            stop();
        }
    }

    if (digitalRead(resetPin) == HIGH)
    {
        if (cntrRunning)
        {
            stop();
            reset();
        }
        else
        {
            reset();
        }
    }
    delay(10);
}

void start()
{
    currentMillis = millis();
    cntrRunning = true;
    Serial.println("started");
}

void keepRunning()
{
    cntrRunning = true;

    if ((millis() - currentMillis) >= 1000)
    {
        sec++;
        currentMillis = millis();
        Serial.println(sec);

        if (sec < 10)
        {
            lcd.setCursor(4,0);
            lcd.print(sec);
        }
        else if (sec == 60)
        {
            min++;
            sec = 0;
            lcd.setCursor(3,0);
            lcd.print("00");
        }
        else
        {
            lcd.setCursor(3,0);
            lcd.print(sec);
        }

        if (min < 10)
        {
            lcd.setCursor(1,0);
            lcd.print(min);
        }
        else if (min == 60)
        {
            min = 0;
            lcd.setCursor(0,0);
            lcd.print("00");
        }
        else
        {
            lcd.setCursor(0,0);
            lcd.print(min);
        }
    }
}

void stop()
{
    cntrRunning = false;
    Serial.println("stopped");
}

void reset()
{
    if (cntrRunning)
    {
        stop();
    }
    reset();
    int sec=0;
    int min=0;
}

My professor wants us to add debouncing to the set/stop button but I'm a little confused on how to implement it.

do you understand the reason why debouncing is required?

No not entirely.

ok ... imagine a tennis ball ... hold it high over your head and drop it ... the ball represents the moving contact of a switch ... the floor represents the fixed contact of a switch ... actual switch contacts do something similar to the ball, but in the millisecond realm .... the probem arises in the fact that the microcontroller sees each of the bounces as a keypress

@Amy, a typical tactile button finishes bouncing and achieves stability after about 50 ms. To test for stability, repeatedly sample the input pin looking for a series of equal values, i.e. 1,1,1,1,1 or 0,0,0,0,0. Your loop() runs once every 10 ms, so 5 equal values in a row is 50 ms of stability. Now base your if decisions on this stable value.


text:
Detect 2 wire thermostat output
I have a 2 wire thermostat. R is +24VAC, W is Heater. I have no Ground wire (C), and I cannot open the thermostat.
When the heater goes on, the thermostat internal relay gets powered and connects R and W together.
How can I detect when the heater is on from those two wires?

measure the current flowing in the wire

R -----/\/\/\---|>|----- W   ... perhaps a high value resistor in series with an LED .... it is possibe that a small amount of current could pass without activating the heater ... the LED would actually be emitter part of an optocoupler ... when the heater is off, the LED is on ... the thermostat contacts short out the LED when they close, which causes the LED to turn off

@jsotola Your opto solution worked! I have used an optocoupler in series with a 22k resistor and it does not trigger the heater. I measured the resistance between emitter and collector terminals of the optocoupler.
`Heater on  → 0 (shorted)`
`Heater off → 17Mohm`

I hope I hooked it up correctly to Arduino to detect it.

You should add a diode in reverse in parallel with the LED of the optocoupler. At the moment you're halving the power delivered to the heater. Also the optocoupler may die from the reverse voltage of AC. That is if it really is AC - you say +24VAC which makes no sense - there is no + in AC, only DC.

@Majenko added D1 but it was working anyway. The heater has a relay so it's on or off. Also added pull-down R2.

I have built the circuit but analogRead(A0) does not change :/

With checking the temperature in the room. When the contact is closed store the current temperature. Check after a minute the temperature again. If it is higher, the heater is on.

I only needed to sense the thermostat output to detect when the heater is on and log the event on my Arduino. The temperature is already checked by the thermostat. I got help in the comments and I updated the circuit which already works.


text:
Using Arduino UNO as FTDI
so , just bought some pre-bootloaded ATmega328(p/pu) to which I need to upload sketches on a breadboard using uno TX and RX pin as FTDI
Here is what I am to do.

I connected Uno GND and Reset .

Arduino Tx to Standalone Atmega Tx

Arduino Rx to Standalone Atmegaa Rx

Connected Crystal , capacitor to standalone pin 9, 10 (XTAL) then grounded it with 2 coupling capacitor.

Standalone vcc to arduino 5v
Standalone GND to Uno GND

Is it possible to do what I need to or i need to buy some USB to TTL devices from the Amazon again?
Thanks for your precious time...

That sounds about right.
The only problem is that normally, when a serial connection is created, the Arduino's reset pin is briefly pulled LOW. You would have to do that manually on the ATMega on your breadboard. I can be a bit tricky to get the timing right.
There is no easy way to get this signal to your breadboard ATMega, while keeping the reset pin on the UNO's ATMega LOW.
Removing the ATMega from the UNO board would work.

I have got to get the right time to reset after uploading the code so, i am doing it manually without FTDI which saved some of my bucks :)

@SubhaJeetSikdar I changed the firmware on the ATMega8u2 on my UNO to also toggle one of the header pins next to it, when it tries to reset the ATMega328P. That way I could upload to custom ATMage328P based board over serial :-)

Can you please send me a video or article link about how you changed the firmware of the programmer ic ATmega8u2, well , mine one seems to be ATmega16u2

I programmed it via DFU. The firmware can be found at https://github.com/arduino/ArduinoCore-avr/tree/master/firmwares/atmegaxxu2. Change  Arduino-usbserial.c to also change one of the ISP pins where it currently change the reset-out pin. It's been way to long, so I don't have the files anymore. Proceed at own risk.

https://youtu.be/EoHD0m3uUhA. Ig this should do it. There are many more tutorials on YouTube to achieve this.

What if I don't want to remove the factory installed atmega on arduino. Actually I dont want to remove factory installed at mega, is there any other way to do this without removing previously installed atmega

If u don't remove the pre installed at mega then it will try uploading the code to both of them which will be a big problem for you . Then you have only one other option to use a FTDI module

What if i connect the ground and reset of the arduino before uploading sketches on breadboard ATmega?

Sorry I am not able to understand what u are asking

https://images.app.goo.gl/g2gEeuHJ9dKAd6hY6

Open the link above, UNO to TTL converter, will it work for what I want to do

Yeah I saw that but I was not able to find any proper tutorial or anything like that for uploading the code I only found few videos for using it for serial monitor . If u have all the parts give it a try and there is one more tutorial which is some what similiar
https://youtu.be/nGEjpZuPXuo

Hmm that video is about bootloading not uploading sketches on a pre bootloaded breadboard ATmega

he basically add a new bootloader to Arduino to program other Arduino using it so basically its the type of thing you wanted

No, i want to upload sketches using my uno board as a bridge between breadboard atmega and my PC , i don't want to burn bootloader, and I already know how to burn bootloader.


text:
Running a DC motor for a set amount of time
I am trying to run a DC motor for 100ms and then turn it off completely. Here is my code any suggestions on why it might not be working?
My Code
const int pirPin = 9;
const int motorPin = 2;
int switchState = 0;
// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(motorPin , OUTPUT);
  pinMode(pirPin, INPUT);
}
void loop() {
  while (digitalRead(pirPin) == HIGH) {
    digitalWrite(motorPin, HIGH);
    delay(100);
    digitalRead(pirPin) == LOW;
    break;
  }
}

What is the voltage of the DC motor are you using any driver IC or transistor becasue if you are not using any then it may damage your arduino also. Can you please share the connections also

So what u exactly want is that the motor runs when the pirpin is high and it should continue to run for extra 100 ms after the pin goes low

Please share a proper code and not a picture. Dose the motor run?

Please explain how the motor is supposed to react to pirPin. Also, have a look at digitalRead(pirPin) == LOW; which will evaluate to true or false and isn't used anywhere.

So what you want is to be explained how the motor will react to pir pin and you want to run the motor when the pir pin is high and run for 100ms and then go off when the pir pin is low

Please reply to that and is your motor currently turning using the Arduino.

The line digitalRead(pirPin) == LOW; has no effect. And you never do a digitalWrite(motorPin, LOW);

What I believe he is thinking is that on digitalRead(pirPin) == LOW;  the program will get out of the while loop and the motor will stop spinning

#include <Arduino.h>

const int pirPin = 9;
const int motorPin = 2;
int switchState = 0;
// the setup routine runs once when you press reset:
void setup()
{
 // initialize the digital pin as an output.
 pinMode(motorPin, OUTPUT);
 pinMode(pirPin, INPUT);
}
void loop()
{
 while (digitalRead(pirPin) == HIGH)//this part of the code gets executed if the pir
 //pin is read high
 {
   digitalWrite(motorPin, HIGH);//the motor pin is set high so if a motor is connected
   //the motor will start turning.
 }
 while (digitalRead(pirPin) == LOW)//this part of the code gets executed if the pir
 //pin is read low
 {
   delay(100);// so your motor stop after running for extra 0.1 seconds
   digitalWrite(motorPin, LOW);//the pin gets low and the motor should stop turning
 }
}

I have commented all the lines
Hope this helps.


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.


text:
How might I add a delay, close the servo and go to the start again?
#include <Servo.h>
Servo myServo;

  const int piezo = A0;
  const int button = 2;
  const int yellow = 3;
  const int green = 4;
  const int red = 5;

  int knockVal;
  int buttonVal;

const int quietKnock = 10;
const int loudKnock = 100;

boolean locked = false;
int numberOfKnocks = 0;

void setup()
{
  myServo.attach(9);
  pinMode(yellow, OUTPUT);
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(button, INPUT);
  Serial.begin(9600);

  digitalWrite(green, HIGH);
  myServo.write(0);
  Serial.println("The box is unlocked!");
}

void loop()
{ //start of loop
  if (locked == false)
  { //start of if1
    buttonVal = digitalRead(button);
    if (buttonVal == HIGH)
    { //Start of if2
      locked = true;
      digitalWrite(green, LOW);
      digitalWrite(red, HIGH);
      myServo.write(90);
      Serial.println("The box is locked!");
      delay (1000);

    }     //end of if2
  }      //end of if1

  if (locked == true)

  { //start of if3

    knockVal = analogRead(piezo);

    if (numberOfKnocks < 3 && knockVal > 0)

    { //start of if4

      if (checkForKnock(knockVal) == true)

      { //start of if5

        numberOfKnocks++;

      }   //send of if5

      Serial.print(3 - numberOfKnocks);
      Serial.println(" more knocks to go");

    }     //end of if4

    if (numberOfKnocks >= 3)

    { //start of if6
      locked = false;

      myServo.write(0);
      delay(20);
      digitalWrite(green, HIGH);
      digitalWrite(red, LOW);
      Serial.println("The box is unlocked!");

    }   //end of if
  }   //end of if3
}           //End of loop

boolean checkForKnock(int value)
{ //start of boolean

  if (value > quietKnock && value < loudKnock)

  { //start of if7

    digitalWrite(yellow, HIGH);
    delay(50);
    digitalWrite(yellow, LOW);
    Serial.print("Valid knock of value ");
    Serial.println(value);
    return true;
  }   //end of if7
  else
  { //start of else
    Serial.print("Bad knock value ");
    Serial.println(value);
    return false;
  }   //end of else
}     // end of boolean

May I know at what point you want to add the delay

You already have delays. Can you specify more completely what you are trying to achieve?

Once the Servo is unlocked I would like to add a delay to lock the servo again and then start the code again. Right now it unlocks but will stay unlocked, if you press the button it will lock for 1 sec then unlock again.

Hey I have answered your question please let me know if it's the thing you wanted in your code or not .

if (buttonVal == HIGH)
{ //Start of if2
  locked = true;
  digitalWrite(green, LOW);
  digitalWrite(red, HIGH);
  myServo.write(90);
  Serial.println("The box is locked!");
  numberOfKnocks = 0;
  delay(1000);
}

I have added numberOfKnocks = 0 at this part of the code so your knock value goes to zero on locking it which will not open the lock again as soon as you lock it. The problem was that you did not change the numberoflnock value which remains same even after locking it so when the code loops back to the unlocking part it automatically unlocks it.
Hope this helps you.


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


text:
How can I use both ultrasonic and IR sensor and ultrasonic sensor at ones with Arduino
I  want to use both the ultrasonic sensor and IR sensor with Arduino + motors for a car project. Will I have to do any kind of multithreading on Arduino, or is it something else

No multithreading needed; it is something else. You may want to be more specific in your question, explain what you want to do and what you have already tried. As it stands, you won't get any useful answers.

While it is completely possible to hook two or more sensors to Arduino, once you talk about multithreading, you need to think about RTOS support. You can achieve parallel processing by creating 2 diffenent tasks using xTaskCreate in freeRTOS. Latest development support in Arduino allow to create such tasks.
https://github.com/feilipu/Arduino_FreeRTOS_Library
While the concepts of RTOS are vast, you can quickstart with Arduino freeRTOS library and check whether it meets your requirements. I used to do such project for obstable avoider bot and faced lot of challenges if there is no parallel processing. I am sure you'll be able to acheive much better results with multithreading.
Regarding sensor, make sure ultrasonic sensor is giving reliable data for every readings and don't use IR sensor under sunlight conditions otherwise it'll give erratic results. All the best with your project!

Arduinos don't do multithreading. There are a number of attempts at implementing such things, but they're a waste of time and resources.
Instead you need to get into the habit of two things:

Write non-blocking code
Make use of the internal hardware peripherals when possible

The motors, using the hardware PWM, are very much "fire and forget" - set them going and you can forget about them until you want to change their speed or direction.
Ultrasonic sensors can be made both more accurate and more "in the background" by using the Input Capture peripheral of the Arduino.
IR sensors (I assume you mean proximity sensors) are usually either just like a button or a potentiometer - you just read them when you want to know what it's doing.
It's your task to learn how to fit all that together into a single program that reacts to the inputs in the way you want and control the motors in the right way.


text:
IMU (MPU9250) and Ticker on ESP32
I want to read the data from an IMU (MPU9250) periodically. To do that I use a ticker as shown in the following code:
#include <Ticker.h>
#include "MPU9250.h"

constexpr int SERIAL_BAUDRATE = 115200;
constexpr float SAMPLING_FREQUENCY = 1.0;

Ticker TimerIMU;
MPU9250 IMU(Wire, 0x68);

void readIMU()
{
    // read the sensor
  IMU.readSensor();
  // display the data
  Serial.print(IMU.getAccelX_mss(),6);
  Serial.print("\t");
  Serial.print(IMU.getAccelY_mss(),6);
  Serial.print("\t");
  Serial.print(IMU.getAccelZ_mss(),6);
  Serial.print("\t");
  Serial.print(IMU.getGyroX_rads(),6);
  Serial.print("\t");
  Serial.print(IMU.getGyroY_rads(),6);
  Serial.print("\t");
  Serial.println(IMU.getGyroZ_rads(),6);
}

void setup()
{
  // serial to display data
  Serial.begin(115200);
  while(!Serial) {}
  // start communication with IMU
  int retVal = IMU.begin();
  if(retVal < 0)
    Serial.println("IMU initialization unsuccessful: check your wiring or try resetting power to the sensor.");
   // start ticker
  TimerIMU.attach(1.0 / SAMPLING_FREQUENCY, readIMU);
}

void loop()
{
}

This approach does not produce the expected results: the IMU returns always the same values. Putting the readIMU function in the main loop and commenting the Ticker works well. I use an ESP32-WROVER.
Where is my error? Any suggestion would be appreciated.

readIMU() is called by the library from an ISR (Interrupt Service Routine). While the ISR runs, other interrupts cannot be handled. The IMU sensor works over I2C, which relies on interrupts being serviced. So, when initiating the communication inside an ISR, the transmission can never be finished correctly, since the needed ISRs are not executed. At least the library doesn't seem to block in that case, so the code runs, but the values are never updated.
You should not do interrupt dependent things inside of an ISR. Instead you can define a global flag variable, which you set inside the ISR. Then in your main code you just constantly check this flag and execute the ISR dependent code, if the flag is set. After the execution you reset the flag.
The response time is dependent on the speed, that your loop runs in. But this shouldn't be a problem here, since you don't have any other code in loop() and your frequency is just 1Hz, so a delay of a few microseconds should not be relevant.

Note, that using Serial is also interrupt dependent. So writing or printing to Serial inside an ISR is also not very good. Though you can get away with it, when you make sure, that you never send more data, than the Serial buffer can hold, and that you leave enough time between the interrupts for the actual transmission. Inside an ISR the printing and writing statements will just fill the buffer. The data will then gets send in the background via interrupts.

Note, that doing this with a Ticker (aka via interrupts) is really not necessary. Instead you can execute the code directly in loop() in a non-blocking style via millis(). Have a look at the BlinkWithoutDelay example, that comes with the Arduino IDE. It demonstrates how to do timed things without blocking with delay calls.


text:
Certain componenet does not seen to respond when given voltage
I am using a part off an electronics set I got a long time ago. It is off a electronic set called

snap circuits rover deluxe

Its a disc launcher and I have wired it to how it seems to want to be wired:

The idea is that these circles you can see on the disc launcher are button tops and connect to other with other buttons just like buttons on a coat and how the pop together. I have some special wires that allow these button tops to be connected to arduino wires (which are what I am using).
In terms of a power supply I have connected a 9V power supply (not 9V transistor battery) and I have connected the + wire to the + button on the disc launcher and the same with the - wire being connected to the - button on the disc launcher. The only confusions that I now have are:

What is the CONT button potentially used for?
What is the EXT potentially used for?
I just tried guessing by putting the 9V power supply into the CONT and EXT buttons by using a breadboard, nothing happened from this, and I was also thinking during this where is the ground for the CONT and EXT pins.

If this will not simply work then, I was wondering does anyone know where I can buy an arduino plastic missile launcher

What is the CONT button potentially used for?

That's the trigger. Connect that to (-) and a disc should fire.

What is the EXT potentially used for? I just tried guessing by putting the 9V power supply into the CONT and EXT buttons by using a breadboard, nothing happened from this,

That is for triggering another device when this triggers. With your pop connections it can be hard to connect multiple things to the same signal, so for convenience they have given you a "pass through" connection. You could use that to chain together multiple disc launchers (EXT on one connected to CONT on the other)

and I was also thinking during this where is the ground for the CONT and EXT pins.

The (-) battery connection is ground.

By using the CONT, could you somehow use a digital pin signal to activate the disc launcher?

Majenko, how are you figuring out the disc shooter? Did you find some specs, or are you making educated guesses about how it works? I wonder if it uses 5V CMOS control signals, or if it drives higher voltages through the signal pins? If the CONT line feeds >5V out it would damage an Arduino digital pin when you set the pin to LOW.

@DuncanC There's certain keywords that have special meaning, such as "Active Low" - which means for an input connect it to ground to activate it, or for an output it will go to ground to indicate that it's active. - on the battery is almost always ground. Everything you need is in that image, you just have to know how to interpret what it says.

You need to connect (-) to both the battery - terminal and to the Arduino ground.
Connect CONT to a digital output pin on the Arudino. When you set the Arudino pin to LOW, it should trigger the disc launcher.
If the disc launcher uses CMOS logic you should be good to go. IF it uses TTL logic then you will need a TTL driver chip or a transistor or you might burn out the Arduino pin. You will need the specs for the disc launcher to be sure, or measure the current it drives through the CONT pin to ground. (It should be effectively zero for a CMOS pin, since CMOS inputs are capacitive. If it's a TTL input it will push like 20mA from the CONT pin to ground, as I recall.)

The digital pin output did not fully work sorry :( . But I had another idea I could use a transistor to turn the circuit on or off when I want to


text:
analogWrite(PIN, 1023) <> digitalWrite(PIN, HIGH)
This question is very similar to this one.
I'm using an ESP8266 for which the maximum analogWrite value is 1023 rather than 255 for some other Arduino boards, but I believe the principal is just the same.
I'm driving 3 LEDs directly from 3 outputs via current limiting resistors.
When I turn them on using analogWrite(PIN, 1023) they are not quite a bright as when the same LED is driven by the same pin using digitalWrite(PIN, HIGH). Which leads me to think that either 1023 does not give a 100% duty cycle or the maximum voltage in the analog case is less than that in the digital one.
Is this to be expected? Are the pins significant (4,5 and 14)?
Another similar Q&A would lead me to believe they should be the same.

Try checking the voltage across the pin but mostly the voltage is lesser by 0.1 while using pwm than just settings the pin High.

Try measuring the current, and see if there is a difference. It might be true. I know, for example, the STM processors have a low and high-speed outputs, and those have different current handling characteristics. If this is an issue in your application you could buffer the output, by driving an transistor connected to the LED, instead of driving the LED directly.

default max is 255. https://arduino-esp8266.readthedocs.io/en/latest/reference.html#analog-output

The default range was originally 1023 so it is a a little bit different from version to version

sorry, yes it is 1023. the doc is changed for 3.0.0

I can confirm that 1023 does indeed give 100% duty cycle. I connected an output of my D1 Mini to my oscilloscope and got a steady voltage.
I can also confirm that the same voltage is output for digitalWrite() and analogWrite().
However the output drivers may not be the same. With analogWrite() it may be using a weaker output driver that can't deliver as much current, so the voltage droops slightly more than it would with digitalWrite(). However even with a 470Ω resistor connected between the output and GND (the smallest value I had easily to hand in a through hole variant) I see no variation in the voltage at all.
So if there is some variation then it might be some variable that is showing a variation in your specific unit but not mine.


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:
voltage regulator
This may not be the best pace to ask this but I have to use a 3.3v regulator with this esp12
. For that I have selected this regulator 3,3v regulator and in the discribtion it is saying to use two capacitors . so are the capacitors compulsory or not and what will happen if i dont use the capacitor

Yes, they are compulsory. They are to prevent oscillation of the regulator and to provide rapid delivery of current over short periods while the regulator adjusts to changing demands.

u guys are a company right and the account is not managed by an individual right.

I am an an individual and a company. What does that matter anyway?

just asking i checked ur profile and clicked on the links and found that u have a well maintained web site.

Not as well as it could be. I'm in the process of a complete re-write using Laravel and Vue.JS.

is the chip kit lenny made by you its a good and powerful board .

Yes, that's my design. Glad you like it.

Majenko is one of the top contributors to this message board. He knows of what he speaks. (And yes, a regulator chip is only part of a regulator circuit. You need capacitors to create the finished voltage regulator.)