text:
Porting SH1106 Oled Driver - 128 x 64 / 128 x 32 Screen is garbled but partially responsive
I'm porting the SH1106 driver to netmf and have found several libraries that more or less accomplish the same thing. A few were much easier to understand and had less abstraction so I followed those.
I've tried the U8glib with my arduino and it works just fine. The ported display driver yields these results:

inverted:

What you're looking at is the screen right after the initialization and attempting to draw a filled circle. You can see the bottom of the circle at the top of the screen. Somehow the origin or page is shifted, but I don't fully understand what's going on. I can send the invert display command and that works as well and turn the display on and off. My initialization code is this:
public void init()
{
    resetPin.Write(true);
    Thread.Sleep(1); // VDD (3.3V) goes high at start,
    resetPin.Write(false); // bring reset low
    Thread.Sleep(10); // wait 10ms
    resetPin.Write(true); // bring out of reset

    dcPin.Write(DisplayCommand);

    SendCommandB(0xAE);    /*display off*/

    SendCommandB(0x02);    /*set lower column address*/
    SendCommandB(0x10);    /*set higher column address*/

    SendCommandB(0x41);//0x40);    /*set display start line*/
    SendCommandB(0xB0);    /*set page address*/
    SendCommandB(0x81);    /*contract control*/
    SendCommandB(0x80);//contrast);    /*128*/
    SendCommandB(0xA1);    /*set segment remap*/
    SendCommandB(0xA6);//invertSetting);    /*normal / reverse*/
    SendCommandB(0xA8);    /*multiplex ratio*/
    SendCommandB(0x3F);    /*duty = 1/32*/
    SendCommandB(0xAD);    /*set charge pump enable*/
    SendCommandB(0x8B);     /*external VCC   */
    SendCommandB(0x30);    // | Vpp);    /*0X30---0X33  set VPP   9V liangdu!!!!*/
    SendCommandB(0xC8);    /*Com scan direction*/
    SendCommandB(0xD3);    /*set display offset*/
    SendCommandB(0x00);   /*   0x20  */
    SendCommandB(0xD5);    /*set osc division*/
    SendCommandB(0x80);
    SendCommandB(0xD9);    /*set pre-charge period*/
    SendCommandB(0x1F);    /*0x22*/
    SendCommandB(0xDA);    /*set COM pins*/
    SendCommandB(0x12);
    SendCommandB(0xDB);    /*set vcomh*/
    SendCommandB(0x40);
    SendCommandB(0xAF);    /*display ON*/

    // Switch to 'data' mode
    dcPin.Write(Data);
    this.ClearScreen();
    this.Refresh();

}

I have two methods to "refreshing"
public virtual void Refresh()
        {
            Spi.Write(displayBuffer);
        }

    /// <summary>
    /// Send buffer to display
    /// </summary>

public void Display()
        {
            //set column address
            dcPin.Write(DisplayCommand);
            SendCommandB(0x21);
            SendCommandB(0);
            SendCommandB((byte)(Width - 1));

            //set page address
            SendCommandB(0x22);
            SendCommandB(0);
            SendCommandB((byte)(_pages - 1));
            dcPin.Write(Data);

            //Spi.Write(displayBuffer);

            for (ushort i = 0; i < displayBuffer.Length; i = (ushort)(i + 16))
            {
                //Spi.Write(displayBuffer);
                SendArray(displayBuffer, i, (ushort)(i + 16));
            }
        }

At this point I'm a little lost. My hunch is something to do with paging and or display RAM. I'm looking for some insight here on how to fix this as I know there's a lot of experience here with these displays. Thanks!

Looks like it's clipped. You are placing the content to high on the screen so only the bottom is visible.

@Gerben yea, something like that. There's a strip only about 1/8 the height of the display. Know how to get it to work?

While your initialization routine looks fine to me (comparing to the datasheet and as evidenced by the fact the display turns on), what doesn't look right is your drawing routine:
//set column address
dcPin.Write(DisplayCommand);
SendCommandB(0x21);
SendCommandB(0);
SendCommandB((byte)(Width - 1));

//set page address
SendCommandB(0x22);
SendCommandB(0);
SendCommandB((byte)(_pages - 1));

The commands 0x21 and 0x22 don't correspond to any commands I can see in the datasheet.  They look more like commands more commonly seen with ILIxxxx or SSDxxxx screens to create an "addressable window" from 0,0 to Width-1, _pages-1.
Instead you should be using the same commands you used in the setup routine to set the current col / page coordinate in RAM to write to.
Commands (0x00 | (col & 0x0F)) and (0x10 | (col >> 4)) set the column position, and (0xB0 | (page & 0x0F)) set the page number.
You then write all 128 bytes for the current page before moving on to the next page.  This means you will have to do it a page at a time, something like:
for (ushort page = 0; page < 4; page++) {

    // Set the current RAM pointer to the start of the currently
    // selected page.
    dcPin.Write(DisplayCommand);
    sendCommandB(0x00); // Set column number 0 (low nibble)
    sendCommandB(0x10); // Set column number 0 (high nibble)
    sendCommandB(0xB0 | (page & 0x0F)); // Set page number

    // Send a single page (128 bytes) of data.
    // Without knowing the rest of your program I don't know the right
    // data sending routines to use, so I made them up. Change it to
    // do it how your program expects.  Maybe with your SendArray
    // function.

    dcPin.Write(DisplayData);
    for (ushort col = 0; col < 128; col++) {
        sendDataB(displayBuffer[page * 128 + col]);
    }
}

Note that this method is very similar to how the KS0108 GLCD drivers work.  Each byte of the page represents 8 pixels on the screen so the screen, at 32 pixels high, is split into 4 pages, where each page is 8 pixels, or one byte, high.
The effect you are currently seeing is because you are never changing the current page number (0) so you are always writing your data to the first page.  This loops around multiple times, so you end up writing all 4 pages to the same strip of the display ending up with the last page being displayed, which is the last 8 lines of your display data.  The rest of the display is never being touched and just contains whatever random data was in the RAM at power-on.

This is a great start. You've confirmed my suspicion and clarified the functionality and the issue. For some reason, I thought the datasheet mentioned that pages will auto-increment when it overflows. Am I wrong? There are still a couple of kinks...The current display I have has 8 pages so I made that change and I'm getting something that's working. I have to figure out the shifting of the start column by 2 as this driver is for 132 columns. Also, the "Hello" should be at the top left.

Just send 0x02 0x10 instead of 0x00 0x10 to start on column 2 instead of column 0. The page never changes. In the DS it states: "When the microprocessor repeats to access to the display RAM, the column address counter is incremented during each access until address 131 is accessed. The page address is not changed during this time.". The location of your "Hello" will be due to where you are telling it to print it since it is drawn in the display buffer not on the screen.

Thanks! That's what I thought..That's from the initialization too. I found the issue with the text too... Regarding the display buffer versus writing directly to the screen. I would still need to increment the pages with direct writes, correct?

@GisMofx Correct.  Unless you manually increment the page the display writes will just loop through the current page over and over again - which is what you saw before where it was stuck on page 0.

Thanks. Is there anything else I should be aware of regarding paging/incrementing while I'm developing some methods for this display?

I always use a framebuffer to store the data locally and output the whole display page in one operation when working with displays of this kind.  It is so much simpler than manipulating the display's RAM.  As long as you do that then there's minimal code for working with the display and everything else becomes completely display agnostic. I recommend sticking to that same approach.

Thanks. I was deliberating over the two approaches. I really appreciate your feedback and help!


text:
Using nrf24l01 with mpu 6050 unstable
I am trying to connect the wireless module nrf24l01 with the gyro mpu-6050.  Each works perfectly on its own.  However, when connecting both to a single atmega328 (in order to send over wireless the gyro data), the code runs for between 30 seconds and 5 minutes.
I have seen many people have issues, none of the suggestions have worked, but it seems like it is more about the combination than the mpu itself.  I have not had any errors, in that all the attempts have uploaded fine.
Some things I have tried (If you have experience with this device, im sure you will know what i am referring to ):
Changing clock rates from 24 to 12, and 400 to 200
Changing the header file for mpu from 100 hz to 20 hz and back
Adding pullup and pulldown resistors on sla/sda
Using external variable power supply to make sure exact voltage
Powering devices off arduino 3.3 and external 3.3
Running code without using serial reader on computer and just transmitting data
Edit:
After more debugging, I reduced the issue (I think).  As each module works fine independently, i thought there could be a code issue.  It seems though, that the issue is the combination of buffers.  I don't think this is exactly right, but to us it seems like the gyro needs to run quickly to stop the risk of causing the arduino to hang(even though we clear the buffer).
The second part is the wireless.  It seems like the code is looking by default for an acknowledgment the package is received.  This slows down the broadcasting.  So, if we disable the ack requirement, the gyro becomes stable.  However, the receiver stops receiving any packets at all.  If someone knows why, please explain.
So what we thought would work is by sending only some packets as the write with ack on a particular pipe.  This way, the gyro will be able to run stably, and the data can sometimes be sent and we can see if this is really the problem.  Again, this does not get recognized by the receiver at all.
Questions:
Does it make sense that the buffers are working against eachother, and this is not solvable through hardware.
Is there a clear reason why the receiver can not find packets that are being sent, just without the ack requirement?

i'm trying to do the same but can't get the code right... i need to read the gyro gy-521 position and to transmit it to move servo's on the other side... i will happy to get help with that and move to the n
ext level (that is you problem now, i believe that changing the baud can help )

Correct me if I am wring, but the nrf24l01 is not a WIFI module. Its a RF Transceiver.

@PhillyNJ Thanks, just modified it. meant wireless

You only used the gyroscope for data transmission? please post the complete code that you used to communicate between the nrf24l01 and the mpu-6050. Thank you

I could not figure out what was wrong, but I changed to this library for NRF24: http://tmrh20.github.io/RF24/
and I started using the GY-85 with the FreeIMU Library : http://www.varesano.net/projects/hardware/FreeIMU
Following this advice:
http://forum.arduino.cc/index.php?topic=164222.msg1539961#msg1539961
It works now, so if it was SRAM as @Avamander suggested, it was not on my side.

It seems to me you are running out of memory (SRAM).  https://www.arduino.cc/en/Tutorial/Memory

source: Stack Exchange

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

sort: votes


text:
CMDmessenger library
I am trying to use the CMDmessanger library on my Arduino uno, and am facing an issue.
My issue starts right from the ArduinoController.ino example.
When i send the frequency command
3,1;

The led starts blinking correctly, once per second.
But when I send a wrong command (basically a command without an argument)
3;

The led just stops blinking. The state of the led depends on which state it was in when I sent the command.
I realised that, when I send the wrongly formatted command, it takes the frequency as 0.
Is there any method by which I can make sure that the command is received in the right format, before it is executed? Ideally I would love it if there is a method to know how many arguments were received, and I could call the readBoolArg, or other equivalent functions to retrieve the argument data.
I am planning on using this library for quite a few projects, and I don't want to be in a situation where things went wrong because there was not formatting check.
Thanks in advance.

