text:
Proteus - How to Debug Invalid Opcode?
While running a program compiled in the Arduino IDE 1.8.5 and then using the .ELF file inside LabCenter Proteus 8.0, for an Arduino Nano ATMEL Mega 328P, for a code involving the use of the SoftwareSerial.h Library, hence involving several loops, without user interaction, I am getting the following error:
Invalid opcode 0x0024 at PC=0x0096

Now I am completely lost. According the AVR Instruction Set Manual such opcode should (not sure about this?) be RETI - Return From Interrupt at the Program Line (?) no.150 = 0x096. The full code has 779 lines plus several library calls, and the line 150 happens to fall just before the loop() function (?), which should never repeat, being just a declaration.
So, how should I debug this error? Evidently I am not asking to solve the problem for me but, how should I proceed for debugging it and find the real error?
I have been unable to find in Proteus a tool for "Debug Stop if Error"
I have been unable to isolate the error in a simple way to share. It should be related someway with interruptions used by the library SoftwareSerial.h, because at some modifications of the program, the code freezes at an interruption return. I am working on that, but advancing really slowly actually.

Related question No.1.

PC=0x96 has no relation to any lines in your source code. So, no, there's no point in looking at line 150. Line 150 is completely irrelevant here. And where exactly in the manual did you read that 0x0024 is RETI?

I am not understanding the situation for debugging this...

Where's the program? Errors like that might easily be caused by out-of-bounds local array modification. Stack damage smashes the stored function's return address, making it "return" to a completely wrong location (e.g. 0x96), hitting "invalid instructions" stored there.

PC=0x96 means the program counter is pointing to that memory location and it is trying to execute the instruction at that location  ..... the last picture shows code at 0x1ab4

I have the same problem. Would you tell me please, if you have solved the problem, and how?

@RamiMa I absolutely forgot what i had to do to fix that. I vaguely remember, I had to avoid something cumbersome I was making, such as using a version or a library or an array. Everything I tried with Proteus with real Arduino code worked fine, serials, ports, logics, analog & digital simulations, etc. In this case, please roll back some steps, and try to keep simple and elliminate the bad step you made. For sure, I did not debug anything. I had to roll back to something understandable to Proteus. I guess: this was cause because Mega become short for my code, and then I think I had to move...

First: Use the ino.hex file instead of the  .ELF file
Second: this error is showing because you are compiling your code with a different board. Make sure you are using the correct board over at the Arduino IDE. My advice is: switch your board to Arduino Uno both in proteus and over at the Arduino IDE and see if it works. Later on, you can try different boards.

Guys if you are facing the error of invalid opcode 0xffff at pc = 0x3e402 in proteus using Arduino, the GO to Arduino IDE software, and from the top menu, click on 'tool' and change the board type, e.g., Arduino UNO to Arduino Mega 2560.


