body:
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.

title: IMU (MPU9250) and Ticker on ESP32

Answers: 1

body:
`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.


body:
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:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/cEoWU.png

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

title: Certain componenet does not seen to respond when given voltage

Answers: 2

body:
> 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.

body:
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.)


body:
This question is very similar to [this one][1].
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][2] would lead me to believe they should be the same.

  [1]: https://arduino.stackexchange.com/questions/24979/the-function-analogwrite-is-outputting-less-voltage-than-digitalwrite-on-my-boar
  [2]: https://arduino.stackexchange.com/questions/35873/whats-the-difference-between-analogwrite-and-digitalwrite

title: analogWrite(PIN, 1023) <> digitalWrite(PIN, HIGH)

Answers: 1

body:
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.


body:
 - 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?

title: Why Windows 10 does not see Nodemcu device?

Answers: 1

body: Read through https://stackoverflow.com/questions/43007501/nodemcu-not-detected-by-computer#:~:text=I had to install the,Afterwards, it worked.&text=For future people with this,and it wouldn't detect. 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.


body:
This may not be the best pace to ask this but I have to use a 3.3v regulator with this [esp12][1]
. For that I have selected this regulator [3,3v regulator][2] 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

  [1]: https://robu.in/product/esp-12f/
  [2]: https://robu.in/product/ams1117-3-3v-1a-sot-223-voltage-regulator-ic-pack-of-5-ics/

title: voltage regulator

Answers: 1

body: 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.


body:
I have an Arduino M0 connected to a peripheral device.

A PC is connected to the arduino via USB. The mode of operation is that the Arduino receives commands via USB that instruct it to do something with the peripheral device. The data from the peripheral device (a struct) is converted to a JSON string and sent to the PC over USB.

I am using `SerialUSB.print();`, `SerialUSB.println();` to write the JSON data, and then after each part of the JSON message is printed, I call `SerialUSB.flush();`.

I am noticing that sometimes the next JSON message will "interrupt" the last (the last message will not finish printing before the next starts).

I have already increased my SerialUSB baudrate to the max supported. What are some strategies I can use to ensure that the JSON message is fully printed printing the next?

Here is the relevant code:

````
typedef struct __attribute__((packed))
{
  uint16_t inner_member1, inner_member2, inner_member3;
  uint16_t inner_member4, inner_member5, inner_member6, inner_member7, inner_member8, inner_member9;
} inner_struct_t;

typedef struct __attribute__((packed))
{
  inner_struct_t i1;
  inner_struct_t i2;
  unsigned long outer_member1;
  uint16_t outer_member2;
  uint16_t outer_member3;
  uint16_t outer_member4;
  uint16_t outer_member5;
  uint16_t outer_member6;
  uint16_t outer_member7;
  uint16_t outer_member8;
  uint16_t outer_member9;
  uint8_t outer_member10;
} outer_struct_t;

void print_inner(inner_struct_t *i)
{
    SerialUSB.print(F("{"));
    SerialUSB.print(F("\"inner_member1\": "));
    SerialUSB.print(i->inner_member1);
    SerialUSB.print(F(", "));
    SerialUSB.print(F("\"inner_member2\": "));
    SerialUSB.print(i->inner_member2);
    SerialUSB.print(F(", "));
    SerialUSB.print(F("\"inner_member3\": "));
    SerialUSB.print(i->inner_member3);
    SerialUSB.print(F(", "));
    SerialUSB.print(F("\"inner_member4\": "));
    SerialUSB.print(i->inner_member4);
    SerialUSB.print(F(", "));
    SerialUSB.print(F("\"inner_member5\": "));
    SerialUSB.print(i->inner_member5);
    SerialUSB.print(F(", "));
    SerialUSB.print(F("\"inner_member6\": "));
    SerialUSB.print(i->inner_member6);
    SerialUSB.print(F(", "));
    SerialUSB.print(F("\"inner_member7\": "));
    SerialUSB.print(i->inner_member7);
    SerialUSB.print(F(", "));
    SerialUSB.print(F("\"inner_member8\": "));
    SerialUSB.print(i->inner_member8);
    SerialUSB.print(F(", "));
    SerialUSB.print(F("\"inner_member9\": "));
    SerialUSB.print(i->inner_member9);
    SerialUSB.print(F("}"));
    SerialUSB.flush();
}

void print_outer(outer_struct_t *o)
{
    SerialUSB.print(F("{\"outer_member10\": "));
    SerialUSB.print(o->outer_member10);
    SerialUSB.print(F(", \"outer_member2\": "));
    SerialUSB.print(o->outer_member2);
    SerialUSB.print(F(", \"outer_member1\": "));
    SerialUSB.print(o->outer_member1);
    SerialUSB.print(F(", \"i1\": "));
    print_inner(&(o->i1));
    SerialUSB.print(F(", \"i2\": "));
    print_inner(&(o->i2));
    SerialUSB.print(F(", \"outer_member3\": "));
    SerialUSB.print(o->outer_member3);
    SerialUSB.print(F(", \"outer_member4\": "));
    SerialUSB.print(o->outer_member4);
    SerialUSB.print(F(", \"outer_member5\": "));
    SerialUSB.print(o->outer_member5);
    SerialUSB.print(F(", \"outer_member6\": "));
    SerialUSB.print(o->outer_member6);
    SerialUSB.print(F(", \"outer_member7\": "));
    SerialUSB.print(o->outer_member7);
    SerialUSB.print(F(", \"outer_member8\": "));
    SerialUSB.print(o->outer_member8);
    SerialUSB.print(F(", \"outer_member9\": "));
    SerialUSB.print(o->outer_member9);
    SerialUSB.print("}");
    SerialUSB.flush();
}
````

title: Arduino SerialUSB.print/println is being interrupted by other prints

Answers: 0


body:
I connected my ESP32 to Wifi and I can see this in my Wireless Statistics:

    ID |       MAC Address      |Current Status| Packets Received | Packets Sent | SSID
    1  | 3C: 71: BF: 0D: CB: 00 | Connected    |         52       |       47     |mySSID

I can ping via IP but I can't see ESP device in the DHCP list or ARP.
Could you explain why? And how I can fix this?

title: ESP32 and wifi router

Answers: 1

body: I made a binding IP and MAC and now I see my ESP)


body:
    #include <Arduino.h>

    void setup()
     {
      pinMode(13, OUTPUT);
     }
    void loop()
    {
     digitalWrite(13, HIGH);
     delay(1);
     digitalWrite(13, LOW);
     delay(1);
    }

I am trying to make an led glow for one second to glow and then go off but nothing happens

title: Arduino led not blinking

Answers: 2

body:
    #include <Arduino.h>

    void setup()
     {
      pinMode(13, OUTPUT);
     }
    void loop()
    {
     digitalWrite(13, HIGH);
     delay(1000);
     digitalWrite(13, LOW);
     delay(1000);
    }

The problem with your code is that the delay function works in milliseconds and not seconds . 1sec = 1000ms .

body:
by increasing the delay value, you can visualize it better.

    {

     digitalWrite(13, HIGH);

     delay(2000);

     digitalWrite(13, LOW);

     delay(1000);

    }


body:
I have a NodeMCU ESP8266  ESP-12E and I tried uploading a file thru the SPIFFS.  I am not sure why I see OTA instead of the SPIFFS?

[![No SPIFFS Only OTA][1]][1]

  [1]: https://i.stack.imgur.com/HUv29.jpg

Is there a configuration that I missed?

title: No SPIFFS only OTA in NodeMCU ESP8266

Answers: 1

body:
SPIFFS (SPI Flash File System)  is also know as FS(File system) . so What you are seeing as FS is basically SPIFFS .The OTA partition on esp8266 is compulsory so you cant get rid of it .

Hope this helps


body: How can I use Arduino Uno Analog Pins as Digital pins, So that I can Attach more components like sensors to the Arduino? My 13 pins are preoccupied and I want more.

title: How can I use Arduino Analog Uno pins as Digital pins?

Answers: 0


body: Is there some way to do raw radio on a esp32 and change frequencies. If not what would I need to transmit rf, wifi, bluetooth, zigbee etc. There seems to be no tutorials on how to do anything of the sort.

title: Wide range of protocols one chip?

Answers: 1

body:
> There seems to be no tutorials on how to do anything of the sort.

That's because doing such a thing is not something the manufacturer of a part typically expects you to want to do. Yes, some chips may be capable of other protocols internally, but making them use those protocols would mean direct manipulation of the low level components in the chip.

Chips like the ESP32 or the nRF24L01 are geared towards specific protocols. They expose functionality that is good for those protocols.

There are other chips which are designed with (almost) any protocol in mind, but there's nothing "arudinoy" about using them. To access other protocols you would download the SDK for that chip and create new firmware specifically for the protocol you want to use. In many cases such SDKs and the associated documentation is protected under NDA so you or I getting access to such a thing is not usually possible.

In general though a chip is designed with a specific protocol and application in mind and is optimised specifically to handle the requirements of that protocol.


body: I am making a CNC router from a dremel and 3-5 NEMA 17 steppers. I am really confused on how I can power all those motors. I am using a RAMPS 1.4 with Arduino Mega. I have a 2.4A USB power supply. Is that enough? If not, what is the minimum specs I need to ensure that I don't burn, blow, or under power anything? I am trying to get my hands on a ATX power supply.

title: Power supply for DIY Arduino CNC Router

Answers: 1

body:
> I have a 2.4A USB power supply. Is that enough?

Not by a long way, no.

NEMA 17 motors are typically 12V, not 5V, so a USB power supply is not even close.

You will need a decent 12V power supply with a lot of current.

My 3D printer has 3 NEMA 17 motors and uses a 200W 12V power supply. Most of that goes to the motors with only a comparatively small proportion to the hot end.

You need to know the current draw of the motors you are using (note: NEMA 17 defines the physical size, not the electrical characteristics).  Sum all those up for all your motors, and that's the absolute minimum you'll need from your power supply. Add some more on top for losses in the motor drivers and to power the Ardiuno.

And I'm not even considering the dremel in any of this...

So yes, an ATX power supply is probably a good choice.


body:
As said no programming skills only started 2 days ago when Nano arrived.
Heads in bits. This is how far i got. Any help much appreciated..[![enter image description here][1]][1]

    int EMagnetPin = 8;
    int solenoidPin = 9;
    int ReedPin = 13;

    void setup()
    {
      pinMode(EMagnetPin, OUTPUT);     // assign pin type
      pinMode(solenoidPin, OUTPUT);   // assign pin type
      pinMode(ReedPin, INPUT);        // assign pin type
      Serial.begin(9600);             //serial port open

    void loop()
    {
    Serial.print(digitalRead(ReedPin));
    if (digital REad(ReeddPin)==0 ) {
    digitalWrite(solenoidPin,HIGH);

             // Once magnet applied to Reed Switch Will activate the below

      digitalWrite(EMagnetPin, low);
      delay(11000);
      digitalWrite(EMagnetPin, HIGH);
      delay(500);
      digitalWrite(EMagnetPin, low);
      delay(500);
      digitalWrite(EMagnetPin, HIGH);
      delay(500);
      digitalWrite(EMagnetPin, low);
      delay(22500);
      digitalWrite(EMagnetPin, HIGH);
      delay(500);
      digitalWrite(EMagnetPin, low);
      delay(500);                          // Stops EMagnet
      digitalWrite(solenoidPin, HIGH);     //Start Solenoid
      delay(500);
      digitalWrite(solenoidPin, low);
      delay(500);
         // Program Ends

  [1]: https://i.stack.imgur.com/Sz2IS.jpg

title: Help a noob, no idea on Programming, only started 2 days ago Help please

Answers: 3

body:
I presume you got some errors, like this:

<!-- language: lang-none -->

    /tmp/arduino_modified_sketch_836883/sketch_oct30a.ino: In function 'void setup()':
    sketch_oct30a:13:3: error: a function-definition is not allowed here before '{' token
       {
       ^
    sketch_oct30a:37:17: error: expected '}' at end of input
           delay(500);
                     ^
    exit status 1
    a function-definition is not allowed here before '{' token

You have to read those. At the end of a function you need a closing brace. So, setup for example would look like this:

    void setup()
    {
      pinMode(EMagnetPin, OUTPUT);     // assign pin type
      pinMode(solenoidPin, OUTPUT);   // assign pin type
      pinMode(ReedPin, INPUT);        // assign pin type
      Serial.begin(9600);             //serial port open
    }   // <------- ADD THIS

Ditto for the end of the loop function.

The next problem is this line:

        if (digital REad(ReeddPin) == 0 ) {

The function "digitalRead" is spelt like that, not as two words. Also you misspelt "ReedPin" as "ReeddPin".

You have to go carefully through your code, look at the error messages, and fix them one by one. C++ is case-sensitive, you can't just thrown in extra spaces in the middle of words, and you have to be consistent with your variable names (ie. not misspell them).

---

I suggest you do a C++ tutorial, or find an Arduino tutorial. These are basic coding mistakes made by beginners. With a bit of practice, and some working through examples, you will stop making them.

body:
    #include <Arduino.h>
    int EMagnetPin = 8;
    int solenoidPin = 9;
    int ReedPin = 13;

    void setup()
    {
      pinMode(EMagnetPin, OUTPUT);  // assign pin type
      pinMode(solenoidPin, OUTPUT); // assign pin type
      pinMode(ReedPin, INPUT);      // assign pin type
      Serial.begin(9600);           //serial port open
    }

    void loop()
    {
      Serial.print(digitalRead(ReedPin));
      if (digitalRead(ReedPin) == 0)//it is known as digitalRead
      {
        digitalWrite(solenoidPin, HIGH);

        // Once magnet applied to Reed Switch Will activate the below

        digitalWrite(EMagnetPin, LOW);
        delay(11000);
        digitalWrite(EMagnetPin, HIGH);
        delay(500);
        digitalWrite(EMagnetPin, LOW);
        delay(500);
        digitalWrite(EMagnetPin, HIGH);
        delay(500);
        digitalWrite(EMagnetPin, LOW);
        delay(22500);
        digitalWrite(EMagnetPin, HIGH);
        delay(500);
        digitalWrite(EMagnetPin, LOW);
        delay(500);                      // Stops EMagnet
        digitalWrite(solenoidPin, HIGH); //Start Solenoid
        delay(500);
        digitalWrite(solenoidPin, LOW);
        delay(500);
      }
    }// please close all loops
    // Program Ends

please remember to close all loops ,enter right spelling

I would suggest you to take a tutorial and also use a program like platformio or Arduino on vscode which will help you to write the code as it has auto code completion so you will always speel the right name for variables and also type the right function names.

Hope this helps.

body:
Note that others already gave good answers; this is just a way to make your code more elegant.

This part:

      digitalWrite(EMagnetPin, low);
      delay(11000);
      digitalWrite(EMagnetPin, HIGH);
      delay(500);
      digitalWrite(EMagnetPin, low);
      delay(500);
      digitalWrite(EMagnetPin, HIGH);
      delay(500);
      digitalWrite(EMagnetPin, low);
      delay(22500);
      digitalWrite(EMagnetPin, HIGH);
      delay(500);
      digitalWrite(EMagnetPin, low);
      delay(500);                          // Stops EMagnet
      digitalWrite(solenoidPin, HIGH);     //Start Solenoid
      delay(500);
      digitalWrite(solenoidPin, low);
      delay(500);

You see there is a lot of duplication (`digitalWrite` plus `delay`).

The only things changing are the pin number, the pin state and the delay time (which is mostly 500).

You can create a new function for this, e.g. `digitalWriteWithDelay`:

    void digitalWriteWithDelay(int pinNumber, int pinState, int delayTime = 500)
    {
        digitalWrite(pinNumber, pinState);
        delay(delayTime);
    }

Now you can rewrite

      digitalWrite(EMagnetPin, low);
      delay(11000);
      digitalWrite(EMagnetPin, HIGH);
      delay(500);

to

    digitalWriteWithDelay(EMagneticPin, LOW, 11000);
    digitalWriteWithDelay(EMagneticPin, HIGH);

and all subsequent lines similarly. Btw, it's best to use LOW and HIGH (keep the capitalization consequent). As you can see in the last line, 500 need not to be passed as it is the default value.


body:
I am fairly new(having less hands on experience) to Arduino and electronics in general. I have a project for which I know the features and required electromechanical parts. I need some advice in choosing the right Arduino. Here's my requirement :-

I need the board to handle the following Hardware/Software parts -
1. 3 Geared motors,
2. 1 BLDC 1000 kva
3. 2 cameras ( one is also ok)
4. TinyML for object detection
5. Mic to receive audio commands
6. Speaker to talk back.
7. Wifi shield to send/receive information to internet or a laptop.
8. 3 small servo motors.
9. 2 Proximity sensor.
10. 1 dc motor (6-9v)

Please advice which Arduino board will be perfect for the above requirements. I was thinking of Arduino Mega 2560, but after looking into various projects I couldn't decide if it was sufficient as I have many hardware parts.

title: Need some Hardware advice with arduino

Answers: 4

body:
To process incoming images, voice commands, produce sounds, and also do WiFi is almost certainly beyond the capabilities of any **micro** computer, like the Arduino (maybe some of the more recent models might). I strongly doubt that the Mega 2560 would. It doesn't have a heap of RAM for one thing (it has 8k of RAM). Look at the sizes of images produced by cameras these days, they are usually measured in megabytes, not kilobytes.

What might work for you would be a Raspberry Pi, which is basically a small Linux computer on a board, with a substantial amount of RAM.

body:
I would suggest you to go with esp32 as it already has a Wi-Fi module and also the specs are pretty good

 1. 2 CPU (one dual core and other one ultra low power)
 2. frequency 240 MHz
 3. flask size upto 16 megabytes
 4. also a inbuilt BLE module
 5. it has around 34 usable pins

Hope this helps.

body:
Your main bottleneck here is the camera. If you want to do real time video, I would suggest getting a Raspberry Pi or the equivalent then using it as a master over something easier to code like an arduino.

The camera and wifi would be handled by the raspberry pi ( using Robot Operating software ) and the low level stuff like motor would be handled by the arduino ( any will do, since the main computing task will be left to the Pi ).

As for the machine learning, most microcontrollers can't handle it. If you want to do machine learning, I would suggest the NVIDIA range of single board computers instead of a Pi, since they have better GPU performance.

body:
If your project is more for fun and not mission-critical, and you have an older smartphone you're no longer using, you can repurpose it. For the motors (BLDC, DC, servos) and proximity sensors you can use any arduino (e.g. Nano) through either its USB port (if it has OTG) or bluetooth (e.g. Pro Micro). Your Arduino code in this case would be very simple, just a few lines to send proximity data, and set servo angles and motor PWMs.

If you choose this path (if you CAN choose it), you can get the most CPU power, memory, and in general doing this in Kotlin or Java is simpler than on any 8-bit microcontroller (or probably on a RPi which is a very good choice otherwise). You can use its camera (very good on most phones), wifi, microphone, speaker, etc. as well. There are libraries for object detection, and many other things. Using its accelerometer, gyro, GPS, mobile internet, NFC, light sensor, touchscreen could be a plus. And they come with batteries (UPS included).

Of course you need to have an old phone (most people replace theirs in around 2-3 years, just ask around in your family and friends), buying one for this costs more than an SBC. Also, Android can kill your app if you're not careful (just uninstall/disable everything else you can, and this probably won't happen), so don't use this to control a nuclear power plant or similar. If you need to build more units, getting old phones becomes harder. But for hobby projects this could work. If not, just choose a SBC (like Raspberry Pi, Orange Pi, BeagleBoard, etc.).


body:
I am using a L298n driver to make a basic RC car. I realise that PWM is used to control the speed of the motors and that the car would turn when the wheels on one side of the car have a rpm different from the other side. I am taking user input from the x-axis of a joystick.

However, I am not sure how to arrive at an exact relationship between rpm and the angle by which the car turns.

My approach so far :

1. If the car is turning left, the wheels on the left side are turning in a smaller arc and hence the inner wheels have a lower rpm. The sharper the turn the slower the inner wheels turn.

2. PWM is used to control the speed of the motors.

3. Each angle of turning corresponds to circles of different radii. Hence a sharper turn would correspond to a circle with a very small radius.

4. So I need to map the x-axis values of the analog stick to angles by which I want the car to turn. Once I know the relation between rpm and the angle by which the car turns, I can map the joystick values to PWM values.

[This question has already been asked here][1] and the consensus seems to be that some sort of feedback mechanism is required for an exact calibration.

I have two questions :

1. Where do I learn more about this feedback mechanism?
2. Purely from a physics perspective, considering an ideal environment, how do I derive a relation between rpm and the steering angle?

  [1]: https://arduino.stackexchange.com/questions/71304/dc-motor-car-steering

title: Deriving the exact relationship between PWM and steering

Answers: 1

body:
> Where do I learn more about this feedback mechanism?

It depends on the kind of feedback. You can have *absolute* or *relative* feedback. Relative would be, for example, to use an encoder on each wheel to find out how much it has turned. Absolute would be using a compass to know exactly what direction the vehicle is facing at any time.

> Purely from a physics perspective, considering an ideal environment, how do I derive a relation between rpm and the steering angle?

If you know how much each wheel has turned then it is really just simple trigonometry. You have two arcs that are the same proportion around the circumference of two circles. The circles must have the same centre point. Well, I say "simple" - that's a relative term. And of course it depends if you are moving like a car (i.e., turning while moving forwards) or like a tank (turning on the spot) as to whether such calculations are particularly meaningful.

But then of course that's only if you actually know the RPM. Which requires feedback.

There is no easy relationship between PWM and the angle turned. This is because PWM does not define the RPM:

* PWM defines the current
* The current defines the torque
* The torque defines the acceleration (and ultimately maximum speed) under different loads and conditions.

Those loads and conditions change depending on lots of factors. With no way to change the angles of the wheels they will need to slip on the surface as you turn. That adds friction and varies depending on both the speed at which you turn, the angle you turn through, and the surface you are driving on at the time. A high friction surface will both increase the power transfer and at the same time require more power to turn. A sharper turn angle will slip more and require more power to overcome the friction.

It's a very complex relationship with far too many variables. Which is why cars have steering mechanism to change the angle of the wheels, and some vehicles have rear-wheel steering as well to change the angle of the rear wheels to reduce slip and friction (such as the Porsche 911 and many large heavy vehicles), and why London cabs use "Ackermann" steering which gives each wheel a different angle while turning to increase the angle the vehicle can turn through so it can turn in the road easier.

So all in all if you want to know what direction you are pointing at any time, although it's harder to interface with and use, and may be a little more expensive, a compass or other absolute rotation sensor is the way to go.

If you want to turn to a specific angle, (or turn through a specific angle, which is just a relative change between two specific angles) then it's a case of "move a bit" then "see what angle I'm at" then "move a bit more" and "see what angle I'm at".

You could either use a simplistic approach where you always move in discrete steps, or use a PID to calculate what would be a good amount to turn to get you closer and closer to the desired angle depending on how far you turned last time.


body: I'm very new to arduino and am doing my first project, a bluetooth run robot. When i plugged in my module to my laptop to upload the code, the module lights up, and afterwards, i was able to run it on my 12v battery. However, later on, my module stopped working suddenly. It came on once after that, but was on AT config and blinked out soon after. Is this problem because I have been using my battery for a month now without a recharge or because its connected to too many devices or because of a faulty bluetooth module

title: What do i do to get my bluetooth module to light up?

Answers: 0


body:
I need help converting my code to change out the `delay()` command into the `millis()` command for smoother operation.

Currently the code only moves after the delay is up. I would like the codes to run simultaneously.

This is my codes

    #define aref_voltage 3.3
    #include <Servo.h>
    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 32 // OLED display height, in pixels
    // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
    #define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
    Servo Servo1;
    int led = 13;
    int sw = 3;
    int bz = 14;
    int ldr = A1;
    int lv = 0;
    int rly = 7;
    int buttonState = 0;
    int servoPin = 8;
    // the setup routine runs once when you press reset:
    void setup()
    {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
      pinMode(sw, INPUT);
      pinMode(ldr, INPUT);
      pinMode(bz, OUTPUT);
      pinMode(rly, OUTPUT);
      digitalWrite(rly, LOW);
       Servo1.attach(servoPin);
      analogReference(EXTERNAL);
      Serial.begin(115200);

       if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
       Serial.println(F("SSD1306 allocation failed"));
       for(;;);
      }
    }
    void loop()
      {
      lv = analogRead(ldr); // read the value off the LDR
      Serial.print("LDR Value is: ");
      Serial.println(lv);
      delay(100);

      buttonState = digitalRead(sw); // Check switch 1 or 0
      Serial.println(buttonState);   //Show the state of pushbutton on serial monitor
      delay(100);

        while ( (lv >= 150) && (buttonState == HIGH) )
    {
        delay(1000);
        display.clearDisplay();
        display.setTextSize(2);
        display.setTextColor(WHITE);
        display.setCursor(0,0);
        display.println("Relay On! ");      // here the message is inside the ""
        delay(1000);
        display.display();

        digitalWrite(rly, HIGH);//relay on 1 min
        delay(6000);
        tone(bz, 1500);//buzzer on for 30 sec
        delay(3000);
        digitalWrite(led, HIGH);//led flash at 1 Hz
        delay(3000);
        digitalWrite(led, LOW);
        delay(3000);

        digitalWrite(led, HIGH); // led 2 kHz
        delay(3000);
        digitalWrite(led, LOW);
        delay(3000);
        tone(bz, 2000); //buzzer at 2 khz
        delay(3000);
        noTone(bz);

        delay(2000);
        display.clearDisplay();
        display.setTextSize(2);
        display.setTextColor(WHITE);
        display.setCursor(0,0);
        display.println("Tank 2 Filled! ");      // here the message is inside the ""
        delay(1000);
        display.display();

        digitalWrite(rly, LOW); // relay low
        digitalWrite(led, HIGH);
        delay(5000);            // led flash 4Hz
        digitalWrite(led, LOW);
        delay(5000);

       Servo1.write(45); // Make servo go to 45 degrees
       delay(1000);

       Servo1.write(135); // Make servo go to 135 degrees
       delay(1000);

       Servo1.write(0); // Make servo go to 0 degrees
       delay(1000);
        break;
    }
       if (buttonState == LOW)
      {
        digitalWrite(rly, LOW); // relay off
        digitalWrite(led, LOW); // led off
        delay(500);
       Servo1.write(0);     // Make servo go to 0 degrees
       delay(1000);
        noTone(bz); // buzzer off

      }
      }

title: Converting my delays to millis for smoother operation

Answers: 2

body:
Your delays are making the program jerky, so you have to get rid of them. :)

I have a [lengthy discussion about this](http://gammon.com.au/blink) on my own web site, but basically you need to restructure so that you use a "state machine" and instead of delaying, make a note of the current time (using millis() function) and then do the next step when the time is up.

Just as an example, when you bake a cake you don't stop what you are doing for an hour and stare at the oven while it cooks, do you? You make a note of the time, and come back when the time is up.

One of the Arduino tutorials [Blink without delay](https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay) has an example of doing that.

The example code is (initial comments removed):

    // constants won't change. Used here to set a pin number:
    const int ledPin =  LED_BUILTIN;// the number of the LED pin

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

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

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

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

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

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

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

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

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

This won't be a one-line change. You have to re-think how you go about handling time delays.

body:
A while back I wrote an [answer to another question about non-blocking programming][1], using "maybe-do" functions - functions that maybe do something if the conditions for doing it are met, typically a time-interval having passed. @nickgammon's excellent article (linked in his answer to this question) shows a similar structure that evaluates the condition within loop() rather than within the maybe-do/action function, as I did in my answer. Both ways work equally well.

It will be a good exercise to play with the BlinkWithoutDelay example sketch, and even write a couple of your own sketches that follow that general format. But soon you'll get tired of writing all of those `if( (millis() - previousMills) >= someInterval){` expressions and the bookkeeping of the various `previousMillis`es that goes with them - not to mention debugging the results of the inevitable typos! )-:

Once you've got the hang of:
```
is (current time - time when we previously acted) >= action interval{
   do the action;
   save the current time as the previous time;
}
// again, for the next action
// yet again, for each remaining action
```
, consider using a timer library such as SimpleTimer. Its job is to maintain all that bookkeeping for you, and to call your action functions at the right time.

 You need to know a few things to use it - some of the same few things you needed to know to write code the previous way, but the more tedious parts will be done for you:
 - How to make a set of timers;
 - How to make an action function (called a 'callback function');
 - How to set an interval (one-time or repeating) that the action- or callback-function will get called.
 - How to run the timers so they can do their jobs.

**How to make timers**:
 - First, you need the library: Visit this [github page][2] and click the green "Download Code" button (it's really a down-arrow, not the word "download"). In the menu that appears, click "Download ZIP".
 - Open the file that you receive, "Arduino-SimpleTimer-master.zip" (how you do this depends on your computer's operating system). In the .zip file you'll find this folder structure:

  `Arduino-SimpleTimer-master --- SimpleTimer --- (some folders and files)`

Drag the 'SimpleTimer' folder into the 'libraries' folder within your Arduino sketch folder. This library can serve every sketch you write from now on.
 - Add the following include file to the top of your sketch:
`#include <SimpleTimer.h>`
- Create a global set of timers:
`SimpleTimer myTimers;`  // creates 10 timers and makes them available for use.

**How to make a callback function** - the function that runs your LED, stepper motor, or whatever other action you need taken at a certain time:
 - A callback function does whatever is necessary to complete the timed task, *and nothing more*. For example, it might toggle an LED off if it is on, or on if it is off.
 - An action function takes *no arguments* and *returns no value*. It *must have the type*:

`void toggleLED(void);`

Of course, you get to name your functions whatever you like.

**How to set an interval.** There are a number of ways, but you're likely to use these two for nearly everything - repeating, or one-time:
- `myTimers.setTimeout(time, toggleLED);`
 sets a one-time timer that
will call my `toggleLED()' function *once* only, after "time" milliseconds. It returns the timer number that will be used. Mostly you can ignore that value for now.
- `myTimers.setInterval(time, toggleLED);`
 sets a repeating timer that will keep calling my `toggleLED()` function *every* "time" milliseconds, for as long as the sketch runs. It also returns the timer number, and again, you can ignore that value for now.

**How to run the timers.**
 - The timer library needs to be called **frequently** for your functions to get called at fairly precise intervals. Your `loop()` function should call `myTimers.run()` each time it runs.
 - `loop()` should not do anything that takes very long, nor call any function that can take very long. Long tasks will disturb the precision of the timing with which your callback functions get called.
 - Your loop function should look like:
```
void loop(){
   myTimers.run();
   // maybe some other fast code here
}
```
The `.run()` function checks each of your timers, and for every one whose time has expired, it calls its callback function (the one you specified when you called `.setInterval()` or `.setTimeout()`). This is how the timer library does its work, and why you need to call it frequently.

Now let's look put it all together in a **sample program to blink 2 LED's** at different intervals using SimpleTimers:
```
// SimpleTimer demo program
//    Blink 2 LEDs at different rates for 15 seconds, then turn off both LEDs and stop.

#include <Arduino.h>
#include <SimpleTimer.h>

/*****< Definitions >*****/
#define LED1 13 // the on-board LED
#define LED2 12 // an external LED

/*****< External and Global Declarations >*****/
SimpleTimer myTimers;  // define a set of timers
bool doHalt = false;   // a flag to tell loop() to stop

/*****< Local Function Prototypes >*****/
void toggleLED1(void);  // function to toggle the state of LED1
void toggleLED2(void);  // function to toggle the state of LED2
void setHalt(void);   // function to set the halt flag

void setup()
{
 // Set the pin modes for our two LEDs:
   pinMode(LED1, OUTPUT);
   pinMode(LED2, OUTPUT);

   // Turn off the LEDs:
   digitalWrite(LED1, LOW);
   digitalWrite(LED2, LOW);

 // Set up the blink intervals
 myTimers.setInterval(800L, toggleLED1); // start timer to blink LED1 slowly
 myTimers.setInterval(300L, toggleLED2); // start timer to blink LED2 rapidly

 // Stop the program after 30 seconds.
 myTimers.setTimeout(15*1000L, setHalt); // start timer to halt the program
}

void loop() {
 myTimers.run();     // keep calling the timers as often as possible

 if( doHalt ){      // if the halt flag is set,
  // Turn off the LEDs:
    digitalWrite(LED1, LOW); //    shut off the leds,
    digitalWrite(LED2, LOW);

    // Hang here, doing nothing
  while(1)       //    and hang here forever.
   ;
 }
}

// Toggle the state of LED1
void toggleLED1(void){
 bool isOn = digitalRead(LED1);

 digitalWrite(LED1, !isOn);
}

// Toggle the state of LED2
void toggleLED2(void){
 bool isOn = digitalRead(LED2);

 digitalWrite(LED2, !isOn);
}

// Set the halt flag to stop 'loop()'
void setHalt(void){
 doHalt = true;
}

/***  end  ***/
```

This program does everything BlinkWithoutDelay does, but without the bookkeeping and the mechanics of calling your action functions. Those are all taken care of by the SimpleTimer library, leaving you free to concentrate on what your program is meant to do.

  [1]: https://arduino.stackexchange.com/questions/60759/how-to-rotate-two-or-more-steppers-simultaneously-by-giving-array-of-angles/66380#66380
  [2]: https://github.com/marcelloromani/Arduino-SimpleTimer


body:
I have a NodeMCU and im trying to control a servo to move from angle A to B and viceversa. The thing is I want to be able to power off the servo after moving so it could stop getting voltage and current. I decided to use an NPN transistor (2N2222A to be more precise) and the servo red cable is connected from one end of the transistor and the other end is connected to the red line in my breadboard while the middle pin is connected to a pin in the NodeMCU. The thing is, it seems to work with a SG90 perfectly but when an MG90S is connected it doesn't move and you can hear a faint clicking from the servo. When the MG90S is instead connected directly to voltage line it works. I don't understand what the problem is. I also implemented the `servo.detach();` function and it works but I don't know if it truly shuts off power to the servo like using a transistor would.

    if (buttonState2 == HIGH) {
      digitalWrite(LED2, HIGH);
      digitalWrite(transistor2, HIGH);

      for (pos2 = 90; pos2 < 180; pos2 = pos2 + 1) {
        servo2.write(pos2);
        delay(15);
      }
      digitalWrite(transistor2, LOW);
      digitalWrite(LED2, LOW);
    }

This is the code that I have, I would really appreciate some help, Thanks!

title: How can I power off a servo the best way? Problems with MG90S servo

Answers: 0


body:
I have bought two original TowerPro MG966R 360 degree continuos rotation Hi-torq digital servos.

Expected results :
- 90       deg -- no rotation
- 90 - 0   deg -- speeding up to one side
- 90 - 180 deg -- speeding up to the other side

Real results :
- When I am sending 50-90 degrees PWM, they behave like standard (non-continuos) servos and turn in 50-90 degree angle.
- Bellow 50 there is small speedup, then continuos rotation at max speed to one side.
- Above 90 there is continuos rotation at max speed to the other side.

I am using standard Arduino Servo library,
servo has external 2A power and
all grounds (servo, arduino, power) are connected together.

Both new servos behave same, so I assume fault is on my side (software).
Same code and wiring works fine with other (cheap,copycat) servo I have.

May I ask for some pointer to what am I doing wrong?

Thanks

My test code :
```
 // 9 - servo pin
 // 2 - pot pin

 #include <Servo.h>

 Servo srv;

 void setup(){
  srv.attach(9);
 }
 void loop(){
  //~ srv.write(map(analogRead(2),0,1023,50,90));
  srv.write(map(analogRead(2),0,1023,0,180));
  delay(10);
 }
```
Bought here : [ebay](https://www.ebay.com/itm/TowerPro-MG996R-Digital-Robotic-Continue-Servo-RoHS-with-360-Rotation/253678010093)

Manufacturer page : [here](https://www.towerpro.com.tw/product/mg995-robot-servo-360-180-rotation/)

title: servo acting weirdly

Answers: 0


body:
I’m trying to write an arduino sketch that makes a dc motor turns one full rotation every 60s similar to a clock. The arduino will be connected to the gate of a typical mosfet and the dc motor will be connected to the drain of the mofset  such that the arduino controls the speed of the motor. Any suggestions on how I go about this?
I’m using an arduino mega 2560 in case that’s relevant.

title: Using an Arduino to rotate a DC motor once a minute (edited)

Answers: 1

body:
The best way would be to check the datasheet: https://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf and set an interrupt on one of the timer.

Example code of this application can be found on this stack here : https://arduino.stackexchange.com/questions/54542/how-to-make-1-second-delay-more-accurate

Another way of doing it if you don't need to do anything between rotation would be to wait by just waiting using delay in a for loop. Be aware that this is less precise than interrupts driven wait.
 https://www.arduino.cc/reference/en/language/functions/time/delay/

edit : if you want to complete one full rotation every 60s

    int i = 0;
    while(1) {
      i++;
      delay(1000);
        if( i == 60){
        doFullRotation();
        i = 0;
        }
    }


body:
I have some basic code that I will soon expand for my project which is a universal remote for air conditioners. I have all of the codes but the problem is 3 of the codes are below 1khz. (500hz). My sketch doesn't allow for anything to go lower and the frequency in the actual code doesn't seem to go that low. 108 is 38khz.

    uint16_t fuck[] = {0,108,0,0,347,173,22,22,22,22,22,22,22,65,22,65,22,65,22,22,22,22,22,65,22,65,22,65,22,22,22,22,22,22,22,65,22,65,22,22,22,65,22,22,22,22,22,65,22,22,22,22,22,22,22,65,22,22,22,65,22,65,22,22,22,65,22,65,22,65,22,1527,347,87,22,3692};
    static uint16_t sent_array_numbers;
    static uint8_t ir_seq_index = 4;
    static uint8_t pin_state;

    void ir_on()
    {
      TCCR1A |= 192;
      pin_state = 1;
    }

    void ir_off()
    {
      TCCR1A &= -193;
      pin_state = 0;
    }

    void ir_toggle()
    {
      if (pin_state)
        ir_off();
      else
        ir_on();
    }

    void ir_start()
    {
      DDRB |= 10;
      ICR1 = 416;
      OCR1A = 104;
      TCCR1A = 2;
      TCCR1B = 24;
      TIMSK1 = 1;
      ir_on();
      TCCR1B |= 1;
    }

    ISR(TIMER1_OVF_vect) {

      sent_array_numbers++;

      if (sent_array_numbers == fuck[ir_seq_index]) {
        ir_toggle();
        sent_array_numbers = 0;
        ir_seq_index++;

           }
    }

    void setup() {
      ir_start();
    }

    void loop() {

    }

title: Infrared Low Frequency Transmission

Answers: 1

body:
Your whole question is not very clear, so I will mainly give you explanations, of how the Timer code works (since you don't seem to understand that) and give hints.

Let's look at `ir_start()`, where you configure Timer1 for the IR operation:

    void ir_start()
    {
      DDRB |= 10;
      ICR1 = 416;
      OCR1A = 104;
      TCCR1A = 2;
      TCCR1B = 24;
      TIMSK1 = 1;
      ir_on();
      TCCR1B |= 1;
    }

First you should better not use the decimal representation of numbers here. Most of them consist of single or few bits, that a bound to a specific configuration option. You can better see, what is going on, when you use hex or better binary. So instead of `DDRB |= 10;` you would write `DDRB |= 0b1010;` (`0b` marking the binary representation, and `1010` being the binary representation of 10). That makes it easier to read by others or by you, when you leave that code for a time and come back to it. Using decimal is good in the cases, where you write registers, that represent a single value (like `ICR1`).

Now let's go through each line. Here I will only state, what the line does, not if that makes sense or if it is correct.

    DDRB |= 10;

is equal to `DDRB |= 0b1010` and will set will configure PB1 and PB3 (pin 9 and 11 on the Uno) as output pins.

    ICR1 = 416;

sets the input capture register 1, which - when not in input capture mode - sets the TOP value of the Timer, meaning the max value, to which it will count until overflow.

    OCR1A = 104;

sets the timer value, where the Timer will toggle the output compare pin A of Timer1 (PB1, aka pin 9) (of course only, if the output compare mode is activated).

    TCCR1A = 2;

is equivalent to `TCCR1A = 0b00000010`. It disables the output compare mode, thus normal port operation. Also bit `WGM11` is set to 1 and `WGM10` is set to 0 (explanation with the next line).

    TCCR1B = 24;

is equal to `TCCR1B = 0b00011000`. It sets `WGM12` and `WGM13` to one. Together with the other bits of the last line, this sets the Timer mode to FastPWM, counting to the value in `ICR1`, resetting there. Also the clock source bits are all set to zero, so disabling the Timer.

    TIMSK1 = 1;

This enables the Timer1 overflow interrupt, and is of course equal to `TIMSK1 = 0b1`.

In `ir_on()` you use

    TCCR1A |= 192;

which is equal to `TCCR1A |= 0b11000000`. It enables the output compare for OC1A, configured for setting it at the compare match and clearing it on resetting (also called inverted mode).

    TCCR1B |= 1;

will set the clock source of the Timer to the main clock without any prescaler. A prescaler would scale the counter values. For example with a prescaler of 8 (setting the clock source bits to `0b010`) would mean, that the Timer value would increment by one every 8 clock transitions, instead of on every transition. Here you have no prescaler, so the Timer runs with full speed. You can make it slower by changing the prescaler. The fine tuning can then be done by changing the `ICR1` value, which is used as TOP. Setting the clock source will also turn the Timer on.

Then in `ir_off()` you use

    TCCR1A &= -193;

Decimal `-193` is a value, that needs 2 bytes as a signed integer (twos-complement). It's binary value is `0b11111111 00111111`. You assign to a 1 byte register, so the high byte will be cut off. So you actually use the decimal value `63`. It will disable the output compare for OC1A, so disabling the PWM output on the OC1A pin.

So, to sum up the actual function of that code: The Timer is configured to run from 0 to 416 without any prescaler. At the value 104 the OC1A pin is set, on timer reset/overflow it is reset. The frequency of the signal will be `16MHz / 416 = 38,5 kHz`, with a duty cycle of `(416 - 104) / 416 = 75%`.

By changing ICR1 and OCR1A, you can go down to `16MHz / 65535 = 244Hz`. So for a frequency of 500Hz, you could use the ICR1 value `32000`. For the same duty cycle you then need the OCR1A value of 8000.

If you need an even lower frequency, you could use the prescaler by setting the clock source bits correspondingly.

Note: You use the timer overflow as your smallest time measure (since you are incrementing `sent_array_numbers` in the ISR). So by changing the Timer frequency, you also change the amount of time, that one increment of `sent_array_numbers` represents. While this time is `1 / 38.5kHz = 26.3us` with 38.5kHz, it will be `1 / 500Hz = 2ms` for 500Hz. Just keep that fact in mind, when writing the IR pulse values into the array.

You can read about all this in the [datasheet of the Atmega328p][1], which is used in the Arduino Uno.

---

Notes besides the Timer configuration:

- Make sure, that all variables, that get changed inside of an ISR, are declared as `volatile`, so that the compiler knows, that the variable can change at any time and that it cannot optimize the access to it.

- Make sure, that the index, that you use with the array, is not exceeding the size of the array. Otherwise you will read from whatever was placed behind that array in the memory.

- Every variable should have a fitting speaking name, which tells exactly, what it is. Its function might not be that obvious, when you look at your code after a few years.

- The first 4 values in the array with the IR codes are not used. From your code I cannot understand, why. (Though you suggested, that this is not the complete code).

---

I hope, that helps. If not, then you need to be more precise with your question. And provide a complete compilable minimal example code.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf


body:
I'll start by saying that the goal here is to have a hand/distance detection device. Basically touch-less button.

I managed to get it working with a simple 2-pin IR emitter and 2-pin IR detector using analog read from the detector to trigger an event. The problem is that I get interference from the sun on bright days.

Is there a way to pulse the emitter at a specific frequency and have the detector activate only on that frequency and keep the 2-pin setup?

One solution I have been leaning towards is changing the IR detector to a IR decoder and basically treat it as a remote control but I can't see a way to detect distance using this method.

I am also open to any other ideas on getting something like this to work, without IR or ultrasonic.

Thanks.

title: Minimizing IR Detection Interference

Answers: 1

body:
This is actually something I have been meaning to try but never got around to it.

My idea is to drive the LED with PWM with a 50% duty cycle. The frequency isn't really that critical, but you don't want it too high for the next part.

Now you sample the receiver at a fixed frequency that is at least 2x the frequency of the PWM into a buffer.

Then you perform FFT on that buffer.

The bucket that contains the frequency of the PWM should have a power value that is proportional to the distance.

Other light sources will be unlikely to affect the same bucket as the PWM frequency - most will only affect the lowest (0Hz+) bucket.

Or that's the theory that I came up with. I have yet to try it in practice.


body:
I have a project in which I control a display using an Arduino Due microcontroller.

The user can navigate on the TFT display (RA8875 driver ic) with a rotary enconder/pushbutton.
The display shows a certain menu. You can the selected item in the menu by rotating the rotary encoder and you can move into a submenu by pressing the rotary encoder (because it is also a button).
This is how the menu looks like:

[![Menu example][1]][1]

The problem is that sometimes when rotating the encoder the menu doesn't refresh the screen properly and seems to have gotten stuck while drawing the screen. Though when rotating the encoder some more the screen gets properly rendered so the code isn't actually 'stuck'.
This is een example of a bad rendering after rotating the encoder. (Sometimes no text gets written, sometimes some text gets written):

[![bad rendering example][2]][2]

I also made a video to make my problem more clear:
[Video with rendering problem][3].

The code for my menu is rather big so I'll try to explain the working principle and attach the used Arduino code.

I attached an interrupt to the encoder signal and to the push button.
> attachInterrupt(digitalPinToInterrupt(BTN_ROT), push_button_interrupt, FALLING);
attachInterrupt(digitalPinToInterrupt(ROT_A), rotary_enc_int, LOW);

In the interrupt function I update a 'virtual position' value. In my main loop I run a function that checks if the virtual position is different from the last seen position and updates the 'current_index'-value of the menu accordingly. It also sets 'refresh_menu' to True.
In the main loop the variable 'refresh_menu' gets checked and if true the screen gets redrawn with the menu item selected according to the value 'current_index'.

Link to full project code: [Arduino due code][4]. All the relevant code for this problem is in 'Menus.h'.

[Side note] I am not sure if my approach to build a menu is 'good'. It's not super responsive and the code is hard to maintain (changing a menu-item from position requires a lote of changes in the code). Any advice in a better approach is appreciated!

  [1]: https://i.stack.imgur.com/9cykP.jpg
  [2]: https://i.stack.imgur.com/vwNT9.png
  [3]: https://drive.google.com/file/d/1USr4ikrp1ZOdKlsef7enDSR3qvLKghmt/view?usp=sharing
  [4]: https://drive.google.com/drive/folders/1-J2r3rWD-DmXOKEkSzW49ufMXkUX-lyC?usp=sharing

title: TFT menu system sometimes doesn't refresh the screen properly

Answers: 0


body: Hello I have been here for a couple hours troubleshooting code and turns out it wasn't even my code that was the problem. My arduino uno is like 2 times slower than what its supposed to be. If I blink a led with a delay of 500ms it takes 1 second. I was using it last night and it was working just fine. I am working on a remote of sorts and the IR led was going retartedly slow. So then I switched it to my backup, still didn't work. Then digitalWrite showed me it was 2 times slower than it should be. I haven't done anything to it besides the following: (Flashed it around 100 times since i got it). I've only had it for like a month so I would appreciate if someone could tell me what I could do to fix it :/

title: Arduino 2 times slower? Broken?

Answers: 0


body:
I have an Arduino Nano 33 IoT and I want to get the angle of it using the built-in gyro but I can't seem to find any example code that does this.

The default gyro and accelerometer example code doesn't help. Is it even possible to do this?

title: Arduino Nano 33 IoT LSM6DS3: get gyro angle in degrees

Answers: 2

body:
You wil have to calculate the angles. Some trigonometry is required, and for the gyroscopes, also some integration. You can read about it [here][1], and in many other places.

You will get the best results if you combine the data from the gyroscopes and the accelerometers using a *complementary filter*, a *Kalman filter*, or an other algorithm. These are also easily googled.

There is some example code for the LSM6DS3 IMU on the Nano 33 IoT [here][2] on Github.

  [1]: http://www.starlino.com/imu_guide.html
  [2]: https://github.com/owennewo/Arduino_LSM6DS3/blob/master/examples/RollPitchYaw/RollPitchYaw.ino

body:
You are supposed to use a filter library on top of the output of the gyro as well as the accelerometer data (both is used!) to get angles ... https://www.arduinolibraries.info/libraries/madgwick

Here is a working example that prints the pitch of the sensor from +90 to -90 degrees:

    //#include <SPI.h>
    //#include <Wire.h>
    #include <Arduino_LSM6DS3.h>
    #include <MadgwickAHRS.h>
    #include <Math.h>

    float pitchFilteredOld;
    Madgwick filter;
    const float sensorRate = 104.00;

    void setup() {
      Serial.begin(9600);
      while (!Serial);
      if(!IMU.begin())  {
        Serial.println("Failed to initialize IMU!");
        while (1);
      }
      filter.begin(sensorRate);
      Serial.println("Setup complete!");
    }
    void loop() {
      float xAcc, yAcc, zAcc;
      float xGyro, yGyro, zGyro;
      float roll, pitch, heading;
      if(IMU.accelerationAvailable() && IMU.gyroscopeAvailable()){
        IMU.readAcceleration(xAcc, yAcc, zAcc);
        IMU.readGyroscope(xGyro, yGyro, zGyro);
        filter.updateIMU(xGyro, yGyro, zGyro, xAcc, yAcc, zAcc);
        pitch = filter.getPitch();
        float pitchFiltered = 0.1 * pitch + 0.9 * pitchFilteredOld; // low pass filter
        Serial.println("pitch: " + String(pitchFiltered));
        pitchFilteredOld = pitchFiltered;
      }
    }


body:
I understand that if the Arduino is powered by Jack or Vin when the USB cable is connected, the internal circuitry would inderdict the USB powering.
But what if I power the arduino througn 5V pin while the USB cable is connected? How does the internal circuit do the choice?
Did I just connect the 5V power supply directly with USB port of the laptop (since the 5V rail directly connects 5V pin and USB port)? Is this allowable? Is this dangerous?
Thank you!

title: Can I power the arduino UNO through the 5V pin while I use USB cable to collect data?

Answers: 1

body:
If u use the VIN pin of arduino, You shouldn't have a problem , as arduino selects it required voltage automatically, it's voltage regulator senses the voltage from USB and External source, if the power of the external source is higher than usb, the the power is bypassed to the External power. But don't know if you are using the 5 volt pin to turn on the arduino.

Well everything I said is applicable for UNO boards don't know other ones.

Thanks...


body:
how my coding works = 1 rfid card detect on first rfid reader and 2 rfid card detect on second rfid reader after that servo go to 90

my second rfid not detect

this is my coding
```
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
Servo  myservo;
int pos = 0;
int angle = 0;
int angle11 = 0;

#define RST_PIN2           8          // Configurable, see typical pin layout above
#define SS_PIN           9          // Configurable, see typical pin layout above
#define SS_PIN2          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN2 );   // Create MFRC522 instance.
MFRC522 mfrc522_2(SS_PIN2, RST_PIN2);   // Create MFRC522 instance.

void setup()
{
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin();        // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  mfrc522_2.PCD_Init(); // Init MFRC522 card
  Serial.println("Approximate your card to the reader...");
  Serial.println();
   myservo.attach(5);

}
void loop()
 {

// Look for new cards

if ( ! mfrc522.PICC_IsNewCardPresent()) {

return;

}

 // Select one of the cards

if ( ! mfrc522.PICC_ReadCardSerial()) {

return;

}

// Dump debug info about the card; PICC_HaltA() is automatically called

mfrc522.PICC_DumpToSerial(&(mfrc522.uid));

  delay(1000);
  // Look for new cards

  if ( ! mfrc522_2.PICC_IsNewCardPresent()) {

    return;

  }
  // Select one of the cards

  if ( ! mfrc522_2.PICC_ReadCardSerial()) {

    return;

    mfrc522_2.PICC_DumpToSerial(&(mfrc522.uid));

  }

  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "09 99 55 B2") //change here the UID of the card/cards that you want to give access
 {
String content= "1";
  byte letter;
  for (byte ii = 0; ii < mfrc522_2.uid.size; ii++)
  {
     Serial.print(mfrc522_2.uid.uidByte[ii] < 0x10 ? " 0" : "1 ");
     Serial.print(mfrc522_2.uid.uidByte[ii], HEX);
     content.concat(String (mfrc522_2.uid.uidByte[ii] < 0x10 ? " 0" : "1 "));
     content.concat(String (mfrc522_2.uid.uidByte[ii], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "09 99 55 B3") //change here the UID of the card/cards that you want to give access

      myservo.write(angle); delay(3000);
   for(angle = 0; angle > 90; angle11)
    myservo.write(angle11);
    delay(3000);

    myservo.write(angle11); delay(3000);
   for(angle = 90; angle11 > 0; angle)
    myservo.write(angle);
    delay(3000);
    }

 else
 {
    Serial.println(" Access denied");
    delay(3000);

    }
  }
```

title: i need help my coding for my fyp

Answers: 1

body:
Right at the start of your loop you have this (and other similar constructs):

```c++
if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
}
```

That means that if no new card is present on reader 1 then the rest of the loop is ignored. Nothing else can happen.

You need to restructure your whole program so that it works in the complete opposite way - instead of saying "If there's no card do nothing" you should say "If there is a card then do something".


body:
```
int out = LED_BUILTIN;
int strt = 3;
int stp = 9;
void setup() {
  pinMode(out,OUTPUT);
  pinMode(strt,INPUT);
  pinMode(stp,INPUT);
}

void loop() {
  while(true) {
    if(digitalRead(strt) == LOW) {
      digitalWrite(out,HIGH);
      delay(1000);
    }
    if(digitalRead(stp) == HIGH) {
      digitalWrite(out, LOW);
      delay(1000);
    }
  }
}
```
I'm a beginner so I believe someone would help me out. Actually the mechanism I'm using for turning the state of Pin 3 & 9 is through 3 wires connected to the **Pins D3,D9 & 5V** in the nano board. Where 5 V is immersed in water and Pin 3 does not touch water Nano's *Built in LED* is turned on and if the water reaches Pin 9 (while the Pin 3 wire is still submerged under water) the LED goes Off.

In the above code, the Built in LED turns High just fine if Input Pin 3 Reads Low. Although as soon as Pin 3 goes High the LED turns Low and does not wait for Reading input pin 9 which is when the LED should actually turn Off.

In the first **IF** Clause (For Reading **Pin 3(strt) to LOW**) I want that part of the code to only set the OUTPUT pin ***LED_BUILTIN*** to be set to **HIGH** & not revert back to **LOW** if **pin 3** is turned to **HIGH**. But only if the INPUT **pin 9** in the second **IF** Clause reads **HIGH** then only should the OUTPUT Pin ***LED_BUILTIN*** be set to **LOW**.

Thank You for the helping hand.

This is the Link for the Code that I used(I Modified the code to have two input Wires) : https://www.instructables.com/Water-Level-Alarm-Using-Arduino/

title: Automatic water pump Trigger System - I need my code FIXED

Answers: 0


body:
iam recently making a projects that include arduino, mpu6050 and bmp280 and finally i have to log that data so, iam using a microSD card module

info of the the microSD card:

```
Initializing SD card...Wiring is correct and a card is present.

Card type: SDHC
Clusters: 1914880
Blocks x Cluster: 8
Total Blocks: 15319040

Volume type is: FAT32
Volume size (Kb): 7659520
Volume size (Mb): 7480
Volume size (Gb): 7.30

Files found on the card (name, date and size in bytes):
```

first i always try to test every modules one by one to find whether they are working good and i will do that with the help Arduibo IDE example codes and my every modules including microSD card module is working well and for microSD card first used cardinfo and it works perfectly and then i used datalogger code and i also logged the data perfectly and it is actually working very very well. Then i started to write my code first for mpu6050 and bmp280 and there is no mistakes in that code and i also so got good values and then i just included the datalogger code from example in my code and after that also there is no mistakes, actually everything is perfect and i just uploaded that code to my arduino nano and see the serial monitor and it shows :

```
⸮?>8>?⸮8⸮>>⸮>⸮⸮?8⸮?⸮??⸮?⸮⸮?⸮
```

and this is the only thing that serial monitor shows !!

iam also posting last lines of upload pane, the ones that say how much program and RAM memory iam using so it will help u :

Sketch uses 27078 bytes (88%) of program storage space. Maximum is 30720 bytes.
Global variables use 1924 bytes (93%) of dynamic memory, leaving 124 bytes for local variables. Maximum is 2048 bytes.
Low memory available, stability problems may occur.

and i also screenshot that so this will help u :

[![enter image description here][1]][1]

and the baud rate in serial monitor is equal to baud rate in Serial.begin() and i choosed the baud rate 9600

and if i delete the data logging code from my main code then it works perfectly but if i include the data logging code in my main code then only it is not working and it shows ⸮?>8>?⸮8⸮>>⸮>⸮⸮?8⸮?⸮??⸮?⸮⸮?⸮ in serial monitor

and main thing is, this problem comes after iam adding a countdown code(basically if a press a button then for loop starts) in my main code after that only the serial shows ⸮?>8>?⸮8⸮>>⸮>⸮⸮?8⸮?⸮??⸮?⸮⸮?⸮ but my countdown code doesn't have any mistakes in it and i also checked it with out adding in my main code and it works well but when i add that in my main code it shows like that and if i delete the data logging code from my main code then everything works well including countdown and if i delete countdown code from my main code then everything works well including data logging and if i add both(data logging and countdown) in my main code then only it serial monitor shows like ⸮?>8>?⸮8⸮>>⸮>⸮⸮?8⸮?⸮??⸮?⸮⸮?⸮ and then it is not working properly

and code :

```c++
void setup() {

  Serial.begin(9600);

  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(buzz, OUTPUT);
  pinMode(chipSelect, OUTPUT);
  pinMode(but, INPUT_PULLUP);

  s.attach(6);

  imuconfig();

  checking();

  countdown();

  delay(1000);

}

void loop() {

  oldtime = newtime;
  newtime = millis();
  elapsedTime = (newtime - oldtime) / 1000 ;

  imu();

  Serial.print(" X axis = ");
  Serial.print(totalX);
  Serial.print(" | ");
  Serial.print(" Y axis = ");
  Serial.print(totalY);
  Serial.print(" | ");

  Serial.print(F("Temperature = "));
  Serial.print(bmp.readTemperature());
  Serial.print(" *C");
  Serial.print(" | ");

  Serial.print(F("Pressure = "));
  Serial.print(bmp.readPressure());
  Serial.print(" Pa");
  Serial.print(" | ");

  Serial.print(F("Approx altitude = "));
  Serial.print(bmp.readAltitude(1011.7));// Adjusted to local forecast!
  Serial.print(" m");
  Serial.print(" | ");

  Serial.println("");

  data();
}

void countdown() {

  v = digitalRead(but);

  if (v == 0) {
    for (int b = 0; b < 6; b++) {
      int buz;
      buz = buz + 1000;
      tone(buzz, buz);
      delay(100);
      noTone(buzz);
      delay(100);
    }

    Serial.println("COUNTDOWN STARTS !!");
    Serial.println("DURATION IS 60s");

    for (int x = 0; x < 60; x++) {

      Serial.println(y);
      v = digitalRead(but);

      if (v == 0) {

        Serial.println("LAUNCH SCRUBBED !!");
        tone(buzz, 100);
        delay(1000);
        noTone(buzz);
        while (w) {

          v = digitalRead(but);
          if ( v == 0) {

            w = 0;

          }
        }
      }
      if (y <= 60 && y > 45) {
        digitalWrite(led2, HIGH);
        delay(500);
        digitalWrite(led2, LOW);
        delay(500);
      }
      else if (y <= 55 && y > 30) {
        digitalWrite(led1, HIGH);
        delay(500);
        digitalWrite(led1, LOW);
        delay(500);
      }
      else if (y <= 30 && y > 10) {
        digitalWrite(led1, HIGH);
        digitalWrite(led2, HIGH);
        delay(500);
        digitalWrite(led1, LOW);
        digitalWrite(led2, LOW);
        delay(500);
      }
      else if (y <= 10 && y > 1 ) {
        digitalWrite(buzz, HIGH);
        delay(500);
        digitalWrite(buzz, LOW);
        delay(500);
      }
      else if (y = 1) {
        tone(buzz, 600);
        delay(1000);
        noTone(buzz);
        delay(500);
      }
      y = y - 1;
    }
  }
}

void data() {

  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println(totalX);
    dataFile.close();
  }

  else {

    Serial.println("error opening datalog.txt");

  }
}
```

and this not my full code but this is where the problem is

and i really don't know why this is happening and if anyone know what is really going on pls pls pls pls say and pls help me to solve this problem, pls pls

[1]: https://i.stack.imgur.com/elfKX.png

title: Problem with data logging in arduino environment

Answers: 0


body:
Want to use Arduino Time library and occasionally sync it with an external RTC (Maxim DS3231 chip).   I am turning LEDs on and off based on time and using a shift register (Nexperia 74HC154PW) and encoder (ST Micro STP16CPS05TTR).

It has all been working fine, until I decided to use libraries as shown in:

[https://github.com/PaulStoffregen/DS1307RTC/commit/160fa0dbca29f6fb3c1465954f89ad7f1f0fbf67][1]

//using libraries shown in examples/SetTime

  [1]: https:////https://github.com/PaulStoffregen/DS1307RTC/commit/160fa0dbca29f6fb3c1465954f89ad7f1f0fbf67 //using libraries shown in examples/SetTime

What I cannot figure out is why using #include <DS1307RTC.h>  prevents the LEDs from lighting.

I have only included code below that lights the LED via a shift register to demonstrate that it runs without an error, but (have to take my word) does not light the LEDs.

**If I comment out #include <DS1307RTC.h>  the LEDs light.**

Note that in the code below time is not used for anything.

What is including  <DS1307RTC.h>  doing to break it?

Puzzled.

    #include <Wire.h>
    #include <Time.h>
    #include <TimeLib.h>
    #include <DS1307RTC.h>    //the problem:  Will not light LEDs if this is used

                              //RTC used is Maxim DS323`chip
                              //RTC connected to ATMEGA328 pin 27 PC4(ADC4/SDA) and pin 28 (PC5 (ADC5/SCL)
                              //RTC works great.

    //Ouputs from Atemga and Inputs into 74HC154 pins
    const int A0_Pin = 4; // Atmega328 pin  2 = Arduino pin 4
    const int A1_Pin = 5; // Atmega328 pin  9 = Arduino pin 5
    const int A2_Pin = 2; // Atmega328 pin 32 = Arduino pin 2
    const int A3_Pin = 3; // Atmega328 pin  1 = Arduino pin 3

    // Shift Register STP16CPS05 has 16 outputs.  Send two sets of 8 bits to turn on columns.  1 = on.
    const int latchPin = 9;   // Aruino Pin 9 = ATMEGA328 DIP Pin15 = TQFP Pin 13. Connected to LE-DM1 of STP16CPS05 pin 4  Latch Pin
    const int clockPin = 13;  // Arduino Pin 13 =  ATMEGA328 DIP Pin19 = TQFP 17. Connected to CLK of STP16CPS05 pin 3  Clock Pin
    const int dataPin = 17;   // Arduino Pin17 = ATMEGA328 DIP Pin 26 = TQFD 26. Connected to SDI of   STP16CPS05 pin 2  Data Pin (SDI)

    void setup() {

    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);
    pinMode(dataPin, OUTPUT);

    pinMode(A0_Pin, OUTPUT);
    pinMode(A1_Pin, OUTPUT);
    pinMode(A2_Pin, OUTPUT);
    pinMode(A3_Pin, OUTPUT);
     }

    void loop() {

      digitalWrite(latchPin, LOW);  //LOW through inverter = HIGH = OEDisabled for both Decoder and Shift Reg
                                   //LOW Shift Reg New Data to Buffer
      digitalWrite(A0_Pin, 0);
      digitalWrite(A1_Pin, 1);
      digitalWrite(A2_Pin, 1);
      digitalWrite(A3_Pin, 0);

      shiftOut(dataPin, clockPin, LSBFIRST, B11000000);
      shiftOut(dataPin, clockPin, LSBFIRST, B11111111);

      digitalWrite(latchPin, HIGH);  //HIGH through inverter = LOW = OE Enabled for both Decoder and Shift Reg
                                   //HIGH Shift Reg Move data to Output pins

    }

