text:
How do I adjust this?
We're supposed to create a Simon Says game for our final. My professor is telling me I shouldn't need to modify much with what I already have. but I'm so confused because it feels like starting over.
The way I have the Simon Says game now, it generates random numbers for each round but increments by one as the rounds increase. I need it to instead repeat the same sequence as the last and add a new random LED and so forth. Why is it so hard? What am I missing?
this is Arduino BTW
    int ledArray[10];
int buttonArray[10];
int loopCounter;
int ledCounter;
int inputCounter;
int game;
int waiting;
int pass;
int wait;
int timeUp;
int levelCounter[10];

//ALL THE BUTTONS & LEDS ARE GIVEN NAMES HERE SO THEY'RE EASIER TO REFERENCE
const int buttonRed = 6;
const int buttonYellow = 7;
const int buttonGreen = 9;
const int buttonBlue = 8;
const int r = 2;
const int y = 3;
const int b = 4;
const int g = 5;
const int x = 10;//LED ON PIN 10 IS THE WHITE LED USED FOR PROMPTS

///USED FOR PROCESSING AND COMPARING INPUTS
int randNumber;
int array_Cmp;

void youWin ()
{ digitalWrite(2, HIGH);
  delay(100);
  digitalWrite(2, LOW);
  delay(100);
  digitalWrite(3, HIGH);
  delay(100);
  digitalWrite(3, LOW);
  delay(100);
  digitalWrite(4, HIGH);
  delay(100);
  digitalWrite(4, LOW);
  delay(100);
  digitalWrite(5, HIGH);
  delay(100);
  digitalWrite(5, LOW);
  delay(100);
}

void ledPrompt()
//prompts player for inout during game after
//the LEDs have been picked randomly each round
{ digitalWrite(x, HIGH);
  delay(1000);
  digitalWrite(x, LOW);
  delay(50);
}

void gameHasStarted()
//LED prompt after first button
//is pushed to start the game
{
  digitalWrite(10, HIGH);
  delay(1000);
  digitalWrite(10, LOW);
  delay(100);
}

void fail() //LED sequence when the wrong input is entered
{ digitalWrite(2, HIGH);
  delay(1000);
  digitalWrite(3, HIGH);
  delay(1000);
  digitalWrite(4, HIGH);
  delay(1000);
  digitalWrite(5, HIGH);
  delay(1000);
  digitalWrite(2, LOW);
  delay(50);
  digitalWrite(3, LOW);
  delay(50);
  digitalWrite(4, LOW);
  delay(50);
  digitalWrite(5, LOW);
  delay(50);
}

void waitToStart() //cycles through LEDs while waiting to start the game
{ digitalWrite(2, HIGH);
  delay(250);
  digitalWrite(2, LOW);
  delay(250);
  digitalWrite(3, HIGH);
  delay(250);
  digitalWrite(3, LOW);
  delay(250);
  digitalWrite(4, HIGH);
  delay(250);
  digitalWrite(4, LOW);
  delay(250);
  digitalWrite(5, HIGH);
  delay(250);
  digitalWrite(5, LOW);
  delay(250);
}

int initiate()//FUNCTION WAITS FOR ANY OF 4 BUTTONS TO BE PUSHED TO START THE GAME
{ game = 0;
  waiting = 0;
  loopCounter = 1;
  randNumber = 0;
  ledCounter = 0;
  inputCounter = 0;
  pass = 2;
  //FUNCTION INCLUDES ALL OF THE ASSUMPTIONS NEEDED TO EXECUTE THE 1ST ROUND PROPERLY
  do {
    if (digitalRead(buttonRed) == LOW)
    { game = 2;
      gameHasStarted();
    }
    if (digitalRead(buttonGreen) == LOW)
    { game = 2;
      gameHasStarted();
    }
    if (digitalRead(buttonBlue) == LOW)
    { game = 2;
      gameHasStarted();
    }
    if (digitalRead(buttonYellow) == LOW)
    { game = 2;
      gameHasStarted();
    }
    else {
      waitToStart();
    }
  }
  while (game <= 1);
  delay(1000);
}//END OF GAME INITIATOR FUNCTION

int pickLed ()//FUNCTION WILL PICK A RANDOM LED
{
  do {
    randNumber = random(2, 6);
    digitalWrite(randNumber, HIGH);
    delay(500);
    digitalWrite(randNumber, LOW);
    delay(100);
    if (randNumber == 2)
    { ledArray[loopCounter] = 0;
      ledCounter++;
    }
    if (randNumber == 3)
    { ledArray[loopCounter] = 1;
      ledCounter++;
    }
    if (randNumber == 4)
    { ledArray[loopCounter] = 2;
      ledCounter++;
    }
    if (randNumber == 5)
    { ledArray[loopCounter] = 3;
      ledCounter++;
    }
  }
  while (ledCounter < loopCounter);
  ledPrompt();//signals for input after it's done picking the LEDs for each round
  wait == 1;
}//END OF PICKLED FUNCTION

int waitForInput ()//FUNCTION WILL WAIT FOR USER INPUT OR END GAME AFTER 10 SECONS OF NO INPUT
{
  do
  {
    if (digitalRead(buttonRed) == LOW)
    { digitalWrite(r, HIGH);
      inputCounter++;
      delay(150);
      digitalWrite(r, LOW);
      delay(150);
      buttonArray[loopCounter] = 0;
    }
    if (digitalRead(buttonYellow) == LOW)
    { digitalWrite(y, HIGH);
      inputCounter++;
      delay(150);
      digitalWrite(y, LOW);
      delay(150);
      buttonArray[loopCounter] = 1;
    }
    if (digitalRead(buttonBlue) == LOW)
    { digitalWrite(b, HIGH);
      inputCounter++;
      delay(150);
      digitalWrite(b, LOW);
      delay(150);
      buttonArray[loopCounter] = 2;
    }
    if (digitalRead(buttonGreen) == LOW)
    { digitalWrite(g, HIGH);
      inputCounter++;
      delay(150);
      digitalWrite(g, LOW);
      delay(150);
      buttonArray[loopCounter] = 3;
    }
    else {
      wait++; //the wait counter is incremented each time the loop reads all 4 input and no input has been made
      delay(250);
    }//the delay here adds 1/4th of a second each time no input is made (every 4 loop here is 1 second);

    if (wait > 40) //40 divided by 0.25 = 10 seconds of wait
    {
      pass = 0;
      fail();
    } //after waiting 10 seconds for input the game automatically fails.
  }
  while (inputCounter < loopCounter);//WAIT FOR INPUT
}   //END OF WAIT_FOR_INPUT FUNCTION

int scoreInput ()//START OF SCORE_INPUT FUNCTION
{ if (memcmp(ledArray, buttonArray, sizeof(ledArray)) == 0)
  {
    delay(1000);
    loopCounter++;
    ledCounter = 0;
    inputCounter = 0;
    game++;
    pass = 2;
  }
  else
  {
    loopCounter = 0;
    ledCounter = 0;
    inputCounter = 0;
    pass = 0;
  }
}
//END OF SCORE_INPUT FUNCTION

void setup ()
{ randomSeed(analogRead(0));
  pinMode (r, OUTPUT);
  pinMode (y, OUTPUT);
  pinMode (b, OUTPUT);
  pinMode (g, OUTPUT);
  pinMode (buttonRed, INPUT_PULLUP);
  pinMode (buttonYellow, INPUT_PULLUP);
  pinMode (buttonGreen, INPUT_PULLUP);
  pinMode (buttonBlue, INPUT_PULLUP);
  pinMode (buttonRed, INPUT);
  pinMode (buttonYellow, INPUT);
  pinMode (buttonGreen, INPUT);
  pinMode (buttonBlue, INPUT);
  pinMode (x, OUTPUT);
  game = 0;
  waiting = 0;
  loopCounter = 1;
  randNumber = 0;
  ledCounter = 0;
  inputCounter = 0;
  pass = 2;
  timeUp = 2;
  initiate();
}

void loop ()//by using functions, the void loop section here is very short.
{
  do {
    pickLed();
    waitForInput();
    scoreInput();
    levelCounter++;
    if (loopCounter > 4)//states the game should end after round 10
    { youWin();
      pass = 0;
    }
  }
  while (pass > 1); // keeps the game going until round 10 or fail
  initiate();
}

sorry I could't post the code properly.

why would you generate numbers at the begining of each round?

It generates a random number for the 1st round and then the next round it generates 2 numbers and so forth. That's how I have it now. The problem is the numbers are different for each round which is wrong. My professor wants the numbers to be same as the last round but with a new random LED generated

that describes what the program does, which you already decribed in your post ... i did not ask for a description .... think about what i asked ... hint: why do you generate only one number before the first round?

Idk how to generate 10 randomly. I've tried the for loop but I don't know and it just sucks but I gave up

you have the right idea ... what does this mean? ... I've tried the for loop but I don't know  .... there are several lines in your code that should give you some ideas ... here is one of them ... buttonArray[loopCounter] = 3;

The thing is that the game works but it doesn't repeat the same sequence each round. It gives a nee random set with each round

i was wrong, you do not understand ... another hint: it doesn't repeat the same sequence each round ... then do not generate the sequence at each round


text:
Powering LED Strip at both ends shorts my psu?
I've got a 200 LEDs strip of sk9822's hooked up to a 5V 8A power supply.
As expected, at full white, there's considerable voltage drop and the far end of the strip turns from white to amber.
I wanted to hook up another set of V+ and GND at the far end of the strip, but doing so trips my psu? The strip blinks full white as a result.
Hooking up ONLY GND or ONLY V+ at the far end significantly improves the drop off where only the middle of the strip turns slightly amber-ish.
But! I do notice a faint buzzing from the PSU if I do this.
Am I doing something wrong here?

difficult to guess if you did something wrong ... you did not say how you connected everything up ... please draw a diagram

Assuming 60mA per led (20mA per colour) you would need a minimum 12A power supply, not 8A. Your PSU is too weak.

What if you only power it at the middle?
But indeed, your PSU may not be able to supply the whole strip, the reason it blinks is that it shuts off on it's limit and starts back up again.
If you really would have shorted it; I think the strip itself would have behaved differently.

Basically, the idea is right. Powering from both ends is fine and will fix (at least enhance) the voltage drop problem. Still, Majenko is right. With 8A you shouldn't let them shine in full white. Some colors might work, though.