text:
Project wont compile when I place functions below function calls
I use VSCode, not the Arduino IDE. I saw and tried to use a lot of code snippets which are provided for Arduino projects...
So when I copy/paste these examples into my VSCode and try to compile it fails. (I won't believe that people offer non-working examples.)
When I place the functions above the function calls it compiles.
Is this normal behavior or do I have to add some settings to get this working as provided?
Fails in VSCode (works in Arduino IDE):
#include "Arduino.h"
void setup() {
}
int zero = 0;

void loop() {
  zero = myfunction();
}

int myfunction(){
  return 0;
}

Works in VSCode (Works in Arduino IDE):
#include "Arduino.h"

void setup() {
}
int zero = 0;

int myfunction(){
  return 0;
}

void loop() {
  zero = myfunction();
}

did you try them in Arduino IDE?

@juraj, I edited my examples, so you can copy/paste them into the editors. Both examples are working in Arduino, only the below one is working in VSCode

Arduino builder adds function prototypes when converting .ino to .cpp

You need to declare your function before you use it.  So either the whole function body needs to be before the usage, or you must add a function prototype declaration.
void myfunction();

myfunction();

void myfunction(){
  return 0;
}

So if I understand you right, this could be done in a header file? I never saw them in the examples I used. But that would make sense...

I think Arduino IDE is doing some "magic" behind the scenes to be able to compile without declaring the functions above the function call. I also updated my examples, to be able to copy and paste them into the corresponding IDEs.

void myfunction() should not return an int

@Jan: Indeed. The Arduino IDE edits your .ino file, adds those function prototypes at the beginning of the file, saves the result as a .cpp file, and calls a C++ compiler (g++) to compile that .cpp.

@Jan, why did you accept an answer which doesn't answer your question?

Just make the the abstract method declaration before writing your code after the header files.
#include<Arduino.h>
void myfunction();
void setup();
void loop();

After this you write your code in any order

source: Stack Exchange

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

sort: votes


text:
how to fix USBASP Unknown USB Device (device descriptor request failed) - Win 10?
I just recently purchased Usbasp from Ali Express, when i'm connecting it to the windows 10 desktop in device manager its Unknown USB Device (device descriptor request failed). How to fix this error? Even in Linux its not detecting.

Sounds like you've got a dud. Contact the seller and get a replacement or refund.

@Majenko I just pick my rework station hotair gun to destroy this board and melt all the solder on the board, then i plugged it in for last time and its stated working but now i'm getting this error https://arduino.stackexchange.com/questions/65321/usbasp-arduino-uno-bootloader-flash-error-win-10

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


text:
The Ultrasonic sensor just detects the same distance
int tPin = 11;
int ePin = 12;
long duration, inches, cm;

void setup()
{
    Serial.begin(9600);
    pinMode(tPin, OUTPUT);
    pinMode(ePin, INPUT);
    pinMode(2, OUTPUT);
}

void loop()
{
    digitalWrite(tPin, LOW);
    delayMicroseconds(5);
    digitalWrite(tPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(tPin, LOW);
    duration = pulseIn(ePin, HIGH);
    cm = (duration / 2) / 29.1;
    inches = (duration / 2) / 74;
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
    delay(100);

    if (inches <= 10) {
        digitalWrite(2, HIGH);
        delay(50);
        digitalWrite(2, LOW);
        delay(50);
    }
    else {
        digitalWrite(2, HIGH);
        delay(500);
        digitalWrite(2, LOW);
        delay(500);
    }
}

The serial print displays the same distance that it first detects. How can I fix this?

What number does it constantly output? Also be aware that you do integer divisions when you do / 2 and / 74, you should change them to float values and also make cm and inches float.

Are you sure it detects the same distance? How far did you try to move the object from the sensor?

First of all you need to make cm, inches and duration float to be more precise. Second, you need to make the delay 2 and 10 microseconds between triggers. Overall, if I'm not wrong you can use the code below without changing your circuit.
int tPin = 11;
int ePin = 12;
float duration, inches, cm; //floating numbers to make the result more precise

void setup()
{
    Serial.begin(9600);
    pinMode(tPin, OUTPUT);
    pinMode(ePin, INPUT);
    pinMode(2, OUTPUT);
}

void loop()
{
    digitalWrite(tPin, LOW);
    delayMicroseconds(2);         //Delay 2 microseconds
    digitalWrite(tPin, HIGH);
    delayMicroseconds(10);        //Delay 10 microseconds
    digitalWrite(tPin, LOW);
    duration = pulseIn(ePin, HIGH);
    cm = duration / 58.2;          //Instead of duration/2/28.1
    inches = cm / 2.54;            //You can use cm that was created before for conversion
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
    delay(100);

    if (inches <= 10) {
        digitalWrite(2, HIGH);
        delay(50);
        digitalWrite(2, LOW);
        delay(50);
    }
    else {
        digitalWrite(2, HIGH);
        delay(500);
        digitalWrite(2, LOW);
        delay(500);
    }
}


text:
Battery charger board with status interface
There are of course a lot of different battery charging boards, which can be used with the Arduino, most being TP4056 based. There are also a few battery charged boards with an on-board display showing the charge status and there are of course also a lot of programmable battery charger controllers (ICs) with status and control interfaces.
But is there any board available, not just the 'raw' IC, using a charging controller with a status interface, which allows access to the status interface from pins on the board? I can't seem to find anything.
For a battery powered Arduino project I am planning, it could at least be very convenient if I could query the battery charging status from software.

You could probably solder some wires to the status leds.

@Gerben Most of the charger boards don't even have status leds. I do however need more precision than just something like 'full' and 'almost empty'.

I know it's been asked quite long time ago, but still.  This is how would have I done the same, with the existing TP4056:

use an electric key in a form of mosfet transistor, controlled by digital output pin to disconnect your battery from the charging board once in a while (like every 5-10 minutes or so, depending on your project power drain) for a very short period of time to do the measurement below.

while the battery is disconnected, use an analog input pin of arduino with resistor-based voltage divider to see what's your battery voltage. Google for "measure voltage with arduino alone" for schemas and code, it's pretty straightforward.

For obvious reasons, you cannot do this measurement while having your charging board connected to battery, because you'll be getting voltage from the charger, and not from your battery. This is why we disconnected battery from the charging circuit in step 1.

Knowing

current voltage you just get from your battery
what is the voltage should be on your battery when it's fully charged
the voltage you allow it to discharge to
... you can calculate percentages

digitalWrite to that pin to enable mosfet to connect your battery back to charging circuit

You might consider a coulomb counter IC, it is designed to give you the state of charge of the battery. There is a module labeled "LTC4150 Coulomb Counter" that will do exactly what you want.


text:
Arduino Strings concatenation
I am working on an arduino mega 2560 sketch.
I have to parse http query strings.
My program is concatenating strings for each http request.
And i have an http request every second during all day.
I have read that this kind of work may cause ram memory fragmentation. I am very upset about this because my program will randomly crash if there are no free ram memory.
Do you know if there is a way to initialise a string with a given memory length ?
I do not want to work with char arrays because i need indexof, substring functions and comparison with ==
Thanks

And how many of those concatenated requests do you expect to fit into the memory???

What is wrong with using the char* functions provided by C? They can do everything a String can, without the problem of memory fragmentation, and if you need a function that does not exist, it's very easy to find an implementation or create it yourself.

There is a way to initialize an Arduino String with a given memory length: see reserve() method. It will generally greatly reduce or entirely eliminate memory fragmentation, if you can afford reserving a sufficient amount of memory in advance.
Just keep in mind that this is a "soft" boundary: once your string gets longer than the reserved amount, String will quietly resume reallocating memory with all those typical consequences.
It is not clear what you plan to do if the pre-reserved amount of memory proves to be insufficient. Fall back to "memory fragmentation"? Anything more elaborate than that will be pretty much as complex as performing manual management of a char[] array.
All the functionalities you requested are present for char[] arrays as well, might just require a few more lines of code. And it is not clear why one might "need" comparisons to be == specifically.
This might also be an XY problem. Why are you trying to concatenate all these requests in memory? What are you planning to do with them once you are done "concatenating"?


text:
Return constant string
Look at this code :
char * function1()
{
    return « hello »
}
Where is stored hello string ?
Is there a copy ?
What i want to avoid is to have a memory leak or accessing to another string instead of hello
Thanks

What language is this code written in? What is the point of asking a question about "code" without specifying the language?

It is arduino c

Arduino C does not support «» quotes. In Arduino C return statement must end in ;.

String literals in C and C++ are stored in static memory, which in case of Arduino platform is ordinary data memory.
If we overlook the typos, your code is essentially equivalent to
char *function1()
{
  static char literal[6] = { 'h', 'e', 'l', 'l', 'o', '\0' };
  return literal;
}

with a remark that in C and C++ you are not allowed to modify string literals. (Some nuances also depend on the specific language - C vs. C++ - which you failed to specify). Regardless of the language, it is always a better idea to use const char * pointers (as opposed to char *) to point to string literals.
There's no dynamic memory allocation here, and therefore no memory leaks possible. What you mean by "accessing another string" is not clear.

const char* function1() { return "hello"; }

Where is stored hello string ? Is there a copy ?

The string is compiled into the program memory. Before setup() is called the constant values are copied to the data memory (aka SRAM).
The function will return the pointer to the same string (memory location).
To save data memory the string literal can be access directly in program memory.
__FlashStringHelper* function1() { return F("hello"); }

Cheers!
Ref.

https://en.cppreference.com/w/cpp/language/string_literal
https://www.nongnu.org/avr-libc/user-manual/pgmspace.html

Thanks but i do not understand. Should i use flashstringhelper and F() to make it work. It does not matter to me where the string is stored. I just want to read it from calling function

The first variant works nicely but will consume data memory. To avoid this the second variant can be used but it will require using special access functions. Please see the references.


text:
Unresolved reference to public function from library
I have three libraries that I've written and I'm trying to use. They're stored as follows
Documents
├── Some/Path/To/Folder
│   └── firmware.ino
└── Arduino
    └── libraries
        ├── error
        │   ├── error.h
        │   └── error.cpp
        ├── lmp91000
        │   ├── lmp91000.h
        │   └── lmp91000.cpp
        └── tps7a7100
            ├── tps7a7100.h
            └── tps7a7100.cpp

Both lmp91000.h and tps7a7100.h have #include "../error/error.h" and are able to access variables and functions declared in error.h and error.cpp just fine.
firmware.ino includes all three libraries as you would expect them to be included and it is able to create instances of classes defined in both lmp91000 and tps7a7100 and use their methods (which depend on error). I am also able to create instances of a struct (ERROR) defined in error.h from firmware.ino, however I am not able to access functions from error.h and error.cpp. Error recived is
firmware.ino:19: undefined reference to `LOG_E(ERROR)'

However when I remove the guards in error.h that error no longer appears (implying that LOG_E can be resolved) but I get the expected errors of multiple definitions as there are multiple #include error.h.
My thoughts are that because of the guards error is not being included in a location where the sketch has access to the functions, but I may be completely off on that. I know there must be a way around this, as I'm able to access Wire.h for example from firmware.ino even though that is included in lmp91000.h - how do I solve this?
firmware.ino
#include <error.h>
#include <lmp91000.h>
#include <tps7a7100.h>
#include <Wire.h>

lmp91000 pot(12);
tpsa7100 vreg(10,9,8,7,6,5,4);

void setup() {
    Wire.begin();
    Serial.begin(115200);
    while(!Serial);
    vreg.enable();
    pot.enable();
    ERROR misc;
    misc.errorCode = 0x50;
    LOG_E(misc);
}

void loop() {
}

error.h
#ifndef error_h_included
#define error_h_included

#include "Arduino.h"

// Error Structure
typedef struct{
    int errorCode;
    char const *errorName;
    char const *errorDesc;
    bool isFatalError;
    bool shouldRetry;
}ERROR;

// Global error types
const ERROR E_SUCCESS = {0x00, "E_SUCCESS", "Success", false, false};
const ERROR E_INVALID_ARG = {0x10, "E_INVALID_ARG", "Invalid argument passed", true, false};
const ERROR E_I2C_NACK_ADDR = {0x20, "E_I2C_NACK_ADDR", "NACK on I2C address byte", false, true};
const ERROR E_I2C_NACK_DATA = {0x21, "E_I2C_NACK_DATA", "NACK on I2C data byte", false, true};
const ERROR E_I2C_BUFF_LEN = {0x22, "E_I2C_BUFF_LEN", "Transmit Data too long for I2C buffer", true, false};
const ERROR E_I2C_ERROR = {0x23, "E_I2C_ERROR", "Undefined I2C Error", true, false};
const ERROR E_I2C_TARGET_DISABLED = {0x24, "E_I2C_TARGET_DISABLED", "Target device for I2C comms disabled", false, false};
const ERROR E_I2C_READ_ERROR = {0x25, "E_I2C_READ_ERROR", "I2C Data could not be read", false, false};
const ERROR E_I2C_WRITE_ERROR = {0x26, "E_I2C_WRITE_ERROR", "Attempting to write zero bytes to I2C bus", false, false};

// Function Definitions
bool E(ERROR error_struct);
void LOG_E(ERROR error_struct);
ERROR WireErrorDecode(int code);

#endif

error.cpp
#include "error.h"

// Error Handling Functions

// E(ERROR)
// Evaluate the successfullness of the error
// Return 0 if error is a success error
// Return >0 if error is not success error
bool E(ERROR error_struct) {
    return (int)(error_struct.errorCode & 0xF0);
}

// LOG(ERROR)
// Log the error
void LOG_E(ERROR error_struct) {
    Serial.print(error_struct.errorCode);
    Serial.print("\t");
    Serial.print(error_struct.errorName);
    Serial.print("\t");
    Serial.println(error_struct.errorDesc);
}

// WireErrorDecode(code)
// Decode Wire.EndTransmission error codes
ERROR WireErrorDecode(int code) {
    switch(code) {
        case 0:
            return E_SUCCESS;
        case 1:
            return E_I2C_BUFF_LEN;
        case 2:
            return E_I2C_NACK_ADDR;
        case 3:
            return E_I2C_NACK_DATA;
        case 4:
            return E_I2C_ERROR;
        default:
            return E_INVALID_ARG;
    }
}

Update: These errors seem to be board specific - see question here

"... implying that LOG_E can be resolved". No, it does not imply anything like that. "Undefined reference" is a linker error. And without include guards you simply never get to the linking stage because of an avalanche of other errors.

check if guard defines are unique

Did you add library.properties files to your libraries? At least test moving all the library files into the sketch folder. That might give some additional information about the build on this "unique" Arduino :)

@MikaelPatel moving the libaries into the sketch folder does allow it to compile without error. I don't unerstand why that would make a difference though, as they were originally in the libaries folder of the Arduino path. Additionally why would it only have an impact on the 101 and not on any other board as descirbed in the linked question

Are you sure that the name error is not already taken by some existing library on 101? Try renaming your library from error to something else.

Next step is to turn on verbose mode when building in the Arduino IDE so that you get the actual compile and link command lines. Study the output and you will find your error.

The filename error.h is not a good name for a library. Some compilers and cores (such as the ESP32 and Curie cores) have a file error.h of their own which will be used in preference to yours.
Instead, name your library something more sensible.


text:
Leonardo soft bricked
I was uploading a sketch to my Arduino Leonardo and I pressed the reset button accidentally while it was still uploading. Now the board does not get recognized by my computer. Is there something that can be done to save it or should I get a new one?

activate the bootloader with reset or double reset and upload a working sketch while the bootloader is active

There's no COM port to send the sketch to, even after double reset. How can I upload a sketch when there's no board recognized?

If you can no longer activate the bootloader, even with the double reset method, then it looks like you will have to reinstall the bootloader.

You'll need to program it trough the ISP port with an AVR programmer if you can't program it through a reset or double reset anymore. This can be done using another arduino. A tutorial is on the arduino.cc website.

Thank you I will try that.


text:
Send Strings via SPI both ways using two Arduino UNOs(Master to Slave & Slave to Master)
I need to create a two way String exchanger via SPI with two Arduino UNOs. Strings and their lengths are independent variables of the main loop and they can change with every iteration. I need both of the Arduinos to communicate with each other regardless of what the strings contain. I want to see basically the same screen with the serial monitor.
It is kind of working. I am not sure how to explain it, I'll just show it below.
Basically the main idea for both of the Arduino's is like this:
Master: hey
Slave: hi

Instead I get this on the master:
Slave:
Slave:
Master: hey
Slave: y
Slave:
Slave:
.
.
.
Slave: i
Slave:
Slave:
.
.

And the slave displays only itself:
Slave: hi

I have created for loops to transfer every char of the string seperatly and respectively but this is still the case. I couldn't find any sample code online for independent string transfering via SPI. I know I probably have many mistakes but how can I fix them to work just as I intend to?

Connections:
Arduino1.pin13 --- Arduino2.pin13
Arduino1.pin12 --- Arduino2.pin12
Arduino1.pin11 --- Arduino2.pin11
Arduino1.pin10 --- Arduino2.pin10

Master Code
//MASTER

#include<SPI.h>

String textSend="", textReceive="";

void setup(){

  Serial.begin(115200);

  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV8);    //Sets clock for SPI communication at 8 (16/8=2Mhz)
  digitalWrite(SS,LOW);
}

void loop(){

  textSend=""; textReceive="";
  textSend = Serial.readString();
  if(textSend != ""){
    for(int i = 0; i < textSend.length(); i++){
      delayMicroseconds (20);
      SPI.transfer(textSend[i]);
    }

    Serial.print ("Master: ");
    Serial.println (textSend);
  }else{
    int i = 0;
    char c;
    do{
      delayMicroseconds (20);
      c = SPI.transfer(1);
      textReceive += c;
      i++;
    }while(textReceive[i] != 0);

    if(textReceive[i] == 0){
      Serial.print ("Slave: ");
      Serial.println (textReceive);
      textReceive = "";
    }
  }
}

Slave Code
//SLAVE

#include<SPI.h>

String textSend="";
String textReceive="";

void setup (void){
  Serial.begin(115200);
  pinMode(MISO, OUTPUT);
  SPCR |= _BV(SPE);
  SPCR |= _BV(SPIE);
  SPI.attachInterrupt();

}

ISR (SPI_STC_vect){ //Interrupt Service Routine

  byte c = SPDR;

  if(c != 1){ //Slave receives
    for(int i = 0; i < textReceive.length(); i++){
      textReceive += SPDR;
    }
    if(textReceive.length() > 0){
      Serial.print("Master: ");
      Serial.println(textReceive);
      textReceive = "";
    }
  }else{
    for(int i = 0; i < textSend.length(); i++){
      delayMicroseconds(20);
      SPDR = textSend[i];
    }
    if(textSend != ""){
      Serial.print("Slave: ");
      Serial.println(textSend);
      textSend = "";
    }
  }
}

void loop() {
  if(textSend == "")
    textSend = Serial.readString();

}

It's not trivial to have both arduinos communicating "with each other" as SPI is a master-slave bus. That means the slave cannot start a transmission, communication must always be initiated by the master instead. Another thing with SPI is that you can't read the slave without writing to it. SPI works like a shifting register: on every clock cycle both devices transmit the byte in their SPDR to each other. So, to read a long string from the slave the master has to transmit the exact same number of dummy-bytes and simultaniously read the incoming stream. This is great if only a specific number of bytes need to be transmitted (e.g. exchanging variables which always consist of the same number of bytes), but becomes complicate when the number of bytes varies. You will then need to implement some protocol that is able to read a variable amount of bytes from the slave (e.g. you will have to tell the master the number of bytes that have to be read).
I think serial communication like UART is perfect for your purpose as communication is real full-duplex, it's no master-slave-system and the common protocol uses a terminating character to end a data stream which makes it ideal to transmit strings. Also the arduino can run several serial interfaces (you might need another for debug output).

First of all, SPI is mandatory for my assignment so I can't use anything else (but thank you for suggesting an alternative for a solution). For keeping the Master listening to the slave, can we maintain a medium which the Master keeps sending a dummy byte constantly to receive Slave's bytes (when the Master does not have anything to send). Slave wouldn't take the dummy byte into consideration and add the anything else to the string? Theoratically, I think it should work that way but I can't get it to work.

Yes, you could kind of emulate the UART protocol on SPI which means you probably will need the master to send continuously. You will then have to define a dummy-byte which will be ignored by both master/slave and a terminating byte (in UART it's typically \n) to mark the end of a string in the byte stream. Even though it's not the most elegant way I see no reason why it shouldn't work.

The reason why it doesn't work are some mistakes in your code. E.g. while(textReceive[i] != 0); is wrong as you continuously check for a condition which can't change while you check it. So the routine either does not enter this loop or it will be stuck for ever. Your master code looks like you haven't fully understood the mechanism behind SPI. Keep in mind that you have to write and read each byte at the same time. That means that a for loop like in your case for(int i = 0; i < textSend.length(); i++) doesn't work because you don't handle the incoming bytes which by this are lost.


text:
Spinning ESC Brushless Motor Slower
I am controlling a g-series 1000kv brushless motor with my arduino. Currently I have my setup as follows:

Now I used the code given to me in a tutorial which is also as seen below:
#include <Servo.h>
Servo ESC;     // create servo object to control the ESC
int potValue;  // value from the analog pin
void setup() {
  // Attach the ESC on pin 9
  ESC.attach(9,1000,2000); // (pin, min pulse width, max pulse width in
microseconds)
}
void loop() {
  potValue = analogRead(A0);   // reads the value of the potentiometer (value between 0 and 1023)
  potValue = map(potValue, 0, 1023, 0, 180);   // scale it to use it with the servo library (value between 0 and 180)
  ESC.write(potValue);    // Send the signal to the ESC
}

at any voltage (tested between 7.4v and 12v) i was not able to change the spin speed despite my knowledge being voltage x 1000 is the rpms. I want to run a piece of code that will spin the motor slowly but no solution is working.

So, does your motor spin at all? Did you carry out ESC's arming sequence? Also, are you powering your Arduino from the BEC built into the ESC?

Arduino is powered from the BEC but sometimes from computer so it is a little of both. And yes I carried out the arming sequence

And the motor does spin just starts off really fast


text:
Usbasp Arduino Uno Bootloader Flash Error - Win 10
I'm trying to flash an Arduino Uno using usbasp but i'm getting the following error,I have checked all the connection and voltage using multimeter but still this error:
Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/bin/avrdude -CC:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cusbasp -Pusb -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Error while burning bootloader.

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

I have tried different three other Usbasp but still same error

This is the same dead programmer from before? Check the traces and connections on the programmer for shorts / open circuits. Also the cable.

@Majenko It's the dead programmer form before. I am using desktop with Intel Coffee Lake processor and MSI Z370 motherboard, can this cause any problem?

Take it out of the lake of coffee? Your computer is irrelevant. The fact that you have a known dead programmer is all that matters.

@Majenko Thanks

@Majenko i just need to flash the boot loader on an arduino uno, this time i'm using Arduino as ISP and getting this https://pastebin.com/3FhQfA6R, Connection: IMG1 IMG2

I have tried two different arduinos as isp but same error.

You have nothing to prevent the Nano resetting when avrdude opens the serial port...?

What i have to do to use the arduino nano to burn the boot-loader on the UNO?

Stop it from resetting. Have you read any of the (good) tutorials?

Can you share me a link of good tutorial to understand fully?

https://hardwarefun.com/tutorials/use-arduino-as-an-isp-programmer-to-program-non-arduino-avr-microcontrollers

@Majenko I have tried different three other Usbasp but still same error

The problem was with the Arduinos i have received from AliExpress All of them are using WAVGAT AVGA 328P-AU chips. I flasthed other Atmel MEGA 328P chip based Arduinos using USbasp and it's working fine. But i dont know how to flash those WAVGAT AVGA 328P-AU chips.

I ran into the same issue. Those clone chips cannot be flashed over the ISP port. So you cannot change the bootloader at all. Just a piece of junk in my opinion.


text:
How to programme a button per colour for a neopixel strip?
I am trying to make a particular pixel in a neopixel strip, turn green, red or blue depending which button has been pressed and to stay on until pressed off again (like a toggle), but currently when I press one of the buttons it flashes the correct colour when button is pressed down but isn't acting as a toggle switch and then goes to a white light.

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinke
#endif

#define BUTTON_PIN1  2
#define BUTTON_PIN2  10
#define BUTTON_PIN3  11
#define PIXEL_PIN    6  // Digital pin 6 connected to the NeoPixels.

#define PIXEL_COUNT 13  // Number of NeoPixels

// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800);

boolean oldState1 = HIGH;
boolean newState1 = HIGH;

boolean toggle1 = LOW;

boolean oldState2 = HIGH;
boolean newState2 = HIGH;

boolean toggle2 = LOW;

boolean oldState3 = HIGH;
boolean newState3 = HIGH;

boolean toggle3 = LOW;

void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN1, INPUT_PULLUP);
pinMode(BUTTON_PIN2, INPUT_PULLUP);
pinMode(BUTTON_PIN3, INPUT_PULLUP);
strip.begin(); // Initialize NeoPixel strip object (REQUIRED)
strip.show();  // Initialize all pixels to 'off'
}

void loop() {
updateButtonState1();
updateButtonState2();
updateButtonState3();

}

void updateButtonState1() {

 // Get current button state.
 newState1 = digitalRead(BUTTON_PIN1);

 if ((newState1 == LOW) && (oldState1 == HIGH)) {
 delay(50);
 newState1 = digitalRead(BUTTON_PIN1);
 if (newState1 == LOW) {
   toggle1 = !toggle1;
  }
 }
 oldState1 = newState1;

if (toggle1 == HIGH) {
strip.setPixelColor(2, 245, 15, 15); //electrical/fire hazard (red)
} else {
strip.setPixelColor(2, 0, 0, 0);
}
strip.show(); // Update strip with new contents
}

void updateButtonState2() {

// Get current button state.
 newState2 = digitalRead(BUTTON_PIN2);

if ((newState2 == LOW) && (oldState2 == HIGH)) {
 delay(50);
 newState2 = digitalRead(BUTTON_PIN2);
 if (newState2 == LOW) {
   toggle2 = !toggle2;
   }
  }
 oldState2 = newState2;

  if (toggle2 == HIGH) {
  strip.setPixelColor(2, 13, 50, 190); //Leak (blue)
  } else {
  strip.setPixelColor(2, 0, 0, 0);
  }
 strip.show(); // Update strip with new contents
 }

 void updateButtonState3() {

 // Get current button state.
 newState3 = digitalRead(BUTTON_PIN3);
 if ((newState3 == LOW) && (oldState3 == HIGH)) {
  delay(50);
  newState3 = digitalRead(BUTTON_PIN3);
  if (newState3 == LOW) {
    toggle3 = !toggle3;
  }
 }
 oldState3 = newState3;

 if (toggle3 == HIGH) {
 strip.setPixelColor(2, 58, 233, 65); //bins/recylcing (green)
 } else {
   strip.setPixelColor(2, 0, 0, 0);
  }
  strip.show(); // Update strip with new contents
}

Why do you want/need to use an array?

Is the shown code not working correctly? If so, include a description in your question, how it IS actually behaving and what you expect from it.

You do not really have to use an array for this, though I do agree that it's the cleanest solution.
Here is a simplified version of your code, do mind you'll still have to do the button handling yourself (by setting buttonpressed to 'true' when the button is pressed.
Also, when adding more colors to the array, you'll have to manually adjust 'totalColors'.
void setup() {
  //Color/pixel declarations based on https://learn.adafruit.com/adafruit-neopixel-uberguide/arduino-library-use
  uint32_t magenta = strip.Color(255, 0, 255);
  uint32_t greenishwhite = strip.Color(0, 64, 0, 64);

  //https://www.arduino.cc/reference/en/language/variables/data-types/array/
  uint32_t colors[] = {magenta, greenishwhite};
  unsigned char totalColors = 2;
  unsigned char currentColor = 0;
}

void loop() {
  if (buttonpressed) {
    //Change the "currentColor" index every time the button is pressed, but make it start at 0 when it reached the end.
    currentColor++;
    if (currentColor >= totalColors) {
      currentColor = 0;
    }

    //From the array of colors, pick the one with the index "currentColor" and show it.
    ledstrip.fill( colors[currentColor] , 0, strip.numPixels() - 1);
    ledstrip.show();

    buttonpressed = false; //Reset flag, so this doesn't get executed until next time button is pressed.
  }
}

You should be able to replace the first 3 lines (setting up the array) with a single:
uint32_t colors[] = {strip.Color(255, 0, 255,  strip.Color(0, 64, 0, 64)};

But I had it split up to better show the idea of the array.
Alternatively you could do:
switch(currentColor){
  case 0:
    //Color RED
  break;
  case 1:
    //Color GREEN
  break;
  case 2:
    //Color BLAUW
  break;
}

Thank you so much! Where in the code do I set up the buttonpressed as true ? I thought potentially an array was the best way to do it as after this I would like to set it up so that first in can be input which neopixel to turn on with one set of buttons then which colour (which is the part this code is trying to address)

It doesn't quite matter where you put "buttonPressed" to true. Though preferably before the code where it checks it. You could even swap "buttonPressed" for ”digitalRead(buttonPin)” and put a delay after changing the colours of the pixels (to avoid contact bounce to call do it multiple times for a single press).


text:
How does input from IR receiver to Arduino UNO board work?
I have a very simple circuit with an Elegoo IR receiver module connected to an Arduino UNO. The three wires are connected correctly with the data wire (Y) connected to pin 8. The code works fine, as every time I press button on the remote, the Serial Monitor displays the corresponding button description.
However, I do not understand how Arduino's pin 8 knows which IR button has been pushed. My understanding is that pin 8 can read either 5V or 0V, but to know which of 20+ remote buttons has been pushed it would have to read PWM. But pin 8 does not the PWM icon next to it and yet it works fine. Unless the PWM icon applies only to pin output? Or is there another way I have failed to find info about?
Thanks!

What do you actually mean by pwm "icon"?

@yannism mean that Pin 8 is not a PWM pin, look at a Arduino UNO pin layout.

Serial RX works on one pin too

The PWM icon says that the pin can be used as PWM output. The remote sends a series of pulses (for instance here there is a brief analysis on the NEC protocol - be aware that there exist many more). You will need to decode the pulses lengths to get a code which represent the key. The IRRemote library was done to help in this task (I used it once to control a robot with a remote controller)

You confuse the different technologies here.

PWM is only an output, not an input. So every pin marked with the PWM symbol can OUTPUT a PWM signal. Reading a signal is a totally different task with different hardware involved.
The IR receiver does not output a PWM (meaning Pulse Width Modulation) signal to the Arduino. It ouputs the demodulated IR signal.

So here is what happens: The remote a code, that consists of different periods of "light on" and "light off" (giving pulses of different length, which encode the data from binary format). Since you want to seperate the remotes signal from any other IR signal, that might roam through the air, the remote also modulates the pulses with a special frequency (often this is 38kHz, but might be another frequency around that). This means that every pulse will be chopped into shorter pulses at the specified frequency. This translates to something like: "light on and off with 38kHz for duration x" --> "light off" --> "light on and off with 38kHz for duration y" --> ...
The receiver module senses the IR light comming in and will electronically discard all signals, that don't have the special frequency, and does the demodulation on this. The outputted signal does not have the 38kHz frequency in it anymore. Just the pulses of different length, that encode the data, meaning
The Arduino then reads the length of the pulses (that only consists of sequences of 0V and 5V) and decodes them into a number. This number represents the pressed button.
A proper library for the Arduino can read the different data protocols used in common IR remotes.

Awesome! So basically my understanding was correct in that the Arduino input pin reads pulses, but I thought it was just another instance of PWM, which is not. Thank you!

The remote control emits encoded IR-bursts (each button has its own code) which are transformed into electrical pulses by the sensor (ref. 6. in here: http://eeshop.unl.edu/pdf/VS1838-Infrared-Receiver-datasheet.pdf). On the arduino those pulses are decoded using a proper library.
That means pin 8 is not reading any analog or pwm signal, but TTL-logic at 5V.

Thanks. Will read more on the TTL-logic.


text:
Data type conversion problem
I have a Wemos D1 board with a OLED display using the u8g2 library.
I am printing my MAC-adress on the serial port & would like to print the same information on the OLED:

#include <ESP8266WiFi.h>
#include <U8g2lib.h>
byte mac[6];
setup(){
  Serial.println(WiFi.macAddress());
  WiFi.macAddress(mac);
  u8g2.drawStr(1,10,WiFi.macAddress());
  u8g2.sendBuffer();
}

This does not work. It prints the MAC-address on the serial port but not on the OLED.
I get: no known conversion for argument 3 from 'String' to 'const char*
How can I print the MAC-information on my oled using the u8g2-library?

Hint: WiFi.macAddress().c_str() https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/c_str/

As said by @Mikael Patel
You need to append .c_str() to u8g2.drawStr(1,10,WiFi.macAddress()); creating the line: u8g2.drawStr(1,10,WiFi.macAddress().c_str());
The problem is that WiFi.macAddress() returns a String not the needed const char* by the drawStr function. c_str converts the String object into a const char*.
Please look at the documentation of the u8g2 library for the drawStr function.
link
And here the documentation for String
link


text:
Variable declared inside void setup() is forgotten in void loop()
If I declare a variable in void setup() and try to do something with it in void loop(), it just says that the variable is undeclared. Here is the code:
#include "Servo.h"

void setup() {
  Servo servo1;
  int x_key = A0;
  servo1.attach(2);
  pinMode(A0, INPUT);
  pinMode(2, OUTPUT);

  int x_position = 90;
}

void loop() {
  if (analogRead(A0) < 512) {
    x_position++;
    servo1.write(x_position);
  }
}

You need to select your code and tap the {} (code formatting) button. I did it for you.

Of course it's undeclared. The variable is in setup. It's not in loop.

Because the variable is only valid, where it is declared, to use the official term: it's scope. When the program moves out of the scope of this variable, it will get thrown away and be no longer available. You can declare it in global scope, meaning outside of any function

This is more a question about C/C++, not about Arduino

@chrisl true, but the OP doesn't know enough to know where to ask the question. We all have to start somewhere. I just wish people would do some self-study before running to the internet looking for somebody else to answer their questions for them.

what is your question? ... you did not ask anything

Yes, that is how C and C++ (and most other C-like languages) work. Variables have "scope". Any variable define inside a pair of curly braces (between a { and a }) is only visible inside those braces.
If you want to reference a variable in both setup() and loop(), you have to make it a global variable, defined at the top of your code.
#include "Servo.h"
Servo servo1;
int x_position = 90;  //Define your global var(s) here

void setup() {
    int x_key = A0;  //This var only exists inside the setup function
    servo1.attach(2);
    pinMode(A0, INPUT);
    pinMode(2, OUTPUT);

}

void loop() {
    if (analogRead(A0) < 512) {
        x_position++;
        servo1.write(x_position);
    }
}

Surely servo1 should be global as well?

Yup, that too. I was in  a bit of a hurry when I made that post.


text:
HTTP myphp request error RFID
This program is a program which readings of rfid are saved to myphp database. I have a problem when running the code The wifi is connected but when the code doesn't save im assuming that the problem is in this part of the code client.print("GET /rfid/nodemcu_rfid/rfid_read.php?allow="); Since i have done a wire shark capture and notice a Bad Request error 400 as shown in the screen shot.
IP Addresses: 192.168.0.14 Is the php server , 192.168.0.19 is the nodemcu
ALL THE CODE :

#include<SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <SPI.h>
#include <MFRC522.h>

const char* ssid = "ARRIS-84AB";
const char* password = "your SSID password ";
//WiFiClient client;
char server[] = "192.168.0.14";   //eg: 192.168.0.222
#define SS_PIN 2 //FOR RFID SS PIN BECASUSE WE ARE USING BOTH ETHERNET SHIELD AND RS-522
#define RST_PIN 15
#define No_Of_Card 3

 WiFiClient client;

//WiFiServer server(80);
SoftwareSerial mySerial(8,9);
MFRC522 rfid(SS_PIN,RST_PIN);
MFRC522::MIFARE_Key key;
byte id[No_Of_Card][4]={
  {44,153,22,219},             //RFID NO-1
  {112,224,72,84},             //RFID NO-2
  {151,94,80,84}              //RFID NO-3
};
byte id_temp[3][3];
byte i;
int j=0;
void setup()
{
 Serial.begin(115200);
  delay(10);
  mySerial.begin(115200);
  SPI.begin();
  rfid.PCD_Init();

    for(byte i=0;i<6;i++)
  {
    key.keyByte[i]=0xFF;
  }

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  // Start the server
//  server.begin();
  Serial.println("Server started");
  Serial.print(WiFi.localIP());
  delay(1000);
  Serial.println("connecting...");
 }
void loop()
{  // Check if a client has connected
  int m=0;
  if(!rfid.PICC_IsNewCardPresent())
  return;
  if(!rfid.PICC_ReadCardSerial())
  return;
  for(i=0;i<4;i++)
  {
   id_temp[0][i]=rfid.uid.uidByte[i];
             delay(50);
  }

   for(i=0;i<No_Of_Card;i++)
  {
          if(id[i][0]==id_temp[0][0])
          {
            if(id[i][1]==id_temp[0][1])
            {
              if(id[i][2]==id_temp[0][2])
              {
                if(id[i][3]==id_temp[0][3])
                {
                  Serial.print("your card no :");
                  for(int s=0;s<4;s++)
                  {
                    Serial.print(rfid.uid.uidByte[s]);
                    Serial.print(" ");

                  }
                  Serial.println("\nVALID");
                  Sending_To_DB();
                  j=0;

                            rfid.PICC_HaltA(); rfid.PCD_StopCrypto1();   return;
                }
              }
            }
          }
   else
   {j++;
    if(j==No_Of_Card)
    {
      Serial.println("inVALID");
      Sending_To_DB();
      j=0;
    }
   }
  }

     // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
 }

 void Sending_To_DB()   //CONNECTING WITH MYSQL
 {
   if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    Serial.println("GET /rfid/rfidread.php?allow=");     //YOUR URL /rfid/rfidread.php?allow
    client.print("GET /rfid/nodemcurfid/rfidread.php?allow=");     //YOUR URL /rfid/rfidread.php?allow  /var/www/html/rfid/rfid_read.php
    if(j!=No_Of_Card)
    {
      Serial.println('1');
      client.print('1');
    }
    else
    {
      Serial.println('0');
      client.print('0');
    }
    Serial.println("&id=");
    client.print("&id=");
    for(int s=0;s<4;s++)
                  {
                    Serial.println(rfid.uid.uidByte[s]);
                    client.print(rfid.uid.uidByte[s]);

                  }
    client.print(" ");      //SPACE BEFORE HTTP/1.1
    client.print("HTTP/1.1");
    client.print("Host: ");
     client.println(server);
    client.println("Host: 192.168.0.14");//eg: 192.168.0.222
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
  client.stop();
 }

client.println("Host: YOUR SERVER IP");//eg: 192.168.0.222 -- Is that really what you have in your running code?

no my that is a sample my code is client.println("Host: 192.168.0.14");

Please show us your real code. We can't tell you what is wrong with your code if you show us something that is not your code.

Edited with all configs (the real code)

Your problem is here:
client.print(" ");      //SPACE BEFORE HTTP/1.1
client.print("HTTP/1.1");
client.print("Host: ");
 client.println(server);
client.println("Host: 192.168.0.14");//eg: 192.168.0.222
client.println("Connection: close");
client.println();

That ends up with:
....(your request)... HTTP/1.1Host: 192.168.0.14
Host: 193.168.0.14
Connection: close

Not only are you sending the Host header twice, but you're not adding the line ending after the HTTP version.
Instead it should look more like:
client.print(" ");      //SPACE BEFORE HTTP/1.1
client.println("HTTP/1.1"); // <-- Note the use of println not print
client.print("Host: ");
client.println(server);
client.println("Connection: close");
client.println();

I have fixed the code like this but still no luck
client.print(" ");      //SPACE BEFORE HTTP/1.1     client.print("HTTP/1.1");     client.println(" Host: 192.168.0.14");//eg: 192.168.0.222     client.println("Connection: close");     client.println();
What is a line ending after HTTP version please ?

See my edit....

Thanks it worked !!!


text:
Problems when racing multiple IR controlled Arduino robots
We are attempting to race 3 IR-controlled Arduino robots (Elegoo IR kit), but the IR signal from each remote seems to be picked up by all three receivers. It is possible to create a unique bond between each IR remote and its receiver? Lego Mindstorms IR remote has channels to solve this problem. Anything I can do with Arduino?

With a regular IR (TV) remote, each button has a different code. What is stopping you from using different codes for the different robots?

For example, the directional keys of a remote for robot 1, the numerical keys for robot 2 and maybe a remote from a completely different manufacturer for robot 3.

Not familiar with Elegoo kit... Question is are they using 1 way or 2 way communication? If they use 1 way communication(which is most likely) there's not much you can do since multiple IR signals interfere with each other, and you would need the toys to send back acknowledge signals to the controller, to do error correction... In that case the most you can do is give them each a unique id, and make them ignore anything else then commands associated with their unique id.
If they do 2 way communication you can also make the controller only send a command when a button is pressed, and when it's released, instead of continuous transmission, while also making sure that the command is understood by the receiver. That minimizes interference for other controllers. And if the command was not understood then wait random milliseconds, and repeat it until the receiver understands it.

IR remote signals are OOK-modulated with different base frequencies (the most common are  36 kHz, 38 kHz and 40 kHz). Elegoo seem to use 38 kHz transmitters/receivers, so if you manage to find 36/40 kHz devices, you'll get 3 channels with somewhat reduced interference.


text:
Encrypting data between NRF24L01 using AES
I am trying to send encrypted data using AES  via a pair of NRF24L01 and two Arduino Uno boards. I have made two sketches but can not get it working.
The used library for AES:
enter link description here
Transmitter code:
// TrackControl - the master or the transmitter

 // http://tmrh20.github.io/RF24/

 //~ - CONNECTIONS: nRF24L01 Modules See:
 //~ http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
 //~ 1 - GND
 //~ 2 - VCC 3.3V !!! NOT 5V
 //~ 3 - CE to Arduino pin 9
 //~ 4 - CSN to Arduino pin 10
 //~ 5 - SCK to Arduino pin 13
 //~ 6 - MOSI to Arduino pin 11
 //~ 7 - MISO to Arduino pin 12
 //~ 8 - UNUSED

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <AESLib.h>

#define CE_PIN   9
#define CSN_PIN 10
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};

// NOTE: the "LL" at the end of the constant is "LongLong" type
// These are the IDs of each of the slaves
const uint64_t slaveID[2] = {0xE8E8F0F0E1LL, 0xE8E8F0F0E2LL} ;

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char  dataToSend[]="123456789012345";

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000;
int txVal = 0;
float ackMessg[2]={1,2};
byte ackMessgLen = 4; // NB this 4 is the number of bytes in the 2 ints that will be recieved

void setup() {

    Serial.begin(9600);
    Serial.println("Track Control Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.enableAckPayload();
    radio.setRetries(10,5); // delay, count
}

//====================

void loop() {

    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {

    radio.openWritingPipe(slaveID[0]); // calls the first slave
                                        // there could be a FOR loop to call several slaves in turn
    aes256_enc_single(key, dataToSend);

    bool rslt;
    rslt = radio.write( dataToSend, sizeof(dataToSend) );
    Serial.print("\nRSLT (1 = success) ");
    Serial.println(rslt);

    if ( radio.isAckPayloadAvailable() ) {
        radio.read(ackMessg,ackMessgLen);
        Serial.print("Acknowledge received: ");
        Serial.print(ackMessg[0]);
        Serial.print("  ");
        Serial.println(ackMessg[1]);
    }
    prevMillis = millis();
 }
}

Receiver code:
// HandController - the slave or the receiver

    // http://tmrh20.github.io/RF24/

    //~ - CONNECTIONS: nRF24L01 Modules See:
    //~ http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
    //~ 1 - GND
    //~ 2 - VCC 3.3V !!! NOT 5V
    //~ 3 - CE to Arduino pin 9
    //~ 4 - CSN to Arduino pin 10
    //~ 5 - SCK to Arduino pin 13
    //~ 6 - MOSI to Arduino pin 11
    //~ 7 - MISO to Arduino pin 12
    //~ 8 - UNUSED

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>

#include <AESLib.h>

#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type

const uint64_t   deviceID = 0xE8E8F0F0E1LL; // Define the ID for this slave
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};

int valChange = 1;

RF24 radio(CE_PIN, CSN_PIN);

char  dataReceived[32];
int ackData[2] = {12,23};

void setup() {

    Serial.begin(9600);
    delay(1000);
    Serial.println("Hand Controller Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.openReadingPipe(1,deviceID);
    radio.enableAckPayload();
    radio.writeAckPayload(1, ackData, sizeof(ackData));
    radio.startListening();
}

void loop() {

    if ( radio.available() ) {
        radio.read( dataReceived, sizeof(dataReceived) );
        radio.writeAckPayload(1, ackData, sizeof(ackData));
         for (int x = 0; x <32; x++) {
      //if (dataReceived[x] < 16) {
      //  Serial.write('0');
    // }

    //  Serial.print(dataReceived[x]);}
    // Serial.println();

        ackData[0] += valChange; // this just increments so you can see that new data is being sent
    }
   aes256_dec_single(key, dataReceived);
    Serial.println("decrypted:");
    Serial.println(dataReceived);
}}

I cannot receive the same message after decryption.

attach your output here so we have better understanding what is the issue.

i got strange characters at the receiver side
when i test AES encryption/decryption a lone without nRf24l01 i receive the input data normally after decryption
when i use nRF24l01 without encryption decryption i receive the sent data on the receiver side normally

aes256_dec_single requires dataToSend to be 256 bits as-well. From what I know, AES only works on multiples of block sizes. It can't handle variable length data. The way to work around that is to pad the data with, for example, zeros, till it's a multiple of the block size.

I still think serial terminal output will help us for better understanding.


text:
How to convert digital signal to analog value
I have spwm output from arduino, and when i read on analogread it shows only 1023 and 0, because it is digital signal.
Is there any way to convert these spwm value into analog value reading

arduino had 10 bit ADC that means maximum value that you can read is 0-1023. It is an analog signal. or if you want to convert digital value into analog value use can DAC IC easily available in the market.

Thanks try to search it

The problem seems to be clear to you: for slow systems a pwm signal can be considered analog, but measuring at higher rates and without a filter reveales the digital nature behind pwm and all you see is either logic high (1023) or low (0).
Possible solutions are:

apply a filter in hardware (LC low-pass)
apply a filter in software (e.g. by calculating a running mean)
attach interrupts to the rising/falling edge of your signal and measure the high/low time to calculate the duty cycle

Which of those options to choose will mainly depend on the PWM frequency you want to measure. For low frequency I recommend option 3 (special cases are duty cycles around 0% and 100% as there are no edges), for higher frequencies I would use option 1/2.

Thanks very much helping


text:
Connecting arduino with MATLAB
I installed Octave support package for Arduino and it is listed in the packages installed when pkg list command is run.But when the command  "a= arduino('COM8')";
is run,"error: serial: Error opening the interface: No such file or directory" is shown.Please respond.

Are you able to connect with the Arduino on COM8 through the Arduino IDE?

So in the Windows device manager, what COM ports do you see?

Using clear command on Octave before executing a=arduino('COM8') will remove this problem.
Use it like this:
clear
a=arduino('COM8')


text:
How to find out the maximum used stack space?
I am creating an Arduino sketch which involves quite some classes, and I want to check if it will run on an Arduino Uno or Mega (2 KB vs 8 KB SRAM).
So far my global variables take up around 1,200 bytes, and I expect this will rise. However, beyond that I need to make sure the stack memory is not using up too much. How can I find the maximum used stack size?.
I can check manually by calculating the maximum function stack and calculating all parameters + local variables, but this is a very tedious job (especially since my application changes still a lot).
Or another way: I know it is possible to get the free space, but should I add this in 'strategic' locations or in the beginning of all functions and continue from there? (there will be many of them).
Or is there preferable some static way of checking this?
The application works within Visual Studio C++ as stand alone too, so maybe that helps for some solution.
I expect the stack size easily to be a few hundred bytes (which is quite a lot for the Arduino Uno SRAM).

Could always use Atmega1284P as well with 16K SRAM space.  I had a project with 45 shift registers, 325 rows of data, that were updated and blasted out over SPI at 20 KHz rate, used 14,625 bytes of SRAM.

@CrossRoads: Can I find a (cheap) Arduino compatible-board with an AtMega1284P? . Actually, as alternative I can use a Mega, and for my 'main' project where I need more memory, I am intending to use an STM32 later.

Look here, www.crossroadsfencing.com/BobuinoRev17  Add 1284 core files to the Arduino IDE  https://github.com/MCUdude/MCUdude_corefiles

You should clarify: are talking about the heap (as in the title) or the stack (as in the question body)?

@CrossRoads cool to be able to use that, but I saw beyond the not so cheap price I rather use a Mega, and another CPU to do the real work. But good to know there are AtMega CPUs capable of more (I didn't knew that.)

@EdgarBonet Yes, mistake from my side, I fixed it, thanks.

You'd maybe want to use stack painting or ask GCC about the stack usage by adding -fstack-usage, for both see https://stackoverflow.com/a/6390246/5296568. There are also post-analysis tools like https://github.com/PeterMcKinnis/WorstCaseStack. Also see https://ucexperiment.wordpress.com/2015/01/02/arduino-stack-painting/

@MaximilianGerhardt Thanks for this info; maybe I can use it on the Windows version to get a good idea already beforehand.

Knowing the stack size is pretty easy: the stack pointer is initially
set to RAMEND and goes down as the stack grows. Thus:
static inline size_t stack_size()
{
    return RAMEND - SP;
}

should I add this in 'strategic' locations [...]

Obviously, the result will depend on where this is evaluated. Ideally
you should test this in the deepest parts of your call chain, as this is
where the stack will be at its maximum size. Note that ISRs stack on top
of all your regular code.
Edit: There is no easy way to know the maximum stack size. You
could get an approximation by sampling the stack at regular intervals,
e.g.:
#include <util/atomic.h>

volatile size_t min_sp = RAMEND;

ISR(TIMER0_COMPA_vect)
{
    if (SP < min_sp)
        min_sp = SP;
}

static inline size_t max_stack_size()
{
    size_t min_sp_copy;
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        min_sp_copy = min_sp;
    }
    return RAMEND - min_sp_copy;
}

If you enable TIMER0_COMPA interrupt in setup():
TIMSK0 |= _BV(OCIE0A);

then the stack size will be sampled every 1.024 ms. Note, however,
that this ISR is itself using some stack space for its own purposes
(9 bytes in my experiment), and that this is not sampling other
ISRs or critical sections.

Thanks, the interrupt way is indeed great to check the maximum size. And good to know about the RAMEND / SP variables (registers).

@MichelKeijzers: RAMEND is actually a constant defined in <avr/io.h>. SP is indeed an IO register or, rather, a pair of registers.

Thanks for the clarification.

This assumes you do not use the heap: no new, no malloc, no String objects. A good idea on small controllers, anyway.

@DataFiddler: The question title was about heap (has been fixed since), but the question body is about stack. My answer specifically addresses the stack, not the heap.

I do not zing you for your response, @Edgar. SP is very easy to use. Much nicer than (int)&aTempLocalVariable. My comment were just my two cents on "stack size is irrelevant if you do not know your dynamic heap requirements".

Initialize the entire SRAM space from the top of the heap to the bottom of the stack, either during setup, or in a modified version of the Arduino-provided main() function, with some unlikely pattern, such as {0x55, 0xAA, ...} or "UnusedUnused...".
After your program has run a while, examine memory for dirty footprints, reading up from the top of heap to find the highest heap excursion, and down from the stack-pointer to find the lowest address used by stack. You could use a debugger if you have one, or just a hex & ASCII dump to the terminal. Pick through it with whatever tools you have handy on your PC. If there's been no collision and you're using a memory dump, it's pretty easy to start somewhere in the middle that wasn't disturbed, and scroll in either direction. The place where your initialized pattern has been overwritten usually stands out very plainly.

I upvoted it because it's another idea, but I think just printing the value seems easier.... or is it possible to download a 'hex dump' from a running program? (e.g. by the Arduino IDE)

I send the hex dump to the Arduino terminal, save it to a PC file, and inspect it on the PC.

Thanks also sounds like an interesting idea. Thanks


text:
Load cell and hx711 with arduino
I wanted to connect the load cell with hx711 to Arduino to check the presence of load. If there is load on the load cell then an LED can light up and when there is no load the LED will be off. I tried several codes but I'm not getting the result I need. If anyone of you can help with this as this is for my graduation project I will be grateful.
EDIT:
Here is my code, I'm a beginner in Arduino so I don't know much about how it works but this is what I managed to write. PS. the hashtaq before include makes the the text in bold so I excluded it here.
include < HX711_ADC.h >

HX711_ADC scale (2,3); //DT pin2 , SCK pin3
int load1 =0;

void setup() {
   pinMode (3,INPUT); // SCK pin
   pinMode (13,OUTPUT); //LED pin
   Serial.begin(9600); }

void loop() {
   load1= digitalRead(3); // read signal from SCK pin

   if(load1==HIGH) // if there is load on load cell
        {
        digitalWrite(13,HIGH); // turn on the LED
        delay(5000);
   } else {
       digitalWrite(13,LOW); // turn off the LED
       delay(5000);
   }
}

Can you show us the code you have written so far?

This isn't a forum. Don't respond to questions with an "answer". Amend your question.

@bummi - Whoops sorry for the rejection, didn't realise that the edit was from the answer. My bad.

look at the line starting with void setup() ... everything after the ; // all way to end of line is a comment .... it is not code that executes .... same goes for the two lines after that .... please correct the code listing

You are not using the https://github.com/bogde/HX711 library properly.  Instead of load1=digitalRead(3); try something like load1 = scale.get_units(); (and initlialize the scale with a scale.begin() in setup and maybe a scale.tare() )


text:
How to drive Arduino UNO as a counter triggered by 555 timer's output (astable mode)
I have an Arduino Uno and a 555 timer configured to astable mode.
What I'm trying to do is to program my Arduino to increase a "counter" variable (counter++) everytime it gets triggered by 555 timer's output (through analogIN pin).
My problem is that Arduino takes 555 timer's output as a continuous triggering and increases my counter as long as the pulse in the analogIN lasts.
So instead of incrementing by 1, it is increased by approximately 97 (sometimes more or less).
I need to take the analog in as a "packet" so everytime analogIN is triggered, no matter how long the pulse lasts, it will be treated as a single event and not as continuous triggering.
What do I have to change?
My code:
int counter = 0;

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

}

void loop() {
  if(analogRead(A0) > 250) {
    counter++;
    Serial.println(counter);
  }

}

Thanks

Have your code remember the previous value, and only increment when the previous value was below 250, and the current value is above 250.

PS is there any reason why you are using analogRead, instead of digitalRead?

you are checking for high, but you assume that low will somehow be magically checked also

No, even when I checked for low it didn't work as expected

You need to create a finite state machine with 2 states:

Waiting for input from 555 to go high.  When this happens increment the counter & advance to the next state.
Waiting for the input from the 555 to go low.  When this happens advance to the next state.  That is, the first state.

In the following Arduino "State Change Detection (Edge Detection) for pushbuttons" example / tutorial you do not need the complex code to debounce the switch.  However, the edge detection and state machine portion of the code can likely be applied to your project.

It seems that edge detection is what I needed. Thank you!

This approach might lead to unreliable readings when many and/or time consuming tasks are handled in loop(). It might be a proper solution to read slow and single events like button activity, but i don't recommend it to read a 555 pulse signal.

I recommend using one of the atmega's counter modules. That way you can count the pulses synchronuously to your program (real paralellism!) and you also don't have to implement any edge-detection youself as the counter module already provides this feature.
A search for "pulse counter" will lead to many tutorials on how to do that.

Edge detection seems to work fine. What is the difference between edge detection and your solution? is it faster? more reliable?

Yes, it is both faster and more reliable because it is handled by a hardware module that is optimized for edge detection and runs in parallel to your program. The counter module btw also gets involved when generating harfware pwm. Instead of counting a clock's edge it just counts the edges of an input signal.

@BrainTrance, the HW solution is good.  If you are new to Arduino or embedded programming it may be a bit difficult.  But should result in a more robust solution.  That said, do concern your self with directly using HW.  It may be the HW resource of interest is already being used by other software such an included Serial Communication Arduino Library or LED Brightness Controller Arduino Library.


text:
Arduino Hardware serial pins with RS485
I tried asking a question in my earlier post - SerialEvent with RS485 communication it helped me understand Hardware serial and Software serial but i had few more questions for which i started this new thread. Now i didn't write any code yet, but i will be using same code as my earlier post if i get expert inputs.
My Project - I have 6 Arduino nano which will do some simple task, mostly its one way communication at a time, like once master send message to slave i don't want immediate response slave will push button or something and then it will send response to master. So its rare that i will have two way communication at same time.
RS485 - I am going to use RS485 as distance is around 40ft.
Now my questions -
1 - Can i use Hardware serial pins with RS485 for 40ft distance, i tested code and it does work but i couldn't test that for 40ft. So not sure if it works or not.
2 - Is it good idea to use hardware serial pins for my project i explained, as i see plus and minus over internet and making me confuse. I see majority people recommend Hardware pins though.
3 - Is there limitation connecting multiple arduino nano with this approach, i only did this with 2 so far.
I would appreciate your inputs, which will make me decide to go on right path. Sorry i didn't post any code because my post is more to understand correct path to be followed...

https://en.wikipedia.org/wiki/RS-485

@Juraj thanks for answer but i don't think it answer any of my questions, i know function of RS-485 what i am looking for more in terms with Arduino nano with its hardware pin.

the MAX485 chip on the adapter does the RS485, not the Nano. Nano communicates only with that MAX485. if you use hardware serial for RS485 communication, how will you debug your code without Serial?

@Juraj i might have asked question incorrectly, from what i understood if i use Pin 0 & 1 which are hardware serial i don't have to use Software serial. Which you can see in my post i mentioned. Now what i wanted to know is weather i can use that SerialEvent approach for my project or not, along with RS485 which uses MAX485.

if you use hardware serial for the rs485 modules, you can't use it for Serial Monitor. USB is wired to the only one hardware serial of the 328p

1 - Can i use Hardware serial pins with RS485 for 40ft distance, i tested code and it does work but i couldn't test that for 40ft. So not sure if it works or not.

Yes.

2 - Is it good idea to use hardware serial pins for my project i explained, as i see plus and minus over internet and making me confuse. I see majority people recommend Hardware pins though.

Yes. SoftwareSerial is awful.

3 - Is there limitation connecting multiple arduino nano with this approach, i only did this with 2 so far.

Yes. The MAX485 and similar chips can only handle up to about 30 devices on one bus. The exact number is in the datasheet for the chip.

Thanks!!! this really helps me to follow correct direction.


text:
Voltage measure range of an arduino?
I recently thought of using an Arduino to measure voltage and I stumbled across the problem that what is the max voltage I can measure??? It is an Arduino Uno and I am thinking that I would also display the voltage measured on a 16 * 2 LCD screen.My guess is max of 5 volts but if this is correct how can I increase its range?

Without any further configuration, the ADC (Analog Digital Converter) of the Atmega328P (which is build onto the Arduino Uno) uses Vcc as voltage reference (meaning 5V in the case of the Arduino Uno). A voltage of 5V will result in the maximal value (which is 1023, since this is a 10bit ADC). So the voltage range in this case is 0 to 5V.
The Arduino Uno has an extra pin, where you can supply an own reference voltage. But it's limit is tied to the ADCs supply voltage AVcc, which is 5V for the Arduino Uno rev3 (as shown in the schematics of the Uno). The reference voltage should then be in the range of 1V to AVcc. So this still gives you only a range of 0V to 5V or smaller.
When you use a standalone Atmega328P, you can make AVcc a bit higher than the chips supply voltage Vcc, but at maximum Vcc + 0.3V.
You can check all these numbers by looking into the datasheet of the Atmega328P, chapter 28.9 (Electrical Characteristics --> ADC Characteristics).

How to increase this range depends greatly on your requirements. If you simply need a constant higher range, you can simply put a voltage divider in front of the analog input. Or you can use a more complex circuit involving an op-amp (amplifier ciruit, here with amplification factor below 1). You can even build this to be variable.
Should it be, that your wanted voltage range exceeds the 5V greatly, for example, if you want to measure mains voltage (230V for most europe, 110V in USA), you should definitely take great care and never connect this directly to electronic like the Arduino. High voltages (especially at high possible currents) should always be handled with great care.

The ATmega328's (it's the microcontroller on the uno) absolut maximum rating is Vcc + 0.5V for any pin (except the reset pin) while Vcc must not be higher than 6V.
In order to measure higher voltages you have to use a voltage divider (read this) to adjust the input voltage to the range 0V - Vcc.

Not 100% right. That value is the absolute maximum rating, which is what voltage you should not exceed. The ADC will read values between Vref- and Vref+. Usually Vref- is ground, while Vref+ is usually set to Vcc (unless you use the internal voltage reference, which is way lower). See chrisl answer for more details


text:
Value read is not changing while rotating pot in arduino?
I am trying to read voltage using analogRead in Arduino Uno from a voltage divider circuit consisting of 1k resistor and 10k pot. The Pot used is bourns 3296. The values obtained only range from 1011 to 1023? Why is the count not reducing further if I rotate the pot?
(this how i have connected the circuit, but the pot is the one that i have mentioned above, i couldn't find that kind in the software, but i have made the connection this way only)

int analogPin = A0;

// variable to store the value read
float val = 0;

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

void loop() {
  Serial.println(val); // read the input pin
  val = analogRead(analogPin); // debug value
}

Since potentiometer itself is a voltage divider, I have tried connecting as per the answer, the ends of the 10k pot to 5V and ground , and the slider pin to the analog pin A0. The new circuit is as shown below, but I am still unable to get the value ranging from 0 to 1023. The values returned only vary in between 1010 to 1023. What is going wrong? How do I get the full range?

And the code your using while your at it.  Issue is probably in the divider circuit, but still good to have a look at all of it.

A potentiometer is a voltage divider in itself. You don't need the extra 1k resistor

@chrisl I am trying to model a sensor which works at 5V as a voltage divider. So can I just use the pot? Most of the simulations that I have seen use a resistor along with pot. Please confirm.

Yes, you only need the pot. Connect it as described at the start of your sketch. A pot is a resistor strip, that gets divided by the middle wiper.

ok, one more question, then what does those voltage dividers with pots serve purpose for?

@chrisl Is it for cases when we really need to lower the voltages , such as using the microcontrollers  working on say 3.3 V?

A potentiometer is already a voltage divider by itself. The outer contacts are connected to the ends of a resistor strip. The middle pin is connected to a wiper, which can slider over the strip, dividing the strip into 2 parts. So you connect it like it is described at the start of your sketch (before the last edit): The outer pins to 5V and ground respectively and the middle pin to the analog input. (When using this in different circuits, keep in mind, that you should not draw too much current from the middle pin. Don't drive any load directly from it. The analog input does only draw a very small amount, so that's absolutely no problem.)
When adding a constant resistor in series with the pot, you are only adding a dead range, that cannot be set with the circuit.

what does those voltage dividers with pots serve purpose for?

Only the pot: Potentiometers are mostly used to give a setpoint, a user controlled voltage, which can be read by a microcontroller or used directly for controlling further electronics.
With an additional resistor: You can put in an additional resistor at the high side of the pot, to lower the voltage further. For example if you - for whatever reason - have to use a higher voltage for the voltage divider, than the microcontroller can handle. You can calculate the value of the resistor, so that the voltage on the analog pin will never exceed the limits. But this scenario must be very rare. I didn't encounter such a situation ever.

I did the connections like you said, but still the value returned varies only between 1010 to 1023. What is wrong?

Please show a wiring diagram of the new situation. You can add it to your question by editing it. Let the original question stay as before, so that others can follow and learn from it later. Just add the new information at the questions bottom

The answer didn't solve the problem, so you can uncheck it, until it does

OK, I am unable to leave a comment (< 50) so...
Use this link to learn about the AREF pin on the Arduino, this may not be your problem but it is good to know about anyway:
what is arduino adc reference?
Your pot MAY be broken. Measure the resistance of the pot with an ohm meter, from the center pin to either of the side pins. Verify when you turn it the resistance varies from 10K to 0.
You can also measure the voltage it is providing your Arduino by measuring the voltage it presents to pin A0. Verify the voltage changes little by little from +5 to 0 when you turn it back and forth.
You list the pot as being a "bourns 3296" which the data sheets show as a "Multiturn / Cermet / Industrial / Sealed" pot.
Just so you know, when you adjust it you will have to turn it 25 turnes to fully adjust it through its entire range. The data sheet shows "Effective Travel.........25 turns nom."


text:
How to compose an HTTP GET request URL with key/value parameters
I am experimenting with some code running on an ESP8266 board to retrieve data using a web API. I would like to store the host address and key/value parameters (API key etc.) of the GET request as constants/variables (I'm not sure which is better) and then use them to compose the full GET URL.
How can I compose the full URL from separate strings/char arrays including the correct syntax for the key/values pairs?
EDIT: Just adding that I am using the ESP8266HTTPClient library.
The example I have been following uses a basic API URL with no parameters and stores the host URL as follows:
const char* host = "http://somehost.com/dir/1";

(Side question: please explain the difference between const char* host and const char *host if there is one)
Using this simple URL I can successfully retrieve the JSON data using this method:
HTTPClient http;
http.begin(host);
int httpCode = http.GET();
Serial.print("HTTP RESPONSE: ");
Serial.println(httpCode);
if (httpCode > 0) {
  String payload = http.getString();
  Serial.println("PAYLOAD:");
  Serial.println(payload);
}
http.end()

I am looking into using the "ArduinoJson" library to manage the json data instead of String, but am more interested in figuring out how to compose the URL at the moment.
What I would like to achieve is adding key/value parameters stored as variables to the host URL e.g.:
const char* host = "http://somehost.com/dir/1";
char* app = "123";
char* user = "123456"
char* api_key = "XXXXXXXXXXXXX";

And then join them with strings or char arrays to create the full URL, or simply pass the host address plus the parameter values to a function that composes the URL or sends the full GET request(with the parameter "key=var", question mark, and ampersands etc.):
http://somehost.com/dir/1/?appid=123&userid=123456&key=XXXXXXXXXXXXX

This was very easy to achieve in python using the "requests" HTTP library. I was able to store the key/value parameters as a dict and then pass the host address and the parameter dict to the requests.get function and it would compose the URL automatically.
I guess there is more than one question buried in there, but the main one is "what is the best way to compose the full URL without hard coding the whole thing?" An example would be so I could change some parameters such as appid by user input before making the GET request.
I am unsure if I am using the right approach using the character arrays, constants or variables, whether I am using the right approach by trying to compose it manually, and in general what the best practices are for doing this efficiently and avoiding memory fragmentation (which is a problem when using string variables?). This device will be required to run constantly and periodically make these GET requests.

Side question: please explain the difference between const char* host and const char *host if there is one

There is no difference; n.b. the arduino IDE uses C++! If you don't know C or C++ you should learn that first.

"what is the best way to compose the full URL without hard coding the whole thing?"

This is basically the same question as how do you manipulate, i.e. compose, composite, concatenate, C strings. c string functions
here is a quick example, without error checking, etc.:
const char* host = "http://somehost.com/dir/1";
char* app = "123";
char* user = "123456"
char* api_key = "XXXXXXXXXXXXX";

char urlout[255];

// we are going to start here
strcpy(urlout, host);
strcat(urlout, "/?appid=");
strcat(urlout, app);
strcat(urlout, "&userid=");
strcat(urlout, user);
strcat(urlout, "&key=");
strcat(urlout, api_key);

// urlout == "http://somehost.com/dir/1/?appid=123&userid=123456&key=XXXXXXXXXXXXX"

Thank you, your solution is what I was looking for. However I don't know if "learn c++ first" was very constructive. Arduino is meant to be standalone, for education, and is many people's first intro into programming. I also just thought I would add in a link to an article that explained in depth and helped me understand about strings, character arrays, and managing memory usage effectively. The Evils of Arduino Strings

@justincs I think the idea that Arduino is meant to be standalone is problematic; the language used is C++, one needs to know enough C++ to use the Arduino, hiding that fact or pretending it doesn't matter/exist does a disservice to the users. It just makes things more confusing; there is simplification, and there is oversimplification! Users now have two problems: their original problem, and learning to program at the same time; this does more harm than good IMHO.


text:
Custom Arduino Due Random Lock up
I have built my own Arduino Due Circuit board. I am having issues with it randomly locking up. I have researched the libraries and have ruled out any issues with them such as the Wire library. I am wondering could an issue with the power supply cause a brown-out that would lock it up. The only way to recover is to unplug it and plug it back in. It can run for 1 hour 1 week or months before it locks up. Does anybody have any idea what could cause this issue and how I can resolve it? Could the fuse or lock bits being set wrong  cause this type of issue?

What is your BOD (brown Out Detect) fuse set to?

Welcome :-) "I have built my own Arduino Due Circuit board" So what did you change, compared to the original? Any component changes (type / value / not populated etc.)? Any layout changes or did you exactly copy the PCB layout too? Please edit your question to add those details. Also add details of any testing & analysis you've done so far, to avoid anyone wasting time suggesting things you've already done. Is your hypothesis of a brown-out based on any specific testing or analysis, or just a guess? Finally, please add photos of your board into the question (ctrl+G in the editor). Thanks.

Further questions: (a) To help confirm that this is a hardware problem, and not a problem with your code, have you had your custom board hang, while running only the most simple "blink LED" code (and if so, can you provide a copy of that code)? (b) Have you been able to change the frequency of the hangs (i.e. make them less frequent or more frequent) by doing anything, during your troubleshooting so far? (c) Also, based on your troubleshooting so far, have you been able to get confidence in a particular power source, for your subsequent tests? Thanks.


text:
exit status 1 'mySerial' does not name a type
I just can't make it work for some reason. I tried #include <SoftwareSerial.h> and I tried #include "SoftwareSerial.h". Can someone help me?
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

uint16_t buf[256];

void setup() {
  Serial.begin(9600);
  while(!Serial);
  for(int i = 0; i < 256; i++)
    buf[i] = (uint16_t)i;
}
  mySerial.begin(4800);
  mySerial.println("Hello, world"); //printLn  L, not I

void loop() {
  Serial.write((uint8_t*)buf, 512);
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

In C and C++ we write executable code inside functions. You for some reason placed executable code outside of any functions. This is what triggered the error. What were you trying to achive by that? (In C++ some executable code can be placed outside, but this is not your case)

simple mistake mySerial.begin(4800);
  mySerial.println("Hello, world"); lines was out of void {}
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

uint16_t buf[256];

void setup() {
  Serial.begin(9600);
  while(!Serial);
  for(int i = 0; i < 256; i++)
    buf[i] = (uint16_t)i;
   mySerial.begin(4800);
  mySerial.println("Hello, world"); //printLn  L, not I
}

void loop() {
  Serial.write((uint8_t*)buf, 512);
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}


text:
I am not able to set the correct configuration of sound module
I have been trying to make sound reactive LED lights but my sound module is detecting only very close voice the LED react only when I press it to the speaker with my hands I have tried to set the potentiometer many times but I got unsuccessful I have connected the Analogue output to Arduino.
The voice module I used:

I have used the following code-

#include <FastLED.h>

/** BASIC CONFIGURATION  **/

//The amount of LEDs in the setup
#define NUM_LEDS 10
//The pin that controls the LEDs
#define LED_PIN 6
//The pin that we read sensor values form
#define ANALOG_READ 0

//Confirmed microphone low value, and max value
#define MIC_LOW 0.0
#define MIC_HIGH 737.0
/** Other macros */
//How many previous sensor values effects the operating average?
#define AVGLEN 15
//How many previous sensor values decides if we are on a peak/HIGH (e.g. in a song)
#define LONG_SECTOR 5

//Mneumonics
#define HIGH  3
#define NORMAL 2

//How long do we keep the "current average" sound, before restarting the measuring
#define MSECS 2000
#define CYCLES MSECS / DELAY

/*Sometimes readings are wrong or strange. How much is a reading allowed
to deviate from the average to not be discarded? **/
#define DEV_THRESH 0.8

//Arduino loop delay
#define DELAY 1

float fscale( float originalMin, float originalMax, float newBegin, float newEnd, float inputValue, float curve);
void insert(int val, int *avgs, int len);
int compute_average(int *avgs, int len);
void visualize_music();

//How many LEDs to we display
int curshow = NUM_LEDS;

/*Not really used yet. Thought to be able to switch between sound reactive
mode, and general gradient pulsing/static color*/
int mode = 0;

//Showing different colors based on the mode.
int songmode = NORMAL;

//Average sound measurement the last CYCLES
unsigned long song_avg;

//The amount of iterations since the song_avg was reset
int iter = 0;

//The speed the LEDs fade to black if not relit
float fade_scale = 1.2;

//Led array
CRGB leds[NUM_LEDS];

/*Short sound avg used to "normalize" the input values.
We use the short average instead of using the sensor input directly */
int avgs[AVGLEN] = {-1};

//Longer sound avg
int long_avg[LONG_SECTOR] = {-1};

//Keeping track how often, and how long times we hit a certain mode
struct time_keeping {
  unsigned long times_start;
  short times;
};

//How much to increment or decrement each color every cycle
struct color {
  int r;
  int g;
  int b;
};

struct time_keeping high;
struct color Color;

void setup() {
  Serial.begin(9600);
  //Set all lights to make sure all are working as expected
  FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS);
  for (int i = 0; i < NUM_LEDS; i++)
    leds[i] = CRGB(0, 0, 255);
  FastLED.show();
  delay(1000);

  //bootstrap average with some low values
  for (int i = 0; i < AVGLEN; i++) {
    insert(250, avgs, AVGLEN);
  }

  //Initial values
  high.times = 0;
  high.times_start = millis();
  Color.r = 0;
  Color.g = 0;
  Color.b = 1;
}

/*With this we can change the mode if we want to implement a general
lamp feature, with for instance general pulsing. Maybe if the
sound is low for a while? */
void loop() {
  switch(mode) {
    case 0:
      visualize_music();
      break;
    default:
      break;
  }
    delay(DELAY);       // delay in between reads for stability
}

/**Funtion to check if the lamp should either enter a HIGH mode,
or revert to NORMAL if already in HIGH. If the sensors report values
that are higher than 1.1 times the average values, and this has happened
more than 30 times the last few milliseconds, it will enter HIGH mode.
TODO: Not very well written, remove hardcoded values, and make it more
reusable and configurable.  */
void check_high(int avg) {
  if (avg > (song_avg/iter * 1.1))  {
    if (high.times != 0) {
      if (millis() - high.times_start > 200.0) {
        high.times = 0;
        songmode = NORMAL;
      } else {
        high.times_start = millis();
        high.times++;
      }
    } else {
      high.times++;
      high.times_start = millis();

    }
  }
  if (high.times > 30 && millis() - high.times_start < 50.0)
    songmode = HIGH;
  else if (millis() - high.times_start > 200) {
    high.times = 0;
    songmode = NORMAL;
  }
}

//Main function for visualizing the sounds in the lamp
void visualize_music() {
  int sensor_value, mapped, avg, longavg;

  //Actual sensor value
  sensor_value = analogRead(ANALOG_READ);

  //If 0, discard immediately. Probably not right and save CPU.
  if (sensor_value == 0)
    return;

  //Discard readings that deviates too much from the past avg.
  mapped = (float)fscale(MIC_LOW, MIC_HIGH, MIC_LOW, (float)MIC_HIGH, (float)sensor_value, 2.0);
  avg = compute_average(avgs, AVGLEN);

  if (((avg - mapped) > avg*DEV_THRESH)) //|| ((avg - mapped) < -avg*DEV_THRESH))
    return;

  //Insert new avg. values
  insert(mapped, avgs, AVGLEN);
  insert(avg, long_avg, LONG_SECTOR);

  //Compute the "song average" sensor value
  song_avg += avg;
  iter++;
  if (iter > CYCLES) {
    song_avg = song_avg / iter;
    iter = 1;
  }

  longavg = compute_average(long_avg, LONG_SECTOR);

  //Check if we enter HIGH mode
  check_high(longavg);

  if (songmode == HIGH) {
    fade_scale = 3;
    Color.r =  8;
    Color.g = 1;
    Color.b = -2;
  }
  else if (songmode == NORMAL) {
    fade_scale = 3;
    Color.r = -1;
    Color.b = 6;
    Color.g = -2;
  }

  //Decides how many of the LEDs will be lit
  curshow = fscale(MIC_LOW, MIC_HIGH, 0.0, (float)NUM_LEDS, (float)avg, -1);

  /*Set the different leds. Control for too high and too low values.
          Fun thing to try: Dont account for overflow in one direction,
    some interesting light effects appear! */
  for (int i = 0; i < NUM_LEDS; i++)
    //The leds we want to show
    if (i < curshow) {
      if (leds[i].r + Color.r > 255)
        leds[i].r = 255;
      else if (leds[i].r + Color.r < 0)
        leds[i].r = 0;
      else
        leds[i].r = leds[i].r + Color.r;

      if (leds[i].g + Color.g > 255)
        leds[i].g = 255;
      else if (leds[i].g + Color.g < 0)
        leds[i].g = 0;
      else
        leds[i].g = leds[i].g + Color.g;

      if (leds[i].b + Color.b > 255)
        leds[i].b = 255;
      else if (leds[i].b + Color.b < 0)
        leds[i].b = 0;
      else
        leds[i].b = leds[i].b + Color.b;

    //All the other LEDs begin their fading journey to eventual total darkness
    } else {
      leds[i] = CRGB(leds[i].r/fade_scale, leds[i].g/fade_scale, leds[i].b/fade_scale);
    }
  FastLED.show();
}
//Compute average of a int array, given the starting pointer and the length
int compute_average(int *avgs, int len) {
  int sum = 0;
  for (int i = 0; i < len; i++)
    sum += avgs[i];

  return (int)(sum / len);

}

//Insert a value into an array, and shift it down removing
//the first value if array already full
void insert(int val, int *avgs, int len) {
  for (int i = 0; i < len; i++) {
    if (avgs[i] == -1) {
      avgs[i] = val;
      return;
    }
  }

  for (int i = 1; i < len; i++) {
    avgs[i - 1] = avgs[i];
  }
  avgs[len - 1] = val;
}

//Function imported from the arduino website.
//Basically map, but with a curve on the scale (can be non-uniform).
float fscale( float originalMin, float originalMax, float newBegin, float
    newEnd, float inputValue, float curve){

  float OriginalRange = 0;
  float NewRange = 0;
  float zeroRefCurVal = 0;
  float normalizedCurVal = 0;
  float rangedValue = 0;
  boolean invFlag = 0;

  // condition curve parameter
  // limit range

  if (curve > 10) curve = 10;
  if (curve < -10) curve = -10;

  curve = (curve * -.1) ; // - invert and scale - this seems more intuitive - postive numbers give more weight to high end on output
  curve = pow(10, curve); // convert linear scale into lograthimic exponent for other pow function

  // Check for out of range inputValues
  if (inputValue < originalMin) {
    inputValue = originalMin;
  }
  if (inputValue > originalMax) {
    inputValue = originalMax;
  }

  // Zero Refference the values
  OriginalRange = originalMax - originalMin;

  if (newEnd > newBegin){
    NewRange = newEnd - newBegin;
  }
  else
  {
    NewRange = newBegin - newEnd;
    invFlag = 1;
  }

  zeroRefCurVal = inputValue - originalMin;
  normalizedCurVal  =  zeroRefCurVal / OriginalRange;   // normalize to 0 - 1 float

  // Check for originalMin > originalMax  - the math for all other cases i.e. negative numbers seems to work out fine
  if (originalMin > originalMax ) {
    return 0;
  }

  if (invFlag == 0){
    rangedValue =  (pow(normalizedCurVal, curve) * NewRange) + newBegin;

  }
  else     // invert the ranges
  {
    rangedValue =  newBegin - (pow(normalizedCurVal, curve) * NewRange);
  }

  return rangedValue;
}

The product page states that the module provides a “signal output” and is based on the LM393 (which is a comparator). Your code seems to expect an analog value.

The potentiometer is only supposed to modify the threshold at which the Digital Output Pin will output a HIGH or LOW value. The Analog Output Pin should be not altered by the potentiometer.
I think your sound module might not be the best for your project, if you are working with weak audio signals. It suits more for projects like clap detectors and such. You might be able to use that sensor for detect weaker signals if you put an audio amplifier after the Analog Output Pin, or change the Analog Reference value on the Arduino.

can suggest me a sound module perfect for this project..