body:
we want to have a LED turn on with the press of a button, and become brigther and brighter as times go by (whithin  a defined time frame), and when it reaches maximum brightness to turn off for a couple of seconds and then start again. in addition to that, we are trying to add a motor that will start spinning 720 degrees when the button has been pressed.
Our main problem is the fact that when we let go of the button the led turns off. How do we set the button so that when it is pressed once it turns everything on, and the led runs in a loop, but the motor doesn't; and when we press it again the whole led turns off completely and the motor runs 720 degrees in the opposite spinning direction than the previous.

Here is what we have managed so far (we didn't get to introduce the motor yet as we got stuck along the way):

    const int switchPin = 11;
    const int motorPin = 6;
    int led = 9;
    int switchState = LOW;
    int previous = LOW;
    int i = 0;
    int fadeAmount = 5;

    void setup()
    {
      pinMode(led, OUTPUT);
      pinMode(motorPin, OUTPUT);
      pinMode(switchPin, INPUT);
    }

    void loop()
    {
      int switchState = digitalRead(switchPin);

      for (int i = 0; i <= 255; i++)
      {
        analogWrite(led, i);
      }

      if (switchState == HIGH && previous == LOW)
      {
        if (i == 0)
        {
          digitalWrite (led, HIGH);
          i = i + fadeAmount;
          delay(1000);
        }

        analogWrite(led, i);

        for (int i = 255; i <= 255; i--)
        {
          digitalWrite (led, LOW);
          i = 0;
        }
      }
      else
      {
        //toggle off
        digitalWrite(led, LOW);
        i = 0;
      }
    }

PS. WE are beginers. Thanks for the help and understanding!

title: How to toggle LED and motor on button press?

Answers: 2

body:
Here is a program that should fade the LED as you specified. Initially the LED is off. If you press the button the LED starts fading within the time frame to its maximum. Then it switches to zero waits a couple of seconds and starts fading from new. If you press the button a second time the LED stops fading and is set to darkness. ;-) This happens emediately, but of cause, you can only see it if the LED is in the fading phase.

I used interrupts in order to have a well defined state transition I can work with.

Aquiring the button pin in the loop, would be more complex to handle. That would require a state variable and some state transition rules. And I was too lazy to work that out. If interupts can't be used for any reason, I would change the answer. (No Mum I don't want to ...)

I removed the motor pin as it makes no sense for the answer. I also think that one pin would not be enough if your motor (stepper, dc with feedback or a servo) should spin a certain amount of degrees.

I tested the program on a Arduino UNO. The button I used is of low quality so I had to debounce it.

If there is something not clear to you, please ask within a comment.

    // Attache the LED to a PWM pin UNO -> 3,5,6,9,10,11
    const byte ledPin       = 9;

    // UNO -> only pin 2 or pin 3 are interrupt pins
    // as we use pullups the button should be connected to GND
    const byte interruptPin = 2;

    // in milli seconds - The time the LED needs to fully light up
    const int timeFrame  = 5000;

    // in milli seconds
    const int aCoupleOfSeconds = 2000;

    const int fadeAmount =    5;

    volatile boolean fadeOn = false;
    volatile long debounceTime = 800;
    volatile long actTime = 0;

    int brightness =   0;

    int stepCount = 256       / fadeAmount;
    int stepDelay = timeFrame /  stepCount;

    void setup()
    {
      pinMode( ledPin,       OUTPUT       );
      pinMode( interruptPin, INPUT_PULLUP );

      attachInterrupt( digitalPinToInterrupt( interruptPin ), pressed, CHANGE );
    }

    void loop()
    {
      if ( fadeOn )
      {
        delay( stepDelay );
        brightness += fadeAmount;
        if ( brightness >= 255 )
        {
           brightness = 0;
           analogWrite( ledPin, brightness );
           delay( aCoupleOfSeconds );
        }
        analogWrite( ledPin, brightness );
      }
      else
      {
        brightness = 0;
        analogWrite( ledPin, brightness );
      }
    }

    void pressed()
    {
      // the debouncing does not work perfectly

      if ( digitalRead( interruptPin ) == LOW )
      {
        if ( millis() - actTime > debounceTime )
        {
          fadeOn = !fadeOn;
        }
      }
      else
      {
        actTime = millis();
      }
    }

body:
Have a look at some code inside the forum from marcello.romani. He posted it on jan 1st, 2013.
  The topic on subject is called : "button pressed more than 2 seconds do somethingelse"
  Marcello's code is so KISS (Keep It Simple Stupid) and efficient that it deserves a Nobel prize.
  The goals is to handle the different signals that come from a button or switch action :
  keyPress, keyRelease, longKeyPress etc.. as you can find in the original sketch.


body:
I have a project where I have three pins to use and I just realized it would be better to use a memory card than replacing the code each time.

I'm building a Arduino with a push button. Press the button and it sends keystrokes to the connected computer with login details.
The login details need to change every three months so having that on a memory card will be easier.

So since I use a digispark Attiny 85 with a total of 6 pins (where two is used to send the keystrokes).
I have one to the push button, and three pins left.

Is there any card reader that can work with three pins? I only need to read if that makes a difference.
The ones I find use four pins (+ vcc and gnd).

Pretty much any memory card type is ok.

title: Can I read from a memory card with three pins?

Answers: 2

body:
SD cards work with SPI. This needs only one pin per device (SlaveSelect) but 3 pins for the other common signals ( MISO / MOSI / SCK )

Card reader modules simply do some voltage level shifting (if at all).

But, you need a lot of RAM to work with SD cards, as data transfer always happens in 512 byte "sectors". With a file system, you need at least two such blocks in parallel. An attiny85 is simply too small.

body:
Not with an ATTiny85, and not with so few pins, no.

However, all is not lost.

The ATTint85 has 512 bytes of EEPROM inside it where you can store your login details. All you need is some way of telling setting that data in your sketch from the PC - and the simplest way is probably through a USB serial connection.

If you don't have a serial connection available (I think Digispark has a custom interface they use) then you can use whatever interface you have available to do the job.


body: I am trying to use an Arduino Uno with Arduino Wifi Shield 101 to receive a signal from phone or webpage over wifi so it will "initiate" my circuit. I was able to connect the board to wifi but am unsure on how I should continue. My main goal is to be able to send it two different commands that would run different parts of code in my arduino script. I am very new to this stuff! Thanks :)

title: Using Arduino Wifi Shield to Receive Signal

Answers: 1

body: Look for the Web Server example in the arduino IDE.  That will give you a starting point to allow you to control the arduino via a web page.  This tutorial is also very in depth : https://startingelectronics.org/articles/arduino/switch-and-web-page-button-LED-control/


body: Encoders are quadrature 600ppr encoders with X2 counting. Therefore 1200 counts per revolution for each encoder. Is there an edge rate limit? I currently have one encoder hooked up using code with interrupts.

title: Will an Arduino Uno be able to read 3x incremental encoders?

Answers: 2

body:
The answer to the title's question is likely yes. But it would appear the real question is how fast can a given Arduino read a GPIO pin.

Consider there are multiple Arduino platforms.  Each possibly using a different type of processors.  Likely those processors are running at different speeds.  To give a specific answer we need to assume a specific platform, processor and speed.  The [current (3rd generation) Arduino Uno runs at 16MHz][1].  And the [Arduino Due runs at 84Mhz][2].  Since most people use an Arduino Uno let us use it for an example.

In [this arduino.cc forum thread][3] it is commented that an Arduino Uno running at 16MHz can execute the "Digital Pin Read" function call in about 4.78us.  Rounding that up to 5us that would be 1/5E-6 or 200000 samples per second.  Likely this can be improved upon if code were written to directly control the processors register for the desired outcome.  This is usually considered a moderately difficult embedded programming task.  And well outside normal Arduino knowledge.  In addition, such code would likely no longer be portable between different Arduino platforms.

  [1]: https://store.arduino.cc/usa/arduino-uno-rev3
  [2]: https://store.arduino.cc/usa/due
  [3]: https://forum.arduino.cc/index.php?topic=337578.0
  [4]: https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/

body:
Here is an example of some code I used to read two encoders using pin change interrupts.  This is possible to do with one ISR since they all share a common port.  The key is it has to be short.  As long as you can keep all 6 pins from your encoder on the same port, this should be easy to extend to 3 encoders.  It might even work for four on one port.  Or you can make a use a second port and get 3 or 4 more depending on which chip you have.

    volatile uint8_t lastPortRead = 0;

    volatile int32_t leftCounter = 0;
    volatile int32_t rightCounter = 0;

    ISR(PCINT2_vect){

     uint8_t portRead = PINC;

     uint8_t whoFired = portRead ^ lastPortRead;
     uint8_t pinsDiff = portRead ^ (portRead << 1); // Will have bits 5 or 7 set if pins on right motor or left motor are diff.  Cleared if same.

     if (whoFired & LEFT_INT_MASK) {
      if (pinsDiff & LEFT_INT_MASK) {
       leftCounter++;
      } else {
       leftCounter--;
      }
     }
     if (whoFired & RIGHT_INT_MASK) {
      if (pinsDiff & RIGHT_INT_MASK) {
       rightCounter++;
      } else {
       rightCounter--;
      }
     }

     lastPortRead = portRead;
    }


body:
I am attempting to write a small sketch with the Arduino IDE (1.8.10) to set the colour of an RGB LED, however my function for setting the colour of the LED is behaving strangely.

Here is the full sketch code:

```c
#define RED 9
#define GREEN 10
#define BLUE 11

void setup()
{
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  digitalWrite(RED, LOW);
  digitalWrite(GREEN, LOW);
  digitalWrite(BLUE, LOW);
  Serial.begin(9600);
}

int gRed = 20;
int gGreen = 21;
int gBlue = 22;

void setRGB(int r, int g, int b)
{
  Serial.println(r);
  Serial.println(g);
  Serial.println(b);
  analogWrite(RED, r);
  analogWrite(GREEN, g);
  analogWrite(BLUE, b);
}

void loop()
{
  //setRGB(gRed, gGreen, gBlue); // WORKS - White-ish
  setRGB(20, 21, 22); // DOESN'T WORK - Blue =/
}
```

As you may tell from the comments, when I pass "global" variables in to ```setRGB()``` the LED lights up the expected colour. But, when I pass literals in it does not.

The Serial monitor shows the following output when using the literals:
```
20
21⸮20
21
20
21
20
21⸮
etc....
```

Can anybody help me figure out what I'm doing wrong?

Board in use is a Mega2560.

title: Function parameter of type int not working as expected

Answers: 0


body:
I am relatively new to Arduino and microchips, but I am good at electronics. I want to connect MPU6050 accelerometer+gyroscope module to Arduino. I searched on the internet and everywhere it is said to connect the SCL and SDA pins to two analog pins of the Arduino. As far as I know, the MPU6050 is a digital sensor, so why 2 analog pins are required for the sensor?