Put a diode to every psu cable or just take only one psu but make a connection between the input and the far end eith a cable of more than 0,5 mm^2... Spesker csble or so.
Problem with two psu is: one gives 5,00 Volt,  the other 5,05... And there is s power of 0,05 Volt / 8 Ampere running.
Second problem can be the influrnce of different PSU switching frequencies.
Regards,  Michael

Why do you assume two different PSUs? As far as I understood, he wants to power it with 1 PSU but 4 connectors (2 on one end, 2 on the other end).

source: Stack Exchange

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

sort: votes


text:
I need to Get my changed SSID and Password in my Serial monitor
I have this(Wifi Manager - Autoconnect IP) program run in my arduino IDE. And I get the output in serial monitor as this

Can Anyone help me in displaying my SSID and PASS in this serial monitor output?
My code is this
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);

    //WiFiManager
    //Local intialization. Once its business is done, there is no need to keep it around
    WiFiManager wifiManager;
    //reset saved settings
    //wifiManager.resetSettings();

    //set custom ip for portal
    //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

    //fetches ssid and pass from eeprom and tries to connect
    //if it does not connect it starts an access point with the specified name
    //here  "AutoConnectAP"
    //and goes into a blocking loop awaiting configuration
    wifiManager.autoConnect("AutoConnectAP");
    //or use this for auto generated name ESP + ChipID
    //wifiManager.autoConnect();

    //if you get here you have connected to the WiFi
    Serial.println("connected...yeey :)");
}

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

}

I am using WIFImanager library example - Autoconnect

https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html#ssid

Thank you for the link juraj.. btw where should I add that line of code. In the main program or in the header file??

You can use functions SSID() and psk() which are available on the WiFi object as documented here.
Put these lines in setup() after wifiManager.autoConnect:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
Serial.print("psk: ");
Serial.println(WiFi.psk());

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


text:
I am interfacing Amonia Sensor RS485 output with Arduino Mega . not getting any response
I am interfacing Amonia Sensor RS485 output  with Arduino Mega but not getting any response. i need to transmit  {0x06, 0x03, 0x00, 0x00, 0x00, 0x04, 0x45, 0xBE};
frame to sensor then senor will send response frame. i am using Max485 converter which has DE RE pins .could you guide ME to write proer code. please help me i am in trouble
#include <SoftwareSerial.h>

#define SSerialRX        0
#define SSerialTX        1

#define modbusModuleDE   8
#define modbusModuleRE   9

SoftwareSerial RS485Serial(SSerialRX, SSerialTX);
byte byteSend;

//ModbusMaster node;

void setup()
{

 Serial.begin(9600);

 pinMode(modbusModuleRE , OUTPUT);
 pinMode(modbusModuleDE , OUTPUT);

  Serial.println("..... ");

  delay(10);

}

byte buf[8];
void loop()
{

     Serial.print("NH: ");
digitalWrite(modbusModuleDE, 1);
 digitalWrite(modbusModuleRE, 1);
 delay(10);
     byte request[] = {0x06, 0x03, 0x00, 0x00, 0x00, 0x04, 0x45, 0xBE};
     RS485Serial.write(request, sizeof(request));
     RS485Serial.flush();
  digitalWrite(modbusModuleDE, 0);
 digitalWrite(modbusModuleRE, 0);
 delay(10);
     RS485Serial.readBytes(buf, 8);

     Serial.print("DATA:");
    Serial.println(buf[3], HEX);Serial.println(buf[4], HEX);

    delay(1000);

}

help you with what? ... you said nothing about any problem

arduino coding . i wan to transmit data frame to my sensor  {0x06, 0x03, 0x00, 0x00, 0x00, 0x04, 0x45, 0xBE};  then sensor will send me its value. i am not able send proper command through arduino master. can check my code @jsotola


text:
Arduino Zero to Arduino Zero SPI configuration
I am in the planning stage of chaning two ATSAMD21 with a Zero or Nano 33 bootloade r in a SPI connection. The rational for this is that i am in need of 30 pin GPIO expansion and using 2 mcp23s17 takes a fair bit amount of space and also slightly bit more expensive. Since the ATSAMD21 has theoretical 37 GPIOs why not use that. having not owned a zero board yet, i would like to know if:
Is it easily doable, just connecting the appropriate pins?
If so, i have read in the Arduino SPI documentation that the zero doesnt have any Slave Select for Master and Slave, does this mean i can use whatever i want? And just code it to detect that pin
Does the built in SPI library capable of handling the slightly higher clock speed of the zero ?

A zero has the same number of IO pins then a UNO, they use the same header layout. So I believe you want to use the chips on a self made PCB. (?)
Based on this, I think a second SAMD21 is not the best solution.
They are easily connectable as they use the same Voltage. I used the SPI lib on a zero, so yes, I think its programmable with Arduino techniques. And you can use a CS pin of your choice. The SPI lib uses Arduino header files for the selected platform. So the MCU clock speed shouldn't be a problem.
But you have to program the master and the slave and maintain this firmware. An MCP23(s/0)17 is ready to use.
Two MCP23S17 (QFN packages) don't take that much space.
SAMD21 is capable of driving max. 3.6 V; MCP can handle 5.5 V. (But if you want to use 5V you have to level shift the connection between your Arduino zero and the MCP.
And adding two more MCP23S17 is way easier that adding a third SAMD21, when even the old firmware must be reprogrammed.
A MCP23S17 can drive and sink 25 mA on each pin.
A SAMD21 can handle 14 mA source current and 19.5 mA sink current per IO cluster (there are 6 clusters each of them has between 2 and 16 pins).
On the other hand, if you are sure, you don't need more than 3.6 volts and ~1 mA per pin and the number of the additional IO pins is enough, there is no reason not to use a second SAMD21.
If you need capacitive  touch pins, or more I2S ports or other capabilities of the SAMD21, then the second SAMD21 is even the better choice.
Have you seen the Arduino DUE? It has all the features of a zero and way more IO pins (54) and 12 analog inputs and 2 real analog outputs.

Correct i will use it on a custom PCB. I am still in the planning phase and evaluating my options, I really like your arduino DUE suggestion this will make things a lot mor easier, It even has a faster clock speed ! Will check the chip its using, and how complicated is its minimal components

If you have experience using the DUE. do you know what is the purpose of the ATMEGA16U2 microcontroller? and can it be removed?

The DUE has two USB ports. The native port is directly added to the SAMD Controller and the programming port is connected to the U2 chip. The U2 chip is responsible for the programming over the serial port and also for ICSP programming over the ICSP1 header. It is also possible to program the DUE over the native port. The SAMD of a DUE can only be programmed if the FLASH has been erased before. And the boot loader on the U2 chip does this for you automatically. If you use the native port it's up to you to erase the Flash memory.

Hello i made some progress since my last reply and would like to talk about it more in chat

unfortunately im having a difficult time creating one, I will just replying here until the pop up  pops up.
About that erasing the flash memory on the arduino due's documentation you have to open and close serial at 1200bps, how can this be simply achieved in hardware?


text:
ESP8266 Webserver ESP8266WebServer variable html page (not as one const char)
The aim is to display a non-static html page depending on some variable condition.
The code I created hast the problem, that the esp8266 is ressetting in the moment I request the page.
const char htmlIndexHeader[] PROGMEM = R"=====(

    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>

Hello World

)=====";

const char htmlIndexProgress1[] PROGMEM = R"=====(

lorem

)=====";

const char htmlIndexProgress2[] PROGMEM = R"=====(

ipsum

)=====";

const char htmlIndexFooter[] PROGMEM = R"=====(

)=====";

char htmlIndexAll[2000];

void handleRoot()
{
  Serial.println("GET /");

   strcpy(htmlIndexAll, htmlIndexHeader);

   if(var1==true)
   {
     strcat(htmlIndexAll, htmlIndexProgress1);
   }

   if(var2==true)
   {
     strcat(htmlIndexAll, htmlIndexProgress2);
   }

   strcat(htmlIndexAll, htmlIndexFooter);

  server.send(200, "text/html", htmlIndexAll);
}

If I display a static page the esp8266 does not restart at page request.

try strcpy_P and strcat_P

@Juraj it is working!

Compiler can't differentiate the PROGMEM strings from constant strings in SRAM strings. Both are const char*. But the PROGMEM string must be handled differently. For that reason _P variants of functions exists.
You should use stcpy_P and strcat_P functions.
Note: On esp8266 some functions of Arduino core use a trick to identify PROGMEM strings by their specific address range.


text:
How can I combine this two codes in one program? And use it in javafx application
The first one reads from sensors and displays it, the second code receives an incoming byte to control LEDs. I tried to combine it but i don't know why it doesn't work. Please help me out. I need it for my project to run both of them.
In my java netbeans i have two GUIs. For monitoring(first code) and controlling(second). I want it both to run with only one combined code in arduino.
I tried to use if else statement for the arduino to know what to do. Not working also. I think i just missed something
const int model = 0;

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

}

float sensitivity[] ={
      0.185,// for ACS712ELCTR-05B-T
      0.100,// for ACS712ELCTR-20A-T
      0.066// for ACS712ELCTR-30A-T

     } ;

void loop() {
static unsigned long count=0;
static float Vsum=0;
float Vave=0;
int volt = analogRead(A1);

float voltage= map(volt,0,1023, 0, 2500)/100.0;
Vsum=Vsum+voltage;

static float Csum=0;
float Cave=0;
 float milli = pow(10, -3);
 float current = (voltage / sensitivity[model]);
 float current1 = current*milli;

Csum=Csum+current1;
count++;
Vave=Vsum/count;
Cave=Csum/count;
float watts = Vave*Cave;

long milisec = millis();
long time=milisec/1000;

 float energy = (watts*time)/3600;
Serial.print(energy,6);
Serial.println("Wh");
delay(1000);

}

And this is the second code. This receives byte from java to control LEDs
int incomingByte;

void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(0, OUTPUT);

}