For some extra context, I am a developer at Inventrom Pvt Ltd and developing a library for interfacing the Bolt WiFi module with the Arduino
Here is a link  if anyone is interested.

The example code uses cmdMessenger.readFloatArg(); (source) to read an argument.
void OnSetLedFrequency()
{
  // Read led state argument, interpret string as boolean
  ledFrequency = cmdMessenger.readFloatArg();
  // Make sure the frequency is not zero (to prevent divide by zero)
  if (ledFrequency < 0.001) { ledFrequency = 0.001; }
  // translate frequency in on and off times in miliseconds
  intervalOn  = (500.0/ledFrequency);
  intervalOff = (1000.0/ledFrequency);
  cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
}

That function will set ArgOk to false if there was no next argument.
float CmdMessenger::readFloatArg()
{
    if (next()) {
        dumped = true;
        ArgOk = true;
        //return atof(current);
        return strtod(current, NULL);
    }
    ArgOk = false;
    return 0;
}

Thus you should try to use public function
bool isArgOk();

/**
 * Returns if the latest argument is well formed.
 */
bool CmdMessenger::isArgOk()
{
    return ArgOk;
}

of the CmdMessenger object (which will return ArgOk) to check if the read argument was okay. You could e.g. modify the code as follows
void OnSetLedFrequency()
{
  // Read led state argument, interpret string as boolean
  ledFrequency = cmdMessenger.readFloatArg();

  //Did we just read garbage because the argument wasn't there?
  if(!cmdMessenger.isArgOk()) {
      //Using Serial might be a bad idea because that cmdMessanger operates on the same Serial stream.. but you get the idea.
      Serial.println("You didn't supply a correct argument! Error.");
      return; //goodbye
  }

  // Make sure the frequency is not zero (to prevent divide by zero)
  if (ledFrequency < 0.001) { ledFrequency = 0.001; }
  // translate frequency in on and off times in miliseconds
  intervalOn  = (500.0/ledFrequency);
  intervalOff = (1000.0/ledFrequency);
  cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
}

Thank you. I didn't realise that's how the isArgOk function worked.

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


text:
Arduino 3rd party cores
I am trying to use Arduino platform.txt to run some extra pre-processing on my Arduino codes.
As far as I can understand the best way to do that is to use prebuild hooks as mentioned below
https://github.com/arduino/arduino/wiki/arduino-ide-1.5-3rd-party-hardware-specification
I am using the hooks as follows
recipe.hooks.sketch.prebuild.1.pattern=echo {source_file} sketch pret;
recipe.hooks.sketch.prebuild.2.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

This is the output I get for the hooks
echo "{source_file}" sketch pret;
{source_file} sketch pret;
"/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc" -c -g -Os -w -std=gnu11 -ffunction-sections -fdata-sections -MMD -flto -fno-fat-lto-objects -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10804 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   {includes} "{source_file}" -o "{object_file}"
avr-gcc: error: {includes}: No such file or directory
avr-gcc: error: {source_file}: No such file or directory
avr-gcc: fatal error: no input files
compilation terminated.

The {source_file} variable is used in a compilation reciep as follows
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

and the recipe runs as follows
"/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10804 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino" "-I/Users/vinayakjoshi/Library/Arduino15/packages/boltiot/hardware/avr/1.0.0/variants/boltduino" "-I/Users/vinayakjoshi/Documents/Arduino/libraries/boltiot-arduino-helper-update-dev/src" "-I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/src" "/var/folders/kp/9gnp402j7_nfb1qpqpdkxgcr0000gn/T/arduino_build_658970/sketch/CommandHandler.ino.cpp" -o "/var/folders/kp/9gnp402j7_nfb1qpqpdkxgcr0000gn/T/arduino_build_658970/sketch/CommandHandler.ino.cpp.o"

As you can see, in a standard recipe, the variable {source_file} and other such definitions are correctly replaced. But in the hooks, this is not happening.
I want to know whether it is possible to get the value of the {source_file} variable to be used with the hooks, so that I can do some extra pre-processing with it. And if it is, how can I do it.
P.S. IDK what tag has to be used. I couldn't find platform.txt or 3rd party cores. I used the Arduino-IDE tag, as this question definitely asks how the IDE works.

It looks like those properties are only expanded in:

recipe.cpp.o.pattern
recipe.S.o.pattern
recipe.c.o.pattern
recipe.preproc.includes
recipe.preproc.macros

They are not expanded in any of the hook recipes.
This actually makes sense for {source_file} with the current build system because the hooks are not run before and after the compilation of each file but rather before and after the entire sketch compilation, so even if that property was expanded it could only give you an arbitrary filename, perhaps the first file to be compiled in the prebuild hook and the last in the postbuild hook, but that leaves all the other filenames inaccessible so it really wouldn't do much good. See related issue report.
If you're actually trying to use {source_file} to get the preprocessed sketch file, that's accessible from any recipe as {build.path}/sketch/{build.project_name}.cpp.
As for {includes}, it seems like an unnecessary restriction for that property to only expand in specific recipes. If you can present a good case for this behavior being changed, it might be worth opening a feature request to see what the Arduino developers will think.

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


text:
expected initializer before 'RF24'
The code i make is this
    */
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Servo.h>
#define CE_PIN   9
#define CSN_PIN 10

const uint64_t pipe = 0xE8E8F0F0E1LL;
int servoy;
int servox;
Servo Yservo;
Servo Xservo;

RF24 radio(CE_PIN, CSN_PIN);

int joystick[2];

void setup()RF24
{
  Serial.begin(9600);
  delay(1000);
  radio.begin();
  radio.openReadingPipe(1,pipe);
  radio.startListening();
  Xservo.attach(3);
  Yservo.attach(5);
}

void loop()
{
  if ( radio.available() )
  {
    bool done = false;
    while (!done)
    {
done = radio.read( joystick, sizeof(joystick) );
servox= joystick[0]/5.683;
servoy= joystick[1]/5.683;
      Serial.println(servoy);
      Yservo.write(servoy);
      Serial.println(servox);
      Xservo.write(servox);
    }
  }
  else
  {
      Serial.println("NO RADIO CONECTION");
  }

}

and i don't know what  happen it's said that
 sketch_aug20b_rc_rc_rc_22:33:13: error: expected initializer before 'RF24'

 void setup()RF24

             ^

C:\Users\ASUS\Documents\Arduino\sketch_aug20b_rc_rc_rc_22\sketch_aug20b_rc_rc_rc_22.ino: In function 'void loop()':

sketch_aug20b_rc_rc_rc_22:51:6: error: void value not ignored as it ought to be

 done = radio.read( joystick, sizeof(joystick) );

      ^

exit status 1
expected initializer before 'RF24'

It's basically saying "Why have you got a random "RF24" in the middle of your code like that?" - and I'm asking the same thing...

You have two problems:
sketch_aug20b_rc_rc_rc_22:33:13: error: expected initializer before 'RF24'

void setup()RF24

         ^

It's basically saying "I don't understand what you mean by RF24 here". That RF24 in that line should not exist. I assume you made some kind of typo or copy-pasta error.
Second:
C:\Users\ASUS\Documents\Arduino\sketch_aug20b_rc_rc_rc_22\sketch_aug20b_rc_rc_rc_22.ino: In function 'void loop()':
sketch_aug20b_rc_rc_rc_22:51:6: error: void value not ignored as it ought to be

 done = radio.read( joystick, sizeof(joystick) );

That is saying that radio.read doesn't return a value - yet you are trying to assign that value that doesn't exist to something.
According to the documentation for RF24::read():

Read the available payload
The size of data read is the fixed payload size, see getPayloadSize()
Note
I specifically chose 'void*' as a data type to make it easier for beginners to use. No casting needed.
No longer boolean. Use available to determine if packets are available. Interrupt flags are now cleared during reads instead of when calling available().
Parameters

buf   Pointer to a buffer where the data should be written
len   Maximum number of bytes to read into the buffer
if(radio.available()){
   radio.read(&data,sizeof(data));
  }

Returns
No return value. Use available().


text:
Getting the I2C Address from a Max9744 amplifier
I just bought 2 Max9744 amplifiers that I wish to scan the I2C addresses, just to check against what is said in documentation. I have the amplifier powered with a 12 v supply and the Arduino powered via usb. I run an I2Cscanner it says Devices found: in the serial monitor but doesn't say the address. The wiring is correct and the 5 v supply is giving 5 V. So what gives?
Thank you
Andrew

Please show exactly, what the Serial Monitor shows (copy and paste it into the question and then format it as text). Also provide a link to the scanner sketch, that you used (or also put it into your question). And please show, how you have connected the Max9744, as it seems to be possible to deactivate I2C by setting the address pins to low.

The Serial Monitor exactly says "Devices Found: " but then nothing else. Link to I2C scanner https://www.elithecomputerguy.com/2019/07/find-i2c-addresses-on-arduino-i2c-scanner. I will add the images in a second

Link to datasheet for the Max9744 amplifier?

https://cdn-shop.adafruit.com/datasheets/MAX9744.pdf


text:
Read two HX711 load cell amps
I need to read two values from hx711 load cells connected to strain guages. Ive found the code below that reads one guage, but being self taught and with little experience I have no idea how to adapt it to work with two, is anyone able to help?
I need two individual readings not a combined one
Thanks in advance, and credit to sparkfun who wrote this code.
#include "HX711.h"

#define calibration_factor -7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch

#define DOUT  3
#define CLK  2

HX711 scale;

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 scale demo");

  scale.begin(DOUT, CLK);
  scale.set_scale(calibration_factor); //This value is obtained by using the SparkFun_HX711_Calibration sketch
  scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0

  Serial.println("Readings:");
}

void loop() {
  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1); //scale.get_units() returns a float
  Serial.print(" lbs"); //You can change this to kg but you'll need to refactor the calibration_factor
  Serial.println();
}

Create a second instance of the HX711 class and begin it with two different IO pins.

make it so that you have something like these two in your code ... scale1.begin(DOUT1, CLK1); and scale2.begin(DOUT2, CLK2);  .... start by renaming scale. to scale1. ... then duplicate all of the scale1. lines

@jsotola, Ive tried that, but when I then try to read it, it tells me that scale2 was not declared in this scope

look at every line in your code above, that contains the word scale ... make two lines out of each one of those lines

The line:
HX711 scale;

is called the "instantiation of the object". It creates a new object called scale which is an instance of the HX711 class. It is this "object" that is your interface to the HX711 physical device.
To use two of them you first need to have two objects - one for each HX711. You can name them whatever you like.  For example:
HX711 scale1;
HX711 scale2;