title: RTC and Time Library Problems

Answers: 0


body:
I was trying to develop a traffic light signal controller . when the button is pressed, the pedestrian green light will turn on faster than before . I used delay() in Interrupt function, But it is not working as expected . I am totally new in Arduino coding.
My whole code is below:

    int carred = 11;
    int caryellow = 10;
    int cargreen = 9;

    int padred = 13;
    int padgreen = 12;

    int padpushbutton = 3;
    int buspushbutton = 2;

    void setup(){
      pinMode(carred , OUTPUT);
      pinMode(cargreen , OUTPUT);
      pinMode(caryellow , OUTPUT);

      pinMode(padgreen , OUTPUT);
      pinMode(padred , OUTPUT);

      pinMode(padpushbutton, INPUT_PULLUP);
      pinMode(buspushbutton,INPUT);
      attachInterrupt(digitalPinToInterrupt(padpushbutton), padcontrol,CHANGE);
     attachInterrupt(digitalPinToInterrupt(buspushbutton), buscontrol,CHANGE);
    }
    void loop()
        {
         carchangeLights();
     }
    void carchangeLights(){

       //turn  carred,padgreen off padred high and cargreen on for 10 seconds
      digitalWrite(carred, LOW);
      digitalWrite(caryellow,LOW);
      digitalWrite(padred, HIGH);
      digitalWrite(cargreen, HIGH);
      delay(10000);

       //cargreen off,  turn on caryellow for 4 seconds

      digitalWrite(cargreen, LOW);
      digitalWrite(caryellow, HIGH);
      delay(4000);

       // turn caryellow and padred off,turn on padgreen, turn on carred for 7 seconds
      digitalWrite(caryellow, LOW);
      digitalWrite(padred,LOW);
      digitalWrite(padgreen,HIGH);
      digitalWrite(carred, HIGH);
      delay(7000);
      //turn padgreen off and padred high , caryellow high for 3 second
      digitalWrite(padgreen, LOW);
      digitalWrite(padred, HIGH);
      digitalWrite(caryellow, HIGH);
      delay(3000);

    }

    void padcontrol(){

      int red = digitalRead(carred);
      int yellow = digitalRead(caryellow);
      int green = digitalRead(cargreen);

      if (red == HIGH && yellow == LOW ) {
        digitalWrite(carred, HIGH);
        delay(2000);
        digitalWrite(padred, LOW);
        digitalWrite(padgreen, HIGH);
        delay(15000);
         }

      else if(yellow == HIGH && red == LOW){
         digitalWrite(caryellow, HIGH);
        delay(2000);
        digitalWrite(caryellow,LOW);
        digitalWrite(carred,HIGH);
        digitalWrite(padred,LOW);
        digitalWrite(padgreen,HIGH);
          delay(15000);
        }
      else if(yellow == HIGH && red == HIGH) {
       digitalWrite(caryellow, HIGH);
        delay(1000);
        digitalWrite(caryellow,LOW);
        digitalWrite(padred,LOW);
        digitalWrite(padgreen,HIGH);
          delay(15000);
        }
       else{
        digitalWrite(cargreen,LOW);
        digitalWrite(caryellow,HIGH);
        delay(3000);

        digitalWrite(caryellow,LOW);
        digitalWrite(carred,HIGH);
        digitalWrite(padred,LOW);
        digitalWrite(padgreen,HIGH);
        delay(15000);
       }

    }

    void buscontrol(){

      int red = digitalRead(carred);
      int yellow = digitalRead(caryellow);
      int green = digitalRead(cargreen);

      if (red == HIGH && yellow == LOW ) {
        digitalWrite(carred, HIGH);
        delay(3000);
        digitalWrite(carred,LOW);
        digitalWrite(padgreen, LOW);
        digitalWrite(padred, HIGH);
        digitalWrite(caryellow, HIGH);
        delay(2000);
        digitalWrite(caryellow,LOW);
        digitalWrite(cargreen, HIGH);
        delay(10000);

         }

      else if(yellow == HIGH && red == LOW) {
        digitalWrite(padgreen,LOW);
        digitalWrite(padred,HIGH);
       digitalWrite(caryellow, HIGH);
        delay(2000);
        digitalWrite(caryellow,LOW);
        digitalWrite(cargreen,HIGH);
          delay(10000);
        }
      else if(yellow == HIGH && red == HIGH) {
       digitalWrite(caryellow, HIGH);
        delay(1000);
        digitalWrite(carred,LOW);
        digitalWrite(caryellow,LOW);

        digitalWrite(padgreen,LOW);
           digitalWrite(padred,LOW);
         digitalWrite(cargreen, HIGH);
          delay(10000);
        }
       else{
        digitalWrite(padred,HIGH);
        digitalWrite(cargreen,LOW);
        delay(10000);

       }
    }

title: what to write instead of delay() in interrupt function?

Answers: 1

body:
> what to write instead of dely() in interrupt function?

Nothing. An interrupt service routine (ISR) should not do any things, that take long. That will block any other things from happening, for example Serial communication (which is done by interrupts in the background).

`delay()` does not work in an ISR, because it relies on the `millis()` counter to increment. But that is done in another ISR. While one ISR is running, no other can run at the same time. Thus `delay()` waits forever, that the `millis()` counter increments.

**What to do instead?**

Instead you should only use the ISR to set a simple flag variable, for example of type `boolean` (because it should be a single byte type). Then in your main code (meaning inside `loop()`) you check for this flag. When it is set by the ISR, you execute the corresponding code and reset the flag. Be sure to declare the flag variable as `volatile`, so that the compiler knows, that is can change at any time.

---

That said, you should really ditch all the `delay()` calls. Instead use a non-blocking coding style involving `millis()` like in the `BlinkWithoutDelay` example, that comes with the Arduino IDE. There are tons of tutorials and explanations about that on the web and this site. Just search for it. Using a non-blocking coding style is needed, if you want the code to be responsive while doing long timed things.

Also you should look into Finite State Machines (FSM). Thats a very powerful principle, that will come in useful. It fits exactly on a traffic light project. I have once wrote a longer explanation about FSMs in my answer to [this question][1], though you can also google something like "Arduino fsm". You basically divide the behavior of the project into individual states. The current state is hold by a variable. By changing that variable you transition between states. For example `padcontrol()` could change the state variable to the state for the pedestrian light. I strongly suggest, that you learn that principle to structure your code. I can attest, that it is really helpful.

  [1]: https://arduino.stackexchange.com/questions/63488/wanted-to-control-2-servos-with-serial-read/63491#63491


body:
I have a programmable power supply, which has serial communication port. If I send a string "VSET1:11.00" then power supply will be set to 11.00V.
But, I need to write a program which will increase the voltage of power supply by 0.10V
For ex from 0V to 11.00V in incrementing steps of 0.10V.
Also, power supply needs a fixed data frame format like Parity bit, Data bits, stop bit.
So, how to create a data frame structure and send from arduino.

Do I need to use Software Serial library?

PS. I'm new to arduino, so may sound foolish.

title: Send data to Programmable Power supply from Arduino by RS232

Answers: 1

body:
First you will need a TTL to RS-232 adaptor. These are most commonly known as the "MAX232" and is available as a little module.

This will convert the 0-5V TTL signal the Arudino produces into the ±10V signal that RS-232 uses. There's plenty of tutorials online about how to use them.

Then you need to generate the signal. Yes, for the Arduino UNO the SoftwareSerial library is what you want.  Again there's plenty of tutorials on using it.

To actually send the instructions it may be something like:

```c++
#include <SoftwareSerial.h>

SoftwareSerial PSU(10, 11); // RX, TX

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

void loop() {
    for (int i = 0; i < 11000; i += 100) { // I'm working in millivolts here.
        PSU.print("VSET1:");
        PSU.println(i / 1000.0, 2); // Convert millivolts into volts with 2 DP
        delay(10); // 10ms delay
    }
}
```

I haven't tested it, but that should give you 0-11v rising at 0.1v per 10ms.


body:
I am a complete novice at arduino. I just want to know if this is possible before I start investing in components. I need to start and stop a chain drive conveyor {can't slip} powered by a 12 volt motor in the exact same place each time I manually start the cycle. I want it to stop automatically. The controller would have to power a relay to power the motor due to high amp draw of motor. This is on a piece of equipment without access to any other power supply but a 12 volt battery. I am looking at an optical rotary encoder to count the revolutions of the shaft. I would count the revolutions the shaft makes between my start and stop point and I assume enter that in the program. Is this possible?
Thanks

title: How do I control a conveyor to start and stop in same location using optical rotary encoder

Answers: 1

body:
Although your solution would work, it seems open to problems such as missed clicks, starting at a different place etc.
A better, more robust and error free solution might be to use a hall sensor.
Essentially what a hall sensor does is close a switch when a megnetic force is applied. So all you have to do is add a magnet to your conveyor/chain. This way, you can easily control where you want it to stop just by moving the magnet, and it doesn't matter what the starting position is because it will always stop as soon as the megnet reaches the sensor.


body:
Here's what I think happens and how long it takes (FIXME means I don't know).  I'd like to end up with solid max times for everything if possible.

 - Power-on, input caps to the 328P begin charging and Vcc to the 328P rising
 - From the time it first comes to life, internal 328P hardware holds an
internal reset line low.
 - Vcc to 328P climbs past the power-on reset voltage threshold V_pot, which has
a maximum value of 1.6V (see the ATmega328P_datasheet_revision_DS40002061A.pdf
Table 29-11).  For a 9V battery with a typical internal resistance of 2 ohms,
the time constant with the ~100 uF of input capacitance on the Arduino
is RC = (2 * 0.0001) = 0.0002 s.  So this normally happens pretty fast,
but note that if additional loads are connected to the Arduino Vcc or Vin
things might take longer.
- A reset timer on 328P begins running.  When it expires the internal reset
line will be released.  How long this timer will run depends on fuse settings.
For the default Arduino fuse settings the timer will run for about 65 ms.
For a 3.3V Arduino variant the typical time will be slightly longer (~69 ms).
See ATmega328P_datasheet_revision_DS40002061A.pdf Table 29-11 Chapter 9
for details.

- The PD7 line of the ATMEGA16U2 chip on on the Arduino holds the external
reset line low past the point in time at which the internal reset is released,
which causes the EXTRF bit of the MCUSR register on 328P the 328P to end up
set (indicating an external reset).  FIXME: does it actually work like this
(hold it low longer)?  FIXME: How long exactly?

- The external reset is released by the ATMEGA16U2

- The bootloader on the 328P begins executing

- The bootloader examines the MCUSR and finds that EXTRF is set, but WDRF
of MCUSR is not set.  It therefore quickly flashes the on-board LED several
times and the attempts to download a new program over the serial line.
This process takes about 1.6 s total.

- The download attempt terminates with a watchdog timer timeout and consequent
watchdog timer reset.  The EXTRF bit of MCUSR remains set (it is sticky and
is only cleared by a power-on reset or explicit 0 write).  Time: pretty quick

- The bootloader starts executing (again).  Time: pretty quick

- The bootloader examines the MCUSR and finds that the EXTRF and WDRF bits
of the MCUSR are both set.  It interprets this to mean that the bootloader
just executed and terminated due to a watchdog timeout, i.e. it decides that
an upload attempt has already been made.  It therefore clears the WDRF flag
(since it thinks it probably set it itself) and jumps to the start of the
application flash instead of making an upload attempt.  Time: pretty quick

- All the setup code required to provide the C environment your main()
program requires runs.  This includes for example copying global variable
intial values from flash to RAM, etc.  Time: FIXME?

- main() begins executing.

title: what happens on Arduino power-on, and how long does it all take?

Answers: 1

body:
This is something that is far far easier to measure than to try and calculate.

Here's an Arduino Uno R2 with a simple sketch that just turns on D2.  Green is the power (7V to the barrel jack) and yellow is D2.

[![enter image description here][1]][1]

As you can see it takes 1.544 seconds (according to the resolution of my oscilloscope which, over those time scales, isn't that great) before D2 is driven high.

The sketch is simply:

```c++
void setup() {
  pinMode(2, OUTPUT);
  digitalWrite(2, HIGH);
}

void loop() {
}
```

  [1]: https://i.stack.imgur.com/tswKA.png


body:
I need to send how many milliseconds elapsed since the beginning of the time the arduino runs to java using Serial.write(). However, the largest integer that I can throw in there is 255, naturally since the largest 1 byte value we can send is 0xFF.

But if we have an integer like 6000 miliseconds that I want to send into java, how can I do this? I was initially thinking of just checking if the number is greater than 255 then bit shift it by 4 to the left then doing `number<<4 & 0xFF00` and also writing `(number<<4)>>8 &0xFF`

**But**
1) that doesn't work for numbers really large and
2) I believe when I stream these int values into Java they get read as characters...

how do I fix this?

**EDIT**
I've created a second version as the following

    void sendData(int a ){
      while(a>0){
        Serial.write(a&255);
        a = a>>8;
      }
    }
on the java side I have to somehow multiply the correct x for 16^(x) to the value that we receive since everything is received backwards I'm not sure if this is the best way to go since we don't necessarily know how many bytes that we'll receive

title: Streaming integer data from Arduino to Java, integer greater than 0xFF

Answers: 1

body:
I'm assuming you will be using the Arduino `millis()` function for keeping time. The output of the `millis()` function in the Arduino environment is a 32-bit unsigned integer*.

A 32-bit integer can be split into 4 x 8-bit bytes. To keep things simple you could program the Java receiving side to always expect 4 bytes (or whatever amount you need, see *). Assuming 32 bits is enough, you could use the following:

    void sendData (uint32_t uptime) {
        int i;
        for (i = 0; i < 4; i++) {
            Serial.write (uptime & 255);
            uptime = uptime >> 8;
        }
    }

On the Java side, you would receive the lowest order byte first, and you could reconstruct the 32-bit value by taking the first received 8-bit value, adding the second value shifted left by 8 bits (=multiplied by 256), adding the third value shifted left by 16 bits (=multiplied by 65536) and adding the fourth value shifted left by 24 bits (=multiplied by 16777216). Java is not my strong point so I will leave that to you.

BTW, is there a particular reason you have to use `Serial.write()`? It would be much easier to just write the value as a string with `Serial.println()`.

**After 2^32 milliseconds (a little under 50 days of uptime) the 32-bit counter that feeds the `millis()` function will wrap around to 0. You could keep the amount of times that the timer has overflowed in a separate (integer) variable and make that (i.e. bytes 5 and onward) part of your output.*


body: I am building a chair for a special 4 year-old with cerebral palsy, I thought it would be a good idea to add two distance sensors on each arm of the chair to measure the angle at which he presses buttons(a gaming chair).  Normally I would figure this out on my own but I don't have much time to finish so I thought i'd ask the experts.  What's the best way to use to ultrasonic sensors data to produce an angle?

title: How to get an angle from two ultrasonic sensors

Answers: 1

body:
Your question is unclear. You say you want "...to measure the angle at which he presses buttons". I don't know what that means.

If you're using ultrasonic sensors those measure distance. buttons tend to be fixed in place. Maybe you're  talking about having a joystick on the gaming chair? Two-axis joysticks should let you input an X and a y value.

If you're trying to calculate the angle between a pair of ultrasonic sensors and something that is in their "line of sight" (line of sound?) then you'd use trig.

You would have your sensors at a known distance from each other. You'd measure the distance to each sensor, form a triangle out of all 3 distances, and use the [law of cosines][1] to calculate the angles.

The formulas from that page are:

cos(C) =  a² + b² − c²/2ab

cos(A) =  b² + c² − a²/2bc

cos(B) =  c² + a² − b²/2ca

(Where upper case letters denote the angles of the triangle at a vertex, and lower-case letters denote the legs of the triangle. See the illustration on that page.)

     SensorA
        \
         \      SensorB
          \       /
           \     /
            \   /
             \ /
              V
            object

(one leg would be the SensorA-to-SensorB distance. Another leg would be the SensorA-to-object distance, and the 3rd leg would be the SensorB-to-object distance.)

However, all of that will only work if the object you are detecting is in the range of angles in which your sensors are able to detect objects, and in the range of distances they provide accurate readings.

## Edit:

When I copied the formulas from the source site, the superscripts were lost. I've edited them back so the formulas are more readable.

  [1]: https://www.mathsisfun.com/algebra/trig-solving-sss-triangles.html


body:
I've been programming an ATMega1284 using the Arduino IDE with the MightyCore package.
I'm now trying to migrate to Atmel Studio.
Atmel Studio (7.0) will now compile the sketch and all required libraries (that took some time) and upload the output via USBAsp to the ATMega (Essentially just calling avrdude). However...

The uploaded sketch is running differently. It seems slower. For example, the Tone() function seems to output a lower pitch. My best guess is that Atmel Studio has the xtal/clock setting wrong, but I can't find where to inspect/change it?

I'm using a 12mhz external xtal, and can only communicate with the chip via UART. If I upload the sketch from Arduino IDE then it reverts back to normal.

title: Clock Problem when Migrating from Arduino IDE Mighty Core to Atmel Studio

Answers: 0