Also, is there any way to connect the sensor with only digital pins? because I need the analog pins for some other purpose.

title: How to connect MPU6050 to arduino using only digital pins

Answers: 1

body:
The MPU6050 communicates over I2C. I2C uses clock line SCL and data line SDA. I2C pins on Uno are pins A4 and A5.
This is because the ATmega328p MCU used on Uno has the I2C peripheral on the same pins. It has nothing to do with the DAC function of the pins.

<s>Alternatively MPU6050 can communicate over SPI. This are pins 11, 12, 13 on Uno and one more pin for CS. Pin 10 must be output while ATmega328p is SPI master so it is recommended to use it as CS for the SPI slave device. </s>  EDIT Sorry, only MPU6000 has SPI.


body:
I am using an HMC-5983 magnetometer compass on my arduino uno to find the heading of a car I'm building.But my compass readings aren't varying linearly.For example when I physically turn my compass by 90 degrees the change in the reading doesn't correspond to 90 degrees.I tried mapping the raw output of the compass to the actual heading but when I do this , the headings in between the points I mapped aren't accurate enough thereby causing my car to behave abnormally.I also looked up on google but couldn't find anything helpful though there was some mention about using an algorithm to sort this issue.Please help me fix this problem.

        #include <Wire.h> //I2C Arduino Library
    #define Magnetometer_mX0 0x03
    #define Magnetometer_mX1 0x04
    #define Magnetometer_mZ0 0x05
    #define Magnetometer_mZ1 0x06
    #define Magnetometer_mY0 0x07
    #define Magnetometer_mY1 0x08
    int mX0, mX1, mX_out;
    int mY0, mY1, mY_out;
    int mZ0, mZ1, mZ_out;
    float heading, headingDegrees, headingFiltered, declination;
    float Xm,Ym,Zm;
    #define Magnetometer 0x1E //I2C 7bit address of HMC5883
    void setup(){
      //Initialize Serial and I2C communications
      Serial.begin(9600);
      Wire.begin();
      delay(100);

      Wire.beginTransmission(Magnetometer);
      Wire.write(0x02); // Select mode register
      Wire.write(0x00); // Continuous measurement mode
      Wire.endTransmission();
    }
    void loop(){

    //---- X-Axis
      Wire.beginTransmission(Magnetometer); // transmit to device
      Wire.write(Magnetometer_mX1);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer,1);
        if(Wire.available()<=1)
      {
        mX0 = Wire.read();
      }
      Wire.beginTransmission(Magnetometer); // transmit to device
      Wire.write(Magnetometer_mX0);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer,1);
      if(Wire.available()<=1)
      {
        mX1 = Wire.read();
      }
      //---- Y-Axis
      Wire.beginTransmission(Magnetometer); // transmit to device
      Wire.write(Magnetometer_mY1);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer,1);
      if(Wire.available()<=1)
      {
        mY0 = Wire.read();
      }
      Wire.beginTransmission(Magnetometer); // transmit to device
      Wire.write(Magnetometer_mY0);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer,1);
      if(Wire.available()<=1)
      {
        mY1 = Wire.read();
      }

      //---- Z-Axis
      Wire.beginTransmission(Magnetometer); // transmit to device
      Wire.write(Magnetometer_mZ1);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer,1);
      if(Wire.available()<=1)
      {
        mZ0 = Wire.read();
      }
      Wire.beginTransmission(Magnetometer); // transmit to device
      Wire.write(Magnetometer_mZ0);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer,1);
      if(Wire.available()<=1)
      {
        mZ1 = Wire.read();
      }

      //---- X-Axis
      mX1=mX1<<8;
      mX_out =mX0+mX1; // Raw data
      // From the datasheet: 0.92 mG/digit
      Xm = mX_out*0.00092; // Gauss unit
      //* Earth magnetic field ranges from 0.25 to 0.65 Gauss, so these are the values that we need to get approximately.
      //---- Y-Axis
      mY1=mY1<<8;
      mY_out =mY0+mY1;
      Ym = mY_out*0.00092;
      //---- Z-Axis
      mZ1=mZ1<<8;
      mZ_out =mZ0+mZ1;
      Zm = mZ_out*0.00092;
      // ==============================
      //Calculating Heading
      heading = filtered_angle(Zm, Xm);// arc tangent of z/x

      // Correcting the heading with the declination angle depending on your location
      // You can find your declination angle at: http://www.ngdc.noaa.gov/geomag-web/
      // At my location it's 4.2 degrees => 0.073 rad
      declination = 0.03717551307 ;
      heading += declination;

      // Correcting when signs are reveresed
      if(heading <0) heading += 2*PI;
      // Correcting due to the addition of the declination angle
      if(heading > 2*PI)heading -= 2*PI;
      headingDegrees = heading * 180/PI; // The heading in Degrees unit
      // Smoothing the output angle / Low pass filter
      headingFiltered = headingDegrees;
      //Sending the heading value through the Serial Port to Processing IDE

      if(headingFiltered >= 0 && headingFiltered <= 89){
                    c_head=map(headingFiltered,0,90,270,359);
            }
        if(headingFiltered > 89 && headingFiltered <= 204){
                    c_head=map(headingFiltered,90,204,0,90);
            }
        if(headingFiltered > 204 && headingFiltered <= 290){
                    c_head=map(headingFiltered,205,290,91,180);
            }
          if(headingFiltered > 290){
                   c_head=map(headingFiltered,291,359,181,269);
            }

    // Serial.print("Degrees - ");
     Serial.println(headingDegrees);
    delay(500);
    }

    float filtered_angle(float p, float q) {
             const float filter_constant = 0.15;
             static float q_f, p_f; // filtered components
             q_f += filter_constant * (q - q_f);
             p_f += filter_constant * (p - p_f);
             return atan2(p, q);
            }

title: Compass heading not varying linearly

Answers: 1

body:
If you can't find and eliminate a systemic error, such as nearby ferrous, magnetic, or electromagnetic sources, causing the errors you see, you'll need to do what navigators have done for ages: swing the compass.

Swinging a compass involves taking the vehicle - your robo-car - somewhere away from external error sources (building wiring, iron/steel masses, f/ex) and taking a set of measurements by heading the vehicle in a number of directions known by a means independent of its own compass. Eg., with a boat, you'd choose a known place in the middle of a harbor and plot a line from that known position to each landmark (for a car, you could use a large playing field). That gives you the True bearing (bearing relative to the north pole) from the chosen position to the landmark. Make a list of those landmarks and their true bearings in columns 1 & 2 of sheet of paper, in clockwise order starting a true north.

