text:
(YX5300 MP3 player) Why is this code not working?
I am trying to implement code for the YX5300 MP3 player into my Arduino Uno project. I have broken down the original code example to all I need - basically just one trigger to cycle play one folder. This does work in that it starts playing when I push the button connected to pin 7 (it also displays the send command on the serial monitor):
#include <SoftwareSerial.h>

#define ARDUINO_RX 5  //should connect to TX of the Serial MP3 Player module
#define ARDUINO_TX 6  //connect to RX of the module

SoftwareSerial mp3(ARDUINO_RX, ARDUINO_TX);

static int8_t Send_buf[8] = {0}; // Buffer for Send commands.  // BETTER LOCALLY

String sbyte2hex(uint8_t b);

const byte playPin = 7;
byte playButton = 0;

/************ Command byte *************************/

#define CMD_SLEEP_MODE    0X0A
#define CMD_WAKE_UP       0X0B
#define CMD_SEL_DEV       0X09
#define CMD_PLAY          0X0D
#define CMD_STOP_PLAY     0X16  // Stop playing continuously.
#define CMD_FOLDER_CYCLE  0X17
#define CMD_SET_DAC       0X1A
#define DAC_ON            0X00
#define DAC_OFF           0X01
#define DEV_TF            0X02

/*********************************************************************/

void setup()
{
  Serial.begin(9600);
  mp3.begin(9600);
  delay(500);

  sendCommand(CMD_SEL_DEV, 0, DEV_TF);
  delay(500);

  pinMode(playPin, INPUT);
}

void loop()
{

  playButton = digitalRead(playPin);
  if (playButton == HIGH) {
    sendCommand(CMD_FOLDER_CYCLE, 1, 0);
  }
}

/********************************************************************************/
/*Function: Send command to the MP3                                             */
/*Parameter: byte command                                                       */
/*Parameter: byte dat1 parameter for the command                                */
/*Parameter: byte dat2 parameter for the command                                */

void sendCommand(byte command){
  sendCommand(command, 0, 0);
}

void sendCommand(byte command, byte dat1, byte dat2){
  delay(20);
  Send_buf[0] = 0x7E;    //
  Send_buf[1] = 0xFF;    //
  Send_buf[2] = 0x06;    // Len
  Send_buf[3] = command; //
  Send_buf[4] = 0x01;    // 0x00 NO, 0x01 feedback
  Send_buf[5] = dat1;    // datah
  Send_buf[6] = dat2;    // datal
  Send_buf[7] = 0xEF;    //
  Serial.print("Sending: ");
  for (uint8_t i = 0; i < 8; i++)
  {
    mp3.write(Send_buf[i]) ;
    Serial.print(sbyte2hex(Send_buf[i]));
  }
  Serial.println();
}

/********************************************************************************/
/*Function: sbyte2hex. Returns a byte data in HEX format.                       */
/*Parameter:- uint8_t b. Byte to convert to HEX.                                */
/*Return: String                                                                */

String sbyte2hex(uint8_t b)
{
  String shex;

  shex = "0X";

  if (b < 16) shex += "0";
  shex += String(b, HEX);
  shex += " ";
  return shex;
}

/********************************************************************************/
/*Function: shex2int. Returns a int from an HEX string.                         */
/*Parameter: s. char *s to convert to HEX.                                      */
/*Parameter: n. char *s' length.                                                */
/*Return: int                                                                   */

int shex2int(char *s, int n){
  int r = 0;
  for (int i=0; i<n; i++){
     if(s[i]>='0' && s[i]<='9'){
      r *= 16;
      r +=s[i]-'0';
     }else if(s[i]>='A' && s[i]<='F'){
      r *= 16;
      r += (s[i] - 'A') + 10;
     }
  }
  return r;
}

This, however, does not work. The wiring is exactly the same. It does display the play command being sent to the YX5300. But the module does not start playing. As far as I am aware, I am using the exact same code for the player. I do not understand why the player won't start playing even though it receives the appropriate command:
/************ init mp3-player ***************/
#include <SoftwareSerial.h>

#define ARDUINO_RX 5  //should connect to TX of the Serial MP3 Player module
#define ARDUINO_TX 6  //connect to RX of the module

SoftwareSerial mp3(ARDUINO_RX, ARDUINO_TX);
static int8_t Send_buf[8] = {0}; // Buffer for Send commands.  // BETTER LOCALLY
String sbyte2hex(uint8_t b);

#define CMD_SLEEP_MODE    0X0A
#define CMD_WAKE_UP       0X0B
#define CMD_SEL_DEV       0X09
#define CMD_PLAY          0X0D
#define CMD_STOP_PLAY     0X16  // Stop playing continuously.
#define CMD_FOLDER_CYCLE  0X17
#define CMD_SET_DAC       0X1A
#define DAC_ON            0X00
#define DAC_OFF           0X01
#define DEV_TF            0X02

/**************** init the real time clock ***************/
#include <Rtc_Pcf8563.h>
Rtc_Pcf8563 rtc;

/**************** setup pins & buttons ***************/
const byte led = 9; // Pin LED is connected to
const byte sixAmPin = 4; // Pin for set-alarm-to-6am-button
const byte sevenAmPin = 5; // Pin for set-alarm-to-7am-button
const byte eightAmPin = 6; // Pin for set-alarm-to-8am-button
const byte stopPin = 7; // Pin for stop button
const byte timeResetPin; // Pin for reset-clock-to-9am-button (useful e.g. after battery failure)
const byte playPin = 8; // Pin for play-music-button

byte sixAmButton = 0; // State of 6am-set-button
byte sevenAmButton = 0; // State of 7am-set-button
byte eightAmButton = 0; // State of 8am-set-button
byte stopButton = 0; // State of stopButton
byte timeResetButton = 0; // State of time-set-button
byte playButton = 0; // State of play-music-button

byte brightness = 0; // LED brightness
bool wakeupMode = false;
unsigned long prevStepTime = millis();
unsigned long time;

/*************** Changeable variables here **************/
byte setHour = 19;
byte setMin = 29;
byte fadeDuration = 1; // Duration of fade in minutes (default: 30)
byte afterBurn = 1; // Keep light on after alarm for this many minutes (default: 30)
/********************************************************/

unsigned long keepLight = afterBurn * 60000UL; // Calculate time to keep LED on after fade (in ms)
int fadeStepLength = fadeDuration * 6000 / 255; // Calculate step duration for increasing LED brightness (in ms) (default: fadeDuration * 60000 / 255)

void wakeup();
void readButtons();

/********** debug class ************/
unsigned long int prevDebugTime = 0;
void debug() {
  unsigned long debugTime = millis();
  if ( debugTime > prevDebugTime + 500 ) {
    Serial.print("Brightness = ");
    Serial.println(brightness);
    Serial.print("Time = ");
    Serial.println(time);
    Serial.print("stopButton = ");
    Serial.println(stopButton);
    Serial.print("playButton = ");
    Serial.println(playButton);
    Serial.print("Time = ");
    Serial.println(rtc.formatTime());
    Serial.println();
    prevDebugTime = millis();
  }
}
/************************************/

void setup() {
  Serial.begin(9600);
  mp3.begin(9600);
  delay(500);

  sendCommand(CMD_SEL_DEV, 0, DEV_TF);
  delay(500);

  // declare LED pin to be an output:
  pinMode(led, OUTPUT);

  // declare button pins as inputs:
  pinMode(stopPin, INPUT);
  pinMode(sixAmPin, INPUT);
  pinMode(sevenAmPin, INPUT);
  pinMode(eightAmPin, INPUT);
  pinMode(timeResetPin, INPUT);
  pinMode(playPin, INPUT);
}

void loop() {

  // If it is wake-up time and wakeupMode is on, trigger alarm and reset trigger; else turn on wakeupMode
  if ( rtc.getHour() == setHour && rtc.getMinute() == setMin ) {
    if (wakeupMode) {
      wakeup();
      wakeupMode = false;
    }
    else {
      wakeupMode = true;
    }
  }

  // Check for button input
  readButtons();

  // update LED in case stopButton was pressed
  analogWrite(led, brightness);

  // Todo: Setup power saving methods

  debug();
}

void wakeup() {
  // If wake-up-mode is true and brightness < 255, add +1 to brightness every 7 seconds (256 steps)
  while (wakeupMode == true) {
    //update clock
    time = millis();

    // If current time is wakeup-time, increase LED brightness slowly over the course of 30 minutes
    if (brightness < 255 ) {
      // Delay brightening in steps. Do only if interval has passed.
      if (time > prevStepTime + fadeStepLength) {
        brightness ++;
        prevStepTime = millis(); // Resets counter to restart interval
      }
    }
    // Turn off light and exit wakupMode x minutes after max brightness
    else if (brightness == 255 && time > prevStepTime + keepLight) {
      brightness = 0;
      wakeupMode = false; // Exit wakeupMode loop
    }

    // Check for input from buttons
    // readButtons(); //uncomment after testing

    //debug();

    // Set LED brightness accordingly
    analogWrite(led, brightness);
  }
}

void readButtons() {
  // Always run this:
  // Check if alarm gets set to 6, 7 or 8am
  sixAmButton = digitalRead(sixAmPin);
  if (sixAmButton == HIGH) {
    setHour = 6;
  }
  sevenAmButton = digitalRead(sevenAmPin);
  if (sevenAmButton == HIGH) {
    setHour = 7;
  }
  eightAmButton = digitalRead(eightAmPin);
  if (eightAmButton == HIGH) {
    setHour = 8;
  }

  // If stopButton is pressed, turn off LED and reset alarm
  stopButton = digitalRead(stopPin);
  if (stopButton == HIGH) {
    wakeupMode = true; //change to false after testing (default: false)
    // brightness = 0; // uncomment after testing
    wakeup(); // for testing purposes
    //sendCommand(CMD_STOP_PLAY); // uncomment after testing
  }

  // Todo: If timeResetButton is pressed, reset clock to 9am
  if (timeResetButton == HIGH) {
    rtc.setTime(9, 0, 0);
  }

  // Todo: If Play music button is pressed, start playing music
  playButton = digitalRead(playPin);
  if (playButton == HIGH) {
    sendCommand(CMD_FOLDER_CYCLE, 1, 0);
  }

}

/********************************************************************************/
/*Function: Send command to the MP3                                             */
/*Parameter: byte command                                                       */
/*Parameter: byte dat1 parameter for the command                                */
/*Parameter: byte dat2 parameter for the command                                */

void sendCommand(byte command){
  sendCommand(command, 0, 0);
}

void sendCommand(byte command, byte dat1, byte dat2){
  delay(20);
  Send_buf[0] = 0x7E;    //
  Send_buf[1] = 0xFF;    //
  Send_buf[2] = 0x06;    // Len
  Send_buf[3] = command; //
  Send_buf[4] = 0x01;    // 0x00 NO, 0x01 feedback
  Send_buf[5] = dat1;    // datah
  Send_buf[6] = dat2;    // datal
  Send_buf[7] = 0xEF;    //
  Serial.print("Sending: ");
  for (uint8_t i = 0; i < 8; i++)
  {
    mp3.write(Send_buf[i]) ;
    Serial.print(sbyte2hex(Send_buf[i]));
  }
  Serial.println();
}

/********************************************************************************/
/*Function: sbyte2hex. Returns a byte data in HEX format.                       */
/*Parameter:- uint8_t b. Byte to convert to HEX.                                */
/*Return: String                                                                */

String sbyte2hex(uint8_t b)
{
  String shex;

  shex = "0X";

  if (b < 16) shex += "0";
  shex += String(b, HEX);
  shex += " ";
  return shex;
}

/********************************************************************************/
/*Function: shex2int. Returns a int from an HEX string.                         */
/*Parameter: s. char *s to convert to HEX.                                      */
/*Parameter: n. char *s' length.                                                */
/*Return: int                                                                   */

int shex2int(char *s, int n){
  int r = 0;
  for (int i=0; i<n; i++){
     if(s[i]>='0' && s[i]<='9'){
      r *= 16;
      r +=s[i]-'0';
     }else if(s[i]>='A' && s[i]<='F'){
      r *= 16;
      r += (s[i] - 'A') + 10;
     }
  }
  return r;
}

Just for some background: This is my code for a light alarm which, instead of playing a sound, will turn on an LED gradually, simulating a sunrise. I features multiple buttons to set the alarm time, stop the alarm (and, later, the music) and to start playing music.
Any hints on overall code architecture are also welcome (this is my first Arduino project, I hadn't written a single line of code for ten years prior to this). But my main concern is finding out where the bug is. My second concern is how to learn how to find out where the bug is.

You use pins 5 and 6 for SoftwareSerial and as INPUT for sevenAmPin and eightAmPin. SoftwareSerial can't work if you set the TX pin as INPUT. I assume you didn't wire the buttons to this pins yet.

Yes. Thank you. I would not have found that in ten years. Thank you for your time. You taught me to look out for theses kinds of conflicts.


text:
IoT gabage monitoring system with my own Android application
I'm developing a device system in our campus - my aim is to provide three IoT smart garbage containers that will get the fill level (to determine the space of garbage inside and to inform the garbage collector if the garbage is empty, not yet full and full), temperature and humidity from the garbage bin and will send the information to my application that I'm going to develop.
I don't know how I can connect these three IoT devices which are a fair distance from each other. I know it should be wireless though I can't figure out the exact Arduino device to provide connection to my mobile application.

Does your campus have WiFi? If so, go with EPS8266 if its pins are OK for your sensors.
ESP Pinout
You'd want to keep an eye on power consumption; you'd sample your sensors per desired interval and deep-sleep at all other times. Check out available sleep here. It also has en example of how to sample and send a sensor, and sleep afterwards.
On the application end, you could either use a ready service such as Blynk, or go for a custom solution and send the data on your server. Of course, you would then need to write an API and some sort of application to present your data.
Let me also point out that for measuring garbage level, you should calculate the total volume of your bin and subtract the volume of garbage your sensor detects. Having non-uniform trash would give you some trouble, but it's a good technique for an estimation of garbage volume. Also, if using ultrasonic distance sensors, given the fact that you have temperature readings available, you should compensate your measurements; check this out.

thank you! :) please guide me for more details. I don't know how to code on ESP8266 and connect it from those 3 devices.

have a look at the second tutorial in the link I provided here. He is presenting a very similar project.

thank you @dBm do I need one breadboard for each sensor devices?

SIR should I use a wifi-module or not?

sir another one should we used a battery for it and battery case holder? thank you

source: Stack Exchange

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

sort: votes


text:
Simplify if then else statements for Neopixel/compass project
I am working on a project where a rotary encoder is generating 0 - 359° output and I am feeding that to a 60 Neopixel ring but I need a way to simplify or come up with a better way of a bunch of if-then-else statements.  Here is some sample code.
// NeoPixel Display
  if ((counter >=3) && (counter <=9))
(
  strip.setPixelColor(0, 255, 0, 0); //set pixel number 1 and set color to red
  strip.show(); //send color to pixel 1 on NeoPixel Ring
)
else if strip.setPixelColor(0, 0, 0, 0);
        strip.show();

  if ((counter >=10) && (counter <=15))
(
  strip.setPixelColor(1, 255, 0, 0); //set pixel number 2 and set color to red
  strip.show(); //send color to pixel 2 on NeoPixel Ring
)
else if strip.setPixelColor(1, 0, 0, 0);
        strip.show();

  if ((counter >=16) && (counter <=21))
(
  strip.setPixelColor(2, 255, 0, 0); //set pixel number 3 and set color to red
  strip.show(); //send color to pixel 3 on NeoPixel Ring
)
else if strip.setPixelColor(2, 0, 0, 0);
        strip.show();

You don't use the correct syntax. I assume you mean:
// NeoPixel Display
if ((counter >=3) && (counter <=9))
{
  strip.setPixelColor(0, 255, 0, 0); //set pixel number 1 and set color to red
  strip.show(); //send color to pixel 1 on NeoPixel Ring
}
else
{
  strip.setPixelColor(0, 0, 0, 0)
  strip.show();
}

And similar for the other colors.
First you see there are a lot of occurences of calls to setPixelColor and show. We make a function of this, where the color and the red value is parameterized:
void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
}

Now we can write your code as
// NeoPixel Display
if ((counter >=3) && (counter <=9))
{
  setPixel(0, 255);
}
else
{
  setPixel(0, 0);
}

void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
  strip.show();
}

And similar for the other colors.
Now we get rid of the if statements. For the first color this will become:
// NeoPixel Display
setPixel(0, ((counter >= 3) && (counter <= 9)) ? 255 : 0);

Combined with the other colors we get
// NeoPixel Display
setPixel(0, ((counter >=  3) && (counter <=  9)) ? 255 : 0);
setPixel(1, ((counter >= 10) && (counter <= 15)) ? 255 : 0);
setPixel(2, ((counter >= 16) && (counter <= 21)) ? 255 : 0);

void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
  strip.show();
}

However, the conditions can be simplified by adding them into the function. So we get
// NeoPixel Display
setPixel(0, counter,  3,  9);
setPixel(1, counter, 10, 15);
setPixel(2, counter, 16, 21);

void setPixel(int pixelNumber, int counter, int lowValue, int highValue)
{
  strip.setPixelColor(pixelNumber,
     ((counter >= lowValue) && (counter <= highValue)) ? 255 : 0,
     0, 0);
  strip.show();
}

If you need to have more checks if a value is in range you can make it a specific function. This will increase the code, but makes it easier to reuse code. So you will get:
// NeoPixel Display
setPixel(0, counter,  3,  9);
setPixel(1, counter, 10, 15);
setPixel(2, counter, 16, 21);

void setPixel(int pixelNumber, int counter, int lowValue, int highValue)
{
  strip.setPixelColor(pixelNumber,
    inRange(counter, lowValue, highValue) ? 255 : 0,
     0, 0);
  strip.show();
}

int inRange(int counter, int lowValue, int highValue)
{
   return ((counter >= lowValue) && (counter <= highValue));
}

Thanks for the great help, I learned a lot on this.  Now onto the Roary Encoder that will feed the NeoPixel ring.

Good luck with the project, glad to heard you learnt something (I still do daily too here).

I'd vote this answer up twice if I could! Good job! Loving the use of the ternary operator and the iterative approach to building up the program.

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


text:
How to connect a MPU-6050 to an Arduino that already has a CNC Shield V3 on top of it?
I have a CNC Shield on top of an Arduino Uno (GRBL pinout) that controls 2 stepper motors through a4988 drivers and it is working like a charm.
Now I want to add an accelerometer to it. From my humble research, the MPU-6050 seems a good pick.
If I purchase stacking headers to lift the CNC shield, can I connect the accelerometer to the unused/reserved A4 and A5 from the Arduino, but power it using CNC's Ground and 5V pins?
I'm open to other approaches if I'm not doing it the proper way.

Minduca, some feedback? you know how SE sites work

Sorry for the delay. I found on the CNC shield v3 the same SCL and SDA pins that you mentioned for the Arduino. Right now I'm gonna test the accelerometer connected directly to it and I comme back later! Thanks ;)

MPU6050 can use only I2C. Those are pins A4 and A5 on an Uno. 5V and ground are 5v and ground, no matter from which pin

Thanks for the info. Altough pins A4 and A5 are available to I2C connection at the arduino, the CNC shield expose these very same SCL and SDA pins and it's simpler to just use them. Same for ground and VCC.

of course, those are the same pins

This may be a bit harder to implement than it might seem. The grbl code uses all but one pin, so you would have to change that in the library. So I checked out the the code for the shield, and under the cpu_map tab it defines the pins. I would first try setting the unused pins to arbitrary values to enable the pins previously used by the code. For instance, if you are not using the Zed axis, try changing
#define Z_STEP_BIT      4  // Uno Digital Pin 4
to something like
`#define Z_STEP_BIT      0`.

This should clear up pin 4 to be setup as a input/output in your main sketch. Another pin definition associated with the Zed axis is
`#define Z_DIRECTION_BIT   7  // Uno Digital Pin 7`

Clear that one out, and you should be able to use pin 7 as an I/O.
I haven't personally tested the code so give it a try. Also just a heads up will probably run into errors while trying to use the MPU6050 library as well as grbl library, the grbl library is a LOT of code (I didn't spend enough time trying to compile so I don't know how much space it's actually using, but it's a lot). You might also run into timer errors as both libraries most likely reconfigure timers to work with each.
I hope this was a bit helpful!

EDIT:
I realized I didn't specify how to exactly free up A5. It has been assigned to the probe in the cpu_map.

MPU6050 uses I2C on pins A4 and A5


text:
Accessing funcition in object via `->` is crashing (resetting) Arduino
I have several classes that call each other running on an Arduino Mega. I am using the ArduinoSTL library to get the std library, most notably the std::vector.
The core problem is as follows: my Manager object that is created in the Arduino global space, is called in the loop(). The Manager object in one of it's functions spawns a derived object Derived derived (the constructor also takes a pin int and a delay value, but just simplifying for now) and calls a function in it derived.startExecution(). All is happy. Then I store a pointer to the object into a std::vector<base*> myVector via myVector.push_back(&derived). All is happy. As long as I don't leave the function, I can then take the pointer out of the vector container and call another function in the object. For example: myVector.back()->continueExecution() and all is great. Now the problem. If I copy paste the line myVector.back()->continueExecution() into a different function, the Arduino restarts. I'm losing my sanity here. I know that the issue is not the pointer, but the call to the function using the pointer. Using println & delay(500), in a new function inside the Manager I can do the following without issue (no restart):

retrieve pointer from vector. All good.
assign pointer from vector to a temporary pointer type to be able to refer to that pointer. All good
calling the function in the object causes instant Arduino Hardware reset (not a single line will execute in the function that is called).

All this leads me to the conclusion that calling the function in the object is causing a problem. I rewrote a simplified version of the code below, and it executes well on this website (please see: https://godbolt.org/z/G3x556), but on the Arduino it crashes.
What can I do to understand why the object crashes the program? how can I validate that the object is OK prior to calling the function? Why does the call to the function in an object that should be alive crashes the system? why does the call work in the function which stored it in the vector, but not in a different function? How can I answer these questions. I have hit a limit on ideas. Thank you for your time!
My code simplified:
#include <iostream>
//#include <ArduinoSTL.h> //commented out to work on website
#include <vector>

//base class is used to be able to push everything into a std::vector
//in ArduinoSTL lib.
class Base
{
    public:
        virtual void continueExecution()
        { std::cout << "Base" << std::endl; }

        // a polymorphic class MUST have a virtual destructor
        virtual ~Base(){};
};

//lots of these classes will exist one day if I keep at this grind
class Derived : public Base
{
    public:
        Derived()
        {
            std::cout<< "Derived constructor" << std::endl;
        }

        void startExecution()
        {
            std::cout << "Derived object, start function"<< std::endl;
            //start work
        }

        void continueExecution()
        {
            //continue when time has eleapsed
            std::cout << "Derived continueExectution " << std::endl;
        }
};

class Manager
{
    public:
        void beginExecutingDerivedObject()
        {

            //derived object
            Derived derivedObj;

            derivedObj.startExecution();

            myVector.push_back(&derivedObj);

            //if I run the line that crashes the code below this
            //comment, all is OK. But that is not where it is needed.
            myVector.back()->continueExecution();
        }

        void finishExecutionOfDerivedObject()
        {
            //CODE CRASH HERE. The moment the function is called, a reset
            //occurs.
            myVector.back()->continueExecution();

            //any code here may appear on the console, but it's just a
            //memory dump. By this point, the Arduino has thrown up it's arms.
        }

    private:
        //create vector
        std::vector<Base*> myVector;
};

//main is actually the arduino loop()
int main()
{
    //this manager class is in the sketch global space
    Manager manager;

    //this is called by a function call in the loop()
    manager.beginExecutingDerivedObject();

    //this is also called by a function call in the loop()
    manager.finishExecutionOfDerivedObject();
}

Derived derivedObj; is a local variable. It's deleted when the function exits. You have saved a pointer to it, but with that object now gone your pointer points to nothing of any interest - so doing anything with it is doomed to failure.
Instead you need to create a new object on the heap, which will already be a pointer:
Derived *derivedObj = new Derived();
derivedObj->startExecution();
myVector.push_back(derivedObj);

And then be sure to delete any objects you remove from the vector or you'll have lost that memory forever.

Note that std::vector<Base*> myVector; is a vector of pointers. You could store values in a vector as std::vector<Base> myVector;, but then you cannot store instances of derived classes.

@Mike In your case, it's a bit complicated, because you have to do it when you remove elements or clear the myVector list. (Iterate over it with a for loop and delete all elements before you clear the vector). Using the STL (and some of the other features you use above) is quite advanced stuff for running on an Arduino, just because it's memory is very limited. You should probably look at some C++ tutorials first and run a few test programs on the PC first (where it's much easier to debug).

A C++11 shared_ptr smart pointer makes it easier, but no idea if ArduinoSTL supports them.

@Majenko You ROCK!!! I don't know C++ at all and it's so hard to learn on the fly. Thanks a ton for your answer. Could I push my luck and please ask for an example on how to use the delete word? I'm totally new to C++ and really appreciate it. Could your example please assume C++99 is being used (if I'm lucky enough to get one)?

Base *ob = myVector[0]; myVector.erase(0); delete ob;

@Majenko  I'm a very new to c++, and have a final follow up to your delete example. In your example, first you copy the pointer from the vector (same as: Base *myObj = myVector.back();. Then you wipe the element in the vector holding pointer (same as myVector.pop_back();). Finally you release the memory using the pointer. Am I correct? Also, when we delete myObj are we not deleting a pointer of Base type? shouldn't we be deleting the actual object, or this does delete the pointer AND the object? Sorry to pester you. I really appreciate your help!

delete is to new what free is to malloc. You give it a pointer (as new provides a pointer) and it frees the object (calling the destructor) that pointer points to. With new, at no point do you ever "have" an object. You only ever have a pointer (with an associated type).


text:
Library for working with a 4-digit 7-segment indicator SH5461AS
Good day. Tell me an excellent library for working with a 4-digit 7-segment indicator.
I am currently using #include <fDigitsSegtPin.h>
But it does not allow you to display letters, does not allow you to put dots in the right place.
I think it is not flexible.
I want it to be easy enough to control the indicator and have sufficient freedom to choose segments (numbers, letters, dots, dashes). I tend to use the library: "SevenSeg library".
Tell me a really good option for my goal, and so that, as always, this library does not slow down all the code
I am using an indicator of the form:

This one  tm1637 sounds good. I was thinking to use it next time.
Edit 1:
Lately posted image suggests that it is without a separate display controller chip, then this library should work.
Edit 2:
This library specific to the SH5461AS display: Library
Include these three libraries:
#include "Segment.h"
#include "Digit.h"
#include "Display.h"

Print needs to be in the loop:
void loop() {
  d.print("1.234"); // Must be looped!
}

For disabling decimal points:
#define DISABLE_DP

The library's Github has very good documentation too

Oh yes, but it doesn't suit me, I forgot to clarify, I have an indicator like the one in the picture in the post above

that requires a display with TM1637 IC

@Антон I put that in the answer because I can't initiate comments. Do we have any markings on it? Looks like 12-pin 0.56", like this

Yes, exactly like that

I have SH5461AS

Thank you, @Антон, I updated the answer.


text:
How to use this confing function
For INA3221 current sensor, I found this library, however, I don't understand how to use the INA3221SetConfig() function as defined in the .cpp file link.
void SDL_Arduino_INA3221::INA3221SetConfig(void)
{

      // Set Config register to take into account the settings above
      uint16_t config =
          INA3221_CONFIG_ENABLE_CHAN1 |
          // INA3221_CONFIG_ENABLE_CHAN2 |
          // INA3221_CONFIG_ENABLE_CHAN3 |
          INA3221_CONFIG_RESET |
          INA3221_CONFIG_AVG1 |
          INA3221_CONFIG_VBUS_CT2 |
          INA3221_CONFIG_VSH_CT2 |
          INA3221_CONFIG_MODE_2 |
          INA3221_CONFIG_MODE_1 |
          INA3221_CONFIG_MODE_0;
      wireWriteRegister(INA3221_REG_CONFIG, config);
    }

It seems like the function is called automatically when the .begin() function is called and whatever is defined in the config function is written to the register. The use of | operator confuses me. I tried to comment out the some settings to see if it works but it makes no difference. There isn't any documentation so I am in a fix. Could you please tell how can I change the configuration settings e.g. instead of all the three channels or change the config_mode?

this is not an arduino related question ... it is a general programming question that may be a better fit at https://stackoverflow.com/questions

Without looking at the library, you can check yourself if this method (INA3221SetConfig) is called from the begin method (of the same class). Just trace back the methods manually until you find a call to this method.
About the | or 'bit-wise-or' operator (see https://en.wikipedia.org/wiki/Bitwise_operations_in_C), these are used to set bits in a byte/word/long.
Most registers have 8, 16 or 32 bits and with the | operator you can easily set multiple bits at the same time. Each value (e.g. INA3221_CONFIG_ENABLE_CHAN) has a value that is a power of 2 (mostly defined in the form 1 << ..something.. you can add them (with +) or | them together, but | is more clear what the purpose is and repeatedly calling | the same bit twice is not a problem (it still gives the same result).

I had to learn about bit -wise operations and manipulations and it becomes understandable :) Thanks for pointing me in the right direction

You're welcome, good luck with your project


text:
Aurdino EMG sensors and servos?
I'm new here and to the aurdino.
I'm building a 3D printed robotic arm controlled by a EMG sensor. I purchased a V3 EMG board and leads on Aliexpress. Here's a list of the things I've purchase for this project

Arduino Uno

EMG sensor

2 MG996R servos 7.2 max voltage I know not to power these through the
board.

X4 AA battery pack with male barrel input lead to power the arduino.
Wiring, header pins and cables.

I don't have any breadboards BTW.
The functionality is basic, servos on pulleys and strings, I'm looking for one servo to control the open close hand function, and the other is to open and close the index and thumb for a pinch function to pick up smaller objects.
I need to know the following,
Option to power servo, EMG sensor and arduino from single power source or two batteries and how to wire these a simple picture or schematic would be great.
What code can I quickly copy and paste to perform the functions I mentioned.
I do have some very basic DC electronic experience.
I just don't want to damage my components by just experimenting as it takes weeks to replace them otherwise.  Thanks.

What is the question?

"What code can I quickly copy and paste to preform the functions I mentioned." - Most likely you won't find a code online, that does exactly, what you want (and we are not a googling machine to search for them). So you will most likely need to write that code yourself. Yes, that will take a while, but you can look at tutorials for each individual part of the project, understand them, and then use that code and understanding for your project. When you have each individual part working, you can put all these things together in one code.

On Arduino Projecthub you can find a lot of tutorials about robotic arms. I don't know what EMG sensor you own, but here is an tutorial.

Your question is like asking for source code and schematic for a prosthetic arm that could be in a million dollar commercial project. I guess there are a few people sharing their work on the internet, but I doubt there is one that you can just, here I quote your words, "quickly copy and paste to perform the functions I mentioned"


text:
Making simple on/off IR servo movement.
I'm new to Arduinos and programming. I'm getting into a project and one of my tasks was to learn how to incorporate servos into Arduino and learn about sensors. I wanted to combine both, but I'm having some problems in my syntax. Can I get some help?
This is my code:
// servo test
#include <Servo.h>
#include <IRremote.h>
#define START_BUTTON //place code for button // code recieved from start
button
#define STOP_BUTTON //place code for button // code recieved from stop
button

int servopin1 = 13; // first servo
int servopin2 = 12; // second servo

int pos = 0;

int receiver_pin = 4; // output pin
int vcc = 5; // vcc ir sensor
int gnd = 6; // gnd for ir sensor
IRrecv receiver(receiver_pin);
decode_results output;
Servo Servo1;
Servo Servo2;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  receiver.enableIRIn();
  pinMode(vcc, OUTPUT);
  pinMode(gnd, OUTPUT);
  digitalWrite(vcc, HIGH);

  Servo1.attach(servopin1);
  Servo2.attach(servopin2);
}

void loop() {
  // put your main code here, to run repeatedly:

    if (receiver.decode(&output)) {
    unsigned int value = output.value;
    switch(value) {
      case START_BUTTON:
        if (pos <= 180){
           Servo1.write(pos);
           delay(500);
           pos = pos + 30;}
        else {
           pos=0;
             }
        if (pos <= 180){
          Servo2.write(pos);
          delay(500);
          pos = pos + 30;}
        else {
            pos=0;}
      break;
      case STOP_BUTTON:
           Servo1.write(0);
           delay(200);
           Servo2.write(0);
           delay(200);
           break;
            }
     }
  }

  //^servo 2 positions and delays
}

I'm trying to figure out why I'm getting a the following error:
C:\Users\Alex\Documents\Arduino\Servo_test2Library\Servo_test2Library.ino:
In function 'void loop()':

Servo_test2Library:38: error: expected primary-expression before ':' token

       case START_BUTTON:

                        ^

Servo_test2Library:53: error: expected primary-expression before ':' token

       case STOP_BUTTON:

                       ^

C:\Users\Alex\Documents\Arduino\Servo_test2Library\Servo_test2Library.ino:
At global scope:

Servo_test2Library:64: error: expected declaration before '}' token

 }

 ^

Multiple libraries were found for "IRremote.h"
 Used: C:\Users\Alex\Documents\Arduino\libraries\IRremote-2.2.3
 Not used: C:\Users\Alex\Documents\Arduino\libraries\Arduino-IRremote-master
Using library Servo at version 1.1.2 in folder: C:\Program Files
(x86)\Arduino\libraries\Servo
Using library IRremote-2.2.3 at version 2.2.3 in folder:
C:\Users\Alex\Documents\Arduino\libraries\IRremote-2.2.3
exit status 1
expected primary-expression before ':' token

Up at the top of your code, you have:
#define START_BUTTON //place code for button // code recieved from start
button
#define STOP_BUTTON //place code for button // code recieved from stop
button

A #define needs 2 parts after it. The first is the new name being created, and the 2nd is the definition of the new name.
You should put the value that you expect for the START_BUTTON condition after the name, such as:
#define START_BUTTON 0x48
#define STOP_BUTTON 0x49

Or whatever your IR remote is sending.
Also, you have one too many closing braces (}) at the end.
      [...]
      case STOP_BUTTON:
           Servo1.write(0);
           delay(200);
           Servo2.write(0);
           delay(200);
           break;
            }  // THIS CLOSES THE SWITCH
     }  // THIS CLOSES THE IF STATEMENT
  }  // THIS CLOSES loop()

  //^servo 2 positions and delays
} // THIS IS NOT CLOSING ANYTHING THAT WAS OPENED


text:
L9110H-bridge motor driver
So I have this old RC car which doesn't seem to connect to the joystick very well so im going to modify it with an Uno with 433 MHz receiver/transmitter.
Both the steer and drive motors work as intended so long as you can reverse their current. I've seen people use the dual channel drivers which is what I know I probably what I should use to drive the motors. I bought a starter kit a while back which came with a single L9110H Chip. I thought maybe I could order another one and just solder them to a PCB and mount the PCB along with the Uno inside the car that way I don't have an extra chip just collecting dust. I've looked at the data sheet for the L9110H and came up with a diagram on Fritzing.

I was hoping someone could tell me if I'm on the right track with this?

Yes, looks good to me. That looks to be identical to the "Application Circuit" on page 2 of the datasheet you link to.

Thanks for your reply. I'm currently trying find out if the motor is too much amperage for the chip I sent the circuit through a multimeter in amperage mode to the motor with it set to 200m and it read 1.36 not to sure if that's 1.36A or  136mA as I do have the lead(red wire) in the 10A plug on the meter

The results are probably meaningless. Measure the resistance of the motor winding.

Well I took a chance and hooked it up and got it working on the back tires gave the steer tires a go since they seem to work on the same principal and they work but there was a sound from the chip so I unplugged it right away haha

@GeraldLeese What kind of a noise?

kind of almost sounds like a buzzer beep.

I’m just testing it using a digitalwrite(pin1,HIGH) with a analogWrite(pin2, 100) maybe changing analogWrite to digitalWrite(pin2, LOW) will stop the beep. Still have to figure out PWM and speed control

Ahh so I started using analogWrite(pin1,  100) and digitalWrite(pin2, LOW) to control the speed the sound I believe is when the pwm is set too low because I when I set it below 50 on the drive motor it starts producing the sound right out of the motor


text:
Resetting Arduino UNO code (newbie)
So today I started to learn Arduino uno. I have an LM35 temperature sensor and I got what I needed from it. Now it's just keep calculating till I plug it off.
I know there is a reset button. When I press it or hold it, it's closing and opening again to do the coding again. I want it to completely stop. Like when I first plug led was flashing to show arduino is connected.
And I know I can just upload another code. But I don't want that.
If it's possible please let me know.

Actually, it already did something when you turned it on when you got it: it was blinking a LED. It did not mean it was connected. A microcontroller (or controller) always does something. Although you can consider an empty endless loop as 'nothing'.
And now you overwritten that sketch with your LM35 sketch.
However, you can put the Blink sketch again in your Arduino, and it can be found here:
https://www.arduino.cc/en/Tutorial/Blink
You don't need to connect the LED, it will use the built in LED.
If you don't want the Arduino to do anything, just switch it off (disconnect the power).

When a microcontroller or a computer is powered on, it always does something. A program on a computer will return and the OS will run again. On a microcontroller there is no OS to return to, so every microcontroller program has an infinite loop.
The void loop() function of the Arduino framework is such an infinite loop. If you want your LM35 temperature code to be only run once, you can put it into the void setup() function, which is run once before going to loop(). When the loop() function is empty, the Arduino will do nothing after it returned from setup().
Otherwise, if you want to put your code into loop() for whatever reason, you can insert an infinite loop whereever you want it:
while(true);

This loops forever and does nothing. Your temperature code will only be executed on the next reset or power on.


text:
Reduce Sketch Size Help!
I dont know what to do?
Sketch uses 3712 bytes (12%) of program storage space. Maximum is 30720 bytes.
Global variables use 210 bytes (10%) of dynamic memory, leaving 1838 bytes for local variables. Maximum is 2048 bytes.
Program:
String texto;
int flag;
void setup() {
Serial.begin(9600);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(7, OUTPUT);//luz stop
pinMode(8, OUTPUT);//faros
}
void loop() {
while (Serial.available())//
{
delay (10);
if (Serial.available() > 0) //verifica que este disponible el puerto serie y verifica que haya algun
caracter
{
char c = Serial.read(); //guara cualquier caracter que haya llegado por el puerto serie
texto += c; //concatenamos
}
} ///Sentencias de control///
if (texto == "1") //compara el contenido de la avariable "texto" con el numero 1
{
digitalWrite(7,LOW); //Apaga la luz stop
digitalWrite(11, LOW);
digitalWrite(12, HIGH);
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
}
if (texto == "3") //compara el contenido de la avariable "texto" con el numero 3
{
digitalWrite(7,LOW); //Apaga la luz stop
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
digitalWrite(10, LOW);
digitalWrite(9, HIGH);
}
if (texto == "2") //compara el contenido de la avariable "texto" con el numero 2
{
digitalWrite(7,LOW); //Apaga la luz stop
digitalWrite(11, LOW);
digitalWrite(12, HIGH);
digitalWrite(10, LOW);
digitalWrite(9, HIGH);
}
if (texto == "4") //compara el contenido de la avariable "texto" con el numero 4
{
digitalWrite(7,LOW); //Apaga la luz stop
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
}
if (texto == "5") //Compara el contenido de la avariable "texto" con el numero 5
{
digitalWrite(7,HIGH); //Enciende la luz stop
digitalWrite(11, LOW);
digitalWrite(12, LOW);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
}
if (texto == "6") //Compara el contenido de la avariable "texto" con el numero 6
{
if (flag==1)
{digitalWrite(8, LOW);
flag=0;
}
else if (flag==0)
{digitalWrite(8, HIGH);
flag=1;
}
}
texto = "";
}

What‘s the problem, you have lots of space left?

I dont know what to do? ... i think that you are the only one who knows the answer to that question

Next time, select your code and press ctrl-K... Also align your code (indent it well).
However, you don't need help actually as you have plenty of memory left. As as written:

You only use 12% of program storage space. This might seem a lot having such a small sketch, but most of it is because of library usage/framework (such as the digitalWrite call(s).
210 bytes of dynamic memory is also not something to worry. Btw, this is unrelated to the sketch size, but to your use of (global and other) variables.

So unless you know beforehand your sketch will be much bigger, don't change it because of that reason (too less space).
However, there is another reason, to shorten the sketch, and that is because of duplicated code. As you can see, there is in the entire sketch a lot of repetition (or almost repetition), as in:
if (texto == "5") //Compara el contenido de la avariable "texto" con el numero 5
{
  digitalWrite(7,HIGH); //Enciende la luz stop
  digitalWrite(11, LOW);
  digitalWrite(12, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
}

What you can do to improve it is:

Either use a switch statement instead of the if/else statements
Or create a function that incorporates this condition, together with the following item. This solution is in your case the most clear.

What you do is creating a new function:
void setPins(bool condition, int pin7, int pin11, int pin12, int pin10, int pin9)
{
  if (condition)
  {
    digitalWrite(7, pin7);
    digitalWrite(11, pin11);
    digitalWrite(12, pin12);
    digitalWrite(10, pin10);
    digitalWrite(9, pin9);
  }
}

And you call your function with:
setPins(texto == "5", HIGH, LOW, LOW, LOW, LOW);

And the same for all other conditions. I only used 5 as example.


text:
Connecting 2-pin JST PH connector to Arduino Mega
I’m want to connect 50 LDR to my Mega, I wondering if I use a 2-female pin JST PH connector to connect the LDR, how can I link 2-pin male JST PH connector board to the Mega and does this board exist?

Design your own.

There exists 2.00 to 2.54mm adapters, like in this link.
They look like below (example of 1.27, 2 and 2.54mm):


text:
How to make a dynamic menu with a sub-menu ( Arduino mega or Arduino Uno)
I have an arduino mega with a LCD shield (from keyestudio KS2056). I am trying to create a menu with a submenu that would have addable and removable strings based on inputs from a RFID scanner(addable) and buttons(to remove selected strings). I am not so sure how I could possibly do this. Any assistance would be great.

I will skip the RFID part, that is unrelated to the menu.
What you can do is creating two variables:
int menuLevel1 = 0;
int menuLevel2 = 0;

Assuming you have 2 levels, if you have more levels consider an array.
Now you can print the screen based on the values of these two variables (use a switch statement for menuLevel1 which calls new functions, each with their own switch statement for menuLevel2.
Note there are more solutions, but this is a rather simple solution.
The RFID scanner just changes the values, so going to a different menu screen.
A slightly different solution is to not use numbers, but an enumeration (or one for the main level, and x for the second level etc). This can add up, so you can also use a single enum value (with one entry per possible menu page).
The last example looks like:
enum EMenuPage
{
   StartPage,
   MainMenu,
   FirstMenu,
   DisplayX,
   SetY,
   …
}

enum EMenuPage _menuPage;

Displaying like:
switch (_menuPage)
{
case StartPage:
   // Fill LCD with start page
   break;

case …

And when an RFID messages comes in:
if (RFID... == Back)
{
  _menuPage = MainMenu;
}
else …

[State machines][1]. it's the general form of the solution provided by michael above. it's a big help on situations when the application have to answer to, or act on many states (e.g. a menu). the good part is you can draw them on a piece of paper , draw a graph, manage input/output and write a general routine to act in various states. the state names themsevles can be represented by an integer variable and represented better by enumeration. after that, there should be a routine to act based on the current state, and the input from current state to go to another state. in it's easiest form, it's just a if-else block.
depsite the idea is the same as the bare variable solution provided in the other answers, ignoring state machine related techniques (e.g. just drawing state graphs down on a piece of paper) makes a big application unmanageable.


text:
Led and button simulation of a blink
My circuit:

My code:
// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2; // pushbutton connected to pin 2.

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == HIGH) // check while the button is pressed
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
  }
}

What I wish to do is that when I press the button, the Led's start flashing and when I press them again, they stop blinking (like a fire alarm). Right now they do nothing and I dont know why. Is it something with the circuit or the code?

There is only one pin of the button connected to IO2. Is the other connection missing only in the diagram? Or is it missing in your actual circuit as well?

@DirkGrappendorf Yeah there is only one pin connected to pin 2. Why is that you need another one? and from where?

I meant the other pin of the button. It is not connected to anything. See my answer.

Another pin of button must be connected with ground. That thing missing in your circuit. Provide ground to another pin of button and it's working fine with your code.

The volatage level on the IO pin needs to change (from low to high and vice versa), only then can the microcontroller detect a button press. Without another connection to the button, IO2 is simply floating (unconnected).
There are two methods to implement this: external pull-up or external pull-down resistors and internal pull-up resistors (both methods are described for example in this tutorial).
I prefer the internal pull-up resitor method. You need to connect the second pin of the button to GND. Then change your setup code to
pinMode(buttonPin, INPUT_PULLUP);

If the button is not pressed, the internal pull up resistor inside the microcontroller pulls IO2 to +5V and a digitalRead(buttonPin) returns HIGH. When you press the button, IO2 is pulled to GND and digitalRead(buttonPin) returns LOW.
So in your case you need to check for a LOW reading, because you want the LEDs to blink when the button is pressed.
(Btw. you can replace the while loop with an if, since the loop() function is already executed in an infinite loop.)

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


text:
LCD Custom Character
I am experimenting the write((byte)num) function, and I stumble upon a pre-made custom character. Usually it's on above ((byte)200) or and below ((byte)10000). If anyone else know this, where could I find the list for a specific character?

Post the code and the output.  You're talking nonsense with a byte with a value of 10000.  A byte can't have a value that high.

@Delta_G  I think that (byte) 10000 is a cast of integer to byte ... it is equal to 16

https://www.sparkfun.com/datasheets/LCD/HD44780.pdf pages 17 and 18 (depending on what ROM your LCD has). And the range is 128-255 - the "high bit set" on ASCII.

Yes, @jstola, that was exactly my point.  There is no character at 10000, he needs to be thinking of what number is actually being used there.

Hi Welcome to Arduino StackExchange
You can build your own LCD characters if you spend some time with the datasheet and user manuals available
Arduino has a dedicated function here
#include <LiquidCrystal.h>

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

byte smiley[8] = {
  B00000,
  B10001,
  B00000,
  B00000,
  B10001,
  B01110,
  B00000,
};

void setup() {
  lcd.createChar(0, smiley);
  lcd.begin(16, 2);
  lcd.write(byte(0));
}

void loop() {}

here is one example:  from our tool here

From the datasheet:

here is one example where a Heart symbol is created using the built-in Arduino LCD library:
You can play here at our LCD1602 simulator to get a hang of it.  Please leave a message or comment if you have any questions :)


text:
I'm trying to upload a sketch to my arduino uno, but I get the Error-Message "avrdude: stk500_recv(): programmer is not responding"
    Arduino: 1.8.13 (Linux), Board: "Arduino Uno"

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I selected the right board (Arduino Uno)
I selected the right port
I selected "USBasp" as programmer
I reset the board multiple times
I have uploaded to the same port multiple times before without getting an Error
I disconnected the USB-cable multiple times and used a different one
I don't get the Error Message on a different board (also Arduino Uno)
When I'm trying to upload with the serial Monitor open i see an orange lamp (RX lamp) blinking in the same speed the Errors are given
When I'm trying to "Burn Bootloader" I get following Error:

Arduino: 1.8.13 (Linux), Board: "Arduino Uno"

avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'
Error while burning bootloader.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I guess you don't have an USBasp programmer, so you get that error message on bootloader burning. Do you habe anything connected to the board, when trying to upload? What other board did you try? Are you able to open the Serial Monitor with the selected com port? If you then send something, is the RX LED on the Uno lighting up shortly?

Have you ever successfully uploaded to this board?

The problem was an Bluetooth extension I connected to the board. I removed it, uploaded the program, reconnected it, and that worked!

So please mark this question as answered since you solved the problem.

I have to wait another hour, then I'll of course do it :)


text:
Programming 328PB from Arduino IDE using Atmel-ICE to ICSP port
Updated question.  The original question was based on using 'Upload' from the Arduino IDE, instead of 'Upload Using Programmer' under 'Sketch'.  The problem in getting the Atmel-ICE to work with Arduino IDE appears now to be one of incorrect ICE drivers loaded when I installed Atmel Studio.
Arduino requires libusb-win drivers, which can be checked with Zadig.   Available here: https://zadig.akeo.ie/
This problem was 99% solved (with help) by selecting  and the libusb-win32 driver using Zadig.   I say 99% solved, because my program now loads and runs! , but I do get the red 'X' there as the WCID status.
Apologies if this amendment to the original question is not in the correct context, this is new to me.   Thank You.
Jaco

i think rhat the yellow exclamation mark in the device manager is an indication that windows cannot talk to the device ... try finding the correct drivers ... your post is unrelated to the arduino, so it is off topic here

Are you choosing "Upload" or "Upload using programmer"?

I'm pretty sure AVRDude needs that the Atmel-ICE has libusb drivers loaded to be able to interface with it (like in https://cyansensors.wordpress.com/portfolio/setting-up-atmel-ice-with-platformio-using-atmega328p/). What happens when you use https://zadig.akeo.ie/ to load libusb-win32 drivers? Also, the upload should happen via a USB device and not a COM port, so make sure to choose "Upload using programmer" when uploading. If that does not help, go to File -> Settings and enable "Verbose Upload" and post the log.

I think Maximilian you have put me on the right path.  Device Manager is happy with   the ICE now appearing under libusb-win32 devices.     I had indeed posted the error from 'Upload', which was in haste, as I had been using Upload Using Programmer.   Now the error is:   "avrdude: usbdev_send(): wrote -22 out of 7 bytes, err =
avrdude: jtag3_send(): failed to send command to serial port
avrdude: failed to sync with the JTAGICE3 in ISP mode"    So it appears the Arduino IDE uses the JTAG mode, not the ICSP protocol?    An Auduino IDE configuration option?   Thank You.

I guess I was too subtle about this before, so I'm going to mention it one last time before disappearing: The things you did to solve the problem go in an answer and not the question.  Someone who discovers this later should be able to see a question (that they can understand, at least if they have the same problem) and separate from that an answer.

Apologies Timeage, I thought the answers were other users responses.   Will make corrections today.   Need here to get a fetter feel for how it's supposed to work.  Again, apologies, I mistakenly thought I understood.

For reference, you said that it works 99% fine except that it won't load WCID driver (which I don't think is very ciritical?), but how did you resolve the error avrdude: usbdev_send(): wrote -22 out of 7 bytes, err = avrdude: jtag3_send(): ?

Hello The 328 "PB" has major issues with running external clocks...(yes I have first hand experience with this PB model)... Try switching to the internal oscillator as I can testify first hand the the external clocks on the PB don't work correctly. They tend to sell the PB a few bucks cheaper because you will only buy them once and only once when you find out how bad the external crystal clock driver is. If you look at the latest datasheet for the PB they try and talk their way out of the bad driver by explaining how you need to match capacitors with the following snippet. I call BS as the 328p never needed such precision on it Xtal1 & 2 pins to run but to be fair they PB is meant to be low power.
This Crystal Oscillator is a low power oscillator, with reduced voltage swing on the XTAL2 output. It gives
the lowest power consumption, but is not capable of driving other clock inputs, and may be more
susceptible to noise in noisy environments.
The crystal should be connected as described in Clock Source Connections. When selecting crystals,
load capacitance must be taken into consideration. The capacitance (Ce+Ci) needed at each TOSC pin
can be calculated by using:
�� + �� = 2�� − ��
where:
• Ce - is optional external capacitors. (= C1, C2 as shown in Figure 11-2)
• Ci - is the pin capacitance in Table 11-3.
• CL - is the load capacitance specified by the crystal vendor.
• CS - is the total stray capacitance for one XTAL pin.
Table 11-


text:
Connection from Arduino Uno to Microsoft SQL Server Database
I would like to make a connection from Arduino Uno to Microsoft SQL Server for storing student attendance records into a table from my database.
So, what is the best way to do that? I need a suggestion or useful references and links.
I have written a web application on Visual Studio using C# language. What Arduino does is getting fingerprint through sensor, then I would like to store the attendance records of a student into database. So the attendance records can be retrieved from database to the web application and display to teachers.
This is just for project purpose only and the connectivity between Visual & SQL Server using these two lines below:
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-H7KQUT1;Initial Catalog=SAOS1;Integrated Security=True";

It is highly doubtful you will ever get the Arduino to connect to Microsoft SQL Server.  Create a Web API as a gateway between the Arduino and SQL using a protocol of your choosing (REST is common with plenty of examples around).

@Majenko Hi, Majenko. Do you have any useful references? Cause I'm new to Arduino. Don't know which is the best one to me to establish connection between Arduino Uno & Microsoft SQL

No, I've never done it. You seem to already be au fait with C# and VS, so I'd guess you'd add it to your web app. Just create some URLs (however you'd do that) that accept data in some way and post them to the SQL server. Of course you'd need a network connection (WiFi, Ethernet, whatever).

Using a layer between Arduino and MSSQL might give you the least headache. Would you like to do this on-premise or in the cloud?
For an easy cloud approach, look at AWS Lambda. Write a Lambda function that inserts into your MSSQL database, possibly running on AWS too. Your choice of Java, Node.js, C#, or Python. Hook it up with incoming MQTT messages from your Arduino.
https://stackoverflow.com/questions/33165045/aws-lambda-and-sql-server-integration
 could help.
For a cloud-free approach, you could run your own local MQTT server (broker, to be exact, Mosquitto being the most popular), and have your C# subscribe as an MQTT client. When the Arduino publishes a fingerprint signature, your C# script can do the database work.

Hi Chris. I've been searching for tutorials about Mosquitto. But I didn't find any useful articles how to send data from Arduino to MSSQL using Mosquitto. Do you have any useful links or tutorials for me to do it?

Mosquitto is just a broker. Think of it more like a phone switch board. You write a piece of C# code that subscribes to a topic (think phone number). When your Arduino publishes information on that topic (dials that number), Mosquitto routes that to your C# client, invoking your code (phone rings). There is a nice intro to MQTT at HiveMQ.

Chris, how can I connect the arduino with mqtt broker or subscribe to the mqtt broker?  Without using ethernet shield or wifi shield


text:
Why is 'n' parameter of snprintf ignored?
I have found that the n parameter of snprintf() seems to be ignored in my code.
char asdf[10];
Serial1.println(snprintf(asdf, 2, "hello"));

This prints 5 when I would expect it to print 2. What is happening?

Does the variable asdf contain "hello" or "h"? If it contains "h" then the parameter has not been ignored.

snprintf() will not write more than <size> (snprintf's 2d argument) characters to your buffer, but it does count (and discard the extra) characters it would have written, had there been space enough, and that is the number it returns. Yeah, it can be confusing!
See this snprintf() reference.

It would be helpful because you could snprintf to a very small buffer, note the number returned, then malloc a buffer of the appropriate size, and do it again. That way you know how many bytes to allocate.

@NickGammon: Or you can snprintf to no buffer whatsoever (a null destination pointer is explicitly described as a valid argument for the destlength==0 case) when measuring the length.

Indeed. That is also done in Windows text output routines to measure how much space some text in some font would occupy, without actually drawing it.

A test sketch for the Arduino Uno:
char buffer[10];

void setup() {
  Serial.begin(9600);
  int n = snprintf(buffer, 2, "hello");
  Serial.println(n);
  Serial.println(buffer);
}

void loop() {
}

As @JRobert wrote, the "would have" is the key. As far as I know only the snprintf and the vsnprintf return a "would have" number.
I think the reason is to be able to tell if the string was truncated. Suppose the 'size' parameter is 25 and the format string is very long, then the return value can be tested against 25. If the return value was 26 (the "would have" number of bytes), then the string was truncated.
This information was not possible to retrieve when the "would have" number was not available.

For completion, the man page for fprintf states:

The snprintf() function shall be equivalent to sprintf(), with the
  addition of the n argument which states the size of the buffer
  referred to by s.  If n is zero, nothing shall be written and s may
  be a null pointer. Otherwise, output bytes beyond the n‐1st shall be
  discarded instead of being written to the array, and a null byte is
  written at the end of the bytes actually written into the array.

and, more relevant:

Upon successful completion, the snprintf() function shall return the
         number of bytes that would be written to s had n been sufficiently
         large excluding the terminating null byte.


text:
Can Arduino accept HDMI input video stream, and output it without any modification to the video?
I'd like to know please whether an Arduino can accept an HDMI signal from a satellite receiver, let it flow without any modification to the stream, and output it to TV?

what do you want to do that wire doesn't?

No.
HDMI uses multiple serial data streams at gigabit rates. No Arduino is ever going to do that sort of thing.  If you want something programmable to do that kind of thing you need an FPGA.


text:
Time between two IR beam sensors
I am working with two sets of IR beam, they are to be placed in X distance. My goal is to measure speed. I would like to measure time between the first IR beam to the second beam when the beam breaks.
I am not sure what's going on, I am not getting any time of the serial port but the LEDs are turning on and off the way I wanted.
Please help me with getting the time between two IR beam sensors.
This the sensor that I am using -  Adafruit IR breakbeam sensors
and I am working with a Mega2560.
#define LEDPIN 13
int startPin = 8, finishPin = 5;
unsigned long starttime = 0, finishtime, time_interval;
float distance = 1, Speed; // Speed calculated
int trigger1 = 0; // Sensor 1
int trigger2 = 0; // Sensor 2
int sensor1State; // Sensor 1 status
int sensor2State; // Sensor 2 status

void setup() {
  pinMode(startPin, INPUT_PULLUP); // Sensor 1 as input
  digitalWrite(startPin, HIGH); // Turn on the pullup
  pinMode(finishPin, INPUT_PULLUP); // Sensor 2s input
  //digitalWrite(finishPin, HIGH); // Turn on the pullup

  pinMode(LEDPIN, OUTPUT);
  time_interval = ((finishtime - starttime) / 1000000);
  Serial.println(time_interval);
}

void loop() {
  sensor1State = digitalRead(startPin); // Read the state of the IR sensor 1:
  if (sensor1State == LOW) // See if IR beam of sensor 1 has been broken
  {
    if (trigger1 == 0 && trigger2 == 0) // Check to make sure both sensors have not triggered
    {
      starttime = micros(); // Save time when sensor 1 was triggered
      digitalWrite(LEDPIN, HIGH);
      trigger1 = 1; // Prevent sensor 1 from triggering again
    }
  }
  if (trigger1 == 1) {
    sensor2State = digitalRead(finishPin); // See if IR beam of sensor 2 has been broken
    if (sensor2State == LOW) {
      // Check to make sure sensor 1 has triggered but not sensor2
      if (trigger2 == 0) {
        // Run speed function
        trigger2 = 1;
        finishtime = micros(); // Save time when sensor 2 was triggered
        digitalWrite(LEDPIN, LOW);
        // time takes to travel between 2 IR Beam  // divide by 1000000 to convert microsecond to second
        Serial.println(time_interval);
      }
      // Reset both sensors
      trigger1 = 0;
      trigger2 = 0;
    }
  }
}

Need to post your code correctly.  Please Edit and add 4 spaces before each line at a minimum.

You will not get a meaningful result with a 16 MHz processor, where every clock cycle takes 62.5nanoseconds, and the speed of light is basically instant at short distances.    time_interval probably needs to be a float also.

@CrossRoads, how is here speed of light in play?

Yeah, never mind that. I think you are close on the triggering and capturing the state kind of logic, just needs a little more thinking I think.  For example, in here you never calculate the interval that you print        if (trigger2 == 0) {
// Run speed function
trigger2 = 1;
finishtime = micros(); // Save time when sensor 2 was triggered
digitalWrite(LEDPIN, LOW);
// time takes to travel between 2 IR Beam  // divide by 1000000 to convert microsecond to second
Serial.println(time_interval);
}

You've tried to print an interval at the bottom of the setup() function, using finishtime before you have ever used it. Fortunately, finishtime will have been initialized to zero before the program runs so the the arithmetic result will be zero, though meaningless.
In loop(), you've never completed the interval calculation before you try to print it.
If nothing at all is being printed, check your wiring and be sure your code is getting the triggers. You haven't showed your wiring, so we can't help you debug that, in case there is a problem with that also.

You never calculate the time_interval that you print. Add that after the finishtime line
  if (trigger2 == 0) {
    // Run speed function
    trigger2 = 1;
    finishtime = micros(); // Save time when sensor 2 was triggered
    digitalWrite(LEDPIN, LOW);
    // time takes to travel between 2 IR Beam  // divide by 1000000 to convert microsecond to second
    Serial.println(time_interval);
  }

Thank you for the respond, I had it like that before still doesnt work, I am not getting any time, not sure whats going on ??

void loop() {
sensor1State = digitalRead(startPin); // Read the state of the IR sensor 1:
if (sensor1State == LOW) // See if IR beam of sensor 1 has been broken
{
if (trigger1 == 0 && trigger2 == 0) // Check to make sure both sensors have not triggered
{
starttime = micros(); // Save time when sensor 1 was triggered
Serial.println(starttime);
digitalWrite(LEDPIN, HIGH);
trigger1 = 1; // Prevent sensor 1 from triggering again
}
}
if (trigger1 == 1) {
sensor2State = digitalRead(finishPin); // See if IR beam of sensor 2 has brok

}
if (trigger1 == 1) {
sensor2State = digitalRead(finishPin);
if (sensor2State == LOW) {
  if (trigger2 == 0) {

    trigger2 = 1;
    finishtime = micros(); // Save time when sensor 2 was triggered
    Serial.println(finishtime);
    digitalWrite(LEDPIN, LOW);

    time_interval = ((finishtime - starttime) / 1000000);
    Serial.println(time_interval);
  }

my wire is good, i hard wire to pin, grd and 5 v. My 1st code that i wrote its work with it,  when i added the condition its not working anymore -  I didnt add any resister do you think thas a reason  its not working,

please do not put code into comments .... nobody will read that .... add the code to your question (make sure that it is indented at least 4 spaces so that it shows up as "code")


text:
Issues with PIR Sensor triggering by itself
I am currently working on my first Arduino project and I am having some issues that I am seeking help with. The robot I am building must have human following capabilities and to do so I am using 3 PIR sensors (One on the front, one on the left and one on the right) and an Ultrasonic Sensor so the robot won't run into a wall or a person it is following. To handle the motors I am using the Adafruit Motor Shield (V.1)
The way I am trying to make this work is as follows.
The robot's main PIR sensor is the one attached to the front. If this sensor reads HIGH then the robot will move forward while checking its distance from any objects in front of it in which case it stops and reverses until there is at least 30cm of space between itself and the object in front. The radius of this sensor had to be reduced so that it only reads HIGH if the person is exactly in front of the robot. This was done using carton paper and black duct tape. Two images of this have been provided below in case this has something to do with my issue.

The other 2 PIR sensors attached to the sides will tell the robot if it should turn left or right. If the left PIR is triggered then the robot will start turning left and keep doing so until the front PIR finally reads HIGH, and then it moves forward. The same thing is done with the right PIR except that it moves right. These PIR sensors are handled using interrupts on the Arduino Mega 2560 board as can be seen in the provided code.
The code I am using can be found below:
#include <AFMotor.h>
#include <NewPing.h>

#define trigPin 34
#define echoPin 32

NewPing sonar(trigPin, echoPin);
int minimumDistance = 30;
int currentDistance = 0;

int calibrationTime = 60;
int redLED = 22;
int greenLED = 24;

int PIR = 26;
volatile int PIR_val = 0;
int PIR_left = 19; // (interrupt 4)
int PIR_right = 18; // (interrupt 5)

AF_DCMotor motorL(1, MOTOR12_64KHZ);
AF_DCMotor motorR(2, MOTOR12_64KHZ);

void setup()
{
  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);

  pinMode(PIR, INPUT);
  pinMode(PIR_left, INPUT);
  pinMode(PIR_right, INPUT);

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

  digitalWrite(redLED, HIGH);
  // Calibration for PIR sensors
  for (int i = 0; i < calibrationTime; i++)
  {
    delay(1000);
  }
  digitalWrite(redLED, LOW);
  digitalWrite(greenLED, HIGH);

  attachInterrupt(4, turnLeft, RISING);
  attachInterrupt(5, turnRight, RISING);
}

void loop()
{
  delay(50);
  currentDistance = sonar.ping_cm();

  if (currentDistance < minimumDistance && currentDistance > 0)
  {
    moveBackward();
  }
  else
  {
    PIR_val = digitalRead(PIR);

    if (PIR_val == HIGH)
    {
      moveForward();
    }
  }
}

void moveForward()
{
  motorL.run(FORWARD);
  motorL.setSpeed(180);
  motorR.run(FORWARD);
  motorR.setSpeed(200);
}

void moveBackward()
{
  motorL.run(RELEASE);
  motorR.run(RELEASE);
  motorL.run(BACKWARD);
  motorL.setSpeed(190);
  motorR.run(BACKWARD);
  motorR.setSpeed(225);

  while (currentDistance < 30 && currentDistance > 0)
  {
    currentDistance = sonar.ping_cm();
  }

  motorL.run(RELEASE);
  motorR.run(RELEASE);
}

void turnLeft()
{
  motorL.run(BACKWARD);
  motorL.setSpeed(150);
  motorR.run(FORWARD);
  motorR.setSpeed(150);

  // While front PIR is reading LOW
  while (PIR_val == LOW)
  {
    PIR_val = digitalRead(PIR);
  }
  // After front PIR reads HIGH
  moveForward();
}

void turnRight()
{
  motorR.run(BACKWARD);
  motorR.setSpeed(150);
  motorL.run(FORWARD);
  motorL.setSpeed(150);

  // While front PIR is reading low
  while (PIR_val == LOW)
  {
    PIR_val = digitalRead(PIR);
  }
  // After front PIR reads HIGH
  moveForward();
}

The first issue I am having is that as soon as the PIR sensors are done calibrating, the robot starts moving forward by itself. Even if I leave the robot alone inside a room with the door closed, after the calibration time passes the robot automatically moves forward on its own.
The other issue I am having is also with the front PIR sensor. While the robot is turning and looking for a human as seen in the 'turnLeft()' and 'turnRight()' methods, the robot will sometimes move forward toward a random direction instead of towards me.
I have already tried replacing the front PIR sensor twice and the sensor itself does not seem to be the issue.
The PIR sensors I am using are the 'HC-SR501' model.
For all PIR sensors, the delay time is set to the lowest possible time (5 seconds) and the sensitivity is set to full.
I welcome any input or suggestions whatsoever. If you would like me to provide any additional information about this project please ask and I will do so.

http://arduino.stackexchange.com/questions/9965/detect-movement-on-moving-robot-pir-sensor
Probably, the answer on your other question will also answer this question.

Try:

turn sensor OFF when robot is moving
turn sensor ON while robot is standing still
look for some prey
repeat from 1 one

Same schema goes with rotating :

rotate to some angle,
stop rotation
detect

xD I was wondering bout it too, but only thinking, not implemented yet!
I think that simple is best, but something advanced with faster reaction would be better!

Could you please edit this answer so that it uses correct grammar? Currently, it is hard to follow what you are trying to say.

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


text:
Problems with L293D

The motor are not rotating in the above circuit . Or rather the Voltage between the two Motor Terminal is zero. I have checked the Pin 10 & 11 and Pin 12 & 13. They are fine and produces desired Voltage.
When I have earlier connected the circuit only to one motor then it worked[ there were no motor right, Pin 12 and Pin 13]. But now, it's not.
What's the problem? The code in the arduino is as follows:
const int echo = 7;// connected to ultrasonic sensor's echo
const int trig = 8;// connected to ultrasonic sensor's trig
const int Right1 = 10;
const int Right2 = 11;
const int Left1 = 12;
const int Left2 = 13;
void setup() {
  pinMode(echo, INPUT_PULLUP);
  pinMode(trig, OUTPUT);
  pinMode(Right1, OUTPUT);
  pinMode(Right2, OUTPUT);
  pinMode(Left1, OUTPUT);
  pinMode(Left2, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(5);
  digitalWrite(trig, LOW);
  int duration = pulseIn(echo, HIGH);
  int cm = microsecondsToCentimeters(duration);
  if (cm > 4)
  {
    digitalWrite(Right1, HIGH);
    digitalWrite(Right2, LOW);
    digitalWrite(Left1, HIGH);
    digitalWrite(Left2, LOW);
  }
  else
  {
    digitalWrite(Right2, HIGH);
    digitalWrite(Right1, LOW);
    digitalWrite(Left1, LOW);
    digitalWrite(Left2, HIGH);
  }
  delay(50);
  Serial.println(cm);
}
long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}

Try these steps

Increase the delay of 50ms to a longer time.

If that fails to work try,
2.Running the motor by just directly connecting the terminal to the 9V battery which you are using.
If the motor runs then most probably the motor requires more current than what the L293D can output which as per the data sheet is 600mA. A solution to this would be using a higher current motor driver like L298N.
If the motor doesn't run directly by the battery then well change the battery to one which can supply enough current.


text:
Blink a LED between servo pulses
Apparently using delay() commands locks the Arduino during the delay period and there are better ways to control a servo that free the Arduino to do other things at the same time as running the servo.
At this point my code consists of a servo going forwards and backwards like this:
void setup()
{
  pinMode(1, OUTPUT); // makes pin 1 an output
}
void loop()
{
for(int i = 0; i<31; ++i) { //keeps in this position for about 400ms
  digitalWrite(1, HIGH); //turns the servo pin to HIGH
  delayMicroseconds(1000); //sets the servo to move clockwise
  digitalWrite(1, LOW); //turns the servo pin to LOW
  delay(19);
}

for(int i = 0; i<31; ++i) { // keeps in this position for about 400ms
  digitalWrite(1, HIGH); // turns the servo pin to HIGH
  delayMicroseconds(2000); //sets the servo to move anti-clockwise
  digitalWrite(1, LOW); //turns the servo pin to LOW
  delay(19);
}}

Where and how will I add some code that will allow the arduino to carry out another task for example blinking an led light during the approximately 20ms between servo pulses.
NOTE: The arduino is using the ATtiny 85 Processor.

Before and after the delay of 19 ms?
In setup add:
pinMode(2, OUTPUT); // LED pin output

Than changen in both cases:
  delay(19);

into
  digitalWrite(2, HIGH); // LED on
  delay(19);
  digitalWrite(2, LOW); // LED off

When you say digitalWrite(2, HIGH); // LED on, you use pin 2 but when you say digitalWrite(1, LOW); // LED off, you use pin one. Is this a typo or what?

@Utsav ... it was a type and I updated it, thanks for the notification

Short answer: don't use delay() if you want to do anything other than waiting, so rewrite your code without that call.
Long answer follows.
Instead of asking the Arduino to go to sleep (1) until a certain amount of time has passed, you should write your code to run continuously and do certain things whenever enough time has passed since the last time they have been executed.
If the previous statement makes sense to you, then the following piece of code translates to C language what I just stated in English:
unsigned long time; // stores the time when the last motor movement happened, in ms
boolean clockwise; // stores the wanted direction: true CW, false CCW
unsigned byte counter; // stores how many time the wanted movement has occurred so far

unsigned long ledTimer; // stores the last time we changed the LED state
boolean ledIsOn; // stores the current LED state
void setup() {
  pinMode(1, OUTPUT); // makes pin 1 an output
  pinMode(13, OUTPUT); // makes pin 13 (onboard LED pin) an output
}

void loop() {
  if (time - millis() >= 19) { // has enough time passed since the last time we executed a step motor movement?
    time = millis(); // reset the timer for next pass
    if (counter < 31) { // have we moved in the same direction enough?
      if (clockwise) {
        moveCW();
      } else {
        moveCCW();
      }
      counter++;
    } else { // we moved enough times in the same direction: reset the counter and switch direction
      counter = 0;
      clockwise = !clockwise;
    }
  }
  // do anything else, but don't use delay()!!!
  // the following does the same as above, but on the LED
  // blinking at 1Hz (500 ms on, 500ms off)
  if (millis() - ledTimer >= 500) {
    if (ledIsOn) {
      digitalWrite(13, LOW);
    } else {
      digitalWrite(13, HIGH);
    }
    ledIsOn = !ledIsOn;
    ledTimer = millis();
  }

  // need to do something more? go ahead and try
  // but remember not to use delay() and not to waste too much time
  // in complex calcs or the loop will take too long to wrap
}

void moveCW() {
  digitalWrite(1, HIGH); //turns the servo pin to HIGH
  delayMicroseconds(1000); //sets the servo to move clockwise
  digitalWrite(1, LOW); //turns the servo pin to LOW
}

void moveCCW() {
  digitalWrite(1, HIGH); // turns the servo pin to HIGH
  delayMicroseconds(2000); //sets the servo to move anti-clockwise
  digitalWrite(1, LOW); //turns the servo pin to LOW
}

There is a beautiful library called elapsedMillis (reference) which can reduce a bit the boilerplate code regarding subtracting millis() and all that stuff, but the code above is practically the same and, probably, more straightforward to begin with.

(1) The term sleep it's incorrect as it implies some sort of power reduction. Instead sleep() is just wasting time at full power.

I'm not sure exactly what you mean with "between servo pulses" but I am assuming it means you want to blink the led while the servo is turning.
Use the Arduino Timer library: https://playground.arduino.cc/Code/Timer
Add this at top of the sketch:
#include "Timer.h"

Timer t;
#define BLINK_TIME 20

in setup, add:
t.oscillate(LED_PIN, BLINK_TIME, HIGH);

inside the two for-loops, add:
t.update();

This will make the led on LED_PIN turn on and off every 20 milliseconds.


text:
How to interface OV5640 to Arduino Mega using Embedded C?
I am trying to interface a OV5640 camera module to Arduino Mega 2560 in Eclipse IDE using C language . However I am not able to figure out the registers that need to be initialised , for the camera to start capturing pictures .
There are Arduino libraries to deal with setup and image transfer , however I do not wish to use them . I would like to code in C , without using any library . I just need to know which registers need to be accessed and modified to get the camera working .
For reference - I am trying to create a CCTV based system that will record picture based on intruder presence . The entire project is written in C language without any libraries .
Data sheet for OV5640 -https://cdn.sparkfun.com/datasheets/Sensors/LightImaging/OV5640_datasheet.pdf
Take a look in this link to get an idea about the kind of program it'll be.
How to get 38 Khz clock from Timer 0/2 in Arduino Mega 2560?

Tackling this kind of project usually requires learning how to read data sheets for yourself.  Failing that, study the libraries until you understand what they are doing well enough to make a simpler version in plain C and change whatever else you may not like about them.  Strictly speaking, the goal of plain C development without libraries is off topic here, because "Arduino" is primarily a library-centric approach to C++ development.

Arducam gives you all the info you need on the necessary register settings. The register values for each color space and resolution are defined in this header while the initialization sequence, image format selection and image capture process among other stuff, are implemented here and documented if you look closely at the variable names and compiler directives.
EDIT: More details
Lines 327 - 372 contain the relevant initialization sequence for this specific camera. For instance, assuming you want JPG images, line 335 marks the start of the needed settings:
delay(100);
wrSensorReg16_8(0x3103, 0x11);
wrSensorReg16_8(0x3008, 0x82); delay(100);
wrSensorRegs16_8(OV5640YUV_Sensor_Dvp_Init); delay(500);
wrSensorRegs16_8(OV5640_JPEG_QSXGA);
wrSensorRegs16_8(OV5640_QSXGA2QVGA);
wrSensorReg16_8(0x4407, 0x0C);  # assuming you arent using the Arducam shield or OV5640 5MP Plus

What wrSensorReg16_8 does is pretty obvious: write the 8-bit 2nd argument into the register specified in the 16-bit 1st argument. wrSensorRegs16_8 merely does the same thing for multiple register-value pairs passed into it. OV5640YUV_Sensor_Dvp_Init, OV5640_JPEG_QSXGA and OV5640_QSXGA2QVGA are all structs defined in the header I mentioned earlier; they contain the rest of the register-value pairs you need to know about. Ultimately, these settings should give you 320x240 JPEG, I think.
You can't use the start_capture method since you don't have the ArduCAM FIFO so you'll have to start grabbing frames yourself (and buffering them somewhere very quickly; transmitting the bytes as you read them is out of the question) by paying attention to VSYNC, HREF and PCLK. Look at the timing diagrams in the datasheet. I assume you'll only be taking frames occasionally since a Mega won't do for video. If you're very lucky, you'll get a nice image on your first try but on the whole, be ready to spend serious time studying the datasheet, ArduCAM code and other 0V5640-related code on the web or just go with the OV7670 which has more examples/tutorials.

@TisteAndil thank you for those links. I could gather some idea about the required registers .however it would be nice , if you can list them in order . I'm new to embedded programming and seeing the list of registers , I feel I am gonna miss out some important register settings. So it'll be helpful if you can make a list out of those entire register set that needs to be set  .   thanks

@BoudhayanDev Edited my answer.

thanks a lot . I guess you are right . Even with these setup configuration , clicking the image and getting the data will turn out to be seriously difficult . If you have solution for that please add it in your answer .  If not it's alright . Thanks for your answer.

@BoudhayanDev You just need more experience before working on a project of this complexity. You can either work with a ready-made solution like the ArduCAM or just go ahead with your current plan, no matter how long it takes.

Thanks . You are right. I'll need to know a bit more in detail before I can succeed with this project.  One last question - which camera do you suggest ? Should I go for the 2640 ,5640 or 7640 variant ? I will be also interfacing a SD card with it to store the captured image . Which camera module is relatively simpler to work with for a beginner?  @TisteAndii

@BoudhayanDev The OV7670 is the most commonly used with Arduinos. Max resolution is 0.3MP at 640x480. Buy the module that comes with an AL422 FIFO so it can buffer frames for you and then search for tutorials that show how to set up the camera and capture frames. Memory card is only useful if you intend to take pictures occasionally or get < 5 fps video (at VGA res).


text:
Comparing 2 char converted from a array
I wrote this little program to test converting and comparing 2 char with each other. With some help from here i have learned that you have to NULL-terminate c stings. But when i try to compare them i still get that they are not equal to each other. this is my program:
char code[4] = {'1','2','3','4'};
char strcode[5];
char pass[4] = {'1','2','3','4'};
char strpass[5];

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

void loop()
{
    memcpy(strcode, code, 5);
    strcode[4] = '\0';
    Serial.println(strcode);
    Serial.println("done");
    delay(1000);
    memcpy(strpass, pass, 5);
    strpass[4] = '\0';
    Serial.println(strpass);
    Serial.println("donepass");
    if (strpass == strcode)
    {
        Serial.println("yes");
    }
    else
    {
        Serial.println("no");
    }
}

I get this in my serial monitor:
1234
done
1234
donepass
no

Why is this not equal to each other?

You cannot compare char arrays with ==. A char array, as far as your program is concerned, is just a block of memory. That memory has an address where it starts. It is that address that is stored in your array variable.
C string library functions take that address and read the block of memory starting there. However it doesn't know how big the memory block is, only where it starts. So they operate on the content up until they find the NULL character (which is why it is vitally important to NULL terminate your strings).
Comparing two char array variables with == is just comparing the addresses stored in those variables. Instead you need to compare, byte by byte, the contents of the memory starting at the specified memory addresses up until the NULL characters.
There's various functions for doing that depending on how you want to compare.
strcmp(a, b)
strncmp(a, b, n)
strcasecmp(a, b)
strncasecmp(a, b, n)

All return 0 for a == b, a negative number for a < b and a positive for a > b.
The "n" variants (e.g., strncmp) take the extra parameter giving a maximum number of characters to compare. Useful for looking at just the first few characters of a string (also useful for stopping buffer overruns).
The "case" variants are case insensitive comparisons - that is "foo" matches with "Foo" and "foO".


text:
Converting array to char
I'm trying to convert a char array to a char. i used this code
char code[4] = {'1','2','3','4'};

char strcode[4];

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

void loop()
{
    memcpy(strcode, code, 4);
    Serial.println(strcode);
    Serial.println("done");
    delay(1000);
}

But for some reason when i read my serial monitor i get this:
1234
done

Why are there 2 squares behind it?  Am I doing it wrong?
EDIT: For some reason stackexchange doesn't show the 2 squares but there are 2 squares behind 1234

C strings need to be NUL-terminated.
char strcode[5];

 ...

 ...
     ...
    strcode[4] = '\0';
     ...


text:
Arduino Due Serial Port Not Showing - Mac
Using a Mac (Big Sur 11.1)
When trying to set up the IDE I was able to install the package that contained the Due board, but the serial port for my Arduino Due isn't appearing in Tools -> Port -> Serial Ports. I did some searching and it seems that other Mac users had this problem as well.
If anyone has any tips on how to get my computer to recognize and show the serial port I'd appreciate it. I'm just getting started with these.

If your Due has an FTDI transceiver on it I'm curious to see a picture of it.  The only Due clones that I've seen, like the original, use at ATMega16u2 for the transceiver chip, in which case the FTDI drivers play no role.

Yeah that was a misstep in my end. I was just trying different things until I learned that. Now I’m wondering if it’s an issue with the OS.

It is probably best to remove that from the question then, because it just creates a rabbit hole.

Do you have anything at all attached to the board besides the USB cable?

Good suggestion. I removed it and no only the USB

It's been a while since I had much contacts with macs, but there should be a "device manager" of some sort.  USB device will list in it even if there are no drivers, wrong, drivers, etc.  You can edit into your question information regarding whatever shows up in there, or if nothing shows up at all.  Make sure you're focused on the "programming" port, since that gives the greatest chance of success.


text:
SIM phone DTMF Signal Frequency Problem
Is there a DTMF signal detection method in the smartphone [SIM] call?ex) keypad value or signal value [not frequency signal]
If you press the keypad button while you're on the phone with two iPhones, you don't hear the signal. So does the SAMSUNG phone.Please let me know how to detect DTMF signals after installing the aduino SIM.
Quectel EC25

And the manual says what?

The SIM telephone [smartphone NO] operates with the program and many telephones are automatically dialed and the voice guidance is given. Here, guide is heard and client presses the consultation -1 denial -2 number.I call my smartphone, so I need to read the DTMF signal from the received smartphone. The latest smartphone seems to be unable to read the signal.

Yes, we know what DTMF is and what it's used for. What does the manual for the Quetcel EC25 say about receiving DTMF tones?

I bought a product that used this component. I need to call, voice, and read the DTMF signal. I read the signal on the wired phone.How do we solve this?

The signal of the received Smart phone has to be read.

you are not answering the question that @Majenko is asking ... it is irrelevant why you want to detect the DTMF signal

@jsotola I have given up asking. I think he's saying it works when he uses a landline but doesn't when he uses his smartphone.

I suspect that because you're going mobile-to-mobile it's assuming it should use rfc2833  and not DTMF.

A way to get the keypad number if you press your keypad. Phone on mobile

We need to get the ivr [DTMF] signal from our customer's smartphone. It's a problem because we don't get it now. How?

How can you read the mobile touch tone?