void loop() {
 // if (Serial.available()>0) {
    incomingByte = Serial.read();

    if(incomingByte == 0x01){
      digitalWrite(13, HIGH);
     Serial.println("ON");

    }else if(incomingByte == 0x00){
      digitalWrite(13, LOW);
       Serial.println("OFF");
    }

    if(incomingByte == 0x02){
      digitalWrite(12, HIGH);
    }else if(incomingByte == 0x03){
      digitalWrite(12, LOW);
    }

    if(incomingByte == 0x04){
      digitalWrite(11, HIGH);
    }else if(incomingByte == 0x05){
      digitalWrite(11, LOW);
    }

    if(incomingByte == 0x06){
      digitalWrite(10, HIGH);
    }else if(incomingByte == 0x07){
      digitalWrite(10, LOW);
    }

    if(incomingByte == 0x08){
      digitalWrite(9, HIGH);
    }else if(incomingByte == 0x09){
      digitalWrite(9, LOW);
    }

    if(incomingByte == 0x10){
      digitalWrite(8, HIGH);
    }else if(incomingByte == 0x11){
      digitalWrite(8, LOW);
    }

    if(incomingByte == 0x12){
      digitalWrite(7, HIGH);
    }else if(incomingByte == 0x13){
      digitalWrite(7, LOW);
    }

    if(incomingByte == 0x14){
      digitalWrite(6, HIGH);
    }else if(incomingByte == 0x15){
      digitalWrite(6, LOW);
    }

    if(incomingByte == 0x16){
      digitalWrite(5, HIGH);
   }else if(incomingByte == 0x17){
      digitalWrite(5, LOW);
    }

    if(incomingByte == 0x18){
      digitalWrite(4, HIGH);
    }else if(incomingByte == 0x19){
      digitalWrite(4, LOW);
    }

    if(incomingByte == 0x20){
      digitalWrite(3, HIGH);
    }else if(incomingByte == 0x21){
      digitalWrite(3, LOW);
    }

    if(incomingByte == 0x22){
      digitalWrite(2, HIGH);
    }else if(incomingByte == 0x23){
      digitalWrite(2, LOW);
    }

    if(incomingByte == 0x24){
      digitalWrite(1, HIGH);
    }else if(incomingByte == 0x25){
      digitalWrite(1, LOW);
    }

    if(incomingByte == 0x026){
      digitalWrite(0, HIGH);
    }else if(incomingByte == 0x027){
      digitalWrite(0, LOW);
    }

  delay(100);
}

This is my sample code from javafx application
    try {
        if (tbLED12.isSelected()) {
            if (arduinoPort != null) {
                arduinoPort.writeByte((byte) 0x02);
                System.out.println("LED 12 ON");
            } else {
                System.out.println("arduinoPort not connected!");
            }
        } else {
            if (arduinoPort != null) {
                arduinoPort.writeByte((byte) 0x03);
                System.out.println("LED 12 OFF");
            } else {
                System.out.println("arduinoPort not connected!");
            }
        }
    } catch (SerialPortException ex) {
        Logger.getLogger(JavaFXApplication11.class.getName())
                .log(Level.SEVERE, null, ex);
    }

You didn't show us your combined code, so we cannot say, what is wrong with it. There are plenty of question like "Need to combine these two codes" on this site. Have you looked into them?

sorry but i cant add my combined code coz its too long but i just add my first code to the second one and it became faulty, but if i run them separately they work well.

don't set pinmode for 0 and 1. it is Serial RX and TX.

Even if you simply put both codes in one file, that shouldn't be too long for the question editor. Otherwise you should create a minimal complete example. Asking how to combine 2 codes without the problematic combined code is a very broad and general question, that was asked and answered many times here. Without your combined code and descriptions about how it is faulty, every answer to prone to a long comment discussion to get to the bottom of the problem (as we see with Peters answer below). This site is not good for this; it's not a forum.

Combining this code is all about synchronizing the reading of the sensors with the control sequences that are sent from the Java program.
The second program reads the Serial port continuously in the loop method. A better way would be to use a serial interrupt for this. Let me give you an example.
My code is written without an IDE so it is just an untested example. But hopefully I did not include errors ;-).
I use the first program as a base:
const int model = 0;
float sensitivity[] = {
  0.185,// for ACS712ELCTR-05B-T
  0.100,// for ACS712ELCTR-20A-T
  0.066// for ACS712ELCTR-30A-T
} ;

unsigned long count = 0;
float         Vsum  = 0;
float         Csum  = 0;

long startTime = 0;

void setup()
{
  Serial.begin(9600);
  // setting the LED pins to output
  // I use a loop
  for ( int i = 2; i < 14; i++ )
  {
    pinMode( i, OUTPUT );
  }
}

void loop()
{
  float Vave = 0;
  float Cave = 0;
  // pow is to expensive for the loop
  // I use a constant
  float milli = 0.001;

  if ( startTime = 0 ) startTime = millis();

  float voltage = map( analogRead( A1 ), 0, 1023, 0, 2500 ) / 100.0;
  Vsum = Vsum + voltage;

  float current  = ( voltage / sensitivity[ model ] );
  float current1 = current * milli;

  Csum = Csum + current1;

  count++;

  Vave = Vsum / count;
  Cave = Csum / count;
  float watts = Vave * Cave;

  // you did not use a time delta here,
  // but energiy it work over a time period
  long timeDelta = ( millis() - startTime ) / 1000;

  float energy = ( watts * timeDelta ) / 3600;
  Serial.print( energy, 6 );
  Serial.println( "Wh" );

  serialHandler();

  delay( 1000 );
}

void serialHandler()
{
   delay( 200 );
   while ( Serial.available() )
   {
     // get the new byte:
     int inByte = Serial.read();

     if(inByte == 0x01)
     {
       digitalWrite(13, HIGH);
       //Serial.println("ON");
     }
     else if(inByte == 0x00)
     {
       digitalWrite(13, LOW);
       //Serial.println("OFF");
     }
     else if(inByte == 0x02) digitalWrite(12, HIGH);
     else if(inByte == 0x03) digitalWrite(12, LOW);
     else if(inByte == 0x04) digitalWrite(11, HIGH);
     else if(inByte == 0x05) digitalWrite(11, LOW);
     else if(inByte == 0x06) digitalWrite(10, HIGH);
     else if(inByte == 0x07) digitalWrite(10, LOW);
     else if(inByte == 0x08) digitalWrite(9,  HIGH);
     else if(inByte == 0x09) digitalWrite(9,  LOW);
     else if(inByte == 0x10) digitalWrite(8,  HIGH);
     else if(inByte == 0x11) digitalWrite(8,  LOW);
     else if(inByte == 0x12) digitalWrite(7,  HIGH);
     else if(inByte == 0x13) digitalWrite(7,  LOW);
     else if(inByte == 0x14) digitalWrite(6,  HIGH);
     else if(inByte == 0x15) digitalWrite(6,  LOW);
     else if(inByte == 0x16) digitalWrite(5,  HIGH);
     else if(inByte == 0x17) digitalWrite(5,  LOW);
     else if(inByte == 0x18) digitalWrite(4,  HIGH);
     else if(inByte == 0x19) digitalWrite(4,  LOW);
     else if(inByte == 0x20) digitalWrite(3,  HIGH);
     else if(inByte == 0x21) digitalWrite(3,  LOW);
     else if(inByte == 0x22) digitalWrite(2,  HIGH);
     else if(inByte == 0x23) digitalWrite(2,  LOW);
     //else if(inByte == 0x24) digitalWrite(1,  HIGH);
     //else if(inByte == 0x25) digitalWrite(1,  LOW);
     //else if(inByte == 0x26) digitalWrite(0,  HIGH);
     //else if(inByte == 0x27) digitalWrite(0,  LOW);
   }
}