Convert the True bearings to Magnetic bearings (relative to the direction from where you are now to the earth's magnetic north pole): Navigation charts will show the difference (in degrees) between True bearings and magnetic bearings for the location(s) covered by that chart; the difference is called "variation" (sometimes called declination). If the magnetic variation at your location is westerly (compasses point 15 degrees W of True North, f/ex), add that value to those bearings you just listed. This third column of numbers is the magnetic bearing to each of those landmarks, and the value an error-free compass should read.

Now take your vehicle to that known point (playing field, middle of the harbor, etc.) and point its center line at each of those landmarks and read its compass for each one. Write these numbers in the fourth column - the compass headings to the landmarks, for *this compass* in *this vehicle*.

Columns 3 & 4 are now a compass correction table. When the compass reads a number that is in column 4 (compass bearing), the actual (corrected) magnetic heading is the corresponding number in column 3 (the magnetic headings).

But of course you don't have every possible heading in your compass correction table. So when you need to know your car's direction, you have to interpolate between a pair of bearings you do have:

 1. Find a pair of bearings in column 4, the compass headings, that bracket the reading you just took.
 2. Find the percentage that reading is of the difference between the bracketing compass bearings.
 3. Apply that same percentage to the difference between the adjacent magnetic bearings in column 3 to find the actual magnetic bearing.

I glossed over the process of interpolation pretty quickly as the question was about correcting the compass. Interpolation, or other ways of applying a correction, is a whole 'nuther topic but the Arduino `map()` function will be great help here. Also, the more correction values (landmarks) you use to make your table, and the more evenly they are spread around the compass, the more accurate your corrections will be.


body:
A follow up question on my previous question, if a memory card reader can be used with three pins (digispark Attiny 85):

https://arduino.stackexchange.com/questions/70590/can-i-read-from-a-memory-card-with-three-pins

Now I came up with another idea.
Since the USB connector or the VCC pin can power an Arduino my guess is that they are in parallel and the actual Arduino is connected to both.
Kind of like this very bad schematic made on my phone: (sorry for that)
[![enter image description here][1]][1]
Where the blue stuff is the Arduino chip.

If that is true then adding the push button between VCC and GND with a resistor between should remove the power of the Arduino?
In that case I can have my code in setup() and use the pus button to reset the Arduino, and still have four pins to the memory card reader.

Or is this wrong? What kind of resistor value do I need to make sure I don't short the USB connector but still have less resistance than the Arduino chip?

  [1]: https://i.stack.imgur.com/j7yUJ.png

title: Reset Arduino by connecting vcc and gnd?

Answers: 1

body:
That is wrong. That is very, very wrong. That is one of the worst things you can do to a USB connection short of plugging it into the mains.

Do not even consider doing this.  Short circuits are never a good idea.


body:
This is my first project with any sort of development board and it has been a blast so far.

I am running into some issues, however, while trying to send serial data from my Uno to a NodeMCU board.

I have the following connections:

Uno Rx to NMcu Tx

Uno Tx to NMcu Rx

Uno GND to NMcu GND

microUSB from computer to power NMcu

usb from computer to power Uno

**EDIT:** after some suggestions, I have also tried the following.

Uno DigitalPin 5 to NMcu D6

Uno DigitalPin 6 to NMcu D5

Uno GND to NMcu GND

microUSB from computer to power NMcu

usb from computer to power Uno

With the following code:

    // UNO sender Code
    #include <SoftwareSerial.h>
    SoftwareSerial toESP(0, 1); //Rx, Tx (also tried 5,6)

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

    void loop()
    {
      Serial.println("sending");
      toESP.println("message from Nano");
      delay(1000);
    }

--------------------------------------

    // NodeMCU receiver code
    #include <SoftwareSerial.h>
    SoftwareSerial fromNano(3, 2); //Rx, Tx (also tried D5, D6)

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

    void loop()
    {
      if (fromNano.available())
      {
        char inChar = fromNano.read();
        Serial.print(inChar);
      }
      else {
        Serial.println("not available");
      }
      delay(2000);
    }

I can pull up a serial monitor from both and see the UNO sending data (the TX led also blinks on the uno).

The NodeMCU code never satisfies the `fromNano.available` condition.

Is there anything I am overlooking that is causing this not to work? I've attached a picture of my connections as well.

[![enter image description here][1]][1]

Any help is much appreciated.

  [1]: https://i.stack.imgur.com/ChFWa.jpg

title: Uno to NodeMCU Serial Connection Problem

Answers: 2

body: Arduino UNO is using pin 0 and pin 1 to have serial with USB serial Communication. You can not use them to softserial. Change softserial to other pins.  /Mikael

body:
@Carlmikael is definitely correct in his answer, I should not have been using hardware pins with softwareserial.

Besides that problem, my issue was resolved ultimately when I noticed that if I powered up the NodeMCU before powering up the Arduino, everything worked as expected.

Maybe someone can elaborate as to why this caused an issue?


body:
[![enter image description here][1]][1]

The code below Gets stuck at function "Led Off?" & "Check button".
I'm using Blockyduino editor.
The check button code was intended as a toggle switch for the lights. When I deleted "Led Off?" and "Turn off All LED", the code did not get stuck.

    int Button_Status;

    // Toggle Code for the button.
    void Check_Button() {
      Serial.println("Check button Activated");
      if (Button_Status == 1) {
        if (digitalRead(13)) {
          Button_Status = 0;
        }
      }
      if (Button_Status == 0) {
        if (digitalRead(13)) {
          Button_Status = 1;
        }
      }
      LED_OFF_();
    }

    void Left_Animation() {
      Check_Button();
      digitalWrite(2, HIGH);
      digitalWrite(3, HIGH);
      Check_Button();
      delay(1000);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      Check_Button();
      delay(500);
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      Check_Button();
      delay(300);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      Serial.println("Finshed Left cycle");
    }

    void Right_Animation() {
      Check_Button();
      digitalWrite(8, HIGH);
      digitalWrite(9, HIGH);
      Check_Button();
      delay(1000);
      digitalWrite(10, HIGH);
      digitalWrite(11, HIGH);
      Check_Button();
      delay(500);
      digitalWrite(8, LOW);
      digitalWrite(9, LOW);
      Check_Button();
      delay(300);
      digitalWrite(10, LOW);
      digitalWrite(11, LOW);
      Serial.println("Finished Right cycle");
    }

    // Main Loop Core
    void Main_Loop() {
      while (Button_Status == 1) {
        Left_Animation();
        Right_Animation();
        Serial.println("Finshed Main Loop 1111");
      }
      while (Button_Status == 0) {
        Check_Button();
        Serial.println("Finished Main Loop 2222");
      }
    }

    // Checks if button toggle variable is off.
    void LED_OFF_() {
      Serial.println("LED off? Activated");
      if (Button_Status == 0) {
        Turn_Off_All_LED();
      }
      Main_Loop();
    }

    // Turns off all LED
    void Turn_Off_All_LED() {
      Serial.println("LED Turn off Activated");
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      digitalWrite(7, LOW);
      digitalWrite(8, LOW);
      digitalWrite(9, LOW);
      digitalWrite(10, LOW);
      digitalWrite(11, LOW);
      Main_Loop();
    }

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

    void loop()
    {
      // Start
      Button_Status = 1;
      Main_Loop();
    }

  [1]: https://i.stack.imgur.com/2rsRi.png

title: Some Blocks of Code gets stuck in a loop, I do not know why

Answers: 1

body:
You have a problem with infinite recursion in this program: `loop()`
calls `Main_Loop()`, which calls `Left_Animation()`, which calls
`Check_Button()`, which calls `LED_OFF_()`, which calls `Main_Loop()`,
which calls `Left_Animation()`, which calls `Check_Button()`, which
calls `LED_OFF_()`, which calls `Main_Loop()`, which calls... This will
pretty quickly exhaust the memory of your Arduino.

If you only know about graphical programming, this may not make too much
sense to you. So I ask you to imagine that, in your definition of
`Main_Loop()` (the big structure titled “to Main Loop”) you replace the
smallish box labeled “Left Animation” by its own definition (the big
structure labeled “to Left Animation”). Within this definition, you
replace “Check Button” by its own definition and so on. You will soon
reach a point where you need to embed the definition of `Main_Loop()`
within itself. It should then look more or less like this:

```text
Main Loop
│ repeat while Button Status = 1
│ do Left animation
│ │  │ Check Button
│ │  │ │ Serial Print “Check button Activated”
│ │  │ │ ...
│ │  │ │ LED OFF?
│ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ if Button Status = 0
│ │  │ │ │ do Turn Off All LED
│ │  │ │ │ Main Loop
│ │  │ │ │ │ repeat while Button Status = 1
│ │  │ │ │ │ do Left animation
│ │  │ │ │ │ │  │ Check Button
│ │  │ │ │ │ │  │ │ Serial Print “Check button Activated”
│ │  │ │ │ │ │  │ │ ...
│ │  │ │ │ │ │  │ │ LED OFF?
│ │  │ │ │ │ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ │ │  │ │ │ if Button Status = 0
│ │  │ │ │ │ │  │ │ │ do Turn Off All LED
│ │  │ │ │ │ │  │ │ │ Main Loop
│ │  │ │ │ │ │  │ │ │ │ repeat while Button Status = 1
│ │  │ │ │ │ │  │ │ │ │ do Left animation
│ │  │ │ │ │ │  │ │ │ │ │  │ Check Button
│ │  │ │ │ │ │  │ │ │ │ │  │ │ Serial Print “Check button Activated”
│ │  │ │ │ │ │  │ │ │ │ │  │ │ ...
│ │  │ │ │ │ │  │ │ │ │ │  │ │ LED OFF?
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ if Button Status = 0
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ do Turn Off All LED
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ Main Loop
...etc ad infinitum...
```

Note that it is possible to write programs using [recursion][], but:

1. This is kind of an “advanced topic”, not suitable for someone still
   programming at a graphic level.
2. You have to take precautions in order to avoid the program to
   infinitely recurse.
3. On a microcontroller with little memory, you have to make sure the
   recursion is always very shallow. Which is hard, so people writing
   embedded code tend to avoid recursion altogether.

[recursion]: https://en.wikipedia.org/wiki/Recursion_(computer_science)


body:
I designed a custom PCB that has the chip, an oscillatorm, decoupling capacitors, and all other connections for the ATmega along with the rest of my circuit. I followed all steps in the tutorial for burning the bootloader to my ATmega chip but when using a nano to program I get an error about getsync() that supposedly means the reset isnt working. I then used the same wiring with an uno like in the examples and I got a different error this time where it goes yikes then something about not recognizing the chip. This is apparently indicative of a wiring or oscillator problem but all those things appear to be correct. I'm not sure what to try next or what could be wrong

Used this tutorial as well as the actual arduino page https://www.electronoobs.com/eng_arduino_tut6.php

Used this tutorial next since I am using ATmega328PB
https://www.circuito.io/blog/atmega328p-bootloader/

Here's the error I get
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "ATmega328, Yes (UART0), 328PB, BOD 2.7V, LTO disabled, 16 MHz external"

\\nas01.itap.purdue.edu\puhome\My Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -C\\nas01.itap.purdue.edu\puhome\My Documents\ArduinoData\packages\MiniCore\hardware\avr\2.0.3/avrdude.conf -v -patmega328pb -cstk500v1 -PCOM5 -b19200 -e -Ulock:w:0x3f:m -Uefuse:w:0b11110101:m -Uhfuse:w:0xd6:m -Ulfuse:w:0b11111111:m

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 "\\nas01.itap.purdue.edu\puhome\My Documents\ArduinoData\packages\MiniCore\hardware\avr\2.0.3/avrdude.conf"

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

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

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0xffffff (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0xffffff (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0xffffff
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Here's the PCB schematic and wiring picture
[![PCB Schematic][1]][1]

[![Wiring][2]][2]

  [1]: https://i.stack.imgur.com/nFYL1.png
  [2]: https://i.stack.imgur.com/ovZj9.jpg

title: Problem burning bootloader to ATmega chip using nano/uno

Answers: 0


body:
This was for photocell data logging for 30 sec intervals, now I want to write a code which commands from the cellphone and sends back the last 10 minute data.

At first I thought if I make an array of 20 buckets and put it in a loop, then send the loop function to android would make it right. But it just sends me continues data. I only want the last 10 minute data of the program.

    float sensorvalue[20];

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

     for (int i = 0; i < 20; i++) {
      pinMode(sensorvalue, OUTPUT);
     }
    }

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

     if(Serial.available()) {
      c=Serial.read();
      if (c=='t')
       sendvalues();
     }
    }

    void sendvalues()
    {
     for (int i=0 ; i<20 ; i++) {

      Serial.println(sensorvalue);
      sensorvalue   = analogRead(A0);
      delay(30000); //every 30 seconds read data

      if (i>=20) {
       i=0; //reset to beginning of array, so you don't try to save readings outside of the bounds of the array
      }
     }
     Serial.println("***********************************");
    }

title: I want to send the last 10 minute data via bluetooth

Answers: 2

body:
Your code doesn't make much sense as written.

You need to:

Collect a new value every 30 seconds and save it into an array of values, incrementing a "current value index" variable with each read.

Do you want to trigger the sending of a buffer-full of data when the array is full, or using a command from the remote phone? If you want to trigger the sending from a phone, what would you do if there wasn't a full buffer of data? What would you do if the buffer gets full and there's no command sent from the phone?

Assuming you send a buffer-full of data every time it's available, just wait until the array index reaches the end. When that happens, transmit the entire buffer of data to your phone and reset the array index to start collecting new data.

If you want to trigger sending from your phone you have to handle edge cases like buffer overflow, or trying to send before you have a full buffer of data. I would suggest creating an array larger than you need (say 100 values), making it a ring buffer (google it) and saving new values continuously until the ring buffer is full. If the sketch receives a send command, it could check to see if it has at least 20 values in the buffer, and send those/remove them from the buffer if it does, or send back a "not enough data collected" message if not.

body:
What you want for this project is called a [ring buffer][]. Before
reading the rest of this answer, I suggest you stop and take the time to
carefully read the Wikipedia page I am linking to.

Did you read it? Good! Now, yours is a somewhat special case in that you
don't need to continuously keep track of both a read pointer and a write
pointer: you only need the write pointer, as the read happens all in one
big batch.

Once your ring buffer is full, you will start overwriting the oldest
readings, those that are more than 10 minutes old. When the program
is instructed to dump the data, it will send out the whole buffer,
starting with the cell pointed to by the write pointer (the cell that
holds the oldest data point and was about to be overwritten).

There is one special case to take care of. What if the program gets the
command to dump the data while it has less than 20 readings stored?
You could decide that this is a user error, and it's OK for the program
to give garbage. I suggest, however, that the program should be able to
detect this situation, and then only send the valid data. For this, it
needs to store a boolean variable in order to remember whether the
buffer has been filled or not.

Here is an implementation I propose for such a ring buffer, together
with the functions for adding an item and for dumping all the data
through the serial port:

```c++
const uint32_t READING_PERIOD = 30000;  // one reading every 30 s
const int MAX_READINGS = 20;           // 20 readings = 10 min

int readings[MAX_READINGS];  // ring buffer
uint8_t reding_index = 0;    // next available slot
bool readings_full = false;  // did we fill the ring buffer?

static void register_reading(int value) {
    readings[reding_index] = value;
    if (++reding_index >= MAX_READINGS) {
        readings_full = true;
        reding_index = 0;
    }
}

static void dump_readings() {
    // If the buffer is full, then the next avaiable slot is the oldest
    // reading in the buffer.
    if (readings_full) {
        for (int i = reding_index; i < MAX_READINGS; i++)
            Serial.println(readings[i]);
    }
    for (int i = 0; i < reding_index; i++)
        Serial.println(readings[i]);
}
```

Now the main program is quite simple. You time the data taken using the
technique shown in the [Blink without delay][] tutorial. You don't want
to use `delay()` because, when the program is delaying, it cannot
respond to your commands. There is one last question remaining: when it
dumps the data, should it forget it? In other words, if you ask it twice
to dump the data, with less that 10 minutes in between, should it
give repeated data the second time, or should it only provide the fresh
data? In the code below I assume the later option, and thus reset the
buffer, but in the end it is your choice:

```c++
void setup() {
    Serial.begin(9600);
}

void loop() {
    // Periodically take a reading.
    static uint32_t last_reading_time;
    if (millis() - last_reading_time >= READING_PERIOD) {
        last_reading_time += READING_PERIOD;
        register_reading(analogRead(A0));
    }

    // Dump the data on command.
    if (Serial.read() == 't') {
        dump_readings();
        reding_index = 0;       // reset the buffer
        readings_full = false;  // ditto
    }
}
```

[ring buffer]: https://en.wikipedia.org/wiki/Circular_buffer
[Blink without delay]: https://www.arduino.cc/en/tutorial/BlinkWithoutDelay


body:
This is on a custom Arduino PCB (32u4) that I am programming with a Sparkfun Pocket AVR Programmer. A different program that I was writing wasn't working the way I expected it to, so I tried the "BlinkWithoutDelay" example sketch from the Digital section of the examples.

https://media.discordapp.net/attachments/572565310679547946/650075749851856908/unknown.png
^ So you don't have to look it up yourselves. previousMillis is initialized to 0.

However, the LED seems to alternate states every 4 seconds instead of every 200 ms with this code. I increased the interval from 200 to 400, and the IRL time increased from 4 seconds to 8 seconds, so at the very least it's consistent that way. My first instinct is that the crystal is broken somehow, but I don't think I'd be able to flash the MCU in the first place if it was. So, does anyone have any idea what's happening? For the record, I had 5 of these PCB's assembled, and the first one worked perfectly for 2 months before something else broke. I've had this issue with the second and third PCB I've tried.

title: Timing taking longer than expected

Answers: 2

body:
Factor 8 in timing smells like wrong fuses.

Perhaps you don't use an external oscillator, but the internal one?

body: On all of the new boards I had tested (excluding the first one that I said worked), I had not burned the bootloader. Burning the bootloader made the timing normal! If anyone can tell me why that's the case, I'll accept your answer as the "correct" answer.


body:
I want to use two serial ports

Serial1 - for debugging - No RX needed

Serial - to read from a different device

I receive garbled output instead of valid characters

Here is code for NodeMCU

    #define LED D0

    void setup() {
      // put your setup code here, to run once:
      pinMode(LED, OUTPUT);
      Serial.begin(9600);
      Serial.flush();
      Serial.swap();
      Serial1.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if(Serial.available()>0)
      {
    //    digitalWrite(LED, HIGH);
    //    delay(500);
    //    digitalWrite(LED, LOW);
    //    delay(500);
    //    digitalWrite(LED, HIGH);
    //    delay(500);
    //    digitalWrite(LED, LOW);
    //    delay(500);
        Serial1.print(Serial.read());
      }
    }

and here is the code for Arduino mega which is emulating a send and receive

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      Serial1.begin(9600);    //Transmit
      Serial2.begin(9600);    //Recieve
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if(Serial.available()>0)
        Serial1.print(Serial.read());

      if(Serial2.available()>0)
        Serial.print(Serial2.read());
    }