The line:
scale.begin(DOUT, CLK);

is where it tells the HX711 object which pins the HX711 chip is connected to. In this case DOUT and CLK which you have defined as 3 and 2 respectively.  You could just as well have written:
scale.begin(3, 2);

Each object has to be "begun", so you would need a begin for each object you instantiate:
scale1.begin(3, 2); // DOUT = 3, CLK = 2
scale2.begin(5, 4); // DOUT = 5, CLK = 4

Now for every operation that you did on scale you would instead do on your two new objects:
scale1.set_scale(calibration_factor);
scale2.set_scale(calibration_factor);

etc.
And when you want to take a measurement you just select which object to read from:
Serial.print(scale1.get_units(), 1);

or
Serial.print(scale2.get_units(), 1);

You can add a third by creating and using scale3 in exactly the same way as scale1 and scale2.


text:
Several lines of code stop program from running?
After a lot of help from you guys (huge thanks) Ive completed my code and gone to test it. unfortunately though one line of code weight = (tip_read.get_units()); stops anything from happening and on the mode one, two or three sub programs it freezes somewhere in there. Any and all help and advice is welcome as Ive been trying to fix this all day and got literly nowhere.
#include <HX711.h>

#include <Wire.h>  // IC2 communication

#include <LiquidCrystal_I2C.h>  //LCD
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4); // Change to (0x27,16,2) for 16x2 LCD.

int max_load;
int interval;
int max_load_prev;
int interval_prev;
int mode;
float handle_weight;
float tip_weight;
int stop1;
int mode_previous;
int interval_sum;

int mode1 = 53;
int mode2 = 51;
int mode3 = 49;
int start1 = 39;
int start2 = 37;
int increment = 47;
float potentiometer1 = A0;
float potentiometer2 = A1;
int tare_1 = 45;
int tare_2 = 43;

//stepper motor controller
int stepPin = 12;
int dirPin = 13;

#
//sensor readings
  HX711 tip_read;
  HX711 handle_read;
  #define DOUT_tip  4
  #define DOUT_handle  6
  #define CLK_tip  3
  #define CLK_handle  5

  //saving to array//
  float data_storage_array[400][3];

void setup() {
  // put your setup code here, to run once:

  lcd.init();
  lcd.backlight();

  pinMode(mode1, INPUT);
  pinMode(mode2, INPUT);
  pinMode(mode3, INPUT);
  pinMode(start1, INPUT);
  pinMode(start2, INPUT);
  pinMode(increment, INPUT);
  pinMode(stop1, INPUT);
  pinMode(potentiometer1, INPUT);
  pinMode(potentiometer2, INPUT);

  //sesnor readings

  tip_read.begin(DOUT_tip, CLK_tip);
  tip_read.set_scale(194);// change to calibration factor

  handle_read.begin(CLK_tip,CLK_handle);
  handle_read.set_scale(43.5);// change to calibration factor

  pinMode(tare_1, INPUT);
  pinMode(tare_2, INPUT);

  Serial.begin(9600);

  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  mode_previous = 0;
  interval = 25;
  max_load_prev = 0;
  interval_prev = 0;
  interval_sum = 0;
  while (digitalRead(start1) == 0){
    if (digitalRead(mode1) == 1){
      mode = 1;
    }
    if (digitalRead(mode2) == 1){
      mode = 2;
    }
    if (digitalRead(mode3) == 1){
      mode = 3;
    }
    if (mode_previous != mode){
      Display_mode_set_up(mode);
      mode_previous = mode;
    }
    if (digitalRead(increment) == 1){
      delay(500);
      if (interval >= 1000){
         interval = 25;
      }
      else if (interval < 1000){
        interval = interval + 25;
      }
    }
    max_load = max_load_reading();
    if (max_load_prev != max_load or interval_prev != interval){
      Display_value_set_up(max_load, interval, mode);
      max_load_prev = max_load;
      interval_prev = interval;
    }
   Display_output(handle_weight, tip_weight);
   tare_one();
  }
  if (mode == 1){
    mode_one(max_load, tip_weight);
  }
  else if (mode == 2){
    mode_two(max_load, interval, handle_weight);
  }
  else if (mode ==3){
    mode_three(max_load, interval, handle_weight);
  }
  Pause_stop();

}

//---SUB ROUTINES---

void mode_one(int max_load, float tip_weight){
  tip_weight = read_tip();
  while (tip_weight < max_load){
    tip_weight = read_tip();
    turn_motor();
    Pause_stop();
    Display_output(handle_weight, tip_weight);
  }
}

void mode_two(int max_load, int interval, float handle_weight){
  int aim_value;
  aim_value = 0 + interval;
  tip_weight = read_tip();
  while (tip_weight < max_load){
    while (tip_weight < aim_value){
      turn_motor();
      Pause_stop();
      Display_output(handle_weight, tip_weight);
      tip_weight = read_tip();
    }
    save_to_array(interval_sum);
    aim_value = aim_value + interval;
    while (digitalRead(start2) == 0){
      delay(1);
    }
  }
}

void mode_three(int max_load, int interval, float handle_weight){
  int aim_value;
  aim_value = 0 + interval;
  tip_weight = read_tip();
  while (tip_weight < max_load){
    while (tip_weight < aim_value){
      turn_motor();
      Pause_stop();
      Display_output(handle_weight, tip_weight);
      tip_weight = read_tip();
    }
    save_to_array(interval_sum);
    aim_value = aim_value + interval;
    delay(1000);
  }
}

void tare_one(){
  if (tare_1 == HIGH) {
    tip_read.tare();
  }
  if (tare_2 == HIGH) {
    handle_read.tare();
  }
}

void turn_motor(){
  digitalWrite(dirPin, HIGH);
  digitalWrite(stepPin, HIGH);
  delayMicroseconds(500);
  digitalWrite(stepPin, LOW);
  delayMicroseconds(500);
}

float read_tip(){
  float weight;
  weight = (tip_read.get_units());
  return weight;
}
float read_handle(){
  float weight;
  weight = (handle_read.get_units());
  return weight;
}

void save_to_array(int interval_sum){
  data_storage_array[interval_sum][0] = interval_sum;
  data_storage_array[interval_sum][1] = tip_read.get_units();
  data_storage_array[interval_sum][2] = handle_read.get_units();
  interval_sum = interval_sum + 1;
}

int max_load_reading(){
  int KG_value;
  int g_value;
  int load_max;
  KG_value = analogRead(potentiometer1);
  g_value = analogRead(potentiometer2);
  KG_value = KG_value * 2;
  KG_value = KG_value/ 100;
  KG_value = round(KG_value);
  KG_value = KG_value* 100;
  g_value = g_value/ 10;
  g_value = round(g_value);
  if (g_value >= 100){
    g_value = 99;
  }
  load_max = KG_value + g_value;
  return load_max;
}

void Pause_stop(){
  if (digitalRead(stop1) == 1){
    delay(1000);
    while (digitalRead(start1) == 0){
      if (digitalRead(stop1) == 1){
        motor_unwind();
      }
      else{
        delay(100);
        lcd.setCursor(0, 2);
        lcd.print("Program Paused");
      }
    }
    lcd.setCursor(0, 2);
    lcd.print("                    ");
  }

}

void motor_unwind(){
  tip_weight = read_tip();
  while (tip_weight < 100){
    digitalWrite(dirPin, LOW);
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  int count = 100;
  while (count > 0){
    digitalWrite(dirPin, LOW);
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
    count = count -1;
  }
}

void Display_mode_set_up(int mode){
  lcd.setCursor(0, 0);
  if (mode == 1){
    lcd.print("Mode: Max           ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:---");
  }
  if (mode == 2){
    lcd.print("Mode: Incrimental    ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:   ");
  }
  if (mode == 3){
    lcd.print("Mode: Automatic      ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:   ");
  }
  lcd.setCursor(0, 3);
  lcd.print("Tp:");
  lcd.setCursor(9, 3);
  lcd.print("Hdle:");
}

void Display_value_set_up(int max_load, int interval, int mode){
  if (mode == 1){
    lcd.setCursor(6, 1);
    lcd.print("      ");
    lcd.setCursor(6, 1);
    lcd.print(max_load);
  }
  if (mode == 2 or mode == 3){

    lcd.setCursor(6, 1);
    lcd.print("      ");
    lcd.setCursor(6, 1);
    lcd.print(max_load);

    lcd.setCursor(17, 1);
    lcd.print("   ");
    lcd.setCursor(17, 1);
    lcd.print(interval);
  }
}

void Display_output(float handle_weight, float tip_weight){
  tip_weight = read_tip();
  handle_weight = read_handle();
  lcd.setCursor(3, 3);
  lcd.print("   ");
  lcd.setCursor(3, 3);
  lcd.print(tip_weight);
  lcd.setCursor(14, 3);
  lcd.print("    ");
  lcd.setCursor(14, 3);
  lcd.print(handle_weight);
}

What's in the function get_units()? In the mode_* subroutines, there are several while loops. Are you sure the conditions are being met for the loops to exit?


text:
Why does this piece of code overflow at 255?
Im having a problem where i got unsinged long variable and i need to increment it in eeprom everytime setup starts and it overflows at 255 back to 0.
unsigned long NumberOfBoots = 0UL;
#define INFO_NUMBER_OF_BOOTS_ADDR 0
#define INFO_NUMBER_OF_BOOTS_LEN sizeof(NumberOfBoots)

// in setup
EEPROM.get(INFO_NUMBER_OF_BOOTS_ADDR, NumberOfBoots);
EEPROM.update(INFO_NUMBER_OF_BOOTS_ADDR, ++NumberOfBoots);

My guess is that its due to Update() fuction. Any ideas?

https://www.arduino.cc/en/Reference/EEPROMUpdate

And also https://www.arduino.cc/en/Reference/EEPROMPut

@DaveNewton
Thanks, so its actual limitation of Update function. I will use put. Thank you both


text:
Why is function mentioned in global declaration?
I came accross this code for writing data into EEPROM in arduino. Why is void printTemp();, void clearEEPROM(); and void writeTemp(); functions are mentioned in global declaration? How will this help?
#include <EEPROM.h>

#define SAMPLE_TIME 2000  //The time between each EEPROM write function call in ms

int tempPin = 0;      //the ADC pin
int printPin = 2;     //the print button pin
int erasePin = 4;    //the erase button pin

int address = 0;      //EEPROM address counter

unsigned long timer;

float conv_coeff = 0.0;   //coefficient for converting from 0-1024 to 0-5 range

void printTemp();
void clearEEPROM();
void writeTemp();

void setup(){
  Serial.begin(115200);     //start the serial connection as always
  conv_coeff = 5.0/1024.0;  //find the coefficient to do the conversion
  timer = millis();         //millis() returns the time since program start in ms
}

void loop(){
  if(millis()-timer > SAMPLE_TIME)  //check if it's time to do a temp sensor sample
  {
    writeTemp();
    timer = millis();
  }

  if(!digitalRead(printPin))  //check if print button is pressed
  {
    printTemp();
    delay(500);
  }

  if(!digitalRead(erasePin)) //check if erase button is pressed
  {
    clearEEPROM();
    delay(500);
  }

  delay(1);
}

void printTemp()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    byte value = EEPROM.read(i);                //read EEPROM data at address i
    if(value != 0)                              //skip "empty" addresses
    {
      float temp = value*conv_coeff;            //convert ADC values to temperature
      temp = (temp - 0.5)*100;                  //take care of the offset

      Serial.println(temp);
    }
  }
}

void clearEEPROM()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    if(EEPROM.read(i) != 0)                     //skip already "empty" addresses
    {
      EEPROM.write(i, 0);                       //write 0 to address i
    }
  }
  Serial.println("EEPROM erased");
  address = 0;                                  //reset address counter
}

void writeTemp()
{
  byte value = analogRead(tempPin);     //read sensor value

  EEPROM.write(address, value);         //write value to current address counter address

  Serial.print("Sensor value stored at address ");
  Serial.println(address);

  address++;                      //increment address counter
  if(address == EEPROM.length())  //check if address counter has reached the end of EEPROM
  {
    address = 0;              //if yes: reset address counter
  }
}

Those are called function prototypes.  They mean "These functions exist somewhere else".  That "somewhere else" could be later on in the same file, or a different file entirely.
Usually these kind of things are provided by header (.h) files, or are automatically created (for functions in the INO file) by the IDE and hidden from you, so you never really see them. But if you're not using the IDE then you need to have them so your code (which is parsed linearly) knows that these functions exist before the parser comes across them.

Thanks! is it recommened to write it in the code? Even when using IDE?

It's a good habit to get into for when you graduate and start programming properly ;)

@Majenko, ouch. We all have to learn sometime!

@DuncanC All I'm saying is that many Arduino users are students, and when you graduate and get a job certain standards will be expected of you ;)

Originally, C (from which C++ inherited the bulk of its syntax) was compiled by a single-pass compiler: the compiler only got one look at the code.
A multi-pass compiler could look over the code and collect function definitions in one pass, then in a later pass, compile the code that calls those functions, or detect errors in those calls, if there are any.
A single pass compiler couldn't do that so it needs either the function or its prototype to appear before any code that uses calls it, for the compiler to have that same information when it needs it.
The prototype provides the function's name, the number and types of its arguments, and the type of value it returns, which is what the compiler needs to confirm and compile a function call or to issue a diagnostic message if the call doesn't match the prototype.


text:
AES Simplified for Arduino - Having hard time achieving desired result
Okay, here's the story. I'm not very familiar with how Arduino works but learning. I have a project that requires AES encryption on the Arduino Uno. As per a previous question we managed to figure out the problem but failed to resolve it fully so we started using another library. (This one: https://github.com/qistoph/ArduinoAES256)
uint8_t key[] = { //
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
  };
Now onto the problem itself. Using an online AES encryption tool such as: http://aesencryption.net/ Simply asks for a Key of the encryption in plain text and the output is base64 as specified by the service here: The result of the encryption will appear in base64 encoded to prevent character encoding problems.

Also, plain text can be used to process the encryption using AES algorithm.
I've been trying to achieve the exact same result using an Arduino Uno board with the exact same requirements. The end result is to have a base64 string that can be decrypted on another remote location having the same key.
Now as for the .ino file it has this setup:
#include "aes256.h" //Include library files
#define DUMP(str, i, buf, sz) { Serial.println(str); \
    for(i=0; i<(sz); ++i) { if(buf[i]<0x10) Serial.print('0'); Serial.print(char(buf[i]), HEX); } \
    Serial.println(); } //Help function for printing the Output

aes256_context ctxt;

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

  Serial.println("Initializing AES256... ");
  uint8_t key[] = { //
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
  };
  DUMP("Key: ", i, key, sizeof(key));
  aes256_init(&ctxt, key);

  uint8_t data[] = { //"asdfasdfasdfasdf"
    0x61, 0x73, 0x64, 0x66, 0x61, 0x73, 0x64, 0x66,
    0x61, 0x73, 0x64, 0x66, 0x61, 0x73, 0x64, 0x66
  };
  DUMP("Unencrypted data: ", i, data, sizeof(data));

  aes256_encrypt_ecb(&ctxt, data);
  DUMP("Encrypted data: ", i, data, sizeof(data));

  aes256_decrypt_ecb(&ctxt, data);
  DUMP("Back decrypted data: ", i, data, sizeof(data));

  aes256_done(&ctxt);
}

void loop() {
}

1) I can't seem to understand what is required to have a plain text key and plain text message to encrypt giving an end result of base64 output.
For example if I were to do this using JavaScript: (And this is just an example).

2) I'd like to achieve something like this:
var key = "32 characters plain text here";
var plain = "Unlimited characters text here that can be used by the library to encrypt this plain message variable";
var base64_output = aes.encrypt256(key, plain);

3) I'd like to have the base64_output as base64 string so that it can be printed on a third-party printer hooked to the Arduino. - Is this impossible to achieve? We've been trying for some time now from endless conversions to splitting up our plain text into chunks of 16 characters so that we can encrypt the message.

Any help is greatly appreciated. If someone doesn't mind us contacting them over the phone we would also greatly appreciate a phone call to have this issue explained and resolve so we can share our experience with the Arduino community.
Thanks in advance.
edit:
We're getting this error

edit2:
Thank you @Nick Gammon for the quick response.
After removing const from the function 4 places and the key variable declaration, everything seems to be working fine now.
We modified the code in order to print all bytes for each cipher block. We have this output:
140 145 154 38 228 66 98 128 116 68 245 193 70 84 205 115
Œ‘š&äBb€tDõÁFTÍsŒ‘š&äBb€tDõÁFTÍs
186 174 17 21 162 83 96 210 128 134 46 206 172 215 0 103
º®¢S`Ò€†.Î¬×
112 4 216 150 27 202 6 176 77 159 123 231 127 128 32 132
pØ–Ê°MŸ{ç€ „pØ–Ê°MŸ{ç€ „
215 110 118 33 167 193 212 121 156 46 63 139 183 124 63 152
×nv!§ÁÔyœ.?‹·|?˜×nv!§ÁÔyœ.?‹·|?˜
130 91 174 118 4 202 250 74 228 7 173 40 246 124 53 173
‚[®vÊúJä(ö|5‚[®vÊúJä(ö|5
231 48 204 82 235 172 202 139 33 134 137 81 209 191 210 217
ç0ÌRë¬Ê‹!†‰QÑ¿ÒÙç0ÌRë¬Ê‹!†‰QÑ¿ÒÙ
184 161 98 135 12 230 86 213 183 113 103 234 187 213 224 133
¸¡b‡æVÕ·qgê»Õà…¸¡b‡æVÕ·qgê»Õà…
Done

We're trying to convert each array of bytes into a char array of hex values then base_64 encode it.  But we're getting this output which is not what we want. Can you please explain how can we achieve this.
Please let us know if it is possible to open a chat with you so that we can understand this better.

What is stopping you? Is it the conversion of the encrypted string to base-64?

Well for starters I am unable to do a simple plain text conversation such as the silly JavaScript example above for the key and plain variables and convert them to uint8_t arrays of hex. Among other issues described above.

What I'm asking, more specifically, is: what have you tried; what were you expecting to happen; and what actually did happen?

@JRobert 1, The lack of documentation out there for implementing AES properly on Arduino devices. And 2, Converting a string such as String plain = "Hello World" into a uint8_t array.

We've been trying for some time now from endless conversions to splitting up our plain text into chunks of 16 characters so that we can encrypt the message. - I'm a little confused as to why that is a problem. Can you show your attempts to break your string of text into groups of 16 bytes? I'm thinking: a for loop - what are you thinking?

possible duplicate of Implementing DES or AES Encryption with DateTime Synchronization on Uno

You have also posted about your AES troubles on AES encryption arduino  - this is against the StackExchange rules: Is cross-posting a question on multiple Stack Exchange sites permitted if the question is on-topic for each site? - The answer being NO by the way.

@NickGammon well, thanks anyway. If having another question is a problem we can remove it.

We've been trying for some time now from endless conversions to splitting up our plain text into chunks of 16 characters so that we can encrypt the message.

To address this question/issue, below is some code that will take an arbitrary length string and break it into 16-character strings suitable for encoding with AES:
const int KEY_SIZE = 32;
const int BLOCK_SIZE = 16;
const char message [] = "Unlimited characters text here that can be used by the library to encrypt this plain message variable";
const byte key [KEY_SIZE] = "32 characters plain text here";

void encrypt_it (const byte plaintext [BLOCK_SIZE], const byte cipherkey [KEY_SIZE]);  // prototype
void encrypt_it (const byte plaintext [BLOCK_SIZE], const byte cipherkey [KEY_SIZE])
  {
  // encrypt here
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  const char * p = message;

  while (strlen (p) > 0)
    {
    byte plain [BLOCK_SIZE];
    memset (plain, 0, BLOCK_SIZE);  // ensure trailing zeros
    // copy block into plain array
    memcpy (plain, p, min (strlen (p), BLOCK_SIZE));
    // encrypt it
    encrypt_it (plain, key);
    // advance past this block
    p += min (strlen (p), BLOCK_SIZE);
    }
  Serial.println ("Done");
  }  // end of setup

void loop ()
  {
  }  // end of loop

I'd like to have the base64_output as base64 string so that it can be printed on a third-party printer hooked to the Arduino. - Is this impossible to achieve?

Of course it is possible. Just look up (Google) a C or C++ function to base-64 encode a string. There must be thousands of them. This is not an Arduino question, this is a C programming question.

As per a previous question we managed to figure out the problem but failed to resolve it fully ...

Namely here: Implementing DES or AES Encryption with DateTime Synchronization on Uno.
This question actually looks remarkably similar to your previous one.

please check our edit on the post. It shows the error that we are getting when trying to implement aes encryption according to your method. Thank you

You can copy and paste error messages you know (the text of them). You don't have to take screenshots. Change const byte on the function encrypt_it to byte (4 places).

sorry for uploading a screenshot. We implemented the changes and updated our post. Appreciate if you can take a look at it again. Thanks in advance

The reason of this conversion is to decode it online using this website which takes a base_64 encoded string. http://aesencryption.net/

2) I'd like to achieve something like this:

  var key = "32 characters plain text here";
  var plain = "Unlimited characters text here that can be used by the library to encrypt this plain message variable";
  var base64_output = aes.encrypt256(key, plain);

So do it.
#define MAX_MESSAGE_SIZE 256
uint8_t key[] = "32 characters plain text here";
uint8_t plain[MAX_MESSAGE_SIZE+1] = "Unlimited characters text here that can be used by the library to encrypt this plain message variable";
aes256_init(&ctxt, key);
aes256_encrypt_ecb(&ctxt, plain);
// plain is now encrypted.

That is limited to a maximum message (and encrypted output) size of 256 bytes due to the (purely arbitrary) size of the array I chose.

I think unlimited is an unwise word to use considering that the Arduino Uno has 2 KB of RAM.

@NickGammon Not my word - copied and pasted from the question.  Like the universe - "Infinite but bounded" - what does it really mean?  Unlimited as long as it's less than the maximum number of characters allowed by the array ;) - as noted in the "That is limit to ..." paragraph.

I realize it isn't your word. It is the OP's word. :)

If you don't have to have the features of the String object, I'd highly recommend you use a uint8_t (or 'byte' or 'char') array from the get-go. It avoids the conversion altogether, as well as the code complexities of dealing with Strings.
uint8_t plain = "Hello World"; works great for a literal string, or if you need more flexibility, uint8_t plain[256+1] = "Hello World"; lets you use or re-use that space for whatever strings you need to hold at run-time (pick a size appropriate for your needs, obviously). Will that let you get past the conversion road-block to focus on encryption (about which, I'd be no help at all).

How will uint8_t plain = "Hello World"; be equal to this?   uint8_t key[] = { //     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,     0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,     0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f   };  Given that Hello World` will change based on keyboard input?

I think you mean uint8_t plain[] = "Hello World" - you forgot the array notation []

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


text:
Can I Implement a PLL on an Arduino?
Is it possible to create a system like a PLL using an Arduino?
I ask this because there are some parts in the PLL system, such as: phase detector, VCO, divider, and I don't know how to make for each part in Arduino board.

The ATTinys have a build in PLL.

thanks gerben, so if i use aduino uno all i have to do to make a PLL is just to coding it right??

An Uno does not use an ATtiny, so no.  You may be able to build a frequency locked loop in software, but right now the major problem with your question is that you don't specify the details of your goal

Uno uses an ATMega328. You can e.g. use a bare ATTiny85 chip, or a board based on that same chip, like a Trinket, or Digispark. (There are other ATTinys beside the 85, but that one is the most popular).

thanks again greben, i forget that one point, this is for my final project my goal is to create a signal (pll output) from the reference signal that come from function generator.
my lecturer said the reference signal i have to give is following the working frekuency and amplitude of arduino uno. so it's doesn't need special req. right?

A PLL is a very complex device which is not something that can easily be created purely in code.
Many microcontrollers include a PLL as part of their oscillator systemm which allows them to run internally at a higher speed than their external crystal.  This is not a programmable peripheral that you can use for your own things, but an integral part of the workings of the microcontroller.
While it may be possible to write one in software the results would be very somewhat limited. The best you could hope for is to use timers to measure an incoming frequency and use the results to output another frequency through some means, maybe PWM.
To create a real PLL you would be best off using either a dedicated PLL chip (which you can buy off the shelf) or use some form of programmable logic like a CPLD that has a built in PLL block.
Some microcontrollers, most notably the Cypress PSoC range, have programmable logic blocks built in that may be more suited to your task than an Arduino.
A typical digital PLL looks something like this:

Implementing all that in code would be both tricky and somewhat slow on a little 8-bit MCU with no floating point support.  However, the basic principal of what a PLL can be summarised in one simple sentence:

The frequency coming in determines the frequency going out.

The PLL, or Phase Locked Loop is just one method of achieving that desired result.
Another method, which is not using any form of PLL, is purely algorithmic and consists of just three things:

Three simple blocks, all of which the Arduino is, to a certain extent, capable of performing.
The first block, the Frequency Detector, works out what the frequency of the incoming signal is.  That could either be by counting the number of pulses that arrive over a certain time frame, or measuring the time between successive pulses.  Which method you use (Frequency Counting or Frequency Measuring) is really down to what frequency ranges you are using.  Frequency Counting is better for higher frequencies, whereas Frequency Measuring is better for low frequencies.  There are many examples on the web of how to do both of those using timers on the Arduino.
The Decision Making is basically working out what your output frequency wants to be according to your input frequency.  This could be as simple as "Output = input * 2", for instance, or something more complex like "Between these frequencies I want to output this frequency, between these frequencies this other frequency, etc".  It's entirely up to you.
The third block just takes the decided-upon output frequency and generates it.  That could be done using the hardware PWM generation of the Arduino.
All this, though, will be limited to relatively low frequencies (tens of kHz maximum really) though with clever coding you could push it up slightly higher.
One thing that really makes this method differ from a PLL is that you don't get the "PL" portion of it - that is, the phase of the incoming frequency is lost, and the output frequency is running entirely with its own phase.  There is little or nothing you can do to synchronise the phases of the input and output like you get with a full PLL.

thanks majenko, sadly i already propose this title for my final project so i have to build this system using arduino. and i think what i aiming is that complex. do you have any idea?

thanks @majenko, i'll consider it by using arduino due just like jack said.
and i'll be concern about the output that arduino gives..

Addendum: Use an output oscillator with reset function. Detect the "reset point" of the input waveform. (The Arduino supports interrupts, for example)

thanks for that @MickLH.. i've already considered by using arduino, despite it might be expensive but i has already propose it..

For countable frequencies, you can easily get the PL phase information by using sort of a Bresenham algorithm counter, incrementing by a quantity for each output pulse, and decrementing by a quantity for each input pulse. (eg, for a 100Hz output from a 1PPS,  bresenham++ each output pulse, and on each PPS bresenham-=100; and adjust the output interval.  When they are in phase, the count is stable.    If they are out of phase, the Bresenham count would tell you which way and by how far, and you could use that phase information for decision making.

You can absolutely make a PLL using an ATMega microcontroller, and I have made one myself using a ATTiny45. The way I did it is by setting the clock source to the internal RC oscillator, and using that as my VCO (or in this case, Numerically Controlled Oscillator). The internal oscillator can be tuned between 50% and 200% of its nominal frequency by adjusting the OSCCAL register, which can safely be done without stopping the processor. I used the ADC to read the input signal. For the phase detector I programmed the MCU to alternatively add, then subtract the ADC registers from an accumulator register. This is mathematically equivalent to multiplying the incoming signal by a square wave from the local oscillator, and integrating the result. After a fixed number of cycles, I checked to see if the accumulator was negative or positive. If its negative, I set OSCCAL to a "high frequency" which is definitely higher than the input signal. If its positive, I set it to a "low frequency", which is definitely too low. Of course this is a form of Bang–bang control, so its never stable per se, but I found works perfectly. Its much better than my attempts at a PID controller. Looking on my oscilloscope, the is almost no jitter visible between the input system and the internal RC clock, which I outputted on the CLKO pin by setting the appropriate fuse bits.
Although I used GCC and USBTinyISP, I see no reason why my system can't be implemented on Arduino. Setting the fuse bits will require a bit of work though, you can read more here:
http://forum.arduino.cc/index.php?topic=124879.0
If there is enough interest, I can add more detailed information to my answer.

Thanks for your answer @Misha and ya, i'm little bit interest with your detail. And first at all to implement pll using arduino, how can i used adc to read the input signal if it come from function generator for example?

There are two types of PLLs, hardware PLLs and software PLLs. Majenko has already addressed hardware PLLs so I will leave you to his answer for that.
Software PLLs perform the same function as regular hardware PLLs, but with code, and as a result are constrained by the clock speed and sample rate of the controller they are running on. Usually this means you are limited to sub MHz frequencies. The math and computation necessary to perform this is quite complicated, and I do not expect you would get particularly good performance out of your standard Arduino controller, as all of them lack a floating point unit to perform these types of computations.
If you were to still try and attempt this you would have to do it using integer math only. The faster the CPU, the higher the frequency it will be able to lock on to. The fastest Arduino available today is the Arduino Due. Aside from being fast, the Due can perform 32-bit arithmetic in a single cycle, which should be handy. The frequency limit will be dictated by how many cycles all of your calculations take.

thanks jake, that's all i need.
i only need a low frequencies in range of KHz, and the amplitudes is follow the maximum input voltage of arduino right?
and which arduino can you suggest?

I've added to my answer a few extra notes on attempting this. All I can say is: Good Luck! Software PLLs are tricky; there are a lot of resources out there about how to do it theoretically, but very few on real world implementations of them.

thanks a lot jake, well i have a lot of work right.. maybe i'll ask you more about it while i'm working on it could i?


text:
Why the program keeps applying what is in loop in first case and stops in the second one?
In the first program after removing hand from the button it keeps on, means it keeps applying what is in the loop:
int led = 13;
int button = 12;
void setup() {
  pinMode(led, OUTPUT);
  pinMode(button, INPUT);
             }
void loop() {
  if (digitalRead(button) == HIGH)
  {
    digitalWrite(led, HIGH);
  }
             }

while in the second one it needs to press the button every time in order to apply what is in the loop,means to flash in this case,
int led = 13;
int button = 12;
void setup() {
  pinMode(led, OUTPUT);
  pinMode(button, INPUT);
            }
void loop() {
  if (digitalRead(button) == HIGH)
  {
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
  }
           }

Why different behavior although the same structure?
The problem is illustrated in this video :
https://www.youtube.com/watch?v=u5WGvKwJYFY&t=2s

Looks confusing to me -- setup() should only run once per power-on cycle, and so since value is only set in setup() and not ever changed in loop() the behavior should never change after the initial powerup.  Is your circuitry somehow resetting the arduino after each iteration?

Both of your sketches are missing a "closing bracket", so they won't compile. They do not match the sketches in the video you've provided. Could you tell us what it is you are trying to accomplish? What should the LED do when you press the button? Flash the LED? What happens if you press the button again? Does it turn the flashing LED off?

no the circuit works fine, i am not trying to accomplish something, it just happened  and i want to know why different in applying the program, i want to understand how  those programs are executed, i thought after pressing the button it should react the same way ,means either  both prorams should apply only when press the button then keep applying or both should stop applying after i press the button, because the both have the same programming structure ,

in the fist code if i press the button again it does nothing the led is already on and keeps on, in the second code sure if i press the button again it flashes again

The code you posted does not compile, but it looks like if it did, it will completely ignore changes to button/value in loop() and not produce the effect you show in the video.

@sumerfattoum, you do not understand ... the code that you posted is not the same as the code in the video

the code posted is the same as in video if you noticce, it wont apply just cus i didnt copy the end brackts

u dont understand the idea, in the fist one posted it just instead of just reading it, i just used the name value , i reposted the code exactly as in the video, how ever could you answer why it acts like that in the video ???

because digitalWrite(led, LOW) turns the led off. but if you don't see it, than stop trying to write programs

ok, you corrected the code. so, now it is the same as in the video .... the two programs do exactly what you programmed them to do .... the loop() function repeats over and over until you press the reset button, or until you turn off the power. ... go through the code step by step. add comments that explain what each command does. you will soon understand why the code works the way it does.

They are two different codes, i tried to understand step by step but i couldn't that's why I ask , to my knowledge they should react the same way when pressing the button because they are the same structure and the only difference is what the led should do..but they act differently when pressing the button which clearly i don't understand

This iteration of your code is better.  Now, the difference in behavior is that nothing in the first code ever executes digitalWrite(led, LOW);, while each iteration though the second code does.  Therefore the LED remains on forever in code 1, and depends on the button press in code two.
If the behavior you desire is that the code remembers if the button has ever been pressed, latch that event in some state variable, and then in loop(), act on the value of the state variable:
int led = 13;
int button = 12;
int everHit = 0;
void setup() {
  pinMode(led, OUTPUT);
  pinMode(button, INPUT);
}

void loop() {
  if (digitalRead(button) == HIGH) everHit = 1;
  if (everHit) {
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
  }
}


text:
Why I could not read the other sms's except the first SMS?
I have to read the incoming SMS on my GSM module SIM900, and I want to print the sender number and message to the serial monitor.
I first configure the GSM module with AT commands and Response() function will give me the response to AT commands.
as any SMS will be in the following pattern
+CMT: "[Mobile number]", "[Date and Time]>"
   [message body]
So, I first extract +CMT and after that I will take mobile number and at last we have message body. The code I have used is
char RcvdMsg[200] = "";
int RcvdCheck = 0;
int RcvdConf = 0;
int index = 0;
int RcvdEnd = 0;
char MsgMob[15];
char MsgTxt[50];
int MsgLength = 0;

void Config() // This function is configuring our SIM900 module i.e. sending the initial AT commands
{
    delay(1000);
    Serial.print("ATE0\r");
    Response();
    Serial.print("AT\r");
    Response();
    Serial.print("AT+CMGF=1\r");
    Response();
    Serial.print("AT+CNMI=1,2,0,0,0\r");
    Response();
}

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

void loop()
{
  RecSMS();
}

void Response() // Get the Response of each AT Command
{
    int count = 0;
    Serial.println();
    while(1)
    {
        if(Serial.available())
        {
            char data =Serial.read();
            if(data == 'K')
            {
                Serial.println("OK");
                break;
            }
            if(data == 'R')
            {
                Serial.println("GSM Not Working");
                break;
            }
        }
        count++;
        delay(10);
        if(count == 1000)
        {
            Serial.println("GSM not Found");
            break;
        }
    }
}

void RecSMS() // Receiving the SMS and extracting the Sender Mobile number & Message Text
{
    if(Serial.available())
    {
        char data = Serial.read();
        if(data == '+'){RcvdCheck = 1;}
        if((data == 'C') && (RcvdCheck == 1)) {RcvdCheck = 2;}
        if((data == 'M') && (RcvdCheck == 2)) {RcvdCheck = 3;}
        if((data == 'T') && (RcvdCheck == 3)) {RcvdCheck = 4;}
        if(RcvdCheck == 4)
        {
            RcvdConf = 1;
            RcvdCheck = 0;
        }

        if(RcvdConf == 1)
        {
            if(data == '\n'){RcvdEnd++;}
            if(RcvdEnd == 3){RcvdEnd = 0;}
            RcvdMsg[index] = data;

            index++;
            if(RcvdEnd == 2){RcvdConf = 0;MsgLength = index-2;index = 0;}
            if(RcvdConf == 0)
            {
                Serial.print("Mobile Number is: ");
                for(int x = 4;x < 17;x++)
                {
                    MsgMob[x-4] = RcvdMsg[x];
                    Serial.print(MsgMob[x-4]);
                }
                Serial.println();
                Serial.print("Message Text: ");
                for(int x = 46; x < MsgLength; x++)
                {
                    MsgTxt[x-46] = RcvdMsg[x];
                    Serial.print(MsgTxt[x-46]);
                }

                Serial.println();
                Serial.flush();
            }
        }
    }
}

The problem of the code is
After receiving first SMS I am getting my mobile number and message body. After that I am only getting the sender number printed to my serial monitor but not the message body.
Where has it gone wrong. I could not understood.
Please help me.......Thanks in advance.

Can you provide me this code if you found solution for your bug. It will be very important for my college project. Thank you for your support!

It looks like RcvdEnd never gets reset back to zero because RcvdConf is set to zero when RcvdEnd is 2, which means it will never get to 3 and reset it (at least not when you are expecting it to). I'm not sure how many new lines you are supposed to be checking for but the way it is set up now or is looking for two on the first message, and three for every message thereafter. You might want to rework the logic and maybe move where that value gets reset.

             {
                MsgTxt[x-46] = RcvdMsg[x];
                Serial.print(MsgTxt[x-46]);
            }
             RcvdEnd =0;
            Serial.println();
            Serial.flush();

Perhaps you'd like to edit your answer to explain why you think this answers the question.


text:
Arduino button voltage versus HIGH/LOW state
I'm measuring voltage between button's ground and input pole on the following sketch. When button is on off state, there's 5V there, when it's switched on and led turs on, there's 0. Is this a correct way, and also how do I make it easier to write code and have LOW represent led being off. In this sketch, digitalWrite(led1, LOW); means the LED is actually turned on, so how do I tweak this to be representative of actual state, high=led on.
#include <ezButton.h>

// -----
// Declaration
// -----

const int button1  = 9;
const int led1     = 4;
int ledState = LOW;

ezButton button(button1);

// -----
// Setup
// -----

void setup()
{

  pinMode(led1, OUTPUT);
  pinMode(button1, INPUT_PULLUP);
  button.setDebounceTime(50);

}

// *****
// Main Loop
// *****

void loop()
{

  if( digitalRead(button1) == LOW ) {
    digitalWrite(led1, HIGH);
  }
  else  {
    digitalWrite(led1, LOW);
  }

}

// *****

@Juraj but doesn't the "int ledState = LOW;" mandate that when starting up the Arduino with this sketch led is off?

what is the purpose of int ledState = LOW;? ... your program does not use ledState

const int LED_Off = HIGH; const int LED_On = LOW;  then use LED_On/Off as you please...

So, if I correctly understand, you are getting confused, because turning the LED on means  writing LOW to it. And you want to change that to not be confused anymore. Is that correct?

To answer your question, Is this a correct way, yes, it is one correct way. There's nothing incorrect about an LED circuit that turns the LED on when the voltage is low, and off when the voltage is high. If you want to change that fundamental property, you have to change the circuit.

If I correctly understand, you're rather confused by the inverse logic of a PULLUP button. Alternatively to @Abel's comment you might define const int PRESSED=LOW; and write if (digitalRead(button1) == PRESSED) digitalWrite(led1, HIGH);

To answer the posted question literally: Yes, it is the correct way for your circuit, which has the button between the pin and GND, and the LED between VCC and the pin:

simulate this circuit – Schematic created using CircuitLab
I can understand the confusion. However, the meaning is right, because the level on the button's pin is LOW if pressed. And the level on the LED's pin needs to be LOW for current to flow.
You can define your own constants:
// other stuff left out

const int LED_ON = LOW;
const int LED_OFF = HIGH;

const int BUTTON_PRESSED = LOW;
const int BUTTON_RELEASED = HIGH;

void loop()
{
  if (digitalRead(button1) == BUTTON_PRESSED) {
    digitalWrite(led1, LED_OFF);
  }
  else {
    digitalWrite(led1, LED_ON);
  }
}

If you want to keep using HIGH and LOW, but interpret them as:

HIGH = button pressed / LED on
LOW = button released / LED off

Then you need to modify the circuit:

simulate this circuit
Unfortunately, there is no pin mode INPUT_PULLDOWN for the button pin, so you need to provide the pull down resistor externally. Make sure to set the pin to INPUT, not INPUT_PULLUP.
A common value for the pull down resistor is 10 kΩ.


text:
Arduino web server-how to get values form URL
I’ve already searched through the internet but cannot find satisfactory answer.
Is there an easy way to get value of variable passed through an URL?
What I mean is I want to start a web server on my Arduino then call the URL like 10.0.0.1/?var1=x&var2=y from my browser and read var1 and var2 to my program.
I could also use JSON format but how to send it to my Arduino and then read it?
I use Arduino Ethernet Shield W5100.
Any ideas?

you could use a WebServer library which among other things parses the parameters


text:
Is it possible to upload a private root certificate to an Arduino Nano33?
I'm trying to connect an Arduino Nano 33 to an mqtt broker with TLS authenticaton on the broker side. To do that I need my Arduino board to have access to the the root certificate.
My understanding is that unlike ESP32, the Nano's NINA wifi module does not have a WiFiSSLClient object with a setCACert method that you can use to pass the root certificate. Instead, the NINA's client has a connectSSL() method which uses whatever root certificate you have uploaded to the Nano using Arduino's IDE. However, as it can bee seen in this tutorial, it looks like it is only possible to upload public domain root certificates by entering the website.
But what if I wanted to upload a root certificate that I have generated using OpenSSL. Would that be possible?

https://www.arduino.cc/en/Tutorial/WiFiNINAFirmwareUpdater#certificate-uploading


text:
Pushbutton to initiate a 5 time flash
The following code operates in a way that LED starts to flash only if the pushbutton is pushed for one second. I want to change this and make the LED flash for 5 times, immediately on push, regardless if the button is held "long" or released immediately. Can anyone help me out with this? I'm using the LC_baseTools library btw. I managed to do this with another library with doFlash(5) but I have to work with LC basetools in this scenario and I can't figure out how to do it.
#include <mechButton.h>
#include <blinker.h>

#define BUTTON_PIN   11
#define LED_PIN      13
#define BLINK_MS     500.0
#define HOLD_MS      1000

mechButton  theButton(BUTTON_PIN);                    // A debounced button object. (Hook button between pin & ground)
blinker     theBlinker(LED_PIN,BLINK_MS/2,BLINK_MS);  // A fire and forget blinker object.
timeObj     pushTimer(HOLD_MS);                       // A timer object

void setup(void) {
   theBlinker.setOnOff(false);            // Make sure the blinker is acutally off.
   theButton.setCallback(btnClicked);     // Set the callback for the button.
}

// This gets called when the button is clicked.
void btnClicked(void) {
   if (!theButton.trueFalse()) {    // If it has been grounded..
      pushTimer.start();            // Start the timer.
      theBlinker.setPercent(100);   // Set the blinker to full on.
      theBlinker.setOnOff(true);    // Fire it up.
   } else {                         // Else, button released..
      theBlinker.setOnOff(false);   // SHut off the blinker.
   }
}

void loop(void) {
   idle();                             // idle runs the stuff in the background (button & binker)
   if (!theButton.trueFalse()) {       // If the button is currently pressed..
      if (pushTimer.ding()) {          // If the timer has expired..
         theBlinker.setPercent(50);    // Start blinking!
      }
   }
}

I don't know the library, but it seems you are using pushTimer to get this long press behavior. Why just not using it by removing the inner if statement in loop()? have you tried that?

@chrisl im not that well versed to be honest, but i'll try to mix it up with removing that part, see what comes of it

it's afternoon hobby work, I am soldering and crimping and arduino'ing out of lockdown boredome, I just took up these hobbies and quite frankly the arduino stuff is fully out of my jurisdiction, i would pay someone to at least guide me on how to do it, and i have some more ideas but no coding knowledge so I think it will inevitably come to me paying someone to get ti done :D I don't have time, with my regular responsibilites and job, to tackle arduino programming, it's not as "piece of cake" as many people suggest.

again, take a coding course

@Varonne think of a pedestrian crosswalk ... the pedestrian does not directly ask the drivers to stop ...  the pedestrian raises a flag in form of a red traffic light ... drivers watch for red light....... put a layer of separation between the button press and the LED blink ... pressing a button sets a flag, nothing else .... the LED blink code watches the flag and blinks when flag is raised .... the flag could have a value 5 ... when the blink code sees the flag being non-zero, then it blinks the LED once and decrements flag value .... on next iteration of loop() it does it again ... etc.

First of all, considering your comment: "I don't have time [...] to tackle arduino programming" - If you don't learn how to code, then you can't work with code (and that includes putting together libraries you find on the internet). And learning takes time, it's that simple.
I recommend you forget about those libraries and implement that easy task from scratch, so you actually learn something. The below code has the logic you ask for, try to understand what it does.
#define BUTTON_PIN   11
#define LED_PIN      13

bool button_was_pressed=false;

void setup(){
  pinMode(LED_PIN,OUTPUT);
}

void loop() {
  if (digitalRead(BUTTON_PIN)) {
    if(!button_was_pressed) {
      for (int i=0;i<5;i++) {
        digitalWrite(LED_PIN,HIGH);
        delay(50);
        digitalWrite(LED_PIN,LOW);
        delay(50);
      }
    }
    button_was_pressed=true;
  }
  else {
    button_was_pressed=false;
  }
}

...pretty simple and it's only a few lines. You may want to debounce the button and use a non-blocking coding style, but that's a different chapter.
My advice is that you learn programming in a structured manner, e.g. by watching tutorials. A Q&A site is not the right place to do so, as we only answer questions.

Thanks @Sim Son for some reason your code gets an error when compiling, "if (digitalRead(BUTTON_PIN) { - error: expected primary-expression before '}' token"

@Varonne missing a closing parenthesis

@Varonne the answer provided by VE7JRO has a much better code. Mine was just intended to show you how such a thing can be implemented.

I managed to do this with another library with "doFlash(5)" but I have to work with LC basetools in this scenario and I can't figure out how to do it.

It looks like you are still allowed to write Arduino code in your sketch, so why not use the BlinkWithoutDelay "concept" and just write your own code.
I would favour an OOP solution for the LED flashing part of your requirement.
// Arduino IDE 1.8.9.
// Sketch uses 1126 bytes (3%) of program storage space.
// Global variables use 25 bytes (1%) of dynamic memory.
class Flasher{

  private:

    byte ledPin;
    byte ledState;
    unsigned int flashCounter;
    unsigned long highTime;
    unsigned long lowTime;
    unsigned long previousMillis;

  public:

    Flasher(byte ledPinNumber, unsigned long ledOnTime, unsigned long ledOffTime){
      ledPin = ledPinNumber;
      ledState = LOW;
      highTime = ledOnTime;
      lowTime = ledOffTime;
      previousMillis = 0;
      pinMode(ledPinNumber, OUTPUT);
      digitalWrite(ledPinNumber, LOW);
    }

    void Update(){

      // Check to see if it's time to change the state of the LED.
      unsigned long currentMillis = millis();

      if((ledState == HIGH) && (currentMillis - previousMillis >= highTime) && ((flashCounter > 0))){
        ledState = LOW;
        previousMillis += highTime;
        digitalWrite(ledPin, ledState);
        if(flashCounter > 0){flashCounter--;}
      }
      else if((ledState == LOW) && (currentMillis - previousMillis >= lowTime) && ((flashCounter > 0))){
        ledState = HIGH;
        previousMillis += lowTime;
        digitalWrite(ledPin, ledState);
        if(flashCounter > 0){flashCounter--;}
      }
    }

    void Start(unsigned int flashNumberOfTimes){
      flashCounter = flashNumberOfTimes * 2;
      ledState = LOW;
      digitalWrite(ledPin, ledState);
    }

    void Stop(){
      Start(0);
    }

    void SetPinHighTime(unsigned long pinHighTime){
      highTime = pinHighTime;
    }

    void SetPinLowTime(unsigned long pinLowTime){
      lowTime = pinLowTime;
    }

};

// Flasher object_name(Pin Number, ON Time MS, OFF Time MS);
Flasher led1(LED_BUILTIN, 500, 500);

void setup(){

  // Flash the LED 5 times.
  led1.Start(5);

}

void loop(){

  // Call the Update function as fast as possible.
  led1.Update();

}

See my comment on https://arduino.stackexchange.com/a/60861/40646.


text:
How to program a Arduino Nano(Bricked) with a working arduino nano
I corrupted my bootloader on one arduino, luckily I had a spare lying around. Please help as there is not a single tutorial to help my exact state

not a single tutorial to help my exact state .... yes there are tutorials about using an Arduino as an ISP

read somewhere to use a capacitor to hold the reset to high state, in some tutorials, not used

Arduino as ISP and Arduino Bootloaders - https://www.arduino.cc/en/Tutorial/ArduinoISP

I have a page about programming a bootloader using another Arduino.
Basically you grab the code from here and then make up wiring from the good device (which you put the sketch onto) to the device to be programmed, like this:
Arduino Nano        Target Nano

D10 (SS)            Reset
D11 (MOSI)          D11
D12 (MISO)          D12
D13 (SCK)           D13

Gnd                 Gnd
+5V                 +5V


text:
360 degree motion of servo with position control
Is there any way I can control the position of servo by changing the value of potentiometer for using it for 360 deg motion?

Rotary encoders are not that expensive, and not really hard to code into a sketch.  Why don't you try that instead of a potentiometer?

A pot doesn't spin all the way around, so you could map hi/lo values, but you can't run more than one lap with it.  You could add a button that silences the pot input, so that you can hold the button and dial back the pot, releasing the button to continue turning the servo with the pot. In that case, you use relative values between samples to turn the servo instead of simply feeding it the ADC value.
A rotary encoder is probably a better fit though, since it can spin 360 just like the servo. You would still want to "gear down" the encoder if you're micro-stepping, so that say, 4 turns of the encoder yields 1 turn of the servo. This allows full 360 and as much arbitrary precision as your project needs.


text:
Data transfer to and from Arduino to Raspberry Pi
I am trying to transmit MPU6050 accelerometer data + data from 3 potentiometers from Arduino to Raspberry Pi. I do post processing here (on Raspberry Pi) and then transfer the data back to Arduino to move actuators. However my problem is that when I try to write the processed data back to Arduino, I see that even the stream of incoming data from Arduino starts getting corrupted and everything becomes really slow . Even If I just read serial data from Arduino, things are slower if than if I do the processing on Arduino directly. Also, the accelerometer data seems to become unresponsive i.e. its value doesn't change if I move the accelerometer. Everything just works fine if all the processing is done on Arduino. I don't know what is going wrong. Below are my Arduino and Python functions / codes.
Arduino Code:
void send_rec_data(){

    Serial.print(Kp);
    Serial.print(",");
    Serial.print(Kd);
    Serial.print(",");
    Serial.print(Ki);
    Serial.print(",");
    Serial.println(Theta_x);

    delay(20);

  if (Serial.available()>0){ // Read data sent by Raspberry Pi / Piserial

    str_data = Serial.readString();

    int firstCommaIndex = str_data.indexOf(',');

    cmd = str_data.substring(0, firstCommaIndex); // This stores the Scaled output from the Raspberry Pi

    param1 = str_data.substring(firstCommaIndex+1); // This stores the error from the Raspberry Pi to decide motor roattion direction

    Output = cmd.toFloat(); my_error = param1.toFloat(); // Change the outputs from string to float

    blink_led(); // Blink LEDS if data is received from Raspberry Pi

  }

}

Python Code:
while 1:

    data = cont.get_serial_data(arduino)

    time.sleep(0.02)

    if data is not None:

        Kp, Kd, Ki, Theta_x = data

        print(" \n Arduino sent Kp = ", Kp , "Kd = ",Kd , "Ki = ", Ki, "Theta_x = ", Theta_x)

        cont.set_tunings(Kp, Kd, 0)

        Output_scaled = cont.Compute_PID_Output(Input = Theta_x) # Compute the output of PID Algorithm

        ff = str(Output_scaled)+','+str(cont.error)

        arduino.write(ff.encode())

        print("\n Computed data sent TO ARDUINO Output_scaled = ", Output_scaled, "Error = ", cont.error)

arduino.close()

I have spent quiet sometime to resolve the issue byputting delays, flushing buffer but nothing has worked so far. Can someone please help.
Thanks.

You should start by seriously thinking about your required communication timings: How many bytes do you want to send in each direction? At what baud rate? How often? Then read Blink without delay, just to learn how to write non-blocking code, then Reading Serial on the Arduino.

Thank you every one. I read through this forum and it also says the same things which you guys also suggested. I did the same thing and now everything is fast.
Serial.readString()

is indeed the problem.


text:
Pulsein not working when share ground
I have 3rd party device that create PWM output which I want to measure it with Arduino, the problem I have is when I shared ground between the two boards which cause the Pulsein output to become zero. (why this is happening, and how to fix it)
The reason I am connecting the ground since I need measure other signals on that board. (All other signals are responding fine)

simulate this circuit – Schematic created using CircuitLab
code:
#define pulse_ip 3
unsigned long duration;
int ontime,offtime,duty;
float freq,period;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(pulse_ip, INPUT);
}

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

  ontime = pulseIn(pulse_ip, HIGH);
  offtime = pulseIn(pulse_ip, LOW);
  period = ontime + offtime;
  freq = 1000000.0 / period;
  duty = (ontime / period) * 100;
  Serial.print(offtime);
  Serial.print("-");
  Serial.print(ontime);
  Serial.print("-");
  Serial.print(period);
  Serial.print("-");
  Serial.print(freq);
  Serial.print("-");
  Serial.print((duty * 255) / 100);
  Serial.print("-");
  Serial.println(duty);
  delay(1000);

}

what is your question?

why I am getting zero when I share the ground

are you sure you don't get only random pulses without common ground?

@Juraj that is good point maybe I am getting random, let me double check

@Juraj Yes I believe you are correct I am getting random numbers and as soon as I share ground become zero

does calling pulseIn twice make sense? check the reference https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/

The reason I am connecting the ground since I need measure other signals on that board. -- no, the reason you connect the grounds is because you have to. https://majenko.co.uk/blog/our-blog-1/the-importance-of-sharing-grounds-12

@Majenko you are of course correct, that was reason I was getting random number

What (approximate) frequency is the PWM signal? And what voltage levels?

@Majenko 3.3V is the voltage,  14.56k freq  of pwm

you should provide a timeout argument so that it runs faster. even then, it's pushing the limits of hardware and CPU speed and will likely be fuzzy/noisy if it works at all. It would be better to use an RC filter to convert the PWM into an analog voltage, then divide that down to 0-5v, then sample the resulting signal. Since you only seem to need 1 sample a second, you can easily use a large capacitor and sample averaging to get a very smooth analog voltage.

Without connected grounds the signal on the input pin you read with pulseIn must be random noise.
Two pulseIn one waiting for HIGH change and second waiting for LOW don't make sense because for parameter HIGH, pulseIn waits for the pin to go from LOW to HIGH, starts timing, then waits for the pin to go LOW and stops timing. Then it returns the length of the pulse in microseconds.


text:
HG-C 1100 measurement sensor
I am using two HG-C 1100 measurement sensor for measuring the width of the metal. In the top of the sensor I will be having the measurement value. The sensor is capable of measuring the dimensions from -35mm to 35mm.
So I am using the formula:
int First_sample = analogRead(6);
int Second_sample = analogRead(7);
float First_sensor = (map(First_sample, 1023, 0, -3500, 3500) / 100.0);
float Second_sensor = (map(Second_sample, 0, 1023, -3500, 3500) / 100.0);
Serial.print("First_sensor:");
Serial.println(First_sensor, 3);
Serial.print("Second_sensor:");
Serial.println(Second_sensor, 3);
Final_sensor = (First_sensor - Second_sensor);
Serial.println(Final_sensor, 4);

If I use this code, I will get the proper width of the metal. But when I place the metal in between the sensor, I am getting the exact width in the serial monitor. But at the top of the sensors the values are different.
I don't why the analog values are different on the serial monitor and the top of the sensors. But the output of the sensor is perfect in the serial monitor.
Can anyone help me with this?

I can't make much sense out the question as written except that the display doesn't show what you expected. The the sensor display seems to have modes for Standard, Inverted, and Offset.  If it doesn't have anything to do with that, and actually has something to do with the Arduino, maybe clarify the question somewhat.

But when I add the arduino code and see in the serial monitor, the values aren't as like the top of the sensor. if the first sensor is -17.5, it is taking as -17.78. if the second sensor is -21.5, it is taking as -21.12.
I have to know why there is a difference.
But the metal I place between the sensor gives me the proper output.
Have you got my point?                                                                                The serial monitor and the top of the sensor value is different.

"Have you got my point?"  No, I haven't.  Nor do I know what to ask you.  Maybe someone else will.  Failing that, you'll have to figure out how to clarify the question until someone understands it well enough.

The HG-C1100 has a resolution of 70 μm (= 0.07 mm) over a measuring range of 70 mm.
You quote errors of 0.28 and 0.38 mm, which is worse than can be expected (±0,07 mm).
The resolution is 1‰ of the measuring range. Therefore the 10 bits range (1024) of the Arduino's Analog-Digital Converter (ADC) is sufficient.
You map the ADC output of 0-1023 to a range of -3500 to +3500 which results in a value in 0,01 mm. Then you divide by 100.0 resulting in a value in mm.
According to Arduino's Reference the function map() uses integer arithmetic, but the arguments are longs and the calculation order is such that maximal accuracy is maintained. This provides sufficient accuracy for this purpose. I am only not sure if you constants should be post fixed wit an "L".
So far everything looks all right.
The errors you mention correspond to about 5 counts of the ADC.
I assume the solution lies in taking measures to prevent noise entering your signals (signal conditioning).
Addition:
When you read the same sensor repeatedly do you get stable readings? You could try to use an average over multiple readings. Did you look at the signal(s) with an oscilloscope?


text:
Unable to upload to arduino
I am coding my arduino for an upcoming robot competition. I have managed to upload my code and run it on my arduino once or twice, however now I am unable to upload code. I now receive the following message:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

I have unplugged USB, pushed the reset button, checked all the settings (ports, programmer, etc), unplugged the arduino and even tried running basic code such as Blink. I've been searching for hours and now I'm not sure what to do. I am getting no response and I'm finding this really frustrating. Does anyone have any advice as to how to resolve this issue?

Are you absolutely sure you checked the port and chose the right one? Sometimes if you unplug an arduino and then connect it back again it might choose different port.


text:
ctc mode on atmega 328
I'm trying to use CTC mode on Arduino 1 but I have the following problem.
I need to generate an interrupt on threshold B and A and I have set the prescaler to 1 since I want to generate interrupt A at 15999 (correspond to 1ms) and interupt B at 15( ie a number small enough from the start of counting).
I'have write a println function in ISR(A and B) to proof the calling of the latter but the program does not print all the characters in the println function and furthermore the counter does not reset at treshold A but stop his work.
How I can resolve the problem?
Here is the program I wrote:
void setup() {
    TCCR1A = 0x00;                // No outputs on compare math, no PWM mode
    TCCR1B = 1 | (1 << WGM12);    // Enable CTC mode up to OCR1A and prescaler /1 -> Start
    //TCCR1B = 0b00001001;
    TCCR1C = 0x00;                // Nothing to set into C register

    OCR1A = 15999;                // Set Threshold A
    OCR1B = 15;                // Set Threshold B
    TCNT1 = 0;                    // Clear Counter

    TIFR1 = (1 << OCIE1A) | (1 << OCIE1B);    // Clear Interrupt flag Match A and B

    TIMSK1 = (1 << OCIE1A) | (1 << OCIE1B);   // Enable Interrapt flag Match A and B

    analogRead(A0);            // Dummy Read to make Arduino setting the AD
    ADCSRA |= (1 << ADIE);     // Enable AD Interrupt on conversion completed
    ADCSRB = 5;                // Select Timer 1 Match B as trigger
    ADCSRA |= 1 << ADATE;      // Enable Auto trigger

    Serial.begin(115200);      // Initialize the USART
    Serial.println("Start");   // Write the welcome message

}

void loop() {
    // Nothing to do
}

ISR(ADC_vect)
{
    Serial.print(TCNT1);
    Serial.print(" - ADC Conversion Completed (");
    Serial.print(ADC);
    Serial.println(")");
}

ISR(TIMER1_COMPA_vect)
{
    TCNT1=0;
    Serial.print(TCNT1);
    Serial.println(" - Interrupt A");
}

ISR(TIMER1_COMPB_vect)
{
    Serial.print(TCNT1);
    Serial.println(" - Interrupt B");
}

In CTC mode TCNT1 is automatically set back to 0 when it reaches OCR1A. So there is no need to do that inside the ISR. In fact TCNT1 might have already increase in value by the time the ISR is called, so the interval would be slightly more that the 1ms you want.

I don't know about configuring the timers on an AVR off hand, but one thing I will point out:

Never ever use Serial in an ISR.

Serial is interrupt driven - when there are characters in the outgoing serial buffer an interrupt routine sends them out through the serial port.  That can't happen when you're in an interrupt routine yourself, so when the buffer fills up the next Serial.write() (print, etc) blocks until there is room in the buffer for the next character.  As the ISR can't run, that space never appears, so the print(), write(), etc never finish and the program locks up.
Instead you should store any incoming values in your ISRs into volatile variables, and set flags to indicate to your main program what has happened in the ISR - then your main loop() reads (and resets) those flags and prints out the statuses you want.

Ok thanks, but why if I increment prescaler setting and threshold the program works?

If you're running the timer slower you're giving it more time between ISR calls to empty out the serial buffer.

serial in an ISR is still bad practice; However, the arduino Serial library detects if interrupts are disabled and will manually run the serial interrupt handlers when necessary so lock up never happens. printing will take a (relatively) long and inconsistent amount of time though.

@BrettAM: Interesting, thanks for the note. This seems to be the case since release 1.5.6 BETA. Interestingly, it appears that, although this behaviour was implemented in April 2013, almost a month before the 1.0.5 release, it didn't make it to 1.0.5, ant not even to 1.0.6, which came eight months after 1.5.6 BETA.


text:
Lighting LED Strip via HC-06 Bluetooth Module
What I Am Working With:
I am working on a project involving an Arduino, some RGB led strip, and my PC.
My Project:
The PC sends UART (serial) data to the Arduino over Bluetooth (through a HC-06 Bluetooth module connected to the Arduino) to change the color of the LED strip. The user could also change "lighting modes" to instruct the Arduino to make the LED blink, fade, etc.
My Problem:
Having no RTOS nor interruptions on data reception, it would be impossible for me to make the LED fade and, also, to receive Bluetooth data to change the lighting mode.
I would appreciate whatever input the community has regarding this problem.
Thanks in advance,
Stanislas.

Welcome. Possibly adding the code you have so far, a schematic and possibly what else you have done to attempt the project.

I'm not at home at the moment, but I'll post that as soon as I get home.

Received serial data is being buffered (in the background). So you only need to occasionally call Serial.available to see if there's any new data.

There are numerous tutorials available online for controlling LEDs from the Arduino over a Bluetooth connection. You might find some of them helpful: Circuit Magic's tutorial, SoldererTV's tutorial. To change the behavior of the LED, just manipulate the serial data you communicate over the HC-06 in much the same way described in these tutorials

Also, it would be helpful to know what model of Arduino you are using when it comes to specifying the appropriate pins to use.

I'm using the arduino uno and plan to use the arduino nano

Thanks you for the edit, this is my first post on this forum, my apologies for this badly written post!

Yes, it can be done. You don't need a realtime OS for something as simple as that. Basically in your loop function you would check the serial port and parse the input (if available) to see if the PC instructed the arduino to change its mode. Then you would call a function - say nextstep() - which would perform whatever the next step is, depending on your current mode. True, when you get serial input your loop() will take longer to execute, which will alter the 'rhythm' of your fades etc. If this is important, you should replace the call to delay() with a loop checking millis() against a value stored at the start of loop().
int currentmode ;
int previousmode ;

void loop()
{
   previousmode = currentmode ;
   currentmode = getnewmode(currentmode) ;
   if (currentmode != previousmode)
      initmode(currentmode) ;  // turn new mode on e.g. change LED color
   nextstep(currentmode) ;     // if current mode is dynamic, make change
   delay(DELAY_INTERVAL) ;
}

int getnewmode(oldmode)
{
   if (!serialpending()) // no serial input
      return oldmode ;
   return parseinput() ;
}