text:
Arduino not recognizing external microcontroller
I've been trying to follow the official Arduino instructions on how to program and power an external breadboard, and I've gotten a pack of ATmega328p's that may or may not have been preloaded with the bootloader (found here). From the title, I assumed that they were, in fact, preloaded, but I followed the instructions to "reload it" from a working Arduino (with its original microcontroller), and I did it with the following circuit setup (this is the best image that I have of it, unfortunately, I promise I've checked that the wiring actually is equivalent to the original diagram, just shifted around for convenience on the breadboard):

I'm not sure whether I should've kept the original microcontroller in, as the guide ambiguously shows a void in the area where the controller should be in the provided diagram...

...but my thinking was that the Arduino basically isn't anything without its attached microcontroller, so attempting to "send" bootloader code to a separate microcontroller would require a plugged in microcontroller, and that was the only way I got it to work.
With all this set up, I tried to test using this new microcontroller, and it worked perfectly when mounted in the provided microcontroller area. However, when I tried to follow this up with the steps detailed in the guide, found here, with the following circuit (slightly better angle):

...I was faced with errors of being unable to connect.

From what I understand, it seems like the Arduino should automatically detect that no microcontroller is plugged in, hence allowing the stated "FTDI chip can talk to the microcontroller on the breadboard instead" from the guide. However, the error I'm getting seems to be the same as the error I got when I just plainly tried to send code or program without any microcontroller connected, so I'm assuming this implies that it can't find any microcontroller, either internal or standalone.
From googling this error, it seems that others have had this problem with seemingly no solution, and I have absolutely no idea how I could fix this. If there's something I'm missing, would greatly appreciate the help.
side note, when I was idly testing out the program with a tiny test circuit that lights up an LED, after programming it with a program that turns on a GPIO pin, connecting that pin to the LED, it did in fact light up. I'm concluding this means that the setup of the actual microcontroller is functional, but it's unable to be written to. this has also happened with the original microcontroller that I tried to simply program externally.
any help is appreciated, thanks for reading!

If you have been able to put the new MCU chip into your Uno and it works, say you can upload a sketch, then it has a bootloader. Clearly,  a chip must be present in the Uno when the Uno is used to burn a bootloader onto another chip because the Uno must run the ISP sketch. For the second part, that is loading a sketch onto the chip on the breadboard, check your wiring carefully between TX, RX and Reset on the Uno and the breadboard. It does look wrong but that could be the picture quality. For this part it is correct that the Uno has no MCU chip.

Simply to eliminate variables, I would not put the crystal away from the chip that way. You can angle that crystal at roughly 45 degrees, connecting the crystal directly to the same breadboard tie points that the MCU's crystal related pins go to. Your load caps can then connect those same exact tie point to the nearby ground bus. In the end, you have jumpers involved in the purely crystal-related part of the circuit. Less crap to go wrong. Or worse, go wrong intermittently while you're troubleshooting.

Can you please see my page about detecting chip signatures. Using your Uno and 6 wires (MOSI, MISO, SCK, SS, 5V, Gnd) you can see if it recognises the chip at all, and if so, is there a bootloader on it, and also the fuse settings. Please edit your question with the results of that.

Also see my page about breadboard Arduinos which describes something very similar to what you are attempting.

apologies for the late responses y'all, getting to this! @6v6gt, I didn't include a Reset as I figured that I didn't need to use the reset (would just rerun the code if I needed a reset). will try to add this in in a bit, I'm fairly certain the TX/RX is right but will try that in a bit

@timemage I see, I'll take this into account, but I don't actually plan on mounting it to the breadboard for an extended period of time, just as a testing framework before I actually mount it on a perfboard (perma-proto)

@NickGammon will check this when I get back to this next, much appreciated! I have honestly been having trouble finding good resources on breadboard Arduinos as I feel like this should be a really simple and well-documented problem, but everyone just seems to ignore it so it's really helpful to see a guide!

NickGammon's second link shows the crystal arrangement I was describing. And I am suggesting that it may be worth doing now (regardless how temporary your setup is) because you are having troubles.

great, so I've just rechecked my work with the circuit and as it turns out, the problem seemed to just lie in the fact that I didn't have the Reset connected, as @6v6gt mentioned. I didn't realize that this could've broken everything, so I'll make sure to be very careful when placing this onto an actual perfboard. if you'd like to write the answer for this I'll absolutely accept! much appreciated :D

You kind of don't really. All that matters is for optiboot is that an external reset happens. It's sufficient that you momentary ground reset within about 1.3 seconds prior to avrdude making programing attempt, which it does repeatedly, which has the effect of making the time much looser. The serial-DTR auto-reset mechanism is nice to have but you needn't use it.  It is not uncommon to just use a jumper wire momentary from gnd to reset, nor uncommon to entirely remove it from the board once reset, which makes its absence in the picture not particularly definitive.

In the case of using an Arduino as a USB/UART (FTDI) adapter to upload a sketch onto a barebones Arduino (ATMEGA328P) via its own bootloader,  a reset of that MCU chip must preceed the sketch upload. That is because, immediately following the reset, the bootloader watches the serial traffic to see if this is marked as a sketch upload and, if so, processes it. If this reset operation fails, for example through a bad or missing connection, the sketch upload attempt will also fail.
A good description of the sketch upload process can  be found here: https://www.instructables.com/Overview-the-Arduino-sketch-uploading-process-and-/

this makes a lot of sense! thanks for explaining the reasoning behind it, was very curious why it couldn't just send a reset signal through the TX/RX, lol


text:
Buttons pressed in correct order
I’m trying to figure out the best way of doing this, currently using a bunch messy if-statements which kind of work. I have an IR sensor and three buttons that all need to be activated in the right order. Each sensor/button will activate LEDs and sound effects. First, when sensor1 goes HIGH, button1 can be pressed momentarily, then button2, then button3. If sensor1 is LOW, then nothing should happen when the buttons are pressed. When sensor1 is HIGH then the buttons should be pressed in the right order to progress through the sequence. When sensor1 goes back to LOW it should reset everything and allow the sequence to be run again when HIGH. Should I look into case switches for this?
Thank you
Jason

what should happen when buttons are pushed in wrong order?

If sensor1 is LOW, then nothing should happen when the buttons are pressed. When sensor1 is HIGH then the buttons should be pressed in the right order to progess through the sequence.

what should happen when the sensor state goes low partway through the button sequence? .... please add the description to your question ... do NOT write a comment

Should I look into case switches for this? ... you can, if you want ... the switch/case  block is equivalent to if else if else if ... .... is that really the only question that you want to ask?

and some pointers to learn to code this. I'm still learning. thanks

This is a classic application for a state machine, in which you keep track of where your process currently is in the sequence of events that must take place. The 'state' is just a numeric variable whose value you change whenever a significant event takes place.
You would probably assign 0 - Initial state, waiting for an event (or the first event); 1 - Sensor is high, 2 - button-1 went high, 3 - button-1 went low; ... etc.
It always helps to sketch out your state machine on paper, drawing a circle for each state, and arrows from each state 'x' to whatever the next state should be if an event 'y' happens while in state 'x'. The events are sensors and buttons going HIGH or LOW. In a particular state, no arrow for some event means you want to ignore that event while you are in that state.
Once you have drawn the map you can code the state machine. A common way of coding it is with a switch-case block, one case per defined state. Inside each case block, you test only for those events for which there is an arrow leading from that state to another state.
As you add new conditions, (e.g. "What should happen if the sensor goes low after button-1 has been pressed?"), switch-case logic will be much easier to modify than if you had used a complex collection of if-then statements. And you will be adding new conditions & removing or fixing wrong ones as you discover ways the device fails or humans do things you didn't anticipate. (Ask me how I know this! :-)
It will be really helpful to be able to go back to your state map to visualize what should (or shouldn't) happen, and what to change (on the map) to make that behavior. From the updated map, it is usually easy to see what code needs to be added, deleted, or fixed in the switch-case block.

+1 for the finite state machine. For the details on how to implement this in code, I usually point people to Majenko's Finite State Machine tutorial, which I find quite good.

source: Stack Exchange

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

sort: votes


text:
I2C HMC5983 communication issue
I have a really weird problem, when I run the exmple wire (I2C) scanner from Arduino, I get:
I2C Scanner
Scanning...
I2C device found at address 0x1E  !
done
However when I try directly to the 0x1E I get the following error code 2:
received NACK on transmit of address.
Below is my code that i did only modify the example code:
#include <Wire.h>

void setup() {
  Wire.begin();

  Serial.begin(9600);
  while (!Serial); // Leonardo: wait for Serial Monitor
  Serial.println("\nI2C Scanner");
}

void loop() {

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

  byte address = 0x1E;

  Wire.beginTransmission(address);
  byte error = Wire.endTransmission();

  if (error == 0) {
    Serial.print("I2C device found at address 0x1E");
  } else if (error == 1) {
      Serial.print("data too long to fit in transmit buffer.");
  }
  else if (error == 2) {
      Serial.print("received NACK on transmit of address.");
  }
  else if (error == 3) {
      Serial.print("received NACK on transmit of data.");
  }
  else if (error == 4) {
      Serial.print("Unknown error at address 0x");
  }

  delay(5000); // Wait 5 seconds for next scan
}

please add a clear, answerable question to your post

It is very clear that I am asking what is wrong ? please do not comment just to comment.

not everyone would ask the same question ... this is a Q&A site, so a clear question is required

What is your pull-up resistor's value? NACK on Addressing could happened if you have weak pull-up, or if the device is busy.

There are certain situations where the device can send a nack after a valid address is sent - search "received NACK on transmit of address". Nothing I read applies specifically to your situation.
I see nothing in the HMC5983 datasheet (https://www.farnell.com/datasheets/1509871.pdf?_ga=2.219060057.1318745487.1555987311-293789508.1555987311) that could account for what you are seeing.
I don't have an HMC5983 on a GY282 module (you mentioned the module in a different forum) as you do, but I have it's predecessor, HMC5883 which I think is largely comparable, but slower.
I tested your code and I DID NOT get the NACK error - it simply reported finding the the device.
Then, I tested the leanest HMC5883 code I could find and I saw systematic output, which changed as I moved the device.
Then I tested similar code for the HMC5983 (see https://wiki.eprolabs.com/index.php?title=GY-282_HMC5983_Module#Hardware_Connections). That code worked on my slower HMC5883 board (e.g., systematic output).
I suggest the following - double check the solder blobs on the board to make sure I2C/SPI is jumpered properly - also the 3v3 CS blobs - a picture would be helpful.
I would also suggest that you try to run the HMC5983 code that I linked and see what you get.
Hope it helps.

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


text:
Connecting the MKR GPS shield by cable or as a shield
I have an MKR WiFi 1010 and an MKR GPS Shield. When I connect my GPS Shield using the I2C cable, it works fine.
This works perfectly (the bottom is the MKR Motor Carrier):

However, when I use it as a shield (hat?) using the pins, it doesn't.
This doesn't work. The code blocks somewhere (I suspect GPS.available()):

My question, should it work the same whether it is cabled or put on with the pins? Or should I change my code somehow?

From the shop page:

It interfaces with Arduino boards either through a serial interface, when used with headers and put on top of a MKR board, or through an I2C interface and a dedicated ESLOV cable supplied as bundle.

From Arduino_MKRGPS library reference:
begin() Parameters:

GPS_MODE_I2C to use the MKR GPS with the I2C cable (default setting),
GPS_MODE_SHIELD if using the MKR GPS as a shield.


text:
How to splitting values in int serial read values
I get values in serial read using the following code,
int32_t bytesSent = 0;

if (mySerial.available()) {
    bytesSent = mySerial.read();
}

Output:
Serial.write(bytesSent); gives -1199/1211 value.
I need to split this value into two values. That should separate using "/" point.
Value 1 - -1199
Value 2 - 1211
The following code is used for char type values separate when numberArray3[20] = "-1199/1211"
    char numberArray3[20];

   int len = strlen(numberArray3);
   int pos = strcspn(numberArray3,"/");

   char First[20];
   char Second[20];

   strncpy(Second, numberArray3+pos+1, len);
   strncpy(First, numberArray3, pos);
   Serial.println(First);
   Serial.println(Second);


text:
How to reduce codes numbers
I am new in Arduino projects, i made a digital counter that counts from 00 to 99.
Here is my code below
void setup()
{
pinMode(0,OUTPUT);
  pinMode(1,OUTPUT);
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
}

void loop()
{
/* segment starts from 00*/
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,HIGH);
digitalWrite(0,LOW);
digitalWrite(3,LOW);
/* segment will now be 10, the 0 will continue counting up to 1*/

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(5,HIGH);
digitalWrite(4,LOW);
/* the segment will now be 20 */

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,HIGH);
digitalWrite(5,HIGH);

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,LOW);
digitalWrite(6,HIGH);
digitalWrite(5,LOW);

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,HIGH);
digitalWrite(6,HIGH);

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(5,HIGH);
digitalWrite(4,LOW);

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,HIGH);

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,LOW);
digitalWrite(7,HIGH);
digitalWrite(6,LOW);
digitalWrite(5,LOW);

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,HIGH);
/* the segment will now be 9 0 */

digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(3,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(0,LOW);
digitalWrite(1,HIGH);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(2,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(1,HIGH);
digitalWrite(0,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(3,HIGH);
digitalWrite(0,LOW);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
delay(500);
digitalWrite(0,HIGH);
delay(500);
digitalWrite(4,LOW);
digitalWrite(7,LOW);
/* when it gets here the segment resets to 00*/
}

It works pretty fine but the problem i have is the code is too long, is there a method i can use to reduce the length of the codes?

What you are writing here is some sort of binary counter: a BCD
(binary-coded decimal) counter to be precise. It turns out that the
processor inside the Arduino already works in binary. It's its native
language, so you do not have to tell it how to do binary. You just have
to know what operators to use in order to access the individual bits.
My approach would be to write a function that can display any number n
between 0 and 99. The first step is to do the decimal decomposition:
divide by 10, and take the quotient (first digit) and the remainder
(second digit). These digits will be represented in binary within the
machine. The next step is to access the individual bits. This is a two
step process:

Shift the bits of the number to the right until the bit you want is
at the far right. This is accomplished with the right-shift operator.

Compute the bitwise AND with the number 1 (0000000000000001 in
binary). This will clear all the bits but the one you want, and
result in either 0 (the same as LOW) or 1 (i.e. HIGH).

For example, if you want to get bit 1 of the number 7, you do
0000000000000111 = 7  initial number
0000000000000011 = 3  shifted one potion to the right
0000000000000001 = 1  bitwise AND-ed with 1

In code:
void display(int n)
{
    int digit0 = n % 10;
    int digit1 = n / 10;
    digitalWrite(0, (digit0 >> 0) & 1);
    digitalWrite(1, (digit0 >> 1) & 1);
    digitalWrite(2, (digit0 >> 2) & 1);
    digitalWrite(3, (digit0 >> 3) & 1);
    digitalWrite(4, (digit1 >> 0) & 1);
    digitalWrite(5, (digit1 >> 1) & 1);
    digitalWrite(6, (digit1 >> 2) & 1);
    digitalWrite(7, (digit1 >> 3) & 1);
}

Edit: If you need more that 2 digits, you have to successively
divide by 10:

Divide the number to be displayed by 10: the rest of the division is
the rightmost digit

replace the original number by the quotient of the division

divide again by 10: the rest of the division is the second rightmost
digit

replace the original number by the quotient of the division

etc.

For example, for three decimal digits:
void display(int n)
{
    int digits[3];  // digits[0] is the rightmost digit
    digits[0] = n % 10;
    n /= 10;
    digits[1] = n % 10;
    n /= 10;
    digits[2] = n % 10;

    // Now make sure that n < 10 (otherwise we are missing digits),
    // then display digits[0], digits[1] and digits[2].
}

The main program now only has to loop through the numbers 0 to 99, and
display each one in turn:
void loop()
{
    for (int n = 0; n < 100; n++) {
        display(n);
        delay(500);
    }
}

Thanks a lot although I have little knowledge on it

Thanks a lot for the help.But how did you get digit0=n%10  digit1=n/10, and if i want to add another bcd to it what calculations do i need to make to get it i have been trying digit2=n/100 but it didnt work well.

@JosephAfodu: Re “how did you get digit0=n%10 [...]”: I learned decimal counting in primary school, and then I learned the meaning of the / and % operators in C++. Re “and if i want to add another bcd”: see amended answer.

@JosephAfodu, The greater part of your confusion may be in not recognizing % as something you're probably already familiar with which is not conventional in math but is fairly conventional in coding.  You'll need to be familiar with the bitwise operators as well.

Is there a way i can make it with 3 bcd's without the middle one displaying letters , I tried but when the last one counts 1, the middle one will be displaying letters.

@JosephAfodu: You must have a mistake in your code. If you compute digits[1] as n % 10, it should not display letters, unless the wiring is wrong.

If i do it that way digit[0] and digit[1] will show the same number at a time

If i need number 999 i use: digit0=n%10; digit1=n/10; digit2=n/100; . Also i changed : for (int n=0; n<100; n++) to for (int n=0; n<1000; n++) because i need numbers up to 999. When it gets to 99 and the third bcd shows 1, insted of the second to show 0, it will show A until it counts to f before it restarts at 1 and maybe by then the 3rd  bcd have already shown 2. Which will make the numbers not get to 999 when it gets to 930 it will restarts from 000. I just need to get rid of the letters displaying on the second bcd.

@JosephAfodu: See my edit from two days ago: the code right after “For example, for three decimal digits”.

I suggest you look up how to do loops in a C or C++ programming tutorial. For example you can replace:
void setup()
{
  pinMode(0,OUTPUT);
  pinMode(1,OUTPUT);
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
}

with:
void setup()
{
  for (int i = 0; i <= 9; i++)
    pinMode(i,OUTPUT);
}

Also, what Edgar Bonet said. :)


text:
Cannot read LED state
I am running into a problem on a very basic functionality.
I want to read the state of an LED.
I have confirmed that under the specified circumstances, the LED receives 1.9V.
I try to read its state with this code:
#define LED_1  5

void setup()
{
pinMode(LED_1, INPUT);
}

void loop()
{
 int led_state = 0;
 if ( digitalRead(LED_1) ) led_state = 1;
 Serial.println("LED State is: ");
 Serial.println(led_state);
}

However, most of the time, the led_state is 0. Sometimes, it goes to 1, but then quickly goes back to 0.
Is it because the voltage is low?
EDIT: I am hooking power directly to one pin of the LED, and the other pin goes to GND (from the same DC power supply).
Also, the power pin from the LED enters inside Arduino Digital Pin 5.

What LED button do you have? How is it wired? What Arduino are you using?

If it's wired how I think it is the analogRead would be better for it. Or internal analog comparator module (depends on MCU, there might not be library for it) or external OpAmp/comparator

@chrisl Sorry it was not a button. I made a typo in the question, it is corrected now. Just a standard LED. I am using arduino uno.

@KIIV Thanks! Can I do analogRead(), on Arduino Digital Pin 5? I am on Arduino Uno.

No, you'll have to wire it into some analog pin. And then you'll have to compare the value with some threshold (basically making software comparator)

@KIIV Since the voltage is 2V DC in, why can't this be "read" by a digital channel?

Read about 5V CMOS Logic levels for the answer (UNO uses 5V). For example here: https://learn.sparkfun.com/tutorials/logic-levels/all

Can you please provide a diagram of how the LED is wired. It sounds like you don't have a current limiting resistor in series with your LED.

@sa_leinad You are right, I just hooked it up to a DC voltage generator... I found the solution though.

@KIIV I did it with analogRead(). If you want, you can post a proper answer so I can mark it as the selected one. One key point though. The GND of the arduino and the power supply had to be connected, otherwise, the reading was random.

I also have to note that I was able to read the LED state in the past, using DigitalRead. However, the operating voltage of the arduino was 3.3V. Thus, it could read voltages of 1.9V. When the operating voltage of the arduino was 5V, it was unable to measure the 1.9V Voltage with digitalRead.

For the CMOS logic the treshold is usually 1/2 Vcc, therefore you might get lucky with arduino 3.3V Arduinos, but it's still in undefined area. That usual threshold can also change with operating temperature (like 5V WS2812 stopped working in the winter if you were using 3V3 mcu as a driver)
So what are the possible solutions?

route it to the Ax pin and use analogRead + condition (basically software comparator)

if the previous is too slow, you can use AC module on the mega328p (Analog Comparator), but you'll most likely have to dig into the datasheet and use specific pin or pins (compare it against internal 1V1 reference or external one set by potentiometer)

external OpAmp/Comparator (this one can be used with the original pin, note comparator needs pullup, opamp doesn't)

NPN transistor (1k or bigger between base and Anode of the LED, internal pullup or external one between Vcc and Collector, Emmiter to the ground)

I just note, for completion.... If you wire up an LED and you try to read it, make sure the GND is common between the LED and the Arduino.

A digital input on the Arduino Uno is guaranteed to read LOW if the
input voltage is less than 1.5 V. It is guaranteed to read HIGH
if that voltage is above 3.0 V. For any voltage in between, you
have no guarantees.
That being said, the datasheet of the microcontroller shows some
“typical” characteristics. According to those, the input should switch
to HIGH when the input voltage goes above 2.6 V, and switch to
LOW when it goes below 2.1 V. There is an hysteretic range in
between.
Note, however, that there is no guarantee that your input will behave
like in the typical characteristics. The only guarantees are for
voltages below 1.5 V and above 3.0 V.

I made an experiment, providing up to 5V in the LED. I could still see the input oscillate from 0 to 1 back to 1. Why is this happening? I didn't cross over the 5V threshold.

@user1584421: I do not know what is happening in your setup because: 1. You cannot “provide” 5V to an LED without burning something. 2. The code you posted does not even compile. Please, edit your question: add a schematic of your circuit, and a version of the code that can be tested.

Thanks! I updated the question.

@user1584421: You should never power an LED like this, as you may burn the LED, the power supply, or both. Always use a current-limiting resistor. If nothing burned, chances are the PSU itself is limiting the current, and thus not providing 5 V to the LED.

Yes, you were right. The PSU was limiting the current. I managed to solve this problem with analogRead(). And by having a common GND between the PSU and the Arduino. Thank you very much for your highly informative post!

On my understanding, this is what you made

But i think you should do it this way

Here is the code

int value;
float input;
int delaytime=500;

void setup() {
pinMode(value,INPUT);
Serial.begin(9600); //serial bud rate
}

void loop() {

value=analogRead(A2);
input=(value*5.0)/1022.0;
Serial.println(value);
Serial.println("LED state is: ");
Serial.println(input);
delay(delaytime);

}


text:
The same button with one click and double click
i hope to get some help with my code.
I am trying to distinguish between a single press and a quick double press of the button with debouncing.
I am making some silly mistake in my code and i can't find out the problem. If I double press the button, both 'single' and 'double' gets printed on the serial monitor.
Thanks in advance for some help.
const int buttonPin = 5;
unsigned long lastPressTime;
int buttonState = 0;
int singlePress = 0;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);

  lastPressTime = millis();
  Serial.begin(9600);
}