When I Send an Charater(Single) I receive something like this
for "s" - 5257525753515257534952575256
for "d" - 5257525652565257534952575256

Kindly help

title: ESP8266 - Garbled output when using serial Swap

Answers: 0


body:
I am using transmitter and receiver but I want to change the data type from character to int

receiver code

    #include <RH_ASK.h>//include radioHead ASK library
    #include <SPI.h> // include dependant SPI libray

     RH_ASK rf_driver; // create ASK object
    int ledon = 13;
    String userid;
    String password;
     //RH_ASK ID1; // create ASK object
    //RH_ASK pass1; // create ASK object

    void setup() {

      rf_driver.init(); //initialize ASK object

      Serial.begin(9600); //setup serial monitor to 9600

      //if(!rf_driver.init())
           //Serial.print("init failed");
    }

    void loop() {

      // set buffer to size of expected message
      uint8_t buf[9];
      uint8_t buflen =sizeof(buf);

      //check if recevied packet is correct size
      if (rf_driver.recv(buf,&buflen))
      {
        int i;
        // message received with valid checksum
        Serial.print("id: ");
        Serial.println((char*)buf);
          userid =(char*)buf;
            Serial.println(userid);

      }

    delay(5000);

       uint8_t buf2[8];
      uint8_t buflen2 = sizeof(buf2);

       if (rf_driver.recv(buf,&buflen))

      {

        int i;
        // message received with valid checksum
        Serial.print("password: ");
        Serial.println((char*)buf);
          password = (char*)buf;
          Serial.println(password);

      }
      delay(5000);

transmitter code

    //Include RadioHead Amplitidue shift keying library
    #include <RH_ASK.h>
    // Include dependatnt ISP library
    #include <SPI.h>

    //create Ampitude shift keying object
    RH_ASK rf_driver;

    void setup() {
     // intialize ASK objct
    rf_driver.init();

    Serial.begin(9600);

      //if(!rf_driver.init())
          //Serial.print("init failed");

    }

    void loop()
    {

      const char *pass= "123456789";
    rf_driver.send((uint8_t *)pass, strlen(pass));
    rf_driver.waitPacketSent();
    delay(5000);

    const char *ID= "A00034732";

    rf_driver.send((uint8_t *)ID, strlen(ID));
    rf_driver.waitPacketSent();
    delay(5000);

title: converting character to strings in transmitter and receiver Arduino

Answers: 1

body:
You have to properly understand what you are trying to do. (It looks like) you have a decimal representation of a number, encoded as a string of characters. "12345" is not a number but a series of characters. <sub>(Technically each character is a number with a certain ASCII value, the digit "1" has ASCII value 49 for instance.)</sub>

To convert "12345" into the number 12345, the CPU needs to take each character, find its digit value, multiply it by the correct power of 10 and add it to all the others. There are a few built-in ways that do this for you. The easiest is the `atoi()` function, e.g.

    int x = atoi("150");

In your case, try this:

    int userid = atoi((char *) buf);

    Serial.println(userid);


body:
I have been trying to implement SPI communication between an Arduino board and a PGA411-Q1 resolver sensor board. I have set up the Arduino SPI settings as indicated on the resolver sensor's datasheet (http://www.ti.com/lit/an/slaa688/slaa688.pdf) - 8MHz sclock, MSB first and SPIMode1.

The communication is done by sending and receiving 32 bits both to and from the Arduino. The bits are distributed as follows.

Outgoing 32bit data frame by Arduino to the sensor:

O-5 bits: Arduino's CRC for data

6-7 bits: Always zero

8-23 bits: Data

24-31 bits: Register address

Incoming 32bit data frame by the sensor to the Arduino:

O-5 bits: Sensor's CRC for data

6-7 bits: SPI communication status

8-23 bits: Data

24-31 bits: Register address

Also, there is mandatory to send and receive a CRC6 code from both the board and Arduino and I have implemented it as well. (I will not be checking the CRC code received by the Arduino board. I will check it later. But I am already sending the CRC code needed by the sensor board).

This is the code written by me:

NOTE: The crc_cal function outputs the crc code from Arduino to the sensor along with the two 'always zero' bits.

    #include <SPI.h>
    unsigned int crc_cal (unsigned long datin);

     const int ncs = 10;
     unsigned char crc_char = 0x3F;

     void setup() {

      // initalize the chip select pin:
      pinMode(ncs, OUTPUT);
      pinMode(FAULTRES,OUTPUT);
      pinMode(NRESET,OUTPUT);

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

      //NRESET must go from LOW to HIGH
      digitalWrite(NRESET,LOW);
      digitalWrite(NRESET,HIGH);

      //wait at least 5ms to complete diagnostics tests
      delay(10);

      //FAULTRES LOW
      digitalWrite(FAULTRES,LOW);

      // start the SPI library:
      SPI.begin();

     // give the sensor time to set up:
      delay(100);

       }

    void loop() {

    SPI.beginTransaction(SPISettings(6400000, MSBFIRST, SPI_MODE1));

    digitalWrite(ncs, LOW);

    byte temp_3 = SPI.transfer(0x41);

    byte temp_2 = SPI.transfer(0x0F);

    byte temp_1 = SPI.transfer(0x0F);

    byte temp_0 = SPI.transfer(crc_char);

    digitalWrite(ncs, HIGH);

    SPI.endTransaction();

    unsigned int angle_raw = 0;
    angle_raw = temp_2;
    angle_raw = angle_raw << 8;
    angle_raw = angle_raw | temp_1;
    angle_raw &= 0x3FF;
    Serial.println(angle_raw);

    int crc = crc_cal(0x410F0F00);
    unsigned char crc_char = crc;
    crc_char = crc_char & 0x3F;
     delay(100);

     }

         /* CRC6 calculation - optimized for PGA411 */
     unsigned int crc_cal (unsigned long datin)
     {
     unsigned int byte_idx, bit_idx, crc= (0x3F << 2);
     /* byte by byte starting from most significant (3-2-1) */
     for (byte_idx = 3; byte_idx >= 1; byte_idx--)
     {
     /* XOR-in new byte from left to right */
     crc ^= ((datin >> (byte_idx<<3)) & 0x000000FF);
     /* bit by bit for each byte */
     for(bit_idx = 0; bit_idx < 8; bit_idx++)
     {
     crc = crc << 1 ^ (crc & 0x80 ? (0x5B << 2) : 0);
     }
     }
     return(crc >> 2 & 0x3F); /*restore two bit offset */

     }

I have used the code provided in the PGA411-Q1's datasheet (http://www.ti.com/lit/an/slaa688/slaa688.pdf) and it works fine when I check it manually. Some examples for input data frames and their CRC codes can be found in the section 7.5.4 of the datasheet found here http://www.ti.com/lit/ds/symlink/pga411-q1.pdf

As you may notice from the code I am sending the register address which I want data from in the first 8 bits of SPI.transfer. The read address of that register is 0x41.

Next, I'm sending two garbage values as data because this is a read-only register.

Finally, I'm sending the CRC code calculated by the crc_cal function.

All I'm receiving in the serial monitor are zeros and I can't figure out what went wrong. I would appreciate some insight into this.

title: SPI communication with Arduino and PGA411-Q1 resolver sensor

Answers: 0


body:
I am using a arduino uno and neo 6m gps module. The problem I am facing is quite weird. When I connected the setup the data from neo6M was seen in serial monitor, I even printed it on a Oled display. It was a close room at night. I used tiny gps plus plus library to parse the data. I got both latitude longitude. After disconnected the circuit i tried again and that is when nothing came out in serial monitor. The same sketch did not work for a day. But again at afternoon at some point i got the data properly.
Sometimes the red led is blinking but nothing happens.
While I change the rx and tx pins in software serial it got data but then again same problem and changing pins don't work. I have tested it in front of my window so there must be a good signal.
Can someone tell me what is wrong with the system? I have so far waited long enough like 10 mins to get the data but nothing. I have to present the project by tomorrow in office.
This is the code :
https://pastebin.com/TMRYXFNw

title: NEO 6M data is not working properly with uno

Answers: 0


body:
I'm trying to burn bootloader to my clean crystals, atmega328p-pu.For this I use the 16MHZ crystal with two ceramic capacitors and USBASP programmer, on Windows 10 Pro. As program for burning I tried: Arduino IDE, AVRDUDESS,AVRDUDEPROG. But when I would to detect my chip(or in IDE try to burn the Chip)., I get this error:
`
avrdude.exe: set SCK frequency to 1500000 Hz
avrdude.exe: warning: cannot set sck period. please check for usbasp firmware update.
avrdude.exe: error: program enable: target doesn't answer. 1
avrdude.exe: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

avrdude.exe done.  Thank you.

`
From this error I understand that the target(My chips) Wouldn't to start. I checked my connection for 1000 times and I tested mt wires too, they works correctly. And supply 5V comes o chip and it become warm(it means that supply comes and it should start). I have got 5 chips And I tested all of them. I searched internet but nothing.

Please,help me, and say how can I burn them.

Best Regards,
E.M.

title: How to burn a bootloader to non-bootloaded(clean crystal) ATMEGA328P-PU with USBASP programmer via Avrdudess?

Answers: 0


body:
I'm looking for the Arduino/C++ equivalent of COBOL's 'copy' statement.

I'm working on a program that is approaching 600 lines of code in the TopLevel.cpp source file.  This is hard to manage because I feel like I spend all my time scrolling up and down the source file.  The code in question does not easily lend itself to conversion to a class because it is sections of loop/main.  I've tried using xxx.h (for storage definitions) and yyy.cpp (for code sections).  Those approaches yield error messages, which I think are due to the different timings of the Arduino pre-processor and the compiler code that resolve the #include statements.

Thanks for the help.
--CVTBrakeman

p.s.
I wrote my first program in 1967; the language was GOTRAN on an IBM 1620.  For almost 50 years, I made my living designing/writing COBOL and SAS code on IBM mainframes.  Yes, Y2K was real and I survived it.

title: How do I segment Arduino program when line count is so large that code maintenance is difficult?

Answers: 2

body:
This is more like a general programming question than an Arduino
question but, anyway...

You don't need to write classes to sort your code into files. You just
need to think in term of independent pieces of functionality. Each of
those pieces would be implemented in a .cpp file, with the interface
declared in a .h file.

As an example, let's say your Arduino is controlling an hyperdrive.
Managing the dilithium plasma generator is one of those functionalities
that can be separated in its own files. The .h files declares everything
that is needed for _using_ that functionality:

**plasma\_generator.h**:
```c++
// Read the state of the plasma.
float plasma_density();
float plasma_temperature();

// Control the plasma.
void set_plasma_target_temperature(float target_temperature);
void ignite_plasma();
void turn_off_plasma();
void add_dilithium(float amount);
```

Then the .cpp file contains the implementation:

**plasma\_generator.cpp**:
```c++
#include "plasma_generator.h"

// A "static" function is a function private to this module.
static float get_gauge_reading(int gauge_number)
{
    ...
}

// Implementation of a public function, described in the .h file.
float plasma_density()
{
    float raw_reading = get_gauge_reading(42);
    ...
}

...
```

In your main program (or even in other modules, if needed) you
`#include` the .h file and use the functionality defined therein.

body:
There are two ways of doing this:

1. Multiple INO files

The Arduino IDE combines multiple INO files into one single CPP file before compilation. You can split your program across multiple INO files at will. It makes it easier to manage, since you can split your program into logical chunks at will, but you don't have to think much beyond "which file shall I stick this function in?"

2. Create libraries

Some functionality of your program could be placed into a library or multiple libraries. This is kind of like option 1, but you have to think more about C++ syntax and suchlike that with INO files (function ordering, externs, etc). It does have the benefit that you could easily re-use code between programs, though

Personally I usually use option 2 before option 1. If a code is genericisable ("able to be made generic") then it can be made into a library - after all, I may want it later for some other program. However, if all you want to do is split your program into different chunks with each chunk a different topic or area of your program then option 1 is definitely for you.

Alternatively you might consider a different IDE, such as [UECIDE](https://uecide.org) which gives you such things as *function bookmarks&* to make navigation of your code easier.


body:
I'm building a simple mobile controlled relay switch. however, I'm out of relay modules, but I do have these esp-01 relays: https://ae01.alicdn.com/kf/HTB1VIKLeJLO8KJjSZFxq6yGEVXaW.jpg

I'm wondering if these can work with a nodemcu? So far no luck.

title: Use esp-01 relay with Nodemcu possible?

Answers: 0


body:
<!-- language-all: lang-cpp -->

    int LDR_deger = 0;

    int Ledpin1 = 12;
    int Ledpin2 = 11;
    int Ledpin3 = 10;
    int Ledpin4 = 9;
    int Ledpin5 = 8;

    int LDR_pin = 0;

    void setup()
    {

      Serial.begin(9600);
      pinMode(Ledpin1, OUTPUT);
      pinMode(Ledpin2, OUTPUT);
      pinMode(Ledpin3, OUTPUT);
      pinMode(Ledpin4, OUTPUT);
      pinMode(Ledpin5, OUTPUT);
    }
    void loop()

    {
      LDR_deger = analogRead(LDR_pin);
    digitalWrite(Ledpin1,HIGH);
    digitalWrite(Ledpin2,HIGH);
    digitalWrite(Ledpin3,HIGH);
    digitalWrite(Ledpin4,HIGH);
    digitalWrite(Ledpin5,HIGH);

    if (LDR_deger <= 80 && LDR_deger> 30) {
      digitalWrite(Ledpin1, LOW);
    } else{
      digitalWrite(Ledpin1, HIGH);
      if (LDR_deger<= 150 && LDR_deger > 80){
      digitalWrite(Ledpin2, LOW);
      digitalWrite(Ledpin1, LOW);
      }else{
        digitalWrite(Ledpin1, HIGH);
        digitalWrite(Ledpin2, HIGH);
        if (LDR_deger  <= 200 && LDR_deger> 150){
          digitalWrite(Ledpin2, LOW);
          digitalWrite(Ledpin1, LOW);
          digitalWrite(Ledpin3, LOW);
         }else{
          digitalWrite(Ledpin1, HIGH);
          digitalWrite(Ledpin2, HIGH);
          digitalWrite(Ledpin3, HIGH);
          if (LDR_deger <= 1000 && LDR_deger> 300){
          digitalWrite(Ledpin2, LOW);
          digitalWrite(Ledpin1, LOW);
          digitalWrite(Ledpin3, LOW);
          digitalWrite(Ledpin4, LOW);
          digitalWrite(Ledpin5, LOW);
         }else{
          digitalWrite(Ledpin1, HIGH);
          digitalWrite(Ledpin2, HIGH);
          digitalWrite(Ledpin3, HIGH);
          digitalWrite(Ledpin4, HIGH);
          digitalWrite(Ledpin5, HIGH);
         }
           }
         }
       }
      }
    Serial.print("LDR Deger: ");
    Serial.print(LDR_deger);
    Serial.println(" ");
    delay(500);
    }

title: Compile code error: 'Serial' does not name a type

Answers: 2

body:
One reason you are receiving the compile error, is due to the code outside of a function. When you write nice, neat, properly formatted code, these errors are easy to spot. The Arduino IDE has a built in feature that will "highlight" a matching curly bracket (or curly brace?).

[![enter image description here][1]][1]

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/G4uKq.png
  [2]: https://i.stack.imgur.com/eh5hw.png

body:
VE7JRO already has answered your question. Below is not an answer to the question but a better way to program something like you have.

In your case, you need to set 5 pins according. I assume the following lines are just for initialization (and not needed when you set them afterwards to FALSE), as I do not see any delay.

    digitalWrite(Ledpin1,HIGH);
    digitalWrite(Ledpin2,HIGH);
    digitalWrite(Ledpin3,HIGH);
    digitalWrite(Ledpin4,HIGH);
    digitalWrite(Ledpin5,HIGH);

It is much easier for each pin to set the conditions direction; this will reduce all the `if` statements and make it very clear for each pin what the value should be.

First we make some variables to prevent duplication. Actually I normally like using bool but it is not a predefined type. Also I like to have the low range on the left and the high range on the right, and using parenthesis. I added the range 200-300, and lower/upper range:

    int LDR_deger_min_inf_30 =  (LDR_deger <= 30);
    int LDR_deger_30_80      = ((LDR_deger >  30) && (LDR_deger <=   80));
    int LDR_deger_80_150     = ((LDR_deger >  80) && (LDR_deger <=  150));
    int LDR_deger_150_200    = ((LDR_deger > 150) && (LDR_deger <=  200));
    int LDR_deger_200_300    = ((LDR_deger > 200) && (LDR_deger <=  300));
    int LDR_deger_300_1000   = ((LDR_deger > 300) && (LDR_deger <= 1000));
    int LDR_deger_1000_inf   =  (LDR_deger > 1000);

Now you can create a table for each pin (which makes great documentation and a clear overview); I would add it in a comment (if you have no other documentation way):

    // pin min_inf_30 30_80 80_150 150_200 200_300 300_1000 1000_inf
    //  1     HIGH     LOW    LOW     LOW   HIGH      LOW     HIGH
    //  2     .. (fill in yourself)
    //  3     .. (fill in yourself)
    //  4     .. (fill in yourself)
    //  5     .. (fill in yourself)

Now you can write the pins one by one (I only did the first as example):

    digitalWrite(Ledpin1, LDR_deger_min_inf || LDR_deger_200_300 || LDR_deger_1000_inf ? HIGH : LOW);
    digitalWrite(Ledpin2, …);


body:
I want to measure the airspeed on a flying vehicle and get the data with arduino. Note that, there will not be any control mechanism on the flying object, it will be flying mechanicaly/passively, I mean no flight controller or something like that will be present.

However, I could not understand whether there is a sensor to measure the airspeed directly or is airspeed something you analyze by using other datas(temperature, pressure etc.)

I saw there are sensors which are sold as "airspeed sensor" however it is not so common that I cannot find examples in which the incoming data is shown.

Anybody ever experienced with this issue may lighten me.

Thanks in advance.

title: How to get air speed, which sensor to use?

Answers: 1

body: Typically you want to use Pitot tube sensor


body:
I recently purchased an ESP32-CAM but have had no luck in programming the board or getting any response whatsoever. I first tried to program it using the an FTDI programmer and the Arduino IDE (following the steps from this tutorial: https://randomnerdtutorials.com/esp32-cam-video-streaming-face-recognition-arduino-ide/).

I used this exact wiring diagram: [![wiring diagram][1]][1] but got the Timed out waiting for packet header error message. This was with the jumper on the FTDI on the 3.3V section.

Other things I've tried:
-Moving jumper to 5V, powering ESP from 5V pin
-Powering ESP from external 5V source (Arduino pin)
-Powering ESP from external 3.3V source
-Switching computers (Linux and Windows)
-Programming board directly from Arduino (bypassing FTDI)
-Various combinations of pressing/holding reset button during flash process

The other thing is that there is no LEDs that turn on when the board is powered. I couldn't find a concrete reference online that said an LED turns on when the device is on, but I assume the one LED would at least flash or something. Also monitoring the serial output with putty during boot did not yield any output. I'm all out of ideas and I am just starting to suspect that the board is completely dead. Any ideas would be appreciated, thank you.

  [1]: https://i.stack.imgur.com/eR0fn.png

title: ESP32-Cam No Response and Unable to Program - Timed out waiting for packet header

Answers: 1

body:
You're right. There is no LED when you power up your ESP32 cam. So this is normal.

Try to power it with the 5V, so you can power it from your USB instead of the 3.3V regulator of your FTDI. The ESP just need 50mA when in programming mode, so it should not be a problem for your FTDI.

Do you see anything on your serial output? Once you connect it in this way, you should set the baudrate to 115200 on your serial terminal and see some characters.

Then, try to program it.
Once you see the output "...___...", press the reset button! Since you are just connecting RDX and TDX, you have to manually press "RESET" on your ESP32 module.

At this point the ESP will reset and enter in the programming mode.


body:
I am trying to read data from an RS232 equipped sensor using a serial monitor connected to an Arduino Mega with RS-232 shield but I do not receive any data.

I am unable to detect the exact cause of the problem, as it only occurs when combining sensor and RS232shield/Arduino, while communication works as expected when testing them separately

What works:

- Connecting the sensor to a computer with a RS232-USB converter cable.
- Passing data from the computer through the USB-RS232 converter cable to RS232 shield and back through Arduino USB output.
- Connecting the RS232-pin 2 to port 10 using {SoftwareSerial} library with inverted logic.

What does not work:

- Passing data from the sensor to the computer via the MAX232 and Arduino.

The setup:

 - Arduino Mega 2560
 - Seeed RS232 shield (MAX232 based)
 - Sensor with RS232 output (57600 8N1)

I have connected the RS232 output of the sensor to the shield using an M-M gender changer. The shield and Arduino are connected with three wires: GND-GND , 5V-5V, 232_TX-RX1), and the Arduino connects to a Macbook via USB. The serial monitor on the computer is set to 56700 baud.

I use the following sketch to transfer data from the RS232 shield to Serial:

````
void setup()
{
// Open serial communications at 5700 baud
    Serial.begin(57600);
    Serial1.begin(57600);

// Check whether Serial1 is active
if (Serial1.available())
     while (!Serial1) {
        ;
    }
    Serial.println("Serial 1 is active");
}

void loop()
{
    if (Serial1.available()){
    Serial.write(Serial1.read());
    }

}
````

title: unable to read RS232 output on Arduino mega with MAX232 shield

Answers: 1

body:
I have solved the above and will share the answer as it may be of help to others:

As the Tx indicator LED on the RS232 shield would not light up when connected to the sensor, I checked the voltage difference between pin 2 (Tx) and pin 5 (GND) of the RS232 connector. This turned out to be only 5V, indicating that the protocol used is TTL-RS232 rather than 'true' RS232.

Due to the low voltage, I have connected the RS232 Tx and GND pins directly to the Arduino. With Tx connected to digital port 10, I used the SoftwareSerial library with logic inversion to read the data: `SoftwareSerial mySerial(10, 11, 1)`.

This works!


body:
I'm working on a project that makes use of a CH926 coin acceptor. The problem we're having is that when I read the serial monitor, the coin value is continuously going up and adding credits when it's supposed to remain at 0 until a coin Is fed into the acceptor.

We've tried a different coin acceptor, different codes, arduinos, wiring, resistors, breadboards, the lot. nothing seems to be solving this problem and we can't determine why, it had been working fine until we tried to tidy up our wiring and untangle it.

we're using a basic code that had worked fine up until we had the issue of the counter value no longer remaining at 0:

    const int coinpin = 2;
    const int ledpin = 3;
    const int targetcents = 100;

    // Variables
    volatile int cents = 0;
    int credits = 0;

    // Setup
    void setup() {

      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(coinpin), coinInterrupt, RISING);
      pinMode(ledpin, OUTPUT);

    }

    // Main loop
    void loop() {

      // If we've hit our target amount of coins, increment our credits and reset the cents counter
      if (cents >= targetcents) {
        credits = credits + 1;
        cents = cents - targetcents;
      }

      // If we haven't reached our target, keep waiting...
      else {
      }

      // Debugging zone
      Serial.print(cents);
      Serial.print(" cents toward current credit and ");
      Serial.print(credits);
      Serial.println(" credit(s) earned so far.");
      delay(1000);

      // Turn off LED
      digitalWrite(ledpin, LOW);

      // Now, write your own cool code here that triggers an event when the player has credits!
      if (credits > 0) {
        // Play music?
        // Spin up a motor?
        // Start a game?
        // It's up to you!
      }

    }

    // Interrupt
    void coinInterrupt(){

      // Each time a pulse is sent from the coin acceptor, interrupt main loop to add 1 cent and flip on the LED
      cents = cents + 1;
      digitalWrite(ledpin, HIGH);

    }

any advice on what may be causing this problem?

cheers

title: Counter on my coin acceptor goes up without a coin input, any advice?

Answers: 1

body: I'm also complicated by that. The advice I saw [here](https://youtu.be/vW3P6iNCblU) was to connect a COIN wire also against an electric "R" 10K and connect  to the second hole on the left in the Arduino "IOREF" now it works.


body: Is it possible to read a microSD card (on a breakout) through the USB port on the arduino? or perhaps another USB port I could attach to the breakout?  Basically, I would like to read data off the card with my laptop without having to go and remove it each time!

title: reading micro SD card directly from PC

Answers: 3

body:
It would be very useful, but afaik this is not possible, since the Arduino sketch you write communicates to the PC via the serial interface only.

The IDE/Arduino driver can use the USB to write your sketch and use the USB for communicating, but for sketches the USB (as direct medium) is not possible.

The SD card will not show up as a specific drive/map/folder on your PC.

Since you want to read the SD card, write in your sketch code to transmit the file(s) you want to send to the PC, to transfer them by UART, and on the PC write a program that reads the serial port and processes it.

body:
In general that's possible. But you can't read the sd card through the arduino's usb port. Instead you have to read the sd card via another protocol, e.g. SPI (look for the apropriate library) and send it to the pc via serial. You'll need software on the pc side to write the content that was read from the arduino to a file.

Take a look at the [SD card tutorial][1] to see how to read it.

  [1]: https://randomnerdtutorials.com/guide-to-sd-card-module-with-arduino/

body:
It can't be done with an Arduino, but it can be done with other microcontrollers. You need a microcontroller with a direct USB ("native") connection plus a USB stack that is capable of acting as a USB Mass Storage Device.  Something like the Teensy or chipKIT series of boards can do that.

Then you can write software that will, on command, detach the SD card from your normal sketch operation and re-attach it to the MSD device in the USB stack. You can then read and write to the SD card (though your sketch otherwise cannot access it) as much as you like - then "unmount" the MSD device and detach the SD card from it, at which point your sketch is then free to re-attach itself to the card and start using it again.

Note that the important thing here is that only one functionality can work at a time - either you can read and write the files on the card with your sketch, *or* you can export the device through MSD. Never both. That way leads to filesystem corruption and loss of data.


body:
I'm using Arduino UNO R3 with NodeMCU and SIM800L module. I have to connect these two devices to UNO and make a serial communication between them: UNO<>SIM800L and UNO<>NodeMCU.

Can I use GPIO0 and GPIO1 of UNO (RX, TX) to communicate with one of above devices?

Thanks in advance.

title: Arduino UNO R3 + SIM800L / NodeMCU via Hadware Serial. Possible?

Answers: 1

body:
If all you need to do is communicate between the NodeMCU and the SIM800L, what do you need the Arduino for?

Connect the SIM800L directly to the NodeMCU and program the NodeMCU to do whatever communication is needed for the SIM800L.


body:
I am using GPRS Shield for Arduino Uno with SIM900 module on it. I am able to communicate with the module just fine (using AT commands), but whenever I try to use a command which involves sim card (like AT+CCID) I get a message saying ERROR and that's it (while AT+CCID=? returns OK as it should).

So I wanted to ask can it be that I am missing out on some parameter on SIM900 module that would allow using sim card? And is it possible somehow to do a hard reset on all module's parameters (in the documentation a command ATZ is mentioned, but it doesn't seem to reset all parameters)?

Thanks in advance!

title: SIM900 module not reading Sim Card

Answers: 0


body:
noob here

So I managed to get my circuit to be a standalone circuit (as pictured below). I want to use this circuit as an input to a game on my computer. What I want to know is could this micro-usb breakout board https://www.diyelectronics.co.za/store/breakout-boards/2414-micro-usb-power-switch-breakout-module.html
 be used to communicate with the computer. Where would the data pins (d+/d-) connect to the atmega328?

Any help will be most appreciated
[![circuit ][1]][1]

  [1]: https://i.stack.imgur.com/VJKWZ.png

title: Using usb port to communicate with standalone atmega328p circuit

Answers: 1

body:
The ATmega328 does not have any native USB capability, so there is nowhere appropriate to connect D+/D- to the ATmega328.

Assuming you are emulating an Arduino Uno, then something like this:

https://www.jaycar.com.au/arduino-compatible-usb-to-serial-adaptor-module/p/XC4464

is what will come closest to mimicking the USB function on an Uno (ie a serial connection).

This shows how such a device would be connected:

https://www.jaycar.com.au/usb-serial-converter


body:
I have an arduino uno connected to my laptop.
and i need to get keypress info from the laptop's keyboard
with only the arduino sketch and without any program running on the laptop.
Is there a specific library or some way of doing so?

title: How to get keyboard input to arduino from the computer its plugged in to?

Answers: 1

body:
You can't. It's impossible.

Or not as you have requested it, anyway.

The Arduino can only talk over Serial, so you will have to have some software running on the PC that transfers data (however that data is generated) over serial to the Arduino to process.

The only other option will be to have one of the Arduino boards that is capable of acting as a USB Keyboard device, such as a Leonardo, plus either a PS/2 keyboard or a USB keyboard plus a USB Host shield. Your Arduino the receives the keystrokes from the keyboard, processes them, and sends the result on to the PC.


body:
It said it has mutiple libraries were found for "nRF24L01.h"
but i check the Ardurino libraries I can only found one.
And it work fine if I compile it to Arduino uno.
```

//Include Libraries
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//create an RF24 object
RF24 radio(8,9 );  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

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

  while (!Serial);
    Serial.begin(9600);

  radio.begin();

  //set the address
  radio.openReadingPipe(0, address);

  //Set module as receiver
  radio.startListening();
}

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

  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));

    Serial.println(text);

  }

}
```
Here is the error message
```
Arduino: 1.8.10 (Windows 8.1), Board: "STM8S103F3 Breakout Board"

Multiple libraries were found for "nRF24L01.h"
bash.exe: warning: could not find /tmp, please create!
 Used:
C:\Users\UserName\Documents\Arduino\libraries\RF24
C:\Users\UserName\AppData\Local\Arduino15\packages\sduino\tools\sdcc\build.10738/bin/sdcc sketch\receiver.ino.cpp

nul re12 -c -Ddouble=float -DUSE_STDINT -D__PROG_TYPES_COMPAT__ -E -MC -mstm8 -DSTM8S103 -DF_CPU=16000000L
-DARDUINO=10810 -DARDUINO_STM8S_BLUE -DARDUINO_ARCH_STM8
-IC:\Users\UserName\AppData\Local\Arduino15\packages\sduino\hardware\stm8\0.4.0\cores\sduino
-IC:\Users\UserName\AppData\Local\Arduino15\packages\sduino\hardware\stm8\0.4.0\variants\standard
-IC:\Users\UserName\Documents\Arduino\libraries\RF24
-IC:\Users\UserName\AppData\Local\Arduino15\packages\sduino\hardware\stm8\0.4.0/STM8S_StdPeriph_Driver/inc
-IC:\Users\UserName\AppData\Local\Arduino15\packages\sduino\tools\sdcc\build.10738/include
Mark re12:C:\Users\UserName\AppData\Local\Arduino15\packages\sduino\tools\sdcc\build.10738/bin/sdcc -c -Ddouble=float -DUSE_STDINT -D__PROG_TYPES_COMPAT__ -E -MC -mstm8 -DSTM8S103 -DF_CPU=16000000L -DARDUINO=10810 -DARDUINO_STM8S_BLUE -DARDUINO_ARCH_STM8 -IC:\Users\UserName\AppData\Local\Arduino15\packages\sduino\hardware\stm8\0.4.0\cores\sduino -IC:\Users\UserName\AppData\Local\Arduino15\packages\sduino\hardware\stm8\0.4.0\variants\standard -IC:\Users\UserName\Documents\Arduino\libraries\RF24 -IC:\Users\UserName\AppData\Local\Arduino15\packages\sduino\hardware\stm8\0.4.0/STM8S_StdPeriph_Driver/inc -IC:\Users\UserName\AppData\Local\Arduino15\packages\sduino\tools\sdcc\build.10738/include sketch\receiver.ino.cpp -o nul
cpp gefunden
In file included from C:/Users/UserName/Documents/Arduino/libraries/RF24/RF24.h:18,
                 from C:\Users\UserName\Desktop\mad\receiver\receiver.ino:4:

C:/Users/UserName/Documents/Arduino/libraries/RF24/RF24_config.h:143:30:
fatal error: avr/pgmspace.h: No such file or directory

compilation terminated.

exit status 1
Error compiling for board STM8S103F3 Breakout Board.

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

```

title: Having problems compiling this code for NRF24l01 on stm8s103f3p6

Answers: 0


body:
I want to measure Temprature, Pressure, Humidity and CO2 in a room with ESP32-CAM & [CCS811+HDC1080+BMP280][1]

Since this module is combination of 3 sensors. Can I integrate it with ESP32-CAM over Software SPI ?

  [1]: https://www.aliexpress.com/item/32871484471.html

title: ESP32-CAM interfacing with CCS811+HDC1080+BMP280

Answers: 1

body:
No. Those three devices are I2C devices, not SPI devices.

Using that is no different to using three individual sensors all wired to the same I2C bus.


body: well I am try to make an project with original arduino. but I want to make this project unique. if my codes are copied and loaded another arduino board, my app should not work. how can make unique app, are there any idea? on Arduino IDE Tools> Get Board İnfo> SN look unique id. but how can read it programmatically.

title: how to read arduino board info serial no programmatically

Answers: 1

body:
You can't. The serial number is burned into the ATMega16U2 chip and is only available to the computer over the USB interface.  There is no method for you to get it from the UART interface that connects the two MCUs together.

To stop people copying your code there are two things you need to do:

1. Don't allow anyone access to the source code or any compiled code files, and
2. Enable the "code protection" facility of the ATMega328P.

The latter will stop people being able to read the code from the Arduino. It would also be beneficial to remove the bootloader and program the board directly. That way there is no other possible route for getting at your code.

You enable code protection by setting the correct fuse bits.


body:
I'm currently working on an arduino project. Were the arduino is communicating with a NodeJS server via web sockets.

The socket connection is working fine and has no problems. But the problem I currently have is that I want to be able interupt an infinite while loop with a socket emit from the NodeJS server.

I found a page that had a solution for this problem but only with a button attached to the arduino.

[Link to page (Interrupt with button)][1]

This is the loop I want to be able to interrupt with a socket:

    bool loopRunning = true;

    void rainbow(int wait) {
    while(loopRunning == true) {

          for(long firstPixelHue = 0; firstPixelHue < 3*65536; firstPixelHue += 256) {
            for(int i=0; i<strip.numPixels(); i++) {
              int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
              strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
            }
            strip.show();
            delay(wait);
          }
        }
    }

I want to set loopRunning to false when I recieve a socket emit.

Anyone have any ides how I can implement this?

[Page to the socket functionality that I use][2]

  [1]: https://www.reddit.com/r/arduino/comments/4d7mcq/neopixel_buttoncycler_make_button_interrupt_loop/
  [2]: https://github.com/timum-viw/socket.io-client

title: Receive socket when in loop arduino (Interupt a while loop with a socket)

Answers: 2

body:
There are two ways to handle events: **interrupts** (hardware triggered) and **polling** (software triggered). Interrupts are much more efficient but also more difficult to use. SocketIoClient uses **polling.**

The necessary part of polling is... polling. That is, many times per second, you (or your library) needs to check if anything interesting is happening.

With this library, you have to call `SocketIoClient::loop()` many times a second. That's why `SocketIoClient::loop()` exists. So it needs to be added to your outer `for` loop.

(If your `delay(wait)` takes too long, you may need to break it up into a series of several shorter ones, but I think you can get away with it in this case.)

Then all you need to do is use `SocketIoClient::on()` to perform an action when an event happens. There is an example in the documentation. You will need to make loopRunning into a global variable.

body:
The problem is the while loop trapping execution.  When you have a small section of your loop that you want to stick in, you can do it two ways. You can do what you did with a while loop, that keeps execution stuck inside the while loop with nothing else happening.  Or you can let the loop function be the loop and use flags and if statements to decide what's running.

Imagine this code:

    void loop() {
      if(loopRunning){
         // do the stuff in your while loop
      }
      else {
         // all the other stuff in loop that you don't want running during that
      }
      // all the stuff you want to run regardless, like listening to your socket.
    }

When you do it like that you still get to have the stuff you were going to while loop to happen on it's own without the rest of loop, but you can also have some stuff that runs both ways.  That logic can be extended in all kinds of ways.  Maybe you want that part to always run but the rest of loop to be skipped when loopRunning is false.

    void loop(){
       //  all the stuff that should run all the time (like your socket)
       if(!loopRunning) {
           // all the stuff you would put into a while(!loopRunning) code
           // but wouldn't be able to catch the socket.
       }
    }


body:
I am trying to use a PS4 controller with my dynamixel setup using the OpenCR 1.0 board. The USB Host Shield 2.0 library is used to talk to the controller, but the current library does not support Open CR 1.0, but it does support other ARM boards. Is it easy to modify the library to talk to Open CR? My guess is that it is just the SPI pins (and other pins) that need to be redefined, but any guidance regarding the same would be great.

https://github.com/felis/USB_Host_Shield_2.0

https://github.com/ROBOTIS-GIT/OpenCR

title: Using Arduino based OpenCR with USB Host Shield 2.0 to connect to PS4 controller

Answers: 0


body:
I've got a Dotstar strip, a piano, and an UNO(w a usb host shield).
I can get and properly translate data from the piano to the UNO, so I'm definitely getting the right information to the board. When i hardcode input values into my code it reacts appropriately, so I know my code works.
However, when I attempt to take data from the USB piano keyboard and light a corresponding LED, the whole strip lights up blue and green and flashes brightly between them. This happens before I even hit a key on the keyboard.
When I hit a key, the correct light lights up for roughly a milisecond before returning to flashing green or blue.

I feel like there's some electrical concept that I'm not getting- I've got the MIDI information correctly making it to the board, and it can correctly control the LEDs. I don't know where it could be getting the data that's causing it to do this.

I think I might need a resistor- I tried to set an AND gate from the SS pin and the data pin, but that didn't do anything.
[![The best image of my wiring that I could make in Paint][1]][1]

Here's the AND gate setup I attempted.
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/1vNoI.png
  [2]: https://i.stack.imgur.com/x7yKA.png

title: Dotstar strip goes nuts when connected to MIDI piano

Answers: 1

body:
The USB host shield and the LED strip use the same SPI bus. The USB host shield has a cable select line, but the LEDs don't, so they're always listening to the bus, even when the USB shield is using it.
You'll have to add some logic gates on the data and clock lines to the LED strip to turn them on or off, depending on another cable select line for the LEDs.

`LED Clock` = NOT `LED CS` AND `SPI CLK`
`LED Data` = NOT `LED CS` AND `SPI MOSI`

If you're only using two SPI devices, you could do:

`LED Clock` = `USB CS` AND `SPI CLK`
`LED Data` = `USB CS` AND `SPI MOSI`

https://forum.arduino.cc/index.php?topic=644679.msg4363133

**Edit**: Judging from the image, you're asking the exact same question as the one I already replied to on the Arduino forum a month ago. Why do you ask the same question twice if you're not even going to reply?


body:
I am trying to convert a float value to a 4-byte hexadecimal value.

For example my input is: 58.5. My expected output is: 426A0000 or like 0x42 0x6A 0x00 0x00.

My program is:

    void setup() {
      Serial.begin(9600);
      float z = 128;
      unsigned i;
      unsigned char *chpt;
      chpt = (unsigned char *)&z;
      Serial.print("Float Value             : ");
      Serial.println(z);
      Serial.print("4 Byte hexadecimal Value: ");
      for (i = 0; i < sizeof(z); i++) {
        Serial.print(chpt[i],HEX);
        //Serial.print(" ");
      }
      Serial.println();
    }
    void loop() {
    }

My current output is:

`Float Value             : 128.00`

`4 Byte hexadecimal Value: 00043`

title: Convert float to hexadecimal value

Answers: 1

body:
This value looks pretty correct to me. It is stored in little endian thou.

0x43000000 is the actual value.

`Serial.print(x, HEX)` truncates leading zeros. so `00` gets `0`
So your output is `0 0 0 43` which corresponds to the little endian representation of the above.

Make yourself familiar with the floating point representation IEEE-754.

Also try the online [FoatConverter][1].

Try the following:

    char floatString[9];
    sprintf(floatString, "XXxx", chpt[3], chpt[2], chpt[1], chpt[0]);
    floatString[8] = '\0';
    Serial.print(floatString);

  [1]: https://www.h-schmidt.net/FloatConverter/IEEE754.html


body:
I use Arduino Mega 2560 to send a file stored in a micro sd by a module "Micro SD adapter" to ftp server. I use the sim800l evb v2.0 module and I proceeded as follows:

I insert the AT command :

    AT+SAPBR=3,1,"CONTYPE","GPRS"

    AT+SAPBR=3,1,"APN","internet"

    AT+SAPBR=1,1

    AT+FTPCID=1

    AT+FTPTYPE="I"

    AT+FTPMODE=0

    AT+FTPSERV="197.158.86.105"

    AT+FTPPORT=42

    AT+FTPUN="user"

    AT+FTPPW="password"

    AT+FTPPUTNAME="test.txt"

    AT+FTPPUTPATH="/"

    AT+FTPPUT=1

Results :

    +FTPPUT:1,62

sometimes `+FTPPUT:1,63`
or `+FTPPUT:1,64`
or `+FTPPUT:1,65`
or `+FTPPUT:1,78`

what do I have to do. Please, can anyone help me? thank you

title: How to upload file from SD card by Micro SD adapter to ftp server using Filezilla?

Answers: 0


body:
I am using the BNO055 IMU and the Adafruit Library.
I want to store the calibration data and load them after the microcontroller is powered off and repowered on.
The Adafruit Library provides an example for storing and restoring but, in actual facts, it does not work. It is always required to recalibrate the magnetometers, but even doing so, the library reperform the whole calibration including the accelerometers.

I would like to simply restore all the calibration data (including the magnetometers) so that no calibration needs to be performed when the IMU starts.

I have read a massive amount of posts on the argument, but I really could not figure out how to reliably load all the calibration data at boot and avoid recalibrating them.

Is there anyone who succeeded and can please share the code?

title: Reliably reloading the calibration data of IMU BNO055

Answers: 1

body:
I found the solution. It is enough to add a function that when reperfoming the calibration of the magnetometer, checks ONLY if the magnetometer is calibrated (while the calibration for the accelerometer and gyroscope is reloaded from the EEPROM).

    void performMagCal(void) {
      uint8_t system, gyro, accel, mag;
      system = gyro = accel = mag = 0;

      while (mag != 3) {

        bno.getCalibration(&system, &gyro, &accel, &mag);
        displayCalStatus();
        Serial.println("");
      }

      Serial.println("\nMagnetometer calibrated!");
    }


body:
I am simply using the following code

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      // set the data rate for the HardwareSerial port
      Serial2.begin(115200);
    }

    void loop() {
      while (Serial2.available() > 0)
        Serial.write(Serial2.read());
    }

the Connection is as follows
pin 16(D27) of esp32 - > Tx of Neo6M
pin 17(D14) of esp32 - > Rx of Neo6M

Now I am not getting any data in the serial monitor. The same module works with arduino with software serial.
I am completely new in this thing and office is keep asking about the progess.

title: esp32 with Neo6M gps gives no data

Answers: 0


body:
I found a couple old calculators and their LCD's have about 130 pins.

I was wondering if I can build an LCD driver to reduce the number of I/O pins, because I don't want to use like 14 I/O extenders; or can I make 1 huge extender?

title: Can you use a 128 pin LCD on an atMega?

Answers: 1

body:
This answer assumes that each LCD segment is controlled by a separate pin (see comment of Juraj).

With a 74HC595 (shift register) you can use SPI to control 8 outputs.
You can daisy chain 4 of them to get 32 outputs with just the SPI pins, to get 128 pins. I assume two pins are for GND and VCC. If you need more than 128 GPIO output pins, than use 5 or more sets of daisy chained shift registers.

Now, since these shift registers use SPI, you can use the slave select to use multiple sets of daisy chained shift registers. I never tried this myself though.

The pins (except GND/VCC) you use is:

- 3 SPI pins (MISO, MOSI, CLK)
- 4 SS pins (one for each set of 4 daisy chained shift registers)

The idea is:

1. Set SS pin to the first set of 4 shift registers
2. Write 32 outputs for the first 32 segment output pins (using the 4 shift registers of the first set)
3. Set SS pin to the next set of 4 shift registers
4. Write 32 outputs for the next set
5. Continue with the next 2 sets (so you can use 32 * 4 = 128 pins)
6. In the next cycle, start with step 1 again


body:
I'm new here. I have tried to write a simple code to turn LED's and light them up in specific pattern and being able to switch it off while in loop. So far I've managed to either get them constantly flashing in pattern and not responding to button or when I wrote in seperate void loops each function IDE Arduino throwing me error 'expected 'while' before 'loop1'' and I'm completely stuck and not got a clue what's the problem with code. Anyone could help?

Here's a code:

    const int ledPin =  2;
    const int ledPin1 = 3;
    const int ledPin2 = 4;
    const int buttonPin = 5;

    int programState = 0;

    int buttonState;
    long buttonMillis = 0;
    const long intervalButton = 300;

    long ledMillis = 300;
    const long intervalLed = 500;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(ledPin1, OUTPUT);
      pinMode(ledPin2, OUTPUT);
      pinMode(buttonPin, INPUT);
      digitalWrite(buttonPin, HIGH);
    }

    void loop()
    {
      unsigned long currentMillis = millis();
      buttonState = digitalRead(buttonPin);

     if (buttonState == LOW && programState == 0)
      do{
       programState = 1;
        }
    void loop1(){
    if {programState = 1 && buttonState == HIGH}
     do  {
       programState = 2;
        ledMillis = currentMillis;
        digitalWrite(ledPin, HIGH);
        delay(200);
        digitalWrite(ledPin1,HIGH);
        delay(200);
        digitalWrite(ledPin2,HIGH);
        delay(200);
        digitalWrite(ledPin2,LOW);
        delay(200);
        digitalWrite(ledPin1,LOW);
        delay(200);
        digitalWrite(ledPin,LOW);
        delay(200);
        digitalWrite(ledPin,HIGH);
        delay(200);
        digitalWrite(ledPin1,HIGH);
        delay(200);
        digitalWrite(ledPin2,HIGH);
        delay(200);
        digitalWrite(ledPin2,LOW);
        delay(200);
        digitalWrite(ledPin1,LOW);
        delay(200);
        digitalWrite(ledPin,LOW);
        delay(1500);}
     }
     void loop2(){
     if (programState = 2 && buttonState == LOW)

     do {
      programState = 2;
        digitalWrite(ledPin, HIGH);
        delay(200);
        digitalWrite(ledPin1,HIGH);
        delay(200);
        digitalWrite(ledPin2,HIGH);
        delay(200);
        digitalWrite(ledPin2,LOW);
        delay(200);
        digitalWrite(ledPin1,LOW);
        delay(200);
        digitalWrite(ledPin,LOW);
        delay(200);
        digitalWrite(ledPin,HIGH);
        delay(200);
        digitalWrite(ledPin1,HIGH);
        delay(200);
        digitalWrite(ledPin2,HIGH);
        delay(200);
        digitalWrite(ledPin2,LOW);
        delay(200);
        digitalWrite(ledPin1,LOW);
        delay(200);
        digitalWrite(ledPin,LOW);
        delay(1500);}

     else if  (programState == 2 && buttonState == HIGH)
     do
       {

        digitalWrite(ledPin, LOW);
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
      }
    }
    yield();
    }

title: Multiple Loops to control on and off LEDs

Answers: 2

body:
You are using the `do` function wrongly:

Like this:

    do{
      programState = 1;
    }

It should be something like:

    do
    {
      programState = 1;
    } while (`some condition`);

Where `some condition` is a condition that repeat the parts in { and } in case `some condition` is true.

However, besides that, it does not make sense normally to assign a variable in a while loop as only statement, since it will be 1 after the first iteration and reassigning it again does not make the value different (`programState` stays at 1).

Also note that in most cases the following form is used (unless you always want the body to be executed at least once):

    while (`some condition`)
    {
      `statements`
    }

Are you sure you need the `do` or `while` statement at all? Otherwise, try to remove the `do` statements and see if that is closer to what you need (I cannot map the code to your requirements). I have the feeling you want to use loops to prevent a lot of code duplication, for that you need to store the `ledPin`, `ledPin1` and `ledPin2` variables in an array and loop over them.

Another way is instead of e.g. the following code:

    digitalWrite(ledPin, HIGH);
    delay(200);

to create a separate function:

    void setPin(int pin, int value)
    {
       digitalWrite(pin, value);
       delay(200);
    }

and call the function by:

    setPin(ledPin, HIGH);

Now you can change all occurences of 'digitalWrite(`some pin`, `some state`); delay(200)' to the single statement above.

Also, I see there is a function `yield` that is not implemented.

body:
In addition to using the `do` construct incorrectly, you are also using an approach that won't work.

You generally should not use a do-while statement in Arduino. That causes your code to "stick" in the body of the do-while statement while the `while` condition is true, which prevents the rest of your code from executing.

You also should not use the `delay()` function if you need to manage timing different things at the same time. (To make a more general statement, you should not use the `delay()` function **at all**. Forget it exists.) There are rare cases (like doing one-time setup of hardware in your `setup()` method.) where using the `delay()` function is appropriate, or **very** short intervals like timing ultrasonic pulses, but the `delay()` function ALWAYS causes your program to come to a complete halt until the delay interval has passed.

You should search on "Arduino blink without delay" and study the example project you find. It outlines how to use the `millis()` function to keep track of timing. With that approach you can time multiple things at the same time. (You'd have multiple "fire time" variables that would remember the `millis()` value at which you want a change to occur, and you get that value of `millis()`, your code would trigger the change (toggling an LED, for example) and then update that "fire time" variable.