text:
Arduino SerialUSB.print/println is being interrupted by other prints
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();
}

Could you show the code you use (edited into question?)

And if you don't flush() does that improve things?

I see the same symptoms when I remove SerialUSB.flush()


text:
ESP32 and wifi router
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?

where does the statistics info come from? ... how are you performing the DHCP list and the ARP? ... please update your question to make it clear what you did ... as it stands, it appears that the question is not related to the Arduino

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

how did you do the binding?

source: Stack Exchange

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

sort: votes


text:
Arduino led not blinking
#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

how did produce a wrong version of the most basic Arduino example? https://www.arduino.cc/en/Tutorial/BuiltInExamples/Blink

Your first step when facing such a problem is to read the documentation. You have 3 functions in your code, which as read in a short time, less than 5 minutes. You would have found the delay() expects the interval in milliseconds. Please do so the enxt time.

#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 .

thanks it is working now

what is next? The "Bare Minimum" example without loop()?

True but just go a little easy in the newbie

@Juraj: The Bare Minimum Blink (https://www.arduino.cc/en/Guide/ArduinoUno#open-your-first-sketch ) works without the line #include <Arduino.h>

I use platform io for programing so in that it is important to include arduino.h maybe the person who asked is also using platform io or something similar

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

 digitalWrite(13, HIGH);

 delay(2000);

 digitalWrite(13, LOW);

 delay(1000);

}

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


text:
No SPIFFS only OTA in NodeMCU ESP8266
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?

Is there a configuration that I missed?

https://www.instructables.com/Using-ESP8266-SPIFFS/?amp_page=true not sure but check this . It may not help

maximum application size is less then 1 MB. so there is no other use for the rest of the flash then FS. for board you selected there is no predefined partitioning without OTA. what is your question?

In this link https://cdn.instructables.com/ORIG/FST/OP12/IZT6TEBJ/FSTOP12IZT6TEBJ.png?auto=webp&frame=1&width=1024&fit=bounds&md=f16daccb8697a6bd8728838feb18d9de it is showing SPIFFS but in my Arduino IDE it is showing OTA?  Why is this so? That is my question

Yes please refer to my answer and that is because he is using an older version of the package and arduino

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

Ohh Okay so that is how it is.. Thank you then!

and why is there in Tools menu FS and not SPIFFS as n the mentioned instructable?

Sorry don't understand what you are asking

the question was that the menu doesn't  show SPIFFS but FS and OTA. a good answer should contain why it is so.


text:
How can I use Arduino Analog Uno pins as Digital pins?
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.

with digitalWrite and digitalRead. what is your question? https://www.arduino.cc/reference/en/language/functions/digital-io/digitalwrite/#_notes_and_warnings

For Arduino Uno

yes for Uno. you tagged the question with [arduino-uno]

Can you provide me any code sample as an instance

Any of the analog pins (with exception of A6 and A7) can also be used as digital pins, just like any other pin of the Arduino. Just use pinMode(), digitalWrite() and digitalRead() on them, as you like.

Thank you Juraj and chrisl


text:
Wide range of protocols one chip?
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.

search for SDR software-defined radio

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.


text:
Power supply for DIY Arduino CNC Router
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.

atx power supply may be useless ... it could shut down in response to a motor current spike

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.

The answer is great but do you know the minimum power requirement in amps?


text:
Help a noob, no idea on Programming, only started 2 days ago Help please
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..
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

Format your code properly by selecting all the code and press the {} icon on the editor menu. 2) What is exactly your question?

What error are you getting what is the exact thing you need can you explain your project idea also

I formatted your code (select it, Ctrl+K) and would have amended your subject line to be more meaningful but I have no idea what the problem is. What do you want it to do? What does it do?

Use uint8_t instead of int for the variables that will never have a value higher than 255. You'll save memory space by using the smallest variable type possible.

You didn't ask a question. What are you trying to do, and how is your project failing to accomplish that goal?

I presume you got some errors, like this:
/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.

#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.

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.


text:
Need some Hardware advice with arduino
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 -

3 Geared motors,
1 BLDC 1000 kva
2 cameras ( one is also ok)
TinyML for object detection
Mic to receive audio commands
Speaker to talk back.
Wifi shield to send/receive information to internet or a laptop.
3 small servo motors.
2 Proximity sensor.
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.

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.

Yeah, unless he either optimizes all of it to a tee I doubt that any arduino could do it. Unless he does all the heavy lifting off of an actual computer somewhere else (aka just use the arduino to gather the data and send signals back to the hardware

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.

A Pi should be able to do rudimentary ML. It might not have a multi-core GPU, but it does have good native floating point performance.

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

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

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

Hope this helps.

The esp32 won't work except ypu extend it with a reasonable amount of external hardware. Take the esp-cam for example: you can take and process images (thanks to the external ram), but it doesn't have free pins left to do anything else.


text:
Deriving the exact relationship between PWM and steering
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 :

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.

PWM is used to control the speed of the motors.

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

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 and the consensus seems to be that some sort of feedback mechanism is required for an exact calibration.
I have two questions :

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

Regarding #1, the turn angle won't be just a factor of the inner wheel RPM. Nor will it be a simple ratio of the 2 wheels RPM. The wheel speed (RPM * wheel circumference) is a better measure. The side-to-side distance between the wheels is also important. You want the ratio of inner to outer wheel speeds to match the ratio of desired inner to outer wheel turn circumference. That would give you a smooth turning circle with no wheel slippage. If the ratio of wheel speeds does not match a ratio inner-to-outer wheel turn circumferences, one or both sets of wheels will slip.

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.


text:
What do i do to get my bluetooth module to light up?
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

How is everything connected? Please show a wiring diagram

are you asking if your battery is dead?


text:
Converting my delays to millis for smoother operation
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

  }
  }

What exactly is your problem in doing that? Have you understood how the millis() function is used? Do you know, what an FSM (Finite State Machine) is? If not, you should really search for it, since that concept will be incredible helpful in implementing, what you want.

The codes only move after the delay is up, i would like the codes to run simultaneously.

Yes, thats a very general description, of what you want. But it doesn't explain, what exactly the problem is. What have you tried so far? Is there something, that you don't understand in the concept of non-blocking code like in the BlinkWithoutDelay example (thats the example explaining millis())? There is already tons of tutorials on the web about this and we need to know, how we can help you better than these.

You have posted a goal, not a question.This site is not a free coding service. You should do a Google search on "Arduino blink without delay", read one of the various tutorials that search finds, and then attempt to refactor your code yourself.

ok thanks for the info

your code is cluttered with useless comments ... for example //led flash at 1 Hz comments a section of code that does not operate at 1 Hz ... same thing with a lot of the other comments

you need to think clearly about how your code flows ... as it stands now, it is filled with silly comands (my apologies for the choice of words, but i cannot think of any other word) ... example in pseudo code: relay ON, wait 6 seconds, buzzer ON, wait 3 seconds, led ON, wait 3 seconds,  led OFF, wait 3 seconds, etc. etc.  ..... simpler code would be relay ON, buzzer ON, led ON, wait 3 seconds,  led OFF, wait 3 seconds, etc. etc

@DuncanC his goal is to get rid of delays and make the code run smoothly, I thought he explained that.

Your delays are making the program jerky, so you have to get rid of them. :)
I have a lengthy discussion about this 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 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.

A while back I wrote an answer to another question about non-blocking programming, 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 previousMillises 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 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.


text:
How can I power off a servo the best way? Problems with MG90S servo
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!

run your code, then turn off the servo power manually at the appropriate time ... doing that shows you the servo behavior if the power was turned off electronically  ... does the servo behave as desired when you do that?

You need a PNP or P-channel FET to switch the + (red) connection. An NPN or N-channel FET won't work right.


text:
servo acting weirdly
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
Manufacturer page : here

there is no reason to use the map function or the analogRead function ... use minimal code when debugging

What @jsotola said, and: you are updating the servo signal at a higher rate than its normal PWM frequency of 50Hz; anything could happen. Try a longer delay.

Ok, thanks for corrections .. I've tried simpler code and longer delays (20,50,2000) but it didn't help - same result.

Hm. Weird. Also weird: the Towerpro MG966R product video at the bottom of this page: http://www.towerpro.com.tw/product/mg995-robot-servo-360-180-rotation/ shows about the same behaviour you describe, but I can't imagine these servos in the video are "working as intended" if they are supposed to be continuous rotation servos.

I've contacted manufacturer and linked this question

looks like a soft start function of some kind

@Jirka-Justra: Any answers yet from the manufacturer?

Guy e-mailed me 'I will get back to you' .. so I am currently on hold.

update : I've send kind reminder; response was that they arrange replacement for me .. hmm - interesting, but ok with me so far

update : I've got new set .. it rotate both side and continuously, but speed is constant :/ ... will communicate with them more - build quality is great as usual


text:
Using an Arduino to rotate a DC motor once a minute (edited)
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.

What exactly do you have problems with? Timed things are mostly done via delay() or (better) via millis() (like in the BlinkWithoutDelay example). Have you tried these?

I having trouble balancing the speed and delay of the motor so that it turns one full rotation every 60s.

You can't rotate a dc motor with just an arduino output, as you can't control the acceleration. You need a stepper motor to have a clean 360° rotation. Or an encoder or this sensor: AS5048A to detect the exact position of your motor.

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 : 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;
    }
}

Sorry my bad, I was not clear in the question. I don’t want it to start turning every 60s, I want it to complete one full rotation every 60s.

oh wait, you mean you want it to rotate one turn over 60 sec? 1 turn per 60 sec?

In that case, you will have trouble with dc motor, since you can't precisely make them turn over a precise angle without feedback from an encoder. Id suggest getting something like a servo or a stepper motor depending on your needs


text:
Infrared Low Frequency Transmission
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() {

}

what is your question?

what is running at the frequency of 500 Hz, and how did you determine it?

You have nothing to reset ir_seq_index, so once you got through the array, it will still increment. Then you will get garbage, since you are reading from outside the array.

If you want the timer to run slower, you could change its settings, for example raising the prescaler

Where did you get this code from? Also the array for the IR code looks very odd. There shouldn't be any zeros in it. Also, most IR codes start with a long pulse, while yours kind of ends with two.

@jsotola I can't go down to 500hz, how would I go about solving that? And I determined it because I checked the frequency :O

@chrisl it's example code to get the concept, not the actual project. Also what do you mean by prescaler?

@Gerben some parts of ir codes arent actually required, some ir spammers actually cut out like half the code and works fine. Also the code is the real ir code. The actual microseconds sent. It's just prontohex converted into uint16 (uint16 seems to only be the working one). It's so I don't have to waste time, and space decoding pronto hex back into uint. When I can just use less memory etc and send the real code.

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, 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.

I can't yet test it (Arduino broke) but from the looks of it this looks to be correct. Thanks alot <3. I'll post code when I can get my arduino to work again :)


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

search VL6180X Time of Flight Distance Ranging Sensor

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

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


text:
TFT menu system sometimes doesn't refresh the screen properly
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:

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

I also made a video to make my problem more clear:
Video with rendering problem.
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. 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!

the video shows serious signal bounce ... rotary_enc_int should be called on signal transition, not on signal level .... increase the time difference in the ISR to 50 ms from 5 ms ... i think that you accidentally forgot the zero

Hi @jsotola, thank you for looking into my code and giving feedback. When I started the project I tested every component seperatly. I also thought I should use FALLING or RISING instead of a signal level. But for some reason - I didn't and stil do not understand - it didn't work but it worked when using the LOW state as I had seen in a tutorial.
I tried your feedback and this is what I got (it didn't transition properly jumped back and forth)
video: https://drive.google.com/file/d/1ELb0AcuUl-Lxjt6BBYF45CzOaRhEknRN/view?usp=sharing
(both rising and falling worked like this).

menus.h, line 122, lastInterruptTime = interruptTime; .... this needs to be inside the if block     ..................... the if may work better as if (interruptTime - lastInterruptTime > 50)

Thank you @jsotola, you are right about the position of lin 122. Thank you for your help, I positioned it inside the if block. As from what I experience I do not have any debouncing issues but I changed the debounce time to 50 an it still worked as before but when rotating fast it didn't see as many rotations as before. So I did reset it to 5.

As for my problem: I didn't find the bug in my program but I tried another approach: instead of redrawing the screen for every change of my index (which requires some time to do) I threw away the color indication of my index and just prepended the selected index with '>'. I do not refresh the whole screen when the index changes but I draw a cube over the old '>' and draw the new one. This also elminated the refreshflickering involved with redrawing the screen.

there are menu libraries available for the arduino


text:
Arduino 2 times slower? Broken?
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 :/

Do you have the right board selected in the menu? Is serial still working at the correct baud rate?

My programmer is set to "AVRISP mkil", board is set to "Arduino uno". And I have used 19200 in Serial.begin before and its possible that I tried to flash it as a esp8266 but yeah.. That's about it :/

If you Serial.print() something, is that received correctly in your Serial Monitor with the same baudrate used in the sketch?

@chrisl I can't tell the speed but if I set the serial monitor to 9600 and Serial.begin(9600) I can see it fine it seems.


text:
Arduino Nano 33 IoT LSM6DS3: get gyro angle in degrees
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?

a gyro detects the rate of angular change, not an absolute angle ... an accelerometer can measure an angle with respect to gravity

I tried looking for both but there is no code that does it. Could you help me find it?

All I can find is changing numbers but no angles.

You wil have to calculate the angles. Some trigonometry is required, and for the gyroscopes, also some integration. You can read about it here, 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 on Github.

This is the best solution. This filter is a lot faster than the MadgwickAHRS! Amazing!

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;
  }
}


text:
Can I power the arduino UNO through the 5V pin while I use USB cable to collect data?
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!

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


text:
i need help my coding for my fyp
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);

    }
  }

I don't quite understand your problem. Please explain more and with good english. If you are not good enough in english, you can ask someone, who can write english better.

change your logic a bit  ... use flags ... pseudo code if card_1_is_present and card_1_is_read, then raise flag_1   .... do not exit, do not stop, do not do anything more than setting the value of flag_1 .... next do the same thing for card_2 flag_2 ......... next, check flag_1 and flag_2 ... proceed with program if both are raised

Right at the start of your loop you have this (and other similar constructs):
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".


text:
Automatic water pump Trigger System - I need my code FIXED
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/

as soon as Pin 3 goes High the LED turns Low  - that makes no sense. The only way the LED can go LOW is if pin 9 reads high.

That is right . That's what was supposed to happen. But as I said earlier when the wire connected to Pin 3 touches the water (ie Pin 3 Goes High) LED goes LOW. But I want nothing to happen if Pin 3 goes High. Only if Pin 3 goes Low should the LED turn on. I hope I'm clear. Please help me!

the while(true){ is redundant .... loop() already does that

change your code so that the led is controled by pin 3 only ... verify that the harware responds as expected by repeatedy dipping pin 3 wire in water (shorten the delay for this)


text:
Problem with data logging in arduino environment
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 :

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

Sounds like a lack of RAM and you're getting buffer overflow / corruption. Optimize your code to reduce RAM usage (wrap string literals in F() for a start) to see if that helps.

yes i also tried that but it didn't work

I agree with Majenko.  Your compile report shows 88%/93% Flash/RAM usage - WAY TOO HIGH

thanks for saying


text:
RTC and Time Library Problems
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
//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

}

Comments are not for extended discussion; this conversation has been moved to chat.


text:
what to write instead of delay() in interrupt function?
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);

   }
}

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, 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.

Just to add to chrisi's excellent answer, I wouldn't use interrupts at all for this project.  Imagine an impatient pedestrian repeatedly pushing the 'walk' button.  Every time this happens, the ISR fires and takes over control of the MCU, no matter what is happening at the time.  So, while the MCU is trying to respond to the pedestrian's first push, it gets interrupted and starts trying to respond AGAIN, and AGAIN, and AGAIN...  If your program isn't structured to handle randomly occurring interrupts, it can make the program behave in unpredictable (read "hard to debug") ways.

You should just use polling to check the state of the buttons.  That way the MCU is in total control, and can ignore the button states while it's busy

Thank you so much . Now I just found a way to go ahead

@SaikotDas While it is important to learn the above about interrupts, user3765883 is right in that simple button checking can be easily done without interrupts in the main code when you use a non-blocking coding style. The loop() can then easily run fast enough to catch all button presses in a timely manner. Also debouncing can be easier that way. Maybe have a look at the Bounce2 library on github


text:
Send data to Programmable Power supply from Arduino by RS232
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.

That sounds like the same PSU that I have. Mine's badged as TENMA though I have seen what looks like the same one badged by other people...

One thing I really find annoying with this PSU is that as soon as you send anything over the serial port it completely locks out the front panel for a while.

Yes that's right. It is TENMA power supply.

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

Thanks Sir, I will try the same.


text:
How do I control a conveyor to start and stop in same location using optical rotary encoder
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

definitely possible .... it would be more reliable to sense the conveyer belt itself, in case there is slippage between the drive and the belt

That sounds fine. Just note that when powering up the system, you don't know the position of the conveyor. If you need that, you'd have to add something to manually "home" the conveyor, or add another sensor to find the "home" position of the belt. Ffor example adding a magnet to the belt, or a piece of reflective tape, and using a hall-effect sensor/photo-reflective sensor to find the "home" position. After that you only need to count rotations of the rotary encoder.

Would a hall sensor work in a dirty or wet environment?

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.


text:
what happens on Arduino power-on, and how long does it all take?
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.

Why not measure this yourself, for your specific setup?

I've made a shield that can turn a controlled arduino on only once in a while (so can operate years on battery).  It also supports wake due to a user signal line activity (it exposes it's own Vcc from low-Iq regulator for this circuitry), and it propagates this signal to controlled arduino once it's safely turned on.  I'm interested in the worst-case time from when one of these signals fires to when arduino is on and running user code that can see the propagated signal, including in cases when user cuts RESET EN on controlled Arduino and reprograms fuses for fast rising power.

Are there any reasons you have to use an Arduino for this?

The 16u2 doesn't hold the "reset" pin low. While the chips is still in pre-startup, all the output pins are High-Z. when running it set the "reset" pin to HIGH (pull-up), and then to OUTPUT. So the pin is never OUTPUT LOW. It's High-Z, then pull-up HIGH, then HIGH. Also the "reset" pin is not directly connected to the reset of the 328p, but via a 100nF capacitor.

If the line from the 16u2 isn't doing it how is the MCUSR EXTIF getting set on power on?  The bootloader always runs and attempts a download, so it's getting set somehow.  But I thought that a normal power-on of a 328P caused PORF to be set but not EXTIF.  I looked around for the actual code that's on the 16u2 but didn't find it.

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.

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:
void setup() {
  pinMode(2, OUTPUT);
  digitalWrite(2, HIGH);
}

void loop() {
}

This is consistent with what I've measured with timer1 on my controller (~1.520 actually without Arduino environment setup whatever that consists of).  So this is a right number for stock arduino with stock optiboot (as of this writing anyway).  It would still be nice to know some of the particular numbers though for cases when the obvious arduino hacks are done.  I guess C (and Arduino wiring) environment setup is the big remaining unknown.