void loop() {
  if (!digitalRead(buttonPin) == HIGH && buttonState == 0) {
    unsigned long currentPressTime = millis();

    //two presses within 500ms
    if (currentPressTime - lastPressTime < 500) {
      singlePress = 0;
      //Do double press action
      Serial.println("double");
    } else {
      singlePress = 1;
    }

    //update the last pressed time
    lastPressTime = currentPressTime;
    buttonState = 1;
  } else if (!digitalRead(buttonPin) == LOW) {
    buttonState = 0;
  }

  //check if 500ms have passed with no second button press
  if (singlePress == 1 && lastPressTime  - millis() > 500) {
    singlePress = 0;
    //DO single press stuff
    Serial.println("single");
  }
}

why not use a library? for example Bounce2

@Juraj...I know there are some library's for this type of situations. I know the Bounce2 and generally I use the OneButton library. In this case I am trying to make it work without the use of a library.

both 'single' and 'double' gets printed on the serial monitor .... you are almost there ... add code to pick one, then print

This looks odd  lastPressTime  - millis() > 500  since lastPressTime will be less than millis() but I don't think that is your only problem. I restructured your solution as a more explicit finite state machine and put it in a simulator: https://wokwi.com/projects/347070000856564307

The problem is this statement:
lastPressTime  - millis() > 500

Because time is stored as an unsigned long, this test as it is written now is always true.
You want to measure the time since the last press, so you should subtract the timestamp of the last press from the current time. Replace it with:
millis() - lastPressTime > 500

And the code will run fine.

If your "answer" is derived 100% from someone else's previous comment pointing out an obvious error, it would be courteous to at least acknowledge it. Even better would be to wait until the originator has had a chance to correct his code and report the results before making a statement such as "And the code will run fine." . (I don't believe it does)

Thank you all for your help...
Definitely the problem in my code, to get the one click and double click working like @mhopeng wrote, was this statement:
lastPressTime  - millis() > 500

changing it to this
millis() - lastPressTime > 500

maked it work.
But what i realize is that my approach is not enough responsive.
Using the approach of @6v6gt is much better than mine.
The reaction is much more responsive and smoother.
// note the simulation speed is about one third of real time
// adjust timings if using on real hardware.

const int buttonPin = 5;
unsigned long inStateAtMs = millis() ;
int buttonState ;  // 0 = waiting for press, 1= waiting for release 2= differentiate single or double 3= wait button release (double)

void setup() {
 pinMode(buttonPin, INPUT_PULLUP);
 Serial.begin(9600);
}

void loop() {

 if ( buttonState == 0 ) {
   // wait for button press
   if ( millis() - inStateAtMs > 100 ) {
     if (!digitalRead(buttonPin)) {
       buttonState = 1 ;
       inStateAtMs = millis();
     }
   }
 }
 else if ( buttonState == 1 ) {
   // wait for stable button release 1
   if ( millis() - inStateAtMs > 100 && digitalRead(buttonPin) ) {
     buttonState = 2 ;
     inStateAtMs = millis();
   }
 }
 else if ( buttonState == 2 ) {
   // differentiate between single and double press
   if ( millis() - inStateAtMs > 400 ) {
     // timeout - is a single press
     Serial.println("single");
     buttonState = 0 ;
     inStateAtMs = millis() ;
   }
   else if (  ( ! digitalRead(buttonPin) ) && (millis() - inStateAtMs > 100 ) ) {
     // got second press within timeout - double
     Serial.println("double");
     buttonState = 3 ;
     inStateAtMs = millis() ;
   }
 }
 else if ( buttonState == 3 ) {
   // wait for stable button release 2
   if ( millis() - inStateAtMs > 100 && digitalRead(buttonPin) ) {
     buttonState = 0 ;
     inStateAtMs = millis();
   }
 }
}

Thanks again all of you for the help

I'm glad you've got something which works for you. I put your original sketch, but with the correction, into the same simulator and it does not appear to work. However, it [the simulator] appears to implement an exaggerated button bounce which you may not encounter on a physical Arduino. It is here if you want to play with it: https://wokwi.com/projects/347070013621928531

I noticed that in the simulator my code does not work, but on the physical Arduino it does.


text:
Adafruit_SSD1306.cpp fatal error: pgmspace.h: No such file or directory using SSD1306 on Arduino Nano RP2040
I am currently trying to get a SBC-OLED01 display to run under my Arduino Nano RP2040. I use the official example from Adafruit, attached is the code.
/**************************************************************************
 This is an example for our Monochrome OLEDs based on SSD1306 drivers

 Pick one up today in the adafruit shop!
 ------> http://www.adafruit.com/category/63_98

 This example is for a 128x64 pixel display using I2C to communicate
 3 pins are required to interface (two I2C and one reset).

 Adafruit invests time and resources providing this open
 source code, please support Adafruit and open-source
 hardware by purchasing products from Adafruit!

 Written by Limor Fried/Ladyada for Adafruit Industries,
 with contributions from the open source community.
 BSD license, check license.txt for more information
 All text above, and the splash screen below must be
 included in any redistribution.
 **************************************************************************/

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library.
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define NUMFLAKES     10 // Number of snowflakes in the animation example

#define LOGO_HEIGHT   16
#define LOGO_WIDTH    16
static const unsigned char PROGMEM logo_bmp[] =
{ 0b00000000, 0b11000000,
  0b00000001, 0b11000000,
  0b00000001, 0b11000000,
  0b00000011, 0b11100000,
  0b11110011, 0b11100000,
  0b11111110, 0b11111000,
  0b01111110, 0b11111111,
  0b00110011, 0b10011111,
  0b00011111, 0b11111100,
  0b00001101, 0b01110000,
  0b00011011, 0b10100000,
  0b00111111, 0b11100000,
  0b00111111, 0b11110000,
  0b01111100, 0b11110000,
  0b01110000, 0b01110000,
  0b00000000, 0b00110000 };

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

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  // Show initial display buffer contents on the screen --
  // the library initializes this with an Adafruit splash screen.
  display.display();
  delay(2000); // Pause for 2 seconds

  // Clear the buffer
  display.clearDisplay();

  // Draw a single pixel in white
  display.drawPixel(10, 10, SSD1306_WHITE);

  // Show the display buffer on the screen. You MUST call display() after
  // drawing commands to make them visible on screen!
  display.display();
  delay(2000);
  // display.display() is NOT necessary after every single drawing command,
  // unless that's what you want...rather, you can batch up a bunch of
  // drawing operations and then update the screen all at once by calling
  // display.display(). These examples demonstrate both approaches...

  testdrawline();      // Draw many lines

  testdrawrect();      // Draw rectangles (outlines)

  testfillrect();      // Draw rectangles (filled)

  testdrawcircle();    // Draw circles (outlines)

  testfillcircle();    // Draw circles (filled)

  testdrawroundrect(); // Draw rounded rectangles (outlines)

  testfillroundrect(); // Draw rounded rectangles (filled)

  testdrawtriangle();  // Draw triangles (outlines)

  testfilltriangle();  // Draw triangles (filled)

  testdrawchar();      // Draw characters of the default font

  testdrawstyles();    // Draw 'stylized' characters

  testscrolltext();    // Draw scrolling text

  testdrawbitmap();    // Draw a small bitmap image

  // Invert and restore display, pausing in-between
  display.invertDisplay(true);
  delay(1000);
  display.invertDisplay(false);
  delay(1000);

  testanimate(logo_bmp, LOGO_WIDTH, LOGO_HEIGHT); // Animate bitmaps
}

void loop() {
}

void testdrawline() {
  int16_t i;

  display.clearDisplay(); // Clear display buffer

  for(i=0; i<display.width(); i+=4) {
    display.drawLine(0, 0, i, display.height()-1, SSD1306_WHITE);
    display.display(); // Update screen with each newly-drawn line
    delay(1);
  }
  for(i=0; i<display.height(); i+=4) {
    display.drawLine(0, 0, display.width()-1, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=0; i<display.width(); i+=4) {
    display.drawLine(0, display.height()-1, i, 0, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=display.height()-1; i>=0; i-=4) {
    display.drawLine(0, display.height()-1, display.width()-1, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=display.width()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, i, 0, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=display.height()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, 0, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=0; i<display.height(); i+=4) {
    display.drawLine(display.width()-1, 0, 0, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=0; i<display.width(); i+=4) {
    display.drawLine(display.width()-1, 0, i, display.height()-1, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000); // Pause for 2 seconds
}

void testdrawrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2; i+=2) {
    display.drawRect(i, i, display.width()-2*i, display.height()-2*i, SSD1306_WHITE);
    display.display(); // Update screen with each newly-drawn rectangle
    delay(1);
  }

  delay(2000);
}

void testfillrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2; i+=3) {
    // The INVERSE color is used so rectangles alternate white/black
    display.fillRect(i, i, display.width()-i*2, display.height()-i*2, SSD1306_INVERSE);
    display.display(); // Update screen with each newly-drawn rectangle
    delay(1);
  }

  delay(2000);
}

void testdrawcircle(void) {
  display.clearDisplay();

  for(int16_t i=0; i<max(display.width(),display.height())/2; i+=2) {
    display.drawCircle(display.width()/2, display.height()/2, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testfillcircle(void) {
  display.clearDisplay();

  for(int16_t i=max(display.width(),display.height())/2; i>0; i-=3) {
    // The INVERSE color is used so circles alternate white/black
    display.fillCircle(display.width() / 2, display.height() / 2, i, SSD1306_INVERSE);
    display.display(); // Update screen with each newly-drawn circle
    delay(1);
  }

  delay(2000);
}

void testdrawroundrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2-2; i+=2) {
    display.drawRoundRect(i, i, display.width()-2*i, display.height()-2*i,
      display.height()/4, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testfillroundrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2-2; i+=2) {
    // The INVERSE color is used so round-rects alternate white/black
    display.fillRoundRect(i, i, display.width()-2*i, display.height()-2*i,
      display.height()/4, SSD1306_INVERSE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testdrawtriangle(void) {
  display.clearDisplay();

  for(int16_t i=0; i<max(display.width(),display.height())/2; i+=5) {
    display.drawTriangle(
      display.width()/2  , display.height()/2-i,
      display.width()/2-i, display.height()/2+i,
      display.width()/2+i, display.height()/2+i, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testfilltriangle(void) {
  display.clearDisplay();

  for(int16_t i=max(display.width(),display.height())/2; i>0; i-=5) {
    // The INVERSE color is used so triangles alternate white/black
    display.fillTriangle(
      display.width()/2  , display.height()/2-i,
      display.width()/2-i, display.height()/2+i,
      display.width()/2+i, display.height()/2+i, SSD1306_INVERSE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testdrawchar(void) {
  display.clearDisplay();

  display.setTextSize(1);      // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE); // Draw white text
  display.setCursor(0, 0);     // Start at top-left corner
  display.cp437(true);         // Use full 256 char 'Code Page 437' font

  // Not all the characters will fit on the display. This is normal.
  // Library will draw what it can and the rest will be clipped.
  for(int16_t i=0; i<256; i++) {
    if(i == '\n') display.write(' ');
    else          display.write(i);
  }

  display.display();
  delay(2000);
}

void testdrawstyles(void) {
  display.clearDisplay();

  display.setTextSize(1);             // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE);        // Draw white text
  display.setCursor(0,0);             // Start at top-left corner
  display.println(F("Hello, world!"));

  display.setTextColor(SSD1306_BLACK, SSD1306_WHITE); // Draw 'inverse' text
  display.println(3.141592);

  display.setTextSize(2);             // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.print(F("0x")); display.println(0xDEADBEEF, HEX);

  display.display();
  delay(2000);
}

void testscrolltext(void) {
  display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 0);
  display.println(F("scroll"));
  display.display();      // Show initial text
  delay(100);

  // Scroll in various directions, pausing in-between:
  display.startscrollright(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrollleft(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrolldiagright(0x00, 0x07);
  delay(2000);
  display.startscrolldiagleft(0x00, 0x07);
  delay(2000);
  display.stopscroll();
  delay(1000);
}

void testdrawbitmap(void) {
  display.clearDisplay();

  display.drawBitmap(
    (display.width()  - LOGO_WIDTH ) / 2,
    (display.height() - LOGO_HEIGHT) / 2,
    logo_bmp, LOGO_WIDTH, LOGO_HEIGHT, 1);
  display.display();
  delay(1000);
}

#define XPOS   0 // Indexes into the 'icons' array in function below
#define YPOS   1
#define DELTAY 2

void testanimate(const uint8_t *bitmap, uint8_t w, uint8_t h) {
  int8_t f, icons[NUMFLAKES][3];

  // Initialize 'snowflake' positions
  for(f=0; f< NUMFLAKES; f++) {
    icons[f][XPOS]   = random(1 - LOGO_WIDTH, display.width());
    icons[f][YPOS]   = -LOGO_HEIGHT;
    icons[f][DELTAY] = random(1, 6);
    Serial.print(F("x: "));
    Serial.print(icons[f][XPOS], DEC);
    Serial.print(F(" y: "));
    Serial.print(icons[f][YPOS], DEC);
    Serial.print(F(" dy: "));
    Serial.println(icons[f][DELTAY], DEC);
  }

  for(;;) { // Loop forever...
    display.clearDisplay(); // Clear the display buffer

    // Draw each snowflake:
    for(f=0; f< NUMFLAKES; f++) {
      display.drawBitmap(icons[f][XPOS], icons[f][YPOS], bitmap, w, h, SSD1306_WHITE);
    }

    display.display(); // Show the display buffer on the screen
    delay(200);        // Pause for 1/10 second

    // Then update coordinates of each flake...
    for(f=0; f< NUMFLAKES; f++) {
      icons[f][YPOS] += icons[f][DELTAY];
      // If snowflake is off the bottom of the screen...
      if (icons[f][YPOS] >= display.height()) {
        // Reinitialize to a random position, just off the top
        icons[f][XPOS]   = random(1 - LOGO_WIDTH, display.width());
        icons[f][YPOS]   = -LOGO_HEIGHT;
        icons[f][DELTAY] = random(1, 6);
      }
    }
  }
}

I downloaded the optimized Adafruit GFX library from github and installed it as described. As board I use Arduino Nano RP2040 from Arduino Mbed OS in V3.4.1.
Now when I compile the code, I get the following error:
[...]Arduino\libraries\Adafruit_SSD1306\Adafruit_SSD1306.cpp:42:10: fatal error: pgmspace.h: No such file or directory
#include <pgmspace.h>
          ^~~~~~~~~~~~
compilation terminated.

exit status 1

Compilation error: exit status 1

Unfortunately, I have not found a solution on the net how to solve the problem, which is why I have now written this question. I tried the "normal" GFX library from the package manager instead of the optimized one, with the same result. I guess the error is in the Adafruit_SSD1306 library, so it doesn't make any difference anyway.

The first entry that came up in Google for me concerns the same issue with another library by the same developer. See https://github.com/Bodmer/TFT_eSPI/issues/1148. The workaround/solution here is apparently to comment out the line #include <pgmspace.h> in Adafruit_SSD1306.cpp.

in Adafruit_SSD1306.cpp try to remove || defined(ARDUINO_ARCH_RP2040) on line 41, which I guess was added for the 'pico core' which is preferred by Adafruit for their RP2040 boards

What is happening is, in the library you have included, another library is included. There are 2 solutions: delete the #include pgmspace.h within one of those libraries or just get pgmspace.h.
Hope this helps!


text:
How to find the correct navigation course by gps navigation with Arduino?
I have a problem for about days ago and here it is :
I have an RC plane and wanna make it autonomous via GPS navigation by Arduino
I have an Arduino Mage 2560 onboard connected to a GPS Ublox-Neo-M8N (GPS module) and there is the problem
I want my RC-Plane to read it's position and go to waypoints
The Coordinates of  two waypoints  are defined before on a matrix variable like this example :
a [1] [3] =
{
    {38.884675, -116.671035,
     245}
};

b [1] [3] =
{
    {38.725019, -116.580951,
     1180}
};

( 1st is Latitude, 2nd is Longitude and 3rd is height)

So i want my Arduino to read it's current position from gps module's data and calculate the correct Azimuth (correct horizontal angle) and the correct pitch angle (vertical angle) to navigate my plane to the waypoints
and remember, when it reaches to the waypoint "a" with a few error (miss distance = 4 meters), it should be able to ignore navigation to the waypoint of variable "a" and then, navigate to waypoint "b"
I WAND THE EXACT COMMAND FROM ANY LIBRARY TO CALCULATE THOSE TWO ANGLE FOR NAVIGATION (azimuth direction angle and pitch angle to navigate RC-Plane from everywhere o the waypoints

The track (course over ground) is typically calculated by the GPS receiver and included in the data it sends. So you do not need to calculate anything there.

The "navigation" part of your question is complex, though. Particularly since your plane does not have 6 degrees of freedom (like a drone) calculating a path to a waypoint includes a curve.

very good question, however it is about navigation, not about Arduino, so it is off topic here ... downvote

The computation is not difficult. Since your drone is unlikely to travel
for thousands of kilometers, you can assume the Earth is locally flat,
and the latitude and longitude are an orthogonal coordinate system.
First, compute the vector to the next waypoint in Cartesian coordinates
(dx, dy, dz):
// Defined at global scope.
const float radians_per_degree = M_PI / 180;
const float degrees_per_radians = 180 / M_PI;
const float meters_per_degree = 1e7 / 90;

// For every reading of the GPS:
float dx = (waypoint.longitude - current.longitude) * meters_per_degree
         * cos(current.latitude * radians_per_degree);
float dy = (waypoint.latitude - current.latitude) * meters_per_degree;
float dz = waypoint.height - current.height;

Then, from this vector you can get the required angles:
float azimuth = atan2(dx, dy) * degrees_per_radians;
float pitch_angle = atan(dz/sqrt(dx*dx + dy*dy)) * degrees_per_radians;

Note that the approximation breaks down if the drone has to travel for a
distance that is a significant fraction of the distance to the closest
pole. Note also that the approximation errors are inconsequential if you
periodically update your estimate of azimuth and pitch angle: the errors
will be corrected along the way as the drone gets closer and closer to
the waypoint.
Edit: timemage posted a very interesting comment, and I would want
to further expand on the precision issue. The AVR floating point support
is indeed limited to single precision. For latitudes and longitudes in
the range shown in the question, the numerical resolution (formally, the
unit in the last place) is (3.81×10−6)° for the latitude
and (7.63×10−6)° for the longitude. This translates to about
42 cm and 66 cm respectively on the surface of the Earth. It
may be just good enough to hit the waypoint to within 4 m.
You could increase the resolution by storing the latitude and longitude
in microdegrees, as 32-bit integers. This should be easy if the GPS
always gives 6 digits after the decimal point: just ignore that
decimal point. Then, once the quantities
waypoint.longitude - current.longitude
and waypoint.latitude - current.latitude are computed, you can safely
use floating point for the rest of the computations.

I was 80% of the way through writing something like this only with TinyGPSPlus when the phone rang, after which this was posted. So, I'll just mention here that if they're being literal about wanting a library, that one will do the course and distance part (which is probably haversine based). The pitch I'd synthesized in pretty much exact same way as this. The only other difference of note I had in mine is just that the user says they're using an Mega, so AVR, so only single precision float is available which is accurate to about 6 decimal places, so they should expect errors at close range.

@timemage: Thanks for this very relevant comment. I edited my answer to address the accuracy issue.

If I understand the OP correctly, he has a wing-type RC plane, not a drone. This can't just move in a specific direction.

@PMF, They asked how to calculate correct azimuth and pitch angle from one coordinate to another. It's true that they didn't use the word "drone." I'm just guessing it's used in the answer because ¨drone" can be taken to mean (semi-)autonomous (which makes sense given the question) vs say "multi-rotor" (implying ability change direction with ease). The OP didn't seem to put any real emphasize on it being a fixed wing craft and the need to plan motion in connection with it being a "RC plane." Maybe the way-points are far enough apart for this to be of real concern.

Thanks for the answer, the main question is : Is there any Arduino's Library (mention the library) which can calculate this ?

You mentioned in the answer that the accuracy is 44 cm and 66 cm. Can you describe it more? For example this accuracy is for each kilometer? If not how much is the accuracy for 5 kilometers?

@Hamid'Smith'Salehi: There may be a library that does this, but I am not aware of any. Also, I do not understand what you mean by “accuracy for each kilometer”. Did you read the Wikipedia article Unit in the last place?

I mean, using this calcution has some error because we assumed that earth is flat, so how much is error in every kilometer distance?

And what is M_PI ?

@Hamid'Smith'Salehi: The approximation error would be quite complex to compute, and depend on the exact start and end points of the path. Not anything as simple as an “error per kilometer”. If you get GPS updates periodically, the approximation error will only make the path slightly curved, instead of being a straight line (or rather, a great circle). The error created by wind is likely to be many orders of magnitude larger. M_PI is π (pi).

M_PI = π =3.14259....  You could divide the 44 and 66cm resolution of each endpoint by the number of kilometers of distance between the two points if you want.  The inaccuracy of using the flat-earth approximation versus calculating a great circle is that the great circle course doesn't have a constant azimuth that the flat-earth approximation would.  How far are your waypoints from each other?

Thanks for your response.Maximum distance is 5 kilometers

I tested it by an example : start point is 52.70594, 13.37933 altitude = 67 meters and the waypoint is : 52.71957, 1338046 altitude is 64 and the result was : azimuth = 87.124287071904 and the pitch angle = -0.113355534.....  . The pich angle seems to be true but i know that the waypoint is in the north of the start point so the azimuth must be something like 0 (less or more). What is the problem?

i replaced latitude with longitude and also longitude with latitude in the formula, and it seemed is working properly. Can you check it please?

@Hamid'Smith'Salehi: You are right. In order for the north to be at 0°, the azimuth must be computed as atan2(dx, dy). I edited the code in my answer.


text:
How to write arduino code in a c/c++ script
I'm pretty new to arduino. But I have some knowledge about programming in c/c++. I know that arduino is written in c. But it can't be used as normal c/c++ code.
for example ,
instead of including some libraries and write the code like this..
#include "arduino.h"

int main(){

    pinMode(13, OUTPUT);

    while(1){
    digitalWrite(13, HIGH);
    .....
    }
}

We have to write it using functions defined in arduino.
void setup(){
    pinMode(13, OUTPUT);
}

void loop(){
    digitalWrite(13, HIGH);
    .....
}

But I have some other libraries and programmes and stuff written in c and c++ and I need to use some arduino code in it and compile. So my question is, is there a way to write arduino in pure c/c++ as in first code snippet.
*I may not need arduino for this. My main target is to use servos, sensors in programms written in c/c++. But I would like to know what is the best way.

It is unclear to me, what exactly your problem is. Arduino code is C++ code. The only difference is what the IDE does before compiling (automatically including arduino.h and writing function prototypes for your defined functions, so that they can be placed whereever you want). The "Arduino functions" are defined in the header files, which are included via arduino.h. Are you trying to program an Arduino without the Arduino framework? Or do you just want to know how to avoid pinMode() and digitalWrite()?

Note: Your first code is just invalid C/C++, because you execute code outside of any function (the pinMode() function in this case)

Thanks I didn't noticed it. What I need to do is combine arduino code to my other c++ programs which uses servos and some sensors in some instances. When I use the ide I have to use setup() and loop() functions. What I need to know is can I write the code as in the first snippet and upload it into the board. If possible, how? Because arduino ide only support .ino files. not .cpp . What I meant by "best way" is that, should I use arduino for controlling servos and sensors or find some other way to connect them to my programmes.

So your question is more about the general project layout? What other C++ programs do you have, that need to be integrated with Arduino? When having programs on a PC and needing to interface peripherals like sensors and servos it is common to use an Arduino (or any other microcontroller), write a program for it to use the sensors  and servos and communicate with the PC over Serial/USB. Is that what you want?

Yes, that's exactly what I want. Should I need to upload the code to the board in order to use the sensors. It's certainly not possible. I'm building a device for reading and copying books. I have few c++ libraries written with opencv for image proccessing part and calculations. I planned to use arduino for the book handling device. I'm not sure is that possible as described in the question.

You won't run OpenCV code on the Arduino: it's not powerful enough for that. You will most likely have to write multiple programs that communicate and work together: one running on the Arduino for handling the books, an another one running on your computer for doing the image processing stuff.

Arduino IDE uses C++ not C.
You don't have to use setup and loop. This is a valid Arduino sketch:
#include <Arduino.h>

int main ()
  {
  init ();  // initialize timers
  Serial.begin (115200);
  Serial.println ("Hello, world");
  Serial.flush (); // let serial printing finish
  }  // end of main

But I would like to know what is the best way.

The way that works best for you. The IDE gives you some convenience functions. You don't have to use them. You can look at the datasheet and directly address the hardware registers.
See here for a few more details.

But how do I upload this to the board. If not possible how to connect the board to my c++ programs. ide is only compettible with .ino files.

@Alien5516788: you can easily convert a C++ program into a .ino program: just change the file extension to .ino.

You use the IDE to upload what I posted to the board. That was an Arduino "sketch". Plus, you can put C++ files into the same folder as the .INO files.

Did you read the link I mentioned in my answer? That shows using C++ files.

@Alien5516788, To be clear, only .ino/.pde files are subject to the kind of preprocessing that makes the Arduino "language" different from ordinary C++. The core, core libraries, and system libraries are all written in a mixture of .c/.cpp/.h files (broadly non-INO files) as is the majority (if not entirety) of most non-core libraries. The bulk code going into any typical Arduino project is in fact written in ordinary C++ (or C) code, whether the end user understands this or not. You are likewise not required to write much of any of your own code within .ino files.

Thanks, I read your article. I was trying to upload .cpp files to arduino board. Now it's all clear. Also I need to know how .ino files work. As described in the article, Arduino.h is included in .cpp file and .ino file is empty. How is that gonna work.

The IDE compiles all the .cpp files and links them together. So an empty .ino file isn't a big deal. The #include directives in the .ino file tell the IDE which libraries to include (link).

@Nick Gammon: The solution you gave here http://www.gammon.com.au/forum/bbshowpost.php?id=12625 is good but the justification less so since all 3 of your examples of bad prototype generation have, at least with IDE 1.8.19 and probably earlier, been fixed. If you still need to illustrate this with an example which currently fails, here is one: https://github.com/arduino/arduino-builder/issues/362

@6v6gt Ah, that was written 8 years ago. Like many things in the computer industry, old code does not necessarily travel well.

Indeed. The one positive thing about the Arduino automatic prototype generation feature is that there are simple work-arounds to avoid unwittingly using it. I'm sure that if we could go back in time, with our present knowledge, that feature would not have emerged in its current form.


text:
Balancing pendulum using PID

Dear all, referring to the video at here on how to make a PID balancing pendulum as shown in the picture and the author also provided the arduino code in the video description. May I ask whether this arduino code can be used on my MPU6050 gyroscope without any modifications because the author in the video does not provide the model of the gyroscope used. I have also searched countless of arduino code on web on balancing pendulum using propeller PID with a DC brushless motor (not 3 phase) and MPU6050 gyrocope, but couldn't find any and I hope someone could show me some examples code.
Thank you and have a nice day!!
// Chuong trinh dieu khien cân bang thanh ngang Nguyen Duc Sang 24/05/2018
//---------------------------------------------------------------

//875=0
//530=90 do
#define SENSOR A1
#define CONTROL 6
#define dongco 7

   void setup() {
       Serial.begin(9600);
       pinMode(SENSOR,INPUT);
       pinMode(CONTROL,OUTPUT);
       pinMode(dongco,OUTPUT);
   }
   double error = 0;
   double realAngle;
   double lastrealAngle;
   double
     kP = 1,
     kI = 0.005,
     kD = 0;
   double
     P = 0,
     I = 0,
     D = 0;
   double PID;
   double setPoint = 90;
   int controlPwm = 85;
   long lastProcess = 0;
  void loop(){
     realAngle = map(analogRead(SENSOR), 1023, 0, -39.73, 229.47);
     //Serial.println(analogRead(SENSOR));
     //Serial.println('gia tri goc realAngle la');
     Serial.println(realAngle);
     Serial.println(setPoint);
    //PID
    error = setPoint - realAngle;
    //thoi gian lay mau
    float deltaTime = (millis() - lastProcess)/100.0;
    lastProcess = millis();
    // P
    P = error * kP;
    // I
    I += (error * kI) * deltaTime;
    // D
    D = (lastrealAngle-realAngle) * kD * deltaTime;
    lastrealAngle = realAngle;
   // Sub pid
  PID = P + I + D;
  if (PID>255){
   PID=255;}

  controlPwm = (PID + 80);

    analogWrite(CONTROL,controlPwm );

  }

Is that all your code?

This cannot be all of your code. Nearly everything important is missing. I guess you had a copy and paste error. But I guess the answer is no. It seems the code is using an analog sensor. From the video I would guess it has a potentiometer at the axle of the arm. So it doesn't use a gyroscope. For the MPU6050 you would see either a corresponding library being imported or the Wire or SPI library being used (since the MPU communicates through I2C or SPI). I can write an answer once you have included the complete code in your question

@chrisl, hi sir, these codes are from the video dessciption. May I ask if there are any code that do balancing pendulum using propeller PID with a DC brushless motor (not 3 phase) and MPU6050 gyrocope ? Have a nice day :)

Either way you have to include the full code in the question, because questions on this site should be self contained. So please copy the full code into the question

@chrisl, done :),  May I ask if there are any code that do balancing pendulum using propeller PID with a DC brushless motor (not 3 phase) and MPU6050 gyrocope ?

The shown code does not use the MPU6050. Instead it uses a sensor with an analog output signal. From the image and the video I suspect, that this sensor is a potentiometer attached to the axle of the arm. So the analog value basically gives you a measure of the angle.

have also searched countless of arduino code on web on balancing pendulum using propeller PID with a DC brushless motor (not 3 phase) and MPU6050 gyrocope, but couldn't find any

That's not really surprising to me, since that is a very specific search request. That assumes that someone did exactly what you want to do and also described it with the same words. Finding a ready-to-use code that way is highly unlikely and I don't have such a code either.
What to do now? You will have to develop the code yourself. First you should divide up your project in individual parts, like: Getting readings from the MPU6050, calculating a stable angle value from the readings (by combining gyro and accelerometer values), driving the DC brushless motor and controlling its speed, implementing a PID feedback loop.
When you are able to implement each individual part by itself you can put them all together to make your project. Each individual part can be researched way easier, because there are many people, who have done these things in their own projects. Also try searching for Arduino libraries for these parts. For example: There are libraries for using the MPU6050, which will handle all the communication to the sensor for you. A good way to find libraries is search for "Arduino library MPU6050" (replace "MPU6050" by whatever single thing you wanna implement, like PID or similar). And such libraries are often hosted at Github, so it is often also good to search for something like "github arduino MPU6050". Try keeping your search request short. Look at the results and assess, if the found libraries are fitting for your situation.
And as help and inspiration you can search for similar projects. A quick search for "Arduino mpu6050 balancing robot" did show promising results and a balancing robot is very similar to your project.


text:
Arduino Uno Stuck at uploading
I wrote a basic blink code and tried to run it on the auduino IDE. Compilation was sucessfull but the code stucks at uploaing. I turned on the verbose output while uploading and this is what I have found..
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is
"/Users/_stelk/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf"
         User configuration file is "/Users/_stelk/.avrduderc"
         User configuration file does not exist or is not a regular file,
skipping

         Using Port                    : /dev/cu.usbmodem101
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200

I don't exactly understand what to do. Can somebody please help. Board is Arduino Uno but I don't think there is any problem with the hardware. Even when I disconnect the board..the same think happens without giving me an error. Everything was fine last night. When I launch the IDE now, it automatically selects the Uno board and when I hit upload, it compiles sucessfully and stucks at uploading. Should it not give an error like "No board found"? This same behaviour happens even when I connect the board and upload again.

try to remove "/Users/_stelk/.avrduderc"

Are you on a Mac? Which version of Arduino IDE? That may be relevant to answer this question. Also, the output you posted is just the output of avrdude before trying to open the usb-serial device for programming. Is there really no other option in the preferences that turns on verbose error logging?

Found this here: "Occasionally, the [Arduino IDE] 2.0 will upload. This typically happens after closing and reopening the app and using the tools menu to select the port and board instead of the automatic drop down menu. Currently, the port options list old ports that are now not connected. Plugging in to a new port does not updated the port list.", also "make sure the Serial Monitor is closed" -- Looks like there are still a lot of bugs in Arduino IDE 2.0. Which IDE version do you use?

By "UNO" you refer to an ATMega328P based UNO and not to an UNO WiFi or any other board with "UNO" in the name, right?

Are you using the correct COM port?  On a PC the COM port number can sometimes change when the PC starts or wakes up.  Also do you mean you wrote the blink program by hand or you used the blink program from the examples?  (Is it possible there is a mistake in your code)


text:
Blank Preferences on Arduino IDE 2.0.1
I just install this new IDE on my pc.
Yesterday, I changed my sketch folder location on preferences.
And when i need to change it again, the preferences shown nothing. Ive restart my pc and its not working.
How to solve this? Should I reinstall this app?

I just reinstall the app. But the preferences still blank.

Run the IDE from a command-line.  If any relevant error or warning messages show up, edit them into the question.

I checked the Arduino IDE issue list and did not find anything about a blank preferences dialog. Seems like the best way forward would be to open an issue there. Until then, it may be that deleting the arduino preferences folders/files somewhere in your user home suffices (probably C:\Users\Meiko.arduino or some subfolder in C:\Users\Meiko\AppData in your case, I'm not on windows). -- Actually, don't delete, move it away so you can include it in a bug report later.

try to provide more info into this thread on arduino forum. it is a discussion with a member of Arduino Team. https://forum.arduino.cc/t/blank-file-settings-menu-in-arduino-ide-2-0-1/1048087


text:
How can I send Arduino sensors data to java application?
my final year project is to do an Arduino watch that has heart rate and body temperature sensors and also a location tracking module. I need to send all the watch data to my java app but I don't how do I need to send it to a database first and then use it? and how can i do that.
I'm using arduino uno and i want to send the data to a database on a server.
I'm using android studio and coding with java
please help :(

To what database do you want to send the data? Where does the database run? How is the Arduino Uno connected to the system running the database?

I asked my teacher and she told me I have to read the data and send it to the server and the server will store it in a database and then display it in the application

i don't know how to work with Arduino it is my first time and i just want to know how i will receive the data to display it in the app

Then you first need to think about how to contact your server, so you need a network connection. Do you need to use an Arduino Uno? Do you have a wifi network available? Or do you need a mobile data connection over LTE? Have you done research about these things?

To send the data from the Arduino, you just need to do this:
Serial.println(the_data);

But then you have to manage some communication link between the Arduino
and whatever is going to collect the data. Typical choices are the USB
link or a Bluetooth module. Then, whatever you do with this data (send
to an Android phone, a Java app, a server, a database, whatever...) is
up to you, and is not an Arduino question.


text:
How to read and parse UART data from human presence radar sensor
I'm working on a project, and I purchased a 24 GHz "Human existence/presence" mm Wave sensor from micradar, the R24DVD1. The output of the module is serial data which varies in length and is of the structure shown below;

The Data element of the stream could get as large as 5bytes and as show each package ends with a 0x54 0x43.
My intention is to have my Arduino Uno read the data for further processing. Since I use the Arduino Uno which has only one physical serial port, I felt using it to read the sensor data could prove problematic since the pc is equally connected to that serial line via USB. So I decided to use the SoftwareSerial to read the data from the senor then forward it to the pc and I wrote the following code for that;
#include <SoftwareSerial.h>

const int txpin = 3;
int const rxpin = 2;
SoftwareSerial mySerial(rxpin,txpin);

const unsigned int PACK_SIZE = 14;
int inByte1;
int inByte2;
unsigned int recvdByte = 0;

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

void loop() {
// put your main code here, to run repeatedly:
if (mySerial.available() > 0){
int pack[PACK_SIZE];

inByte1 = mySerial.read();
inByte2 = mySerial.read();

if(inByte1 != 84 && inByte2 != 67){
  pack[recvdByte] = inByte1;
  pack[recvdByte+1] = inByte2;
  recvdByte += 2;
 }
else{
  pack[recvdByte] = inByte1;
  pack[recvdByte+1] = inByte2;
  recvdByte = 0;
 }
for(int i = 0; i < PACK_SIZE; i++)
{
  Serial.print(pack[i],HEX);
}
Serial.println();

 }
}

I would like to know if my thought process in reading and parsing the data is correct because the output is quite inconsistent to what I expect

you read two bytes if maybe only one is available

My thought process was to read two bytes so I can compare if two consecutive bytes are 0x54 and 0x43 then I know it's the end of a frame of data. Any suggestion on how to go about it?@Juraj

First of all, I would advise you against using SoftwareSerial,
especially at this high baud rates: it is a recipe for problems. Since
you seem to be using the link to the computer only for writing, and the
link to the sensor only for reading, you can use the hardware serial
port for both. Connect the sensor's TX to the Arduino RX, and you will
be able to read the sensor data with Serial.read(). Do not connect
the sensor's RX, and you will be able to Serial.print() to the serial
monitor without disturbing the sensor.
Next, you must be aware that serial data is received one byte at a time.
If you waited until you had a full packet in the serial buffer, then
you could read and process the whole packet at once. This is, however,
difficult, because you cannot know the length of the packet before
starting to read it.
I would recommend that instead you process one incoming byte at a time,
and you do the necessary sanity checks in the process. Here is how I
would do it (warning: untested code):
const unsigned int MAX_PACKET_SIZE = 14;
const unsigned char char start_signature[] = {0x53, 0x59};
const unsigned char char end_signature[] = {0x54, 0x43};

unsigned char packet[MAX_PACKET_SIZE];
int recvdByte = 0;  // number of bytes received and buffered so far
int dataLength = 0;  // length of the data field

void processPacket();  // defined elsewhere

// Handle a single input byte.
void processInputByte(unsigned char inByte) {
    if (recvdByte < 2) {  // check the start signature
        if (inByte != start_signature[recvdByte]) {  // wrong signature?
            recvdByte = 0;  // discard the packet
            return;
        }
    } else if (recvdByte == 4) {  // grab the data length
        dataLength = inByte;
        if (dataLength > MAX_PACKET_SIZE - 9) {  // overlong packet?
            recvdByte = 0;  // discard the packet
            dataLength = 0;
            return;
        }
    } else if (recvdByte == 5) {  // check the second data length
        if (dataLength != inByte) {  // doesn't match?
            recvdByte = 0;  // discard the packet
            dataLength = 0;
            return;
        }
    } else if (recvdByte == 6 + dataLength) {  // check sum
        // TODO: Look at the datasheet to see how to control that
        // the checksum is correct. Discard the packet if it is not.
    } else if (recvdByte >= 7 + dataLength) {  // check end signature
        if (inByte != end_signature[recvdByte - (7 + dataLength)]) {
            recvdByte = 0;  // discard the packet
            dataLength = 0;
            return;
        }
    }

    // All correct so far, we can buffer the incoming byte.
    packet[recvdByte++] = inByte;

    // If we have a complete packet now, handle it.
    if (recvdByte == 9 + dataLength) {
        processPacket();
        recvdByte = 0;  // reset for the next packet
        dataLength = 0;
    }
}

You may want to sprinkle a few Serial.println() here and there for
testing and debugging. These could be removed once everything works as
expected.
Then, in the main loop, you just have to:
void loop() {
    if (Serial.available() > 0) {
        processInputByte(Serial.read());
    }
}

Thanks a million Edgar. This with a little modification does the trick most of the time. I will keep working on it to see if I can get it working better


text:
How to work with a pulled high input pin where it needs to read a value from an analog sensor?
I have a small ESP32 module, that has some in-built features, like a TFT, and has few available pins for general use.
It has some input only pins (GPIO36 to 39) that are used by buttons soldered in the pcb, and they are all pulled high by 4.7k resistors, in the schematics below:

I won't use these pins as buttons (and I won't press them), and I need to connect the analog output (0-3.3V) of one sensor in one of these inputs and use analogRead() to get the results.
Is is possible to use a pulled high pin to read an analog voltage from a sensor? It just inverts the readings of the output voltages? When the sensor outputs 3.3V the pin will read 0V and when the sensor outputs 0V the pin will read 3.3V?
It's just a matter of inverting the values read in the code? Or anything else?
Thanks!

Do these pins have external pullups on the PCB or are the builtin ESP32 pullups used (which can be activated and deactivated via software)?

There will be no inversion because of the on board button's external pullup resistor.
The impedance of an analog pin is extremely high (say 10Mohms) so a 4.7k series resistor in series will make little difference.
Any required inversion of the analog result can be done in software.
Don't press the connected button though if a sensor is applying a voltage.

@chrisl these pull-ups are wired in the pcb, not inside the chip. I'll update the question

@6v6gt, so nothing happens? It acts as a normal analog input?

@Rodrigo Can you add how you would be connecting the sensor to the drawing?

You need to remove the pull-up resistor if you want to use it as analog ADC pin.

@Rodrigo My previous comment may not be correct under all circumstances. If your sensor is say a light dependent resistor, then you need a pullup to form part of a potential divider. If the sensor, however, delivers a voltage (say some types of  microphone), then you need to remove the pullup resistor (or cut a track)  as already mentioned by hcheun . It depends on the sensor. What sensor are you using ?


text:
Problem to store values from Arduino MKR 1010 to mysql?
I have problem to store values to MySQL table from Arduino MKR 1010 Wifi.
I get the following message.
trying
got: 0 retrying
trying
got: 0 retrying
ERROR!

I have also tried to turn off firewall without success.
Is my code wrong? Can someone help me with this issue?
#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include <MySQL_Encrypt_Sha1.h>
#include <MySQL_Packet.h>
#include <DHT.h>
#include <DHT_U.h>
#include <dht.h>
#include <WiFiNINA.h>
#include <wifiinfo.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

#define DHT22_PIN 7
#define DHTTYPE 22
DHT deviceMonitor(DHT22_PIN,DHTTYPE) ;

IPAddress server_addr(192,168,86,39);  // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password2[] = "test1234";        // MySQL user login password

char ssid[] = SECRET_SSID;        // your network SSID (name)
char password[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the Wifi radio's status

float hum;
float temp;
float humError;
float tempError;
int checkTemp;

char INSERT_DATA[] = "INSERT INTO weather (temp, hum) VALUES ('%s','%d')";
char query[128];
char temperature[10];

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to network: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, password);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.println("You're connected to the network");

  Serial.println("----------------------------------------");
  printData();
  Serial.println("----------------------------------------");

  if (conn.connect(server_addr, 3306, user, password))
  {
    delay(1000);
  }
  else
  {
     Serial.println("Mysql connection failed.");
  }
    }

void loop()
{
  delay(5000);
  if (conn.connect(server_addr, 3306, user, password2)) {

    MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
    checkTemp = deviceMonitor.read(DHT22_PIN);
    hum = deviceMonitor.readHumidity();
    temp = deviceMonitor.readTemperature();
    Serial.println((String)"Temperature: " + temp + " Celsius");
    Serial.println((String)"Humidity: " + hum +"%");
    Serial.println();
    sprintf(query, INSERT_DATA, temp, hum);
    cur_mem->execute(query);
    delete cur_mem;
    Serial.println("Data recorded.");
    delay(10000);
 }
 else
 {
   Serial.println("ERROR!");
 }
}

void printData()
{
  Serial.println("Board Information:");
  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  Serial.println();
  Serial.println("Network Information:");
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.println(rssi);

  byte encryption = WiFi.encryptionType();
  Serial.print("Encryption Type:");
  Serial.println(encryption, HEX);
  Serial.println();
}

Your output listing seems to have nothing to do with the the code you're apparently trying to run.

I granted full right to user root in MySQL and now got this error instead.
ERROR: Timeout waiting for client.
Error: -1 = Mysql connection failed.

Can someone help me with this problem?

Not an answer..


text:
Confusion about Oscope reading of Arduino Software Serial
I am trying to troubleshoot a Software Uart Connection from my Arduino Nano, and I do not understand this output. The setup is simple, I have a Software Serial connection on pins 2 and 3. I send 170, which I expect to be 10101010 of course with a low start bit and high stop bit.
I hook up to the TX line with my Oscope and check the waveform, but its not as I expect.... I only see 101010
#include <Arduino.h>
#include <SoftwareSerial.h>

#define SW_RX 2
#define SW_TX 3
#define SW_BAUD 9600

SoftwareSerial Serial2(SW_RX,SW_TX);

void setup(){
  Serial2.begin(SW_BAUD);
  delay(1000);
}

void loop(){
  Serial2.write(170);
  delay(100);
}

Can someone help me to understand this output?

it is helpful if you start thinking in hex because the conversion to binary is direct, without any math ... you sent 0xAA ... try 0x55 ... 0x40 ... 0x02 ... what do these values reveal about the problem you are trying to solve?

It is working exactly as expected. The scope trace shows 10010101011:

1: idle state of the serial port
0: start bit
0: first data bit
1010101: other data bits
1: stop bit.

Keep in mind that the data bits are sent least-significant first.

thank you so much that makes sense


text:
The code to turn off the RGB LED by pressing the 4,5,6 switches in sequence doesn't work
I'm making photoresister alarm. When distance under 5cm over notes[] 5 times, piezo speaker off. And I want to turn off the led rgb by pressing the 4, 5, 6 switches in sequence. The code to turn off the led rgb by pressing the 4, 5, 6 switches in sequence does not work. What's wrong? Here is a code below.
int pins[]={4,5,6};
int melody[]={262,294,330};
int notes[]={392,392,440,440,392,392,330};
int b=0,r=0,g=0;

void setup() {
  // put your setup code here, to run once:
 randomSeed(analogRead(A0));
 for(int i=0;i<3;i++){
   pinMode(pins[i],INPUT);
 }
}
int c=0;
int value1=digitalRead(4);
int value2=digitalRead(5);
int value3=digitalRead(6);

void loop() {
  // put your main code here, to run repeatedly:
  int vin=analogRead(A0);
  if (c>5){
    //  b=0,r=0,g=0;
    noTone(8);
    //analogWrite(11,b);
    //analogWrite(10,r);
    //analogWrite(9,g);
   // return;
  }
  if(digitalRead(0)==HIGH){
    if(digitalRead(1)==HIGH){
      if(digitalRead(2)==HIGH){
       b=0,r=0,g=0;
       noTone(8);
       analogWrite(11,b);
       analogWrite(10,r);
       analogWrite(9,g);
       return;
      }
    }
  }
  if(vin>800){
    for(int i=0; i<7 ;i++){
      tone(8,notes[i],100);
      delay(200);
      noTone(8);
      analogWrite(11,random(256));
      analogWrite(10,random(256));
      analogWrite(9,random(256));
      delay(200);
    }
  }
  long duration = pulseIn(3,HIGH);
  long distance=duration/58.2;
  if(duration == 0){
    return;
  }
  if (distance<5){
    c++;
  }

}

The code to turn off the RGB LED by pressing the 4, 5, 6 switches in sequence, RGB LED is off. And when distance under 5cm over notes[] 5 times, piezo speaker off.

How are the switches connected? Have you tested with a single switch to see what effect it has? There are presently a number of odd things in your code. At the moment it looks like you need to press switches connected to port 0, 1 and 2 (shouldn't that be 4, 5 and 6?) simultaneously to turn off the LED. You need a simple state machine to allow your code to detect them in sequence. You're declaring value1, value2 and value3 but never use them. You're initializing the pins[] array with the values 4, 5 and 6 but never use it except in the initialization code.

thank you for your advice. I goin' to check my code.

What's wrong? ... your program is unfinished

Umm... I'm goin' to check the code.

This might not be correct because I'm new in arduino projects but i think the problem comes from here
On your setup
for (int i=0;i<3;i++)
pinMode(i,OUTPUT);

SHOULD BE
for (int i=4;i<=6;i++)
pinMode(i,OUTPUT);

on your loop
if(digitalRead(0)==HIGH){
    if(digitalRead(1)==HIGH){
      if(digitalRead(2)==HIGH){
       b=0,r=0,g=0;
       noTone(8);
       analogWrite(11,b);
       analogWrite(10,r);
       analogWrite(9,g);
       return;
      }

I think you need to change the pin to
if digitalRead(4).....
if digitalRead(5)......
if digitalRead(6)....

Just change it that way maybe it may work.
Remember to remove the // on the b=0,r=0,g=0
And also remove the double slash // from the analogWrite
And I see you declaring value 1,2,3 and not using them.
hint...
int value1;
int value2;
int value3;
int delaytime=500; //half a second

value1=digitalRead(4); /* you are supposed to press the button on pin 4 by now */
if (value1==HIGH) {
  delay(delaytime);
  value2=digitalRead(5); /* you are supposed to press the button on pin 5 by now */

  if (value2==HIGH) {
    delay(delaytime);
    value3=digitalRead(6); /* button on pin 6 is supposed to be pressed by now */
    if (digitalRead(6)==HIGH) {
       b=0,r=0,g=0;
       noTone(8);
       analogWrite(11,b);
       analogWrite(10,r);
       analogWrite(9,g);
       return;
      }
  }
}

I added the delay because that might be the greatest problem you have. Arduino is fast at processing, so in order for it to work when you press the three button you will need to press the three all at once before it can give you the output. But if you want to press them one by one, you need to add the delay and make sure you press the three button before the delay time elapse.

I Appreciate to your advice.


text:
Continous Rotation Servo not changing directions
I have coded a robot to be controlled by a ps3 Controller. I am using continous rotation servos but unfortunately I can not figure out how to get them to change direction. My input for my if statements is correct, but for some reason even if the input from the PS3 controller shows to do the reverse direction, the continuous rotation servo still rotates forward.
Here is my Code:
  #include <PS3BT.h>
  #include <usbhub.h>

  // Satisfy the IDE, which needs to see the include statment in the ino too.
  #ifdef dobogusinclude
  #include <spi4teensy3.h>
  #endif
  #include <SPI.h>

  #include <Servo.h>

  USB Usb;
  //USBHub Hub1(&Usb); // Some dongles have a hub inside

  BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
  /* You can create the instance of the class in two ways */
  PS3BT PS3(&Btd); // This will just create the instance
  //PS3BT PS3(&Btd, 0x00, 0x15, 0x83, 0x3D, 0x0A, 0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch

  bool printTemperature, printAngle;

  // identifying servos
  Servo LeftServo;
  Servo RightServo;

  void setup() {
    Serial.begin(115200);
    #if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
  #endif
    if (Usb.Init() == -1) {
      Serial.print(F("\r\nOSC did not start"));
      while (1); //halt
     }
    Serial.print(F("\r\nPS3 Bluetooth Library Started"));

  // Attaching Pins to Servos
    LeftServo.attach(2);
    RightServo.attach(3);

  }
  void loop() {
    Usb.Task();

    if (PS3.PS3Connected || PS3.PS3NavigationConnected) {
    if (PS3.getAnalogHat(LeftHatY) < 117){
Serial.print(F("\tLeftHatY: "));
Serial.print(PS3.getAnalogHat(LeftHatY));
  LeftServo.attach(2);
LeftServo.write(180);

}
else if (PS3.getAnalogHat(LeftHatY) > 140) {
     Serial.print(F("\tLeftHatY: "));
Serial.print(PS3.getAnalogHat(LeftHatY));
    LeftServo.attach(2);
  LeftServo.write(0);
  }
else {
LeftServo.detach();
   }
   }
    }

I added the rest of my code, I thought to only post the relevant section but this has changed.

forget about your code for now ... write a simple program that runs the motor in one direction for two seconds, stops the motor,  then runs the motor in the opposite direction

please, format your code properly ... it is a mess that is difficult to read

What are the specific servos that you’re using?

Are you able to add a schematic showing how you’re connecting and powering the servos?

Is this related to your other question yesterday? https://arduino.stackexchange.com/questions/91238/different-code-needed-for-continuous-rotation-servo

im new in Arduino projects but i think this might work, try changing some things in your else sttement, you should try and change this
LeftServo.attach(2);
  LeftServo.write(0);

Try changing it to this
LeftServo.attach(2);
  LeftServo.write(180*(-1));
// or, LeftServo.write(-180);
/* if you use (180*(-1), the servo might go the opposite direction continuously until
(PS3.getAnalogHat(LeftHatY) is less than 117 */


text:
How to unload a sketch
I've loaded a sketch onto Arduino using the Ardunio IDE and it works but when I press the reset button I realize it doesn't remove the program. Is there a way to unload the program? Why? Because when I take it apart to put it away I don't know if having that program turning pins on or off and having nothing connected to it would break anything.

how can a device turn pins on and off when there is no power to run the device?

@jsotola right correct. i'm looking at it as if i'm going through examples for training purposes. for the case where, if i disconnect everything and put it away (but the program is not removed) then later i plug it back in where i don't have anything else connected to it then i was concerned what would have happened

Frist: The Arduino cannot break when nothing is connected to it, doesn't matter what the code does.
If you want to remove the current code from the Arduino, you have to overwrite it with an empty sketch (one with only setup() and loop(), both empty). So upload an empty sketch.
The reset button is not meant for erasing the code. It is meant to return the Arduino in a definited starting state (not erasing program space or EEPROM) and executing the program on the Arduino (including the bootloader) from its start.

OK Thank you. So pressing reset cuts the power, clears the memory and runs the setup and then loop function again.

It doesn't cut the power. The reset is a hardware function of the microcontroller on the Arduino. The controller will then start program executing from programm address zero. So first the bootloader gets executed (which enables to you program via USB/Serial), then your program starts, which also includes building the stack in memory for your variables. The memory is not actually erased (as in overwritten with zeros or ones), but your program implicitly will initialize the used memory with the defined values (the compiler creates such machine code from your C++ code). Then setup and co runs

You can't remove a program by resetting the Arduino. If you want to be sure that it can't activate any pins in your next experiment, then just before you finish with it, upload a new program that does nothing, such as the Basics | Bare Minimum example program. It will effectively replace the previous program.
At power-up, all of your pins[*] get configured as inputs during power-up. With the Bare Minimum program, nothing will change those pins, until you start writing & uploading new code that modifies them.
[*] Note that the bootloader will re-configure pin-1, the serial transmitter pin, as an output.


text:
Library not found when using the arduino-cli command (although working with the Arduino IDE)
I have a sketch which I can upload without problem with the Arduino IDE. I installed the arduino-cli  Version: 0.28.0 Commit: 06fb1909 Date: 2022-10-18T15:53:04Z. I want to compile and upload a code on an arduino uno and use the command line
arduino-cli compile --fqbn arduino:avr:uno mysketch.ino

but get the following error:
/path/to/mysketch.ino:44:10: fatal error: LiquidCrystal.h: No such file or directory
 #include <LiquidCrystal.h>
          ^~~~~~~~~~~~~~~~~
compilation terminated.

Used platform Version Path
arduino:avr   1.8.5   /Users/user/Library/Arduino15/packages/arduino/hardware/avr/1.8.5

Error during build: exit status 1

how could I proceed to debug?

/path/to/mysketch.ino looks like an invalid path

@jsotola. Thank you for your comment. It is indeed not the real path. I edited it for the question. But it is the path where the .ino file is

how to debug? ... if your OS is Windows ... download process monitor from Microsoft ... use it to figure out where the program is looking for the file ... https://learn.microsoft.com/en-us/sysinternals/downloads/procmon

The LiquidCrystal library is bundles with Arduino IDE 1 so it is not installed in your sketchbook folder's libraries folder so CLI can't find it.
Install the library with Arduino CLI or simply copy it from Arduino IDE 1 installation folder into libraries folder of your sketchbook.

many thanks for your answer @Juraj. what would be the command to install it with the Arduino CLI?

@ecjb you work with CLI and you don't know the commands? https://arduino.github.io/arduino-cli/latest/commands/arduino-cli_lib_install/

The command is: arduino-cli lib install LiquidCrystal for future visitors' convenience.