EDIT:
I changed the code a little bit according to Juraj comments. I also
commented the `Serial.println' s that had reported the LED 13 state.

serialEvent is not an interrupt. outside the loop() the core tests Serial.available() and if is not 0 it calls serialEvent() .

I cannot control the LEDs. One LED only will light up when i run the program even though i switched them all on. But the monitoring works

@Juraj And again, i learned something. Meanwhile I'm at home and could try out my program, and it didn't worked as I expected. And you gave the explanation. And now I feel sad and thinking about the ice cream in my refrigerator and if I should eat it. Hmmm yes I'll do that. But before I find a better solution for the problem. Perhaps I renmae the funtion, wait a little bit after sending the values to java and then trigger the former event callback. Then I wait one second and once again.

@RicaJacutina Which LED does work, 13 perhaps? Thats the built in LED. Did you connect the others correctly. Are you sending the right values? Are you aware that for LED 13, you have to send an odd value (1) to switch it on. The others are switched on by even values ( 2,4,6,8,10,12,). This functionallity should work I tried it a few minutes ago with my own setup.

@PeterPaulKiefer I tried your code, The monitoring works but when i control LED it does not work properly on my java gui. Yes the 13 switched on, but does not switch off. When i tried to run the program again, no LED worked. :( I am aware that 13 light up to odd value and others on even values. And i am sure that i connected it all the right way.

@RicaJacutina There is one thing I'm unsure about and that's: Can the Java GUI handle the String "ON" and "OFF" you send with Serial.println("OFF"); or Serial.println("ON");? (in the LED 13 cases) Perhaps your GUI crashes because it does not receive values, And then, will not not send the other control values? Have the send backs some meaning or can you savely removed them? Then, please try removing them. Or do not control LED 13 only the other ones, to see if that works.  BTW: Is the Java GUI a Processing application?

I am using javafx application. I added my my java code above. The third one

The interesting part is the receiving part. Not the sending part. What happens if the your program receives the string "ON" when the LED 13 is set on? Can that lead to an exception that closes the Serial port for example. Have you seen @Juraj comment to your Question. That's something I've complete missed. As pins 0 and 1 are used for the serial connection, you can not use it to drive LEDs. I will change my code a littlle bit. Perhaps then it works for your setup.

@RicaJacutina So; I changed the code. But the LEDs 0 and 1 won't work with that version.

void serialEvent();
const int model = 0;
float sensitivity[] = {
  0.185,// for ACS712ELCTR-05B-T
  0.100,// for ACS712ELCTR-20A-T
  0.066// for ACS712ELCTR-30A-T
} ;

unsigned long count = 0;
float         Vsum  = 0;
float         Csum  = 0;
float         DecPowerRate = 9.8623 ;//kWh
long          startTime = 0;
float         no_voltage = 0.00;
//float           address = 0;
float         no_CURRENT = 0.000;
float energy;
long timeDelta;float consumption;float Kwatts;
void setup()
{
  Serial.begin(9600);
  // setting the LED pins to output
  // I use a loop
  for ( int i = 2; i < 14; i++ )
  {
    pinMode( i, OUTPUT );
  }
}

void loop()
{
  float Vave = 0;
  float Cave = 0;
  float milli = 0.001;// pow is to expensive for the loop

  if ( startTime = 0 ) startTime = millis();

  float voltage = map( analogRead( A1 ), 0, 1023, 0, 2500 ) / 100.0;

  if( voltage >no_voltage){
  Vsum = Vsum + voltage;

  float current  = ( voltage / sensitivity[ model ] );
  float current1 = current * milli;

  Csum = Csum + current1;

  count++;

  Vave = Vsum / count;
  Cave = Csum / count;
  Kwatts = (Vave * Cave)/1000;
  }
    if (Cave >no_CURRENT){
  // you did not use a time delta here,
  // but energiy it work over a time period
  timeDelta = ( millis() - startTime ) / 1000;
  energy = ( Kwatts * timeDelta ) / 3600;
  consumption = energy * DecPowerRate;
}

  //Serial.print( energy, 6 );
 // Serial.println( "kWh" );

  Serial.print( "P " );
  Serial.print( consumption, 6 );
  Serial.println( "/kWh" );
  delay( 1000 );

}
// naming convention for a serial interrupt
void serialEvent()
{
   while (Serial.available())
   {
 // get the new byte:
 int inByte = Serial.read();

 if(inByte == 0x01)
 {
   digitalWrite(13, HIGH);
   //Serial.println("ON");
 }
 else if(inByte == 0x00)
 {
   digitalWrite(13, LOW);
   //Serial.println("OFF");
 }
 else if(inByte == 0x02) digitalWrite(12, HIGH);
 else if(inByte == 0x03) digitalWrite(12, LOW);
 else if(inByte == 0x04) digitalWrite(11, HIGH);
 else if(inByte == 0x05) digitalWrite(11, LOW);
 else if(inByte == 0x06) digitalWrite(10, HIGH);
 else if(inByte == 0x07) digitalWrite(10, LOW);
 else if(inByte == 0x08) digitalWrite(9,  HIGH);
 else if(inByte == 0x09) digitalWrite(9,  LOW);
 else if(inByte == 0x10) digitalWrite(8,  HIGH);
 else if(inByte == 0x11) digitalWrite(8,  LOW);
 else if(inByte == 0x12) digitalWrite(7,  HIGH);
 else if(inByte == 0x13) digitalWrite(7,  LOW);
 else if(inByte == 0x14) digitalWrite(6,  HIGH);
 else if(inByte == 0x15) digitalWrite(6,  LOW);
 else if(inByte == 0x16) digitalWrite(5,  HIGH);
 else if(inByte == 0x17) digitalWrite(5,  LOW);
 else if(inByte == 0x18) digitalWrite(4,  HIGH);
 else if(inByte == 0x19) digitalWrite(4,  LOW);
 else if(inByte == 0x20) digitalWrite(3,  HIGH);
 else if(inByte == 0x21) digitalWrite(3,  LOW);
 else if(inByte == 0x22) digitalWrite(2,  HIGH);
 else if(inByte == 0x23) digitalWrite(2,  LOW);

   }
}

This worked! Thanks for the help! <3


text:
Continuous servo speed control with Arduino Uno controller and servo shield
It is very simple device, 2 continuous servos FS5113R, rotates continuously in one direction. Here is device original content, which is this servo shield it looks like russian, and here is library, I have added to Arduino IDE, also I have original code, which runs this device, given below.
I'm trying to figure out, what can I do with speed, to run it slower, I've tried change  delay(15); number to 1000, but it moves with same speed.  I've tried  increment variable  in  while (z < 2) loop and pass it with interval, but speed is same:
#include <Wire.h>
#include <Multiservo.h>

#define SERVO_COUNT 2

Multiservo servo[SERVO_COUNT];

int pos1 = 0;
int pos2 = 0;

int z = 1;

void setup(void)
{
  Wire.begin();

  for (int i = 0; i < SERVO_COUNT; ++i)
  {
    servo[i].attach(i);
    servo[i].write(0);
  }
}

void loop(void)
{
    while (z < 2){
        pos1 + 1;
        pos2 + 1;
        servo[1].write(pos1);
        servo[2].write(pos2);
        delay(15);
    }
}

Any advice, guide or example would be useful

It is unclear what exactly you are trying to achieve. You never change pos1 or pos2, thus the speed doesn't change. Try doing pos1++; instead of pos1 + 1

@chrisl Hello, same behavior with pos1++, but I'm trying rotate motor slower, example above shows exist code, which runs servos with given speed

If you use the above code with a continuous rotation servo, the servo will first rotate in one direction, getting slower (1.3 seconds duration), then changing rotation direction (as the value goes through 90), then getting faster for 1.3s and then keeping this speed, until pos1 and pos2 overflow. This would take 136h. Is this, what you are seeing? Since the servo cannot change direction very fast, that movement wouldn't be very strong, maybe just a long twitch at the start of the program

@chrisl I see movement of both motors always in one direction without changing direction as required, but too fast, code above is default  for device. My goal is to make movement   in one direction,  but with a slower  speed, same way as it is done, except for the behavior that you described, although I did not checked it for 136h

The speed of your servo is controlled by the pulswidth of a square wave signal. According to the datascheet of the servo the motor stops on a pulsewith of about 1500 µSec (+- 5 µSec).
From 1500 to 900 μSec the motor turns clock wise. And it getting faster with decreasing pulsewidth.
From 1500 to 2100 μSec the motor turns counter clock wise. And it getting faster with increasing pulsewidth.
Next we have to check whether your shield and the library can handle that values and which value you have to give to the servo[i].write(?) function. I can read cyrillic but I do not understand russian good enough to read the f. manual. So I have to look into the code on GitHub (https://github.com/amperka/Multiservo/blob/master/library/Multiservo ).
Et voila:
Multiservo::attach(int pin, int minPulse, int maxPulse)

You can define the min and max pulseWidth, that's great. Let's do it:
#include <Multiservo.h>
#define SERVO_COUNT 2

Multiservo servo[SERVO_COUNT];
// speed is 0 ( full speed CW )
int speed = 0;

void setup(void)
{
  for (int i = 0; i < SERVO_COUNT; ++i)
  {
    servo[i].attach( i, 900, 2100);
    // 900 - 2100 is mapped from 0 to 180
    // so 90 is the middle where the motor stopps
    // 180 the motor runs as fast as possible CCW
    // 0 the motor runs as fast as possible CW
    servo[i].write( speed );
  }
}

void loop(void)
{
   // Here I halt the program if the motor stops.
   // If you use a lower value than 89 you can halt the program
   // at the corresponding speed. If you use a higher value instead of 89
   // the motor starts rotating counter clockwise.
   // Do not use a value greater then 179 or less than 1.
   if ( ++speed > 89 ) speed = 90;

   servo[1].write( speed );
   servo[2].write( speed );

   delay(25);
}

Ah, of cause I have not hte hardware, so I can not test the program. Use it as an example.

Hello, thank you for your answer. As I've said I want change code for this device to make move both servos always in one direction with slower speed, but now I'm not able to check your example, because seems like this shield is damaged, besides, I don't understand russian either, so I've to change this device very soon and check upload with your code, then I will comment about result to mark you answer


text:
Running in loop or once according to a slide switch position
I have a question.
I made a system which includes a servo, a stepper and a wiper motor :)
All these parts has one job to do and I can code it. But, I want to make 2 modes in this system Single Operation, Loop operation.
for example position 1-single operation, 2-loop operation.
I can code the loop operation thanks to arduino syntax :)
But I cannot code single one. I can read switch state detection.  I want to do exactly same things, but only one time when slide switch on the position.
The code is really long and it includes Turkish defines. If you need to see the code, let me know.

Let's assume the switch is on pin 9, that the pinMode() has already been set, and that the switch reads HIGH for loop operation.
#define MODE_SWITCH  9
#define DO_LOOP  HIGH

// This loop will execute once if the mode-switch is off, or
// will execute continously if the mode-switch is on:
do {
  servo_things();
  stepper_things();
  motor_things();
} while( digitalRead(MODE_SWITCH) == DO_LOOP );

in C/C++, 'do-while' loops always execute at least once, since the condition isn't tested until after the first pass through the loop. If the 'while' condition is satisfied (or TRUE), the loop will execute again, otherwise the loop will exit.

I think you should do a digitalRead() inside the while condition. I think you meant that and only wrote it simplified, but since this isn't written in pseudo code, others might copy the code directly, what means to compare 9 to 1, which is always false.

Good catch, @chrisl - that was exactly right. Tthanks. Fixed now.

I'll try this. Thanks to you


text:
programming STM32 with arduino IDE issues
I'm currently trying to program an STM32 with arduino, but along the way, i encountered some issues with pin modes. To be more specific, programming certain pins to certain modes. Some pins have consistent digital outputs like PC13, while others have wonky outputs like PA11 and PA12, despite being able to be used as digital outputs.

here is what i get from PA12

here is what i get from PA11
i've read the pinout diagrams, and im not too sure if both mentioned pins can be used digitally according to this pinout diagram :

can anyone help me explain what is going on, how do i program an STM32 with Arduino IDE exactly (stm32duino programming procedures, rule of thumb, etc), and can an stm32duino be used to do complex programs like an arduino like for example driving a motor with PWM in a balancing robot or do we have to use C or C++ using atollic TrueSTUDIO and all of those software?

In both images, it looks like you are reading and printing PA0. It's normal for a floating pin to read random 1's and 0's.

others have wonky outputs like PA11 and PA12, despite being able to be used as digital outputs.

As the pinout diagram you included in the question yourself shows, PA11 and PA12 provide the USB interface.
You can't use those pins for both USB and other GPIO roles at the same time.
Your Arduino core and add-on bootloader are presumably using the USB port for programming and communication with the host PC.  Custom projects which did not use the pins for USB would be possible, but you'd likely be largely on your own and unable to use those particular Arduino components (or at least not without heavily modifying them).
There are other pins which have key purposes, too, for example those which support external clock crystals, those which provide the SWD debug interface, those which could provide serial UART output, etc - some designs can use these as generic I/O's but only by forgoing the unique functionality which many designs need them to provide.


text:
EEPROM page rotates while writing to it
The following code intends to read from serial port and write the data byte by byte to a 24LC01B EEPROM.
// 24LC01B PINS
// Pin 1, A0: float
// Pin 2, A1: float
// Pin 3, A2: float
// Pin 4, VSS: GND
// Pin 5, SDA: Arduino A4
// Pin 6, SCL: Arduino A5
// Pin 7, WP: Write/Protect = GND
// Pin 8, VCC: +5

#include <Arduino.h>
#include <Wire.h>

// I2C Bus address of 24LC256 EEPROM;
// if more than one eeprom, they will have different addresses (h/w configured);
#define EEPROM_ADDR 0x50
byte m_addr = 0;

#define MAX_ADDRESS 128

byte eeprom_write(byte address, byte *data, byte len)
{
    byte r = 0;
    for(byte i=0; i<len; )
    {
        Wire.beginTransmission(EEPROM_ADDR | m_addr);
        Wire.write(address + i);
        byte l = len > 8 ? 8 : l;
        Wire.write(data+i, l);
        r |= Wire.endTransmission();
        delay(3);
        i += l;
    }
    return r;
}

byte eeprom_read(byte address, byte *data, byte len)
{
    Wire.beginTransmission(EEPROM_ADDR | m_addr);
    Wire.write(address);
    byte tr = Wire.endTransmission();
    if(tr)
        return tr;

    Wire.requestFrom((uint8_t)(EEPROM_ADDR | m_addr), len);
    byte avail = Wire.available();
    if(avail < len)
        return 0xFF;

    for(int i=0; i < len; i++)
    {
        // store data in raw bcd format
        data[i] = Wire.read();
    }
    return 0;
}

void setup()
{
    Wire.begin();
    Serial.begin(9600);
    delay(500);
    Serial.println("Type something to store in EEPROM");
}

byte i = 0;

void loop()
{
    if(Serial.available())
    {
        byte data = Serial.read();
        int rc = eeprom_write(i, &data, 1);
        if(rc==0)
        {
            Serial.print("EEPROM[0x");
            Serial.print(i, HEX);
            Serial.print("] = 0x");
            Serial.print(data, HEX);
            Serial.print(" (");
            Serial.print((char)data);
            Serial.print(")");
            Serial.println();

            Serial.println("Reading from EEPROM:");
            for(byte j=0;j<MAX_ADDRESS;j++)
            {
                if(byte rc=eeprom_read(j, &data, 1))
                {
                    Serial.print("Error in reading from EEPROM (rc=0x");
                    Serial.print(rc, HEX);
                    Serial.println(")");
                }
                else
                {
                    Serial.print(data, HEX);
                    Serial.print(' ');
                    if((j + 1) % 8 == 0 && j != MAX_ADDRESS - 1)
                        Serial.print("| ");
                }
            }
            Serial.println("");
        }
        else
        {
            Serial.println("Write error.");
        }
        i++;
    }
}

Every time I write one byte to the EEPROM, I read back the data on it.
The result is a bit disappointing for me. I understand that 24LC01B has a page size of 8 bytes. But, it does not make sense to me why the bytes withing the page rotate right every time I write into it
Type something to store in EEPROM
EEPROM[0x0] = 0x61 (a)
Reading from EEPROM:
61 4 4F 0 80 0 80 4 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x1] = 0x62 (b)
Reading from EEPROM:
4 62 4 4F 0 80 0 80 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x2] = 0x63 (c)
Reading from EEPROM:
80 4 63 4 4F 0 80 0 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x3] = 0x64 (d)
Reading from EEPROM:
0 80 4 64 4 4F 0 80 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x4] = 0x65 (e)
Reading from EEPROM:
80 0 80 4 65 4 4F 0 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x5] = 0x66 (f)
Reading from EEPROM:
0 80 0 80 4 66 4 4F | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x6] = 0x67 (g)
Reading from EEPROM:
4F 0 80 0 80 4 67 4 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x7] = 0x68 (h)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x8] = 0x69 (i)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 69 4 4F 0 80 0 80 4 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x9] = 0x6A (j)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 6A 4 4F 0 80 0 80 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xA] = 0x6B (k)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 80 4 6B 4 4F 0 80 0 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xB] = 0x6C (l)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 0 80 4 6C 4 4F 0 80 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xC] = 0x6D (m)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 80 0 80 4 6D 4 4F 0 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xD] = 0x6E (n)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 0 80 0 80 4 6E 4 4F | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xE] = 0x6F (o)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4F 0 80 0 80 4 6F 4 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xF] = 0x70 (p)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 4F 0 80 0 80 4 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x10] = 0x71 (q)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 4F 0 80 0 80 4 70 | 71 4 4F 0 80 0 80 4 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x11] = 0x72 (r)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 4F 0 80 0 80 4 70 | 4 72 4 4F 0 80 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF

Reading the code and serial EEPROM specifications takes a lot of time.  Try this and if it works I'll provide a more complete answer:  Write all 8 bytes in a page.

@st2000, I actually have tried 8 bytes data writing and it worked fine. No problem with that. The problem raises when you write less than a page (8 bytes). Is writing minimum as much as size of the page anything standard requirements for EEPROMs? I have not seen something like that in the datasheets.

It doesn't matter if you write 1 byte or a complete page. the only import thing is, you do not cross a page border while writing.

The global variable data is a byte variable. But in the read and write function you use it as an byte array (data[i] or 'data +i').
That's not OK, but also not an error in the case you use length 1 ;-).
In your read function you performed a so called random read action that must be terminated by a STOP signal on the I2C bus. This can be forced by:
// ...

for(int i=0; i < len; i++)
{
    // store data in raw bcd format
    data[i] = Wire.read();
}

Wire.endTransmission(true);

return 0;

// ...

It's just a guess.
Writing single bytes must also be ended by a STOP condition but you used
r |= Wire.endTransmission();

that does not send a STOP signal.
Again you can force it with:
r |= Wire.endTransmission( true );

I'm not a Wire lib wizard, so I had read the Arduino documentation. Hopefully I understood it correctly.

Your problem is
byte l = len > 8 ? 8 : l;
in the eeprom_write() function.
You wrote byte NumberOfBytes = len > 8 ? 8 : NumberOfBytes; and that will leads to an undefined behavior.
And for the future, if you want to write more than 1 Byte it is not important how many byte you write in a block but that the addresses are all located on the same eeprom page.
((address / pagesize) == ((address + length) / pagesize) must be true


text:
Trying to read different gas levels with MQ2 Gas Sensor
I found a link on how to connect MQ-2 Gas Sensor to Arduino Uno.
http://electronicsprojectshub.com/how-to-connect-mq2-gas-sensor-to-arduino/
After I bought all the parts and tried it out, the sensor gave me this in the serial monitor

Ro: 10.81 kohm
LPG:0.00ppm    CO:0.00ppm    SMOKE:0.00ppm
LPG:0.00ppm    CO:0.00ppm    SMOKE:0.00ppm

and so on.
Here is the code I used
#include <MQ2.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16,2);
int Analog_Input = A0;
int lpg, co, smoke;
MQ2 mq2(Analog_Input);

void setup(){
  pinMode(A0, INPUT);
  Serial.begin(9600);
  lcd.begin();
  lcd.backlight();
  mq2.begin();
}

void loop(){
  float* values= mq2.read(true);
  //lpg = values[0];
  lpg = mq2.readLPG();
  //co = values[1];
  co = mq2.readCO();
  //smoke = values[2];
  smoke = mq2.readSmoke();

  lcd.setCursor(0,0);
  lcd.print("LPG:");
  lcd.print(lpg);
  lcd.print(" CO:");
  lcd.print(co);
  lcd.setCursor(0,1);
  lcd.print("SMOKE:");
  lcd.print(smoke);
  lcd.print(" PPM");
  delay(1000);
}

Please help me fix it so that it can perform just the same as the video. Thanks.

I want it to show this
LPG: 4  CO:2803
SMOKE: 16 PPM
on the LCD. Please help. Thanks.

blow the right amount of gas and smoke onto the sensor so that you get those readings

First this should be like this:
float* values= mq2.read(false); //false

and then write this to be printed in the serial monitor
Serial.print('\n');
  Serial.print("LPG:");
  Serial.print(lpg);
  Serial.print(" CO:");
  Serial.print(co);

  Serial.print('\n');
  Serial.print("SMOKE:");
  Serial.print(smoke);
  Serial.print(" PPM");
  Serial.print('\n');


text:
String to Dynamic Byte array
I'm new in Arduino stuck in String to a dynamic byte array.
My String:
String Finalval="6D616320747820636E662031352033300D0A";

Dynamic Byte array:
byte ft[]={0x6D,0x61,0x63,0x20,0x74,0x78,0x20,0x63,0x6E,0x66,0x20,0x31,0x35,0x20,0x33,0x30,0x0D,0x0A};

Common C-string to byte array functions as shown in https://stackoverflow.com/questions/3408706/hexadecimal-string-to-byte-array-in-c work perfectly fine.
Source hex string: 6D616320747820636E662031352033300D0A
Conversion OK buff 0x289 len 18
output byte array:
  00 6d 61 63 20 74 78 20 63 6e 66 20 31 35 20 33 30  mac tx cnf 15 30
  10 0d 0a                                            ..

#include <Arduino.h>

void hexDump (const char *desc, const void *addr, const int len);

bool convert_hexstr_to_bytearray(const char* source, uint8_t* &output,
        size_t& output_len) {
    size_t len = strlen(source);
    //cannot convert non-even string length
    if ((len % 2) != 0) {
        return false;
    }
    //dynamically allocate output buffer
    output_len = len / 2;
    output = (uint8_t*) malloc(output_len);
    const char* curPos = source;
    for (size_t count = 0; count < len; count++) {
        sscanf(curPos, "%2hhx", output + count);
        curPos += 2;
    }
    return true;
}

String Finalval="6D616320747820636E662031352033300D0A";

void setup() {
    Serial.begin(115200);
    Serial.print("Source hex string: ");
    Serial.println(Finalval);
    Serial.flush();

    uint8_t* buffer = nullptr;
    size_t buffer_len = 0;
    if(convert_hexstr_to_bytearray(Finalval.c_str(), buffer, buffer_len)) {
        Serial.println("Conversion OK buff 0x" + String((long)buffer,HEX) + " len " + String(buffer_len));
        hexDump("output byte array", buffer, buffer_len);
    } else {
        Serial.println("Conversion failed\n");
    }

    //free memory
    if(buffer)
        free(buffer);
}

void loop() {
}

void PrintHex8(const uint8_t *data, uint8_t length) // prints 8-bit data in hex
{
     char tmp[length*2+1];
     byte first;
     byte second;
     for (int i=0; i<length; i++) {
           first = (data[i] >> 4) & 0x0f;
           second = data[i] & 0x0f;
           // base for converting single digit numbers to ASCII is 48
           // base for 10-16 to become lower-case characters a-f is 87
           // note: difference is 39
           tmp[i*2] = first+48;
           tmp[i*2+1] = second+48;
           if (first > 9) tmp[i*2] += 39;
           if (second > 9) tmp[i*2+1] += 39;
     }
     tmp[length*2] = 0;
     Serial.print(tmp);
}

void hexDump (const char *desc, const void *addr, const int len) {
    int i;
    unsigned char buff[17];
    const unsigned char *pc = (const unsigned char*)addr;

    // Output description if given.
    if (desc != NULL) {
        Serial.print (desc);
        Serial.println(":");
    }

    if (len == 0) {
        Serial.print("  ZERO LENGTH\n");
        return;
    }
    if (len < 0) {
        Serial.println("  NEGATIVE LENGTH: " + String(len));
        return;
    }

    // Process every byte in the data.
    for (i = 0; i < len; i++) {
        // Multiple of 16 means new line (with line offset).

        if ((i % 16) == 0) {
            // Just don't print ASCII for the zeroth line.
            if (i != 0) {
                Serial.print ("  ");
                Serial.println((char*)buff);
            }

            // Output the offset.
            Serial.print ("  ");
            PrintHex8((uint8_t*)&i, 1);
        }

        // Now the hex code for the specific character.
        Serial.print(" ");
        PrintHex8(pc + i,1);

        // And store a printable ASCII character for later.
        if ((pc[i] < 0x20) || (pc[i] > 0x7e))
            buff[i % 16] = '.';
        else
            buff[i % 16] = pc[i];
        buff[(i % 16) + 1] = '\0';
    }

    // Pad out last line if not exactly 16 characters.
    while ((i % 16) != 0) {
        Serial.print ("   ");
        i++;
    }

    // And print the final ASCII bit.
    Serial.print ("  ");
    Serial.println((char*)buff);
}

I'm trying this but not working         Serial.write(buffer,sizeof(buffer))

@VikashSingh, there is no statement: Serial.write(buffer,sizeof(buffer))  anywhere in the posted code.

@VikashSingh sounds like you're having an advanced problem when handling the decoded buffer. What is the exact code?

@MaximilianGerhardt thanks for help my problem solved


text:
What type of Arduino is this?
I found a bunch of Arduinos (seemingly), but I can't identify the type.
I first thought of a Micro, but the chip is a MEGA328PAU and the Micro should have a MEGA32U4 instead:

I know it's also not a Nano, because the Nano is a bit longer:

Next, I looked up the List of Board Specs. Based on the chip, the following models remain:

Lilypad, can easily be excluded due to its shape
Lilypad SimpleSnap, can easily be excluded due to its shape
Uno, can easily be excluded due to its size
Ethernet, can easily be excluded, because of the Ethernet port
Mini
Pro
Pro Mini

So I am left with Mini, Pro Mini and Pro. The back of the board is not very helpful, since it IMHO misses the markers in the silk sceen:

It definitely looks like the Pro Mini from Arduino Store, but the Arduino store seems not to offer the Mini and Pro, so I don't have a comparison.
What type of Arduino is this? And, if possible, do you have a visual comparison of the three remaining types?

The voltage regulator is BAPG (sure) and the quartz has A.8 on it (very hard to see)

the only info about the marking I found, has 8 for 8 MHz and X for 10 MHz. I would guess A is 16 MHz. my 16 MHz Nano has A as first letter on the resonator too https://www.murata.com/en-us/support/faqs/products/timingdevice/ceralock/char/cch0005

did my answer help?

@Juraj: sort of. It strengthens my opinion that it is a Pro Mini, but it does not eliminate the other two options: Mini and Pro.

It is a version of Pro Mini.
here in DIY MORE shop
The Mini has regulator. Power it over RAW pin with 7 to 12 V and measure the Vcc pin if it shows 5v or 3.3 V.
To determine the frequency, look at the resonator (the component next to pin 2).
EDIT: the resonator markings are hard to read and very cryptic. to determine the frequency you could install Sparkfun boards package. There you can select the different variants of Pro Mini. Upload Blink. If the upload is successful and it Blinks in 1 second intervals, you have the right setting.

Unfortunately, the marks on the back are missing. If it's really a 8 MHz version, it might allow Vcc = 3.3V only.

@DataFiddler The only difference between the 8Mhz and 16Mhz version is the crystal and the regulator. You can run a 8Mhz 3.3V Pro Mini fine on 5V. Though not the other way around, since the ATMega328 requires at least 3.8V to run at 16Mhz (higher speeds, require a higher supply voltage).

Do you think the Mini and Mini 05 are just one thing? If so, this would be the Mini: https://store.arduino.cc/arduino-mini-05

there are different revisions of Mini, but the Pro is different. Pro has A6 and A7

here is yours https://www.diymore.cc/products/pro-mini-atmega328-3-3v-5v-16m-replace-atmega128-for-arduino-nano?_pos=6&_sid=8931d4b6d&_ss=r

@ThomasWeller, and the voltage and frequency?


text:
How can I save my float 'ave' on the EEPROM continuously?
How can I save my output continuously to EEPROM? Or is this even possible? Please help me out.
void setup() {
  Serial.begin(9600);
}

void loop() {
  static unsigned long count = 0;
  static float sum = 0;
  float ave = 0;
  int volt = analogRead(A1);
  float voltage = map(volt, 0, 1023, 0, 2500) / 100.0;
  Serial.print("Voltage: ");
  Serial.println(voltage, 2);
  sum = sum + voltage;
  count++;
  ave = sum / count;
  Serial.print("Average: ");
  Serial.println(ave, 2);
  Serial.println("-----");
  delay(3000);
}

Add an FRAM to your system. They can support 10 trillion writes.  34 billion years worth of writes. Plus they can be accessed at SRAM speeds, while the onboard EEPROM takes 3.3mS to write to it, and can be corrrupted if power is lost during the write.  With FRAM, you can toggle between 2 addresses, if one gets lost you can back up to the good one and only be a few seconds behind. (you can do that with EEPROM too)

It's possible, but it's certainly not advised.
EEPROM has a limited number of writes before it's dead. By writing continuously to the EEPROM you will kill it in no time at all.

How limited is it? Maybe I can adjust the seconds on when I will save data per day?

100,000 IIRC but I'd have to check the datasheet. Better to use something like a 47L16 EERAM.

The answer is: Read the Arduino Reference and find EEPROM.put
But your actual problem is that
1) if you write to eeprom every 3 seconds, the Arduino eventually
    won't survive you
2) you eventually rather want to write the sum and the count, in
    your case ?
You should also think about how to initialize from EEPROM after Restart.
Perhaps it's sufficient to save restart values only once after 1 minute / 1 hour / daily if it still changes?
BTW the "Update only if it changed" is already built into the put() method.

What if i will just store my latest data? Every data it will received will be replaced by new one every 3sec. As long as I can save or store my last data, that will be fine.

You might like to consider whether there's a chance to detect the power-down before the Arduino actually stops working. If detected your values are saved, some milliseconds suffice. This could be done with some hardware but depends on your environment.

@Rica Jacutina: That was my basic idea as well. If you always store the latest data every 3 sec, you will store them  28800 times a day. atmega EEPROM has a lifetime of about 100000 writes, so your system survives 4 days. Not very smart for an "average since ever". You can write them to different locations and use all EEPROM memory and thus extend lifetime to about a year, but the busybee's idea is much better.

I'll try your suggestions. Thanks a lot!


text:
Adafruit motorshield v2.3 not working
I want to connect my adafruit motor shield v2.3 to a touch board from bare conductive so that the motor turns when one of the electrodes is touched.
I've tested the touch part and that isn't a problem so i tested the motor shield on my arduino uno. I am using the DCMotorTest example and when uploading it doesn't give any errors. The shield is getting powered, but the motor isn't turning.
The motor does turn when connected to a 9v battery.
The motor doesn't turn when connected to motor shield without external power and VIN jumper connected.enter image description here
The motor doesn't turn when connected to motor shield with external power with and without VIN jumper connected.
/*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438
*/

#include <Wire.h>
#include <Adafruit_MotorShield.h>

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  myMotor->run(FORWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tock");

  myMotor->run(BACKWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tech");
  myMotor->run(RELEASE);
  delay(1000);
}

https://i.stack.imgur.com/uzsEb.jpg

If you are using a 9V block battery: don't use it. These batteries are made for low power applications and can only provide a low current. Not fitting to drive motors

What should i use instead?

Many possibilities. For example a fitting number of AA batteries in series. Or a LiPo battery

You have two possibilities of powering the shield according to the adafruit documentation.
A: power the Arduino over the power plug (not the USB plug) of the Arduino and set the VIN jumper.
B: Leave the VIN jumper off and power over the power connector of the shield.
Don't try other possibilities. They may kill the shield or the Arduino.
The reason your motor doesn't turn is because you switched it off
myMotor->run(RELEASE);  immediately after you switched it on myMotor->run(FORWARD);.

Setting the VIN jumper is connecting the pins or leaving them not-connected?

I'm unsure, if I understood  your question correctly. If I do, the answer is: Setting the VIN jumper means taking a jumper or other conducting materials and putting it on/between the two VIN pins. These are the two pins close to the power connector on the shield. If they are connected together, the power of the Arduino (but only from the ext Power plug, not from the USB connector) is connected to the power management of the shield and you don't need extra power on the shield.

Yhea that's what i meant sorry for formulating the question so werid. When i leave the VIN jumper and connect the shield to o 9v battery the shields led lights up, but the arduino doesn't

When connecting a couple of AA batteries the same thing happens, i also changed the M1 to M4 but this also didn't do anything

If I understood the documentation correctly, the Arduino must be powered separately even if you power the shield externally. But you can power the shield from the arduino if the VIn Jumper is set on the pins. Then you don't need to power the shield externally.

I just used a different motor-shield and it works now, thank you all for your replies and research in this!


text:
How do I write my code to reverse the motors in the opposite direction so the RSLK can move backwards?
I've assembled the TI RSLK Robot Maze Edition for a final project for my embedded systems class. Instead of using the MSP432P401R LaunchPad that came with the kit to control the power board, I've used an Arduino MEGA 2560 instead. I'm also using a KY-023 Analog Joystick to control the two dc motors.
int xPin = A0; // analog input for x-axis joystick
int yPin = A1; // analog input for y-axis joystick

int yPosition = 0;
int xPosition = 0;

//Right motor pins
#define MRSpeed 11
#define MRDir 10
#define MRSleep 9

//Left motor pins
#define MLSpeed 8
#define MLDir 7
#define MLSleep 6

void setup() {
 Serial.begin(9600);
 pinMode(xPin, INPUT); // setup x input
 pinMode(yPin, INPUT); // setup y input

 pinMode(MRSpeed, OUTPUT);
 pinMode(MRDir, OUTPUT);
 pinMode(MRSleep, OUTPUT);
 digitalWrite(MRSleep, 1);

 pinMode(MLSpeed, OUTPUT);
 pinMode(MLDir, OUTPUT);
 pinMode(MLSleep, OUTPUT);
 digitalWrite(MLSleep, 1);

 }

 void loop() {

  yPosition = analogRead(yPin);
  xPosition = analogRead(xPin);

  //Steer Forward
  if (yPosition > 1020)
  {
    analogWrite(MRSpeed, 255); //To move right wheel forward
    analogWrite(MLSpeed, 255); //To move left wheel forward
  }

   //To stop both wheels
    else if (yPosition = 506 || 505)
    {
      analogWrite(MRSpeed, 0);
      analogWrite(MLSpeed,0);
    }

     //Turn Right
      if(xPosition < 512)
      {
       analogWrite(MRSpeed, 0);
       analogWrite(MLSpeed, 255);
      }

     //Turn Left
       if(xPosition > 1020)
       {
         analogWrite(MRSpeed, 255);
         analogWrite(MLSpeed, 0);
       }

       }

Have you tried to use those MRDir/MLDir outputs?

And also: (yPosition = 506 || 505) won't work as you hope it'll

@KIIV I've added
else if (yPosition < 505)
{
digitalWrite(MRDir, HIGH);
analogWrite(MRSpeed,255);
} But I get no movement

@Angel Please update the code in your question, if you change something, so that we can exactly see, what you changed.


text:
Is it possible to split project into several folders?
It is possible to split the project into server files. However, it looks like they all must be in the same folder with the.ino file.
Is it possible to split project into several folders? I’ve got several git repositories which I want to use in the same project and I can’t use them as libraries. Each repository must have its own folder…

What operating system are you using?

@Majenko Win10. Does it matter for this case? All things are quite similar everywhere nowadays.

Yes you can. It works and many projects use subfolders. And NO, you will not see them in your Arduino IDE. As st2000 said, Arduino IDE is simple and people likes it because it is simple. If you want the control of your processor and code, use PlatformIO.

@Adriano how? I can refer the headers in subfolders but Arduino IDE does not compile the definitions from subfolders. And, guys, how you even can call it simple? Looks like things are simple only for simple deeds.

If you have a header inside a subfolder, you can just call #include "subfolder/header.h" and it works. You can see this big project for example: https://github.com/xoseperez/espurna/tree/dev/code/espurna - but you will not see the files inside the Arduino IDE. Simple means, that if you don't have programming skills, you are able to open and edit something without loose time to find out what an IDE is and how it works. In future, with the PRO version, it will be easier to develop something... I hope ;)

@Adriano As I said, I have no problem with headers. I have .cpp files inside a subfolder. How to make IDE compile them? I don't need to work with them via IDE, it's ok.

@zhekaus I wrote the answer as answer, not as comment. Hope this is ok for you. I know what you want. You want the comfort of Visual Studio in a simple text editor with integrated compiler. You can use Visual Studio + Visual Micro and you will have all the comfort you want ;) But Arduino IDE also gives you a lot of options to develop more complex projects.

I will try to give an answer as it is not easy to understand what you mean.
Probably it is also better if you know how the Arduino IDE works, before try to make complex projects.
Short answer:
Yes, it is possible
Normally, you have an ino-file, some other files and many libraries. If you want create something for your project, you can just create a folder inside the library folder.
But this is not what you want right?
You can create many folders inside your project and include any header inside your folders just with
#include "subfolder/yourfile.h"
The files will not be opened with your Arduino IDE.
You can also create your "mini library", so the compiler will compile it with your project. This library need to be in a subfolder called src. At this point it will be converted and compiled for your project.
Simple working example:
testsub.ino
#include "src/test.h"
Test *test = new Test();
void setup(){
  Serial.print(test->number());
}
void loop(){
}

Create a subfolder src and place your files:
test.h
class Test
{
public:
  Test();
  int number();
};

and
test.cpp
#include "test.h"
Test::Test() {
}
int Test::number() {
  return 95;
}

If you want another "library", you can create another subfolder called src.

You know, that's finally quite something! Thank so much!
However, how can I have extra subfolder with the same name src?

You need to place the second subfolder inside the src folder. And there, you can place another src folder. This is the only way at the moment.


text:
expected '}' at end of input
hi i am getting this error, im guessing i have a bracket missing or one in the wrong place.  any help is appreciate, still new at this. thank you
(code bellow)
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
#include <XBOXRECV.h>

Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x40);

USB Usb;
XBOXRECV Xbox(&Usb);

// our servo # counter
// You can change the value from 0 to 15 (servo 1 through 16)
uint8_t util1servo = 0;
uint8_t util2servo = 1;
uint8_t ldoorservo = 2;
uint8_t rdoorservo = 7;
uint8_t sdoorservo = 3;
uint8_t mdoorservo = 8;

//Servo limits definition.
//You will have to figure out which numbers match your servo be carefull with these,
//it can break your servo if you go beyond the limits. The ones listed here are for my own setup
#define UTIL1MIN  150 // Close position of the Top Utility arm
#define UTIL1MAX  310 // Open position of the Top Utility arm
#define UTIL2MIN  140 // Close position of the Bottom Utility arm
#define UTIL2MAX  300 // Open position of the Bottom Utility arm
#define LDOORMIN  390 // Close position of the Left door
#define LDOORMAX  550 // Open position of the Left door
#define RDOORMIN  555 // Close position of the Right door
#define RDOORMAX  360 // Open position of the Right door
#define SDOORMIN  492 // Close position of the Small door
#define SDOORMAX  200 // Open position of the Small door
#define MDOORMIN  550 // Close position of the Mid door
#define MDOORMAX  380 // Open position of the Mid door

//Status for each door open/close
int LDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int RDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int SDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int MDOORSTATUS = 0; // Status 0 = Closed, 1 = Open

void setup() {

   pwm1.begin();

  pwm1.setPWMFreq(60);  // Analog servos run at ~60 Hz updates

  Wire.begin();

}

void loop() {

//Left door
if (Xbox.getButtonClick(LEFT, 0)){
  if (Xbox.getButtonPress(R1, 0)) {
    if(LDOORSTATUS == 0){
          for (uint16_t lpulselen = LDOORMIN; lpulselen < LDOORMAX; lpulselen++){
          pwm1.setPWM(ldoorservo, 0, lpulselen); //Open the door
          delay(1);
          }
          LDOORSTATUS = 1;
          }
        else if (LDOORSTATUS == 1){
             for (uint16_t lpulselen = LDOORMAX; lpulselen > LDOORMIN; lpulselen--){
             pwm1.setPWM(ldoorservo, 0, lpulselen); //Close the door
             delay(1);
             }
             LDOORSTATUS = 0;
     }

Auto-format in the IDE is your friend...

You should edit your question, select the code, and press the {} code formatting button.

downvote because you are asking for help with sloppily formatted code

Auto-formatting produced the following - look at your loop() function and you'll see the problem:
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
#include <XBOXRECV.h>

Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x40);

USB Usb;
XBOXRECV Xbox(&Usb);

// our servo # counter
// You can change the value from 0 to 15 (servo 1 through 16)
uint8_t util1servo = 0;
uint8_t util2servo = 1;
uint8_t ldoorservo = 2;
uint8_t rdoorservo = 7;
uint8_t sdoorservo = 3;
uint8_t mdoorservo = 8;

//Servo limits definition.
//You will have to figure out which numbers match your servo be carefull with these,
//it can break your servo if you go beyond the limits. The ones listed here are for my own setup
#define UTIL1MIN  150 // Close position of the Top Utility arm
#define UTIL1MAX  310 // Open position of the Top Utility arm
#define UTIL2MIN  140 // Close position of the Bottom Utility arm
#define UTIL2MAX  300 // Open position of the Bottom Utility arm
#define LDOORMIN  390 // Close position of the Left door
#define LDOORMAX  550 // Open position of the Left door
#define RDOORMIN  555 // Close position of the Right door
#define RDOORMAX  360 // Open position of the Right door
#define SDOORMIN  492 // Close position of the Small door
#define SDOORMAX  200 // Open position of the Small door
#define MDOORMIN  550 // Close position of the Mid door
#define MDOORMAX  380 // Open position of the Mid door

//Status for each door open/close
int LDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int RDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int SDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int MDOORSTATUS = 0; // Status 0 = Closed, 1 = Open

void setup() {

  pwm1.begin();

  pwm1.setPWMFreq(60);  // Analog servos run at ~60 Hz updates

  Wire.begin();

}

void loop() {

  //Left door
  if (Xbox.getButtonClick(LEFT, 0)) {
    if (Xbox.getButtonPress(R1, 0)) {
      if (LDOORSTATUS == 0) {
        for (uint16_t lpulselen = LDOORMIN; lpulselen < LDOORMAX; lpulselen++) {
          pwm1.setPWM(ldoorservo, 0, lpulselen); //Open the door
          delay(1);
        }
        LDOORSTATUS = 1;
      }
      else if (LDOORSTATUS == 1) {
        for (uint16_t lpulselen = LDOORMAX; lpulselen > LDOORMIN; lpulselen--) {
          pwm1.setPWM(ldoorservo, 0, lpulselen); //Close the door
          delay(1);
        }
        LDOORSTATUS = 0;
      }


text:
how to wrire into the contents of the registers in ADMV1013 up converter using arduino Due?
There are nine registers inside and the contents of the registers can be changed to perform several operations. The link of the data-sheet is given here(Page 26). The write cycle sampling must be performed on the rising edge.
The 16 bits of the serial write data are shifted in, MSB to lower
sideband.
The link: https://www.analog.com/media/en/technical-documentation/data-sheets/ADMV1013.pdf

I do not understand what you are asking for. Especially "MSB to lower sideband" makes no sense for me. MSB and LSB have nothing to do with the lower or upper side band of the up converter. If you want to program the Due to transfer the data words to the registers of the convert, you could use the SPI library. It is a core library and always available in the IDE. It is documented on the Arduino page. One special note: The converter uses 1.8V input and output level. So you should use a level shifter to connect it to the Due.

https://www.arduino.cc/en/reference/SPI

Yes I am using a level translator to generate 1.8 V for the up converter. I am using the SPI.transfer() command to write into the registers but I could not understand how to change the contents of the registers .I mean when I am sending a specific data by SPI.transfer(data),will that data be stored in the registers???and also if we look into the data sheet of the up converter,you can see the timing diagram for the read and write is mentioned specifically.the changing of the MSB is for to enable  the read or write more if operation.


text:
Circuit requirement for Arduino Due custom circuit without the ATMEGA16U2
I would like to create a custom Arduino board based on the Arduino Due. Upon looking at the Due's schematics under the documentation tab there are some stuff that i do not need and removed them. the last thing that i want removed is the ATMEGA16U2. This part just takes so many components that i want it removed.
I would like to build my code using the arduino IDE and with the 16u2 gone i do not know a way how to upload my codes.
This seems to be possible since under the documentations there is a native usb port of the due that is directly connected to the SAM3X8E,
from here on out im lost what how do i upload my code to the same sam3x8E
Special tools that i have that might be usefull:

J-link EDU Mini
USB to UART

My Current draft schematics:

Since you have USB you just connect it to your computer. As long as the flash is blank (use the erase button) it will enter the BOSSA bootloader at powerup and you can use the Arduino IDE to upload the code as normal (or the bossac command line tool)

@Majenko thank you good sir, the erase button is handled by the 16u2 and without it how will i erase the flash? which means i basically can upload only 1 code and thats it, which is kinda not ideal

You add a button (or a jumper) to your schematic.

@Majenko wait what ?? "Opening and closing the Native port at 1200bps" from the documentation can be done by  shorting PC0 ? or im misunderstanding, can you elaborate from where to where will the jumper be connected?

There are two ways of entering the bootloader: 1. Wipe the flash with the ERASE button (or trigger from 16U2). 2. Open the native port at 1200 baud. The latter is only possible if you have first programmed the board with a sketch with that ability in it. The most sure-fire way is to include the erase button. It should be there in the schematics already - did you erase the erase button?

Oh i get it now, i might have misunderstood the the erase button, the line from the 16u2 is parrallel to the reset button so it is an alternative, okay got it. A follow up question in actually uploading the code the steps are: plug the usb -> press the erase -> click upload on the IDE ? is this the right sequence?

Possibly. I'm a bit rusty on the Due - not having used it for ages. But I seem to recall that's how it works, yes.

If you may post the your comment as answer good sir, i would like to mark it as the correct answer.

Since you have USB you just connect it to your computer. As long as the flash is blank (use the erase button) it will enter the BOSSA bootloader at powerup and you can use the Arduino IDE to upload the code as normal (or the bossac command line tool).
There are two ways of entering the bootloader:

Wipe the flash with the ERASE button (or trigger from 16U2).
Open the native port at 1200 baud.

The latter is only possible if you have first programmed the board with a sketch with that ability in it. The most sure-fire way is to include the erase button.
You can either provide a physical button (as shown in the existing schematics) or a simple jumper that can be shorted when erasing is needed.

By the way, does the reset pin (PC0) need to be pulled down ?

To erase? I can't remember. You'll have to check the datasheet.

It has internal pull-down resistor about 100k. So it can be left unconnected for normal operations.

@KIIV thanks for that !


text:
Stuck in a loop using IR Receiver
I am new to Arduino Programming and I have bought an Arduino UNO , Ultrasonic Sensor (HC-SR04), A Piezo Buzzer, IR Receiver (VS1838B) and a RGB LED....
I wrote a program to Calculate Distance form the Ultrasonic Sensor to an object and a Processing Sketch to Display the results.
Now I want to use the IR Receiver to increase the Distance Threshold which makes the buzzer beep...I mean I want to press 1 in my remote to keep the distance about 5 cm after which the buzzer beeps, and when I press 2 the distance becomes 10 cm and so on...I want to stop everything when I press 0 in my remote...
I have already found out the hex codes of my remote buttons but the program makes the task harder...
Please help me with the program that I have already written :-
#include <NewTone.h>
#include <IRremote.h>

const int rec = 9;
IRrecv irrecv(rec);
decode_results results;

#define BUTTON_0 0xFF6897
#define BUTTON_1 0xFF30CF
#define BUTTON_2 0xFF18E7
#define BUTTON_3 0xFF7A85
#define BUTTON_EQ 0xFF906F
#define BUTTON_4 0xFF10EF

const int redPin = 5;
const int greenPin = 6;
const int bluePin = 10;
const int trigPin = 12;
const int echoPin = 11;
const int buzPin = 3;
double duration;
double distanceCm, distanceInch;
double dur;

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(buzPin, OUTPUT);
  irrecv.enableIRIn();
  Serial.begin(9600);
}

void loop()
{
  if (irrecv.decode(&results))
  {
    if (results.value != BUTTON_0)
    {

      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      distanceCm = duration * 0.034 / 2;
      distanceInch = duration * 0.0133 / 2;
      dur = duration / 10000;

      Serial.print(distanceCm);
      Serial.print("  cm ");
      Serial.print("                         ");
      Serial.print(distanceInch);
      Serial.print(" Inch ");
      Serial.print("                         ");
      Serial.print(dur);
      Serial.print(" Seconds");
      Serial.print("\n");
    }

    if (results.value == BUTTON_0)
    {

      noNewTone(buzPin);
      analogWrite(redPin, 0);
      analogWrite(greenPin, 0);
      analogWrite(bluePin, 0);
    }

    if (results.value == BUTTON_1)
    {

      if (distanceCm <= 5)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 10 && distanceCm > 5)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }

    if (results.value == BUTTON_2)
    {

      if (distanceCm <= 10)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 20 && distanceCm > 10)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }

    if (results.value == BUTTON_3)
    {

      if (distanceCm <= 30)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 50 && distanceCm > 30)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }

    if (results.value == BUTTON_4)
    {

      if (distanceCm <= 100)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 200 && distanceCm > 100)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }
    irrecv.resume();
  }
}

I am using the "IRremote.h" and "NewTone.h" Libraries....
The main problem is that the "irrecv.resume();" pauses the program and waits for the IR input but I want the program to run continuously till I give an IR Input...
I request you to help me with the program.

I edited my program to this and this worked:-
#include <NewTone.h>
#include <IRremote.h>

const int rec = 2;
IRrecv irrecv(rec);
decode_results results;

#define BUTTON_0 0xFF6897
#define BUTTON_1 0xFF30CF
#define BUTTON_2 0xFF18E7
#define BUTTON_3 0xFF7A85
#define BUTTON_EQ 0xFF906F
#define BUTTON_4 0xFF10EF

const int redPin = 5;
const int greenPin = 6;
const int bluePin = 10;
const int trigPin = 12;
const int echoPin = 11;
const int buzPin = 3;
double duration;
double distanceCm, distanceInch;
double dur;

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(buzPin, OUTPUT);
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop()
{
  if (irrecv.decode(&results))
  {

    do
    {
      if (results.value == BUTTON_0)

      {

        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }

      if (results.value == BUTTON_1)
      {
        sonic();

        if (distanceCm <= 5)
        {
          red();
        }
        else if (distanceCm <= 10 && distanceCm > 5)
        {
          blue();
        }
        else
        {
          green();
        }

      }

      if (results.value == BUTTON_2)
      {
        sonic();
        if (distanceCm <= 10)
        {
          red();
        }
        else if (distanceCm <= 20 && distanceCm > 10)
        {
          blue();
        }
        else
        {
          green();
        }
      }

      if (results.value == BUTTON_3)
      {
        sonic();
        if (distanceCm <= 30)
        {
          red();
        }
        else if (distanceCm <= 50 && distanceCm > 30)
        {
          blue();
        }
        else
        {
          green();
        }
      }

      if (results.value == BUTTON_4)
      {
        sonic();
        if (distanceCm <= 100)
        {
          red();
        }
        else if (distanceCm <= 200 && distanceCm > 100)
        {
          blue();
        }
        else
        {
          green();
        }

      }
    }
    while (digitalRead(rec) == 1);

    irrecv.resume();
  }
}

void sonic()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distanceCm = duration * 0.034 / 2;
  distanceInch = duration * 0.0133 / 2;
  dur = duration / 10000;

  Serial.print(distanceCm);
  Serial.print("  cm ");
  Serial.print("                         ");
  Serial.print(distanceInch);
  Serial.print(" Inch ");
  Serial.print("                         ");
  Serial.print(dur);
  Serial.print(" Seconds");
  Serial.print("\n");
}

void green()
{
  noNewTone(buzPin);
  analogWrite(redPin, 0);
  analogWrite(greenPin, 255);
  analogWrite(bluePin, 0);
}

void blue()
{
  noNewTone(buzPin);
  analogWrite(redPin, 0);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 255);
}

void red()
{
  NewTone(buzPin, 2000);
  analogWrite(redPin, 255);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 0);
}

But now the problem is I need to press the IR Remote button two times because when I press once the program moves to the irrecv.resume(); command and waits for another IR Input and I need to press the button again.
Can this be solved (with only one press)?

The call to irrecv.resume() should not block. The IR detection runs on a timer interrupt. Maybe you have 2 parts of code, that both try to use one timer. Can you try, if the IR code is working, when you comment out all NewTone code or all analogWrite code? (Both also use timers)

Your code becomes more readable, if you use functions with return values.
For example, something like this structure
unsigned int limit; // 0 = off, else limit in cm  ...
void loop() {
  if (irrecv.decode(&results)) {
      byte key = getIRKey(results.value); // 0 , 1, 2, etc.,  0xFF for unknown
      irrecv.resume();
      switch (key) {
         case 0: limit = 0; break;
         case 1: limit = 5; break;
         ...
         default: break; // wrong key does not change limit
      }
  }
  if (limit) {
     unsigned int dist = sonic(); // returns the measured distance or 0
     if (dist && dist < limit) NewTone(buzPin, 2000);
     else noNewTone(buzPin); // off: too far
  } else noNewTone(buzPin); // off: no check
}

This code should not block. Have fun modifying sonic() and creating the other helper function.

You really should use switch-case.
irrecv.resume() does not halt the code.

Your program is running fine. It seems like you want to make sensor readings continuously and act only when you press the button. Am I right?

Yes, You are Right... I want to do a loop till another button is pressed and when it is pressed it should go into another loop.