body:
I have been working on my project but I get an error and I need some advice or correction.

I use I2C method to communicate between master and slave. I've got two questions:

1. I send 7 inputs (from master) to the slave but only receives 6
2. Will my coding make an output like [this video][1]

  [1]: https://youtu.be/BSGmdM2NbQk

**Master Code**

    // Master Code
    #include <Wire.h>
    byte nChar =0;
    char input[7];

    void setup () {

      Serial.begin(9600);
      Wire.begin();
    }

    void loop()
    {
      if (nChar < 7) {if (Serial.available()) { input[nChar++] = Serial.read();}}

        else {

          Wire.beginTransmission(1);

          //a
          Wire.write(input[0]);
          Serial.print("Drawer : ");
          Serial.println(input[0]);

          //x
          Wire.write(input[1]);
          Serial.print("Output : ");
          Serial.println(input[1]);

          //00
          Wire.write(input[2]);
          Wire.write(input[3]);
          Serial.print("Output : ");
          Serial.print(input[2]);
          Serial.println(input[3]);

          //y
          Wire.write(input[4]);
          Serial.print("Output : ");
          Serial.println(input[4]);

          //00
          Wire.write(input[5]);
          Wire.write(input[6]);
          Serial.print("Output : ");
          Serial.print(input[5]);
          Serial.println(input[6]);

          delay(15);

          while (Serial.available())
          {
            //Remove extra
            Serial.read();
          }
          Wire.endTransmission();
            nChar = 0;
        }
      }

**Slave Code**

    #include <Wire.h>
    byte ledPins[] = {12, 11, 10, 9, 8, 7, 6};
    byte ledPins2[] = {12, 11, 10, 9, 8, 7, 6};
    byte count;
    byte nChar;
    char c;
    char input[8];
    char data[30] = "";
    int n;
    #define nBits sizeof(ledPins)/sizeof(ledPins[0])
    #define nBits sizeof(ledPins2)/sizeof(ledPins[0])

    void setup()
    {
      Wire.begin(1);
      Serial.begin(9600);
      for (byte i = 0; i < nBits; i++) {
        pinMode(ledPins[i], OUTPUT);
      }
    for (byte i = 0; i < nBits; i++) {
        pinMode(ledPins2[i], OUTPUT);
        }
      Serial.begin(9600);
    }

    void loop()
    {
      if (nChar < 8) {                    //accumulate three characters
        if (Serial.available()) {
          c = Serial.read();
          input[nChar++] = c;
        }
      }
      else {
        input[8] = 1;                   //atoi() expects string terminator
        n = atoi(input);                //convert the input characters to integer
        dispBinary(n);
        delay(100);                     //wait for any additional characters
        while (Serial.available()) {    //ignore them
          c = Serial.read();
        }
        nChar = 1;
      }
    }

    void receiveEvent(int howMany)
    {
      while (1 < Wire.available()) {
        char c = Wire.read();
        Serial.print(c);
      }
    }

    void dispBinary(int n) //Vertical
    {
      if (n >= 0 && n <= 5) {
        for (byte i = 0; i < nBits; i++) {
          digitalWrite (ledPins[i], n & 1);
          n /= 2;
        }
      }
    }

    void dispBinary2(int n) //Horizontal
    {
      if (n >= 0 && n <= 5) {
        for (byte i = 0; i < nBits; i++) {
          digitalWrite (ledPins2[i], n & 1);
          n /= 2;
        }
      }

    }

    void b()
    {
      if (data[0] != 'a')
      {
        dispBinary(atoi("00"));
        delay(100);
        dispBinary2(atoi("00"));
        delay(100);
        goto fin;
      }
      if (data[1] = 'x')
      {
        char xdata[2] = {data[2], data[3]};//(data[2], data[3]);
        dispBinary2(atoi(xdata));
        delay(100);
      }
      if (data[4] = 'y')
      {
        char ydata[2] = {data[5], data[6]};//(data[5], data[6]);
        dispBinary(atoi(ydata));
        delay(100);
      }

    fin:;
    }

title: I2C communication is not working

Answers: 1

body:
Most coders would your `while (1 < Wire.available()) {` write as `while ( Wire.available() > 1) {` and read it "repeat while there is more the 1 byte available". but wait, why leave that one byte there? you want "repeat while there is no more byte available".

you need `while (0 < Wire.available())`


body:
 Im quite new to arduino in general and i'm sorry for the beginner question.

could someone explain what the 3.3v and 5v on boards do? I know their voltages. but can you run one on the other? whenever i try to search about it i see people saying that most newer modules are running on 3.3v so they convert their 5v arduino to 3.3v. something about if you run one on the other it could break it.

the arduino I [bought][1] looks like it has both! is that even possible?

 I also [purchased][2] this LED matrix as I wanted to make a wifi enabled scrolling text display. the matrix says it requires 5v. since this arduino says vin is 5-12v the two should connect and work properly, right?

  [1]: http://a.co/d/20ajP2o
  [2]: http://a.co/d/gLlisJn

title: Difference between 3.3v & 5v

Answers: 2

body:
The difference for different voltage boards lies in the parts, that are soldered on it. Often microcontrollers support more than one supply voltage, but impose different performance limits on the system. Take for example the Arduino Uno: It uses the Atmega328p, which can run both on 3.3V and 5V. But on the UNO there is a 16MHz quartz, which generates the controllers clock signal. The Atmega328p cannot run 16MHz with only 3.3 volts. To run a board on a voltage, for which it wasn't directly build, mostly requires you to resolder it with the correct parts.

---

> whenever i try to search about it i see people saying that most newer modules are running on 3.3v so they convert their 5v arduino to 3.3v

There are special chips, called voltage regulators/converters. They come with various working principles, but basically they are converting one voltage to another. The Arduino Uno has one connected to Vin, so that you can apply between 7V and 12V to Vin and the Arduino itself will only see the 5V it get's from the regulator. Some modules also have a voltage regulator, but not all. Be careful not to provide more than the specified voltage to any board or you may destroy it.

---

> the arduino I bought looks like it has both! is that even possible?

First, as Juraj wrote, this is not an Arduino. It is an ESP8266, a totally different chip and board. But you can also program it through the Arduino IDE, without it being an Arduino. Second: When they write, that you can provide it with either 3.3V or 5V, they mean, that you can provide 5V through the USB jack and a voltage regulator will convert it to 3.3V for the ESP, which runs completely on 3.3V. You should not connect 5V to any other pin.

---

> since this arduino says vin is 5-12v the two should connect and work properly, right?

As stated above the 12V is only, what you can at maximum provide at Vin. The ESP8266 runs on 3.3V, so you will have to provide 3.3V (or more over the Vin pin). The LED matrix runs at 5V, as you stated. So you need a 5V source and a level shifter for the 2 lines between the ESP8266 and the matrix. If you connect them directly, you would damage the ESP8266. So: No, you cannot use it directly. It is up to you, if you want to use a level shifter or buy another matrix display, which can be controlled by a 3.3V signal.

body:
As seen in the OEM data sheet for the MAX7219
https://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf
the MAX7219 needs a supply voltage of 4 to 5.5V.
with a minimum signal voltage for High of 3.5V when Vcc = 5V.

Folks often get counterfeit parts from e-bay or elsewhere, with unknown characteristics.

For best results, I would power the '7219 from 5V, and use a buffer chip powered from 5V, such as 74AC125,
http://www.onsemi.com/pub/Collateral/MC74AC125-D.PDF
which will take ~ 2.5V with Vcc = 5V
to boost the ~3V output from the ESP2855 to 5V levels.


body:
My project uses ESP8226 to allow:
    1) user to set an alarm.
    2) after 20 sec of the alarm ringing, it will notify to phone via blynk app using motion sensor.
    3) after 40 sec it will turn off sensor and will not send notification
       again.
There are two problems that I have:

 - Got error with coding (digitalRead(nilai_sensor, LOW);) "too many arguments to function 'int digitalRead(uint8_t)"
 - I need help with coding for turn off the sensor and
   will not nofify again.

Below is my Arduino code:

    #define BLYNK_PRINT Serial
    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    #include <TimeLib.h>
    #include <WidgetRTC.h>
    BlynkTimer timer;
    WidgetRTC rtc;
    WidgetLED led1(V10);
    // You should get Auth Token in the Blynk App.
    // Go to the Project Settings (nut icon).
    char auth[] = "a7d4522186464dd297870f2ab8e53250";

    // Your WiFi credentials.
    // Set password to "" for open networks.
    char ssid[] = "NabiL";
    char pass[] = "limaringgitlimapuluhsen";
    int flag = 0;
    int buzzer = 12;
    int motor = 13;
    int sensor = 4;

    int saat;
    int on_delay;
    int off_delay;
    int ok_delay;

    int get1 = 0;
    int get2 = 0;
    int nilai_sensor = 0;

    void blinkLedWidget()
    {
      if (led1.getValue()) {
        led1.off();
        Serial.println("LED on V1: off");
      } else {
        led1.on();
        Serial.println("LED on V1: on");
      }
    }

    void clockDisplay()
    {
      // You can call hour(), minute(), ... at any time
      // Please see Time library examples for details

      String currentTime = String(hour()) + ":" + minute() + ":" + second();
      String currentDate = String(day()) + "/" + month() + "/" + year();
      Serial.print("Current time: ");
      Serial.print(currentTime);
      Serial.print("Current Time: ");
      Serial.print(currentDate);
      Serial.println();

      // Send time to the App
      Blynk.virtualWrite(V1, currentTime);
      // Send date to the App
      Blynk.virtualWrite(V2, currentDate);
    }

    BLYNK_CONNECTED() {
      // Synchronize time on connection
      rtc.begin();
    }
    BLYNK_WRITE(V5) // Timer
    {
      Serial.println(param.asStr());

      if (param.asInt())
      {
        on_delay = saat + 20;  //20Saat
        off_delay = saat + 10;  //10Saat
        ok_delay = saat + 40;  //40Saat

        digitalWrite(buzzer, HIGH);
        digitalWrite(motor, HIGH);
      }
    }
    BLYNK_WRITE(V6) // Timer
    {
      Serial.println(param.asStr());

      if (param.asInt())
      {
        on_delay = saat + 20;  //20Saat
        off_delay = saat + 10;  //10Saat
        ok_delay = saat + 40;  //40Saat

        digitalWrite(buzzer, HIGH);
        digitalWrite(motor, HIGH);
      }
    }
    BLYNK_WRITE(V0){
      Serial.println(param.asStr());

      if (param.asInt())
      {

        digitalWrite(buzzer, HIGH);
        digitalWrite(motor, HIGH);

      }
      else

      {
        digitalWrite(buzzer, LOW);
        digitalWrite(motor, LOW);

      }
    }
    BLYNK_WRITE(V12){
      Serial.println(param.asStr());

      if (param.asInt())
      {

        digitalWrite(buzzer, HIGH);
      }
      else

      {
        digitalWrite(buzzer, LOW);
      }
    }
    BLYNK_WRITE(V13){
      Serial.println(param.asStr());

      if (param.asInt())
      {

        digitalWrite(motor, HIGH);
      }
      else

      {

        digitalWrite(motor, LOW);
      }
    }
    void setup()
    {
      // Debug console
      Serial.begin(9600);
      Blynk.begin(auth, ssid, pass);
      setSyncInterval(10 * 60); // Sync interval in seconds (10 minutes)

      // Display digital clock every 1 seconds
      timer.setInterval(1000L, clockDisplay);
    timer.setInterval(1000L, blinkLedWidget);
      // Setup notification button on pin D1

      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(4, INPUT);

    }
    void loop()
    {
      saat = millis() / 1000;

      if(saat == off_delay)
      {
        digitalWrite(buzzer, LOW);
        digitalWrite(motor, LOW);
      }

       if(saat == on_delay)
      {
        Serial.println("Time Up");
        get1 = 1;
      }

         if(get1 == 1)
        {
         Serial.println("Program Sensor");

       nilai_sensor = digitalRead(sensor);

        if(nilai_sensor == HIGH)
        {
          Serial.println("Still sleeping");
         Blynk.notify("Still sleeping");

        //delay(5000);
       }
      }

    if(saat == ok_delay)
      {
        Serial.println("Shut Down Sensor");
        get2 = 1;
      }
     if(get2 == 1)
      {
        Serial.println("turn off Sensor");
        nilai_sensor = digitalRead(sensor);
       digitalRead(nilai_sensor, LOW);

      }

      Blynk.run();
      timer.run(); // Initiates BlynkTimer

    }

title: ESP8266 too many argument to function

Answers: 1

body:
The function [`digitalRead()`][1] has only one argument: the digital pin that you want to know the state (_high_ or _low_).

You must change the use of this function, to something like this:

    int state = digitalRead(nilai_sensor)

    if (state == low) {
        //do something here
    }

Hope you can find helpfull :D

  [1]: https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/


body:
I am going through an Arduino Learning Book(978-1-59327-448-1) and I've run into the same issue twice now.

When I enter data into the serial monitor, the number that it reads and displays(when asked to print) is way different than what I'm entering.

In diagnosing the problem, I went to https://www.arduino.cc/en/Serial/Read
Copied the code into a new sketch, and tried to run it.
When I Enter 0, I get 48, and a second line saying 10. Enter 1, I get 49 and 10, etc. Here are the results when I enter 0, then 1, then 2, then 3

I received: 48
I received: 10

I received: 49
I received: 10

I received: 50
I received: 10

I received: 51
I received: 10

here is the code I'm using

    int incomingByte = 0;   // for incoming serial data

    void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
    }

    void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, DEC);
        }
    }

I have the serial monitor set to 9600.
All sketches have worked fine so far, including those that use Serial.print functions, but when I use Serial.read, things seem to get screwed up.

I'm sure I'm missing something stupid, but I've googled around and all the answers are much higher level than just trying to run the code in the Arduino.cc example

Thanks in advance for helping a first timer!

PS: I Tried to get all of the code into the grey box with various line spacing and indenting strategies, but it's not perfect. Does anyone have any tips on that?

title: Serial monitor returns "48" when I enter "0"

Answers: 2

body:
>                Serial.println(incomingByte, DEC);

You told it to print the incoming byte in decimal, so that is what it did. 48 is the decimal equivalent of ASCII '0'.

Change that line to:

    Serial.println((char) incomingByte);

That casts the thing you are printing to a character, and then the appropriate version of Serial.println prints it as a character, not a decimal number.

---

10 is the decimal equivalent of a new line (newline) so that is why you are also seeing 10 printed.

---

>  I need to convert the incoming stuff into integers so that it can see if im guessing right or not

Assuming you mean an integer other than 0 to 9 (like, 42 for example) then you need a bit more work. I have a page about that sort of thing:

http://www.gammon.com.au/serial

Example code:

<!-- language: lang-c++ -->

    /*
    Example of processing incoming serial data without blocking.

    Author:   Nick Gammon
    Date:     13 November 2011.
    Modified: 31 August 2013.

    Released for public use.
    */
    // how much serial data we expect before a newline
    const unsigned int MAX_INPUT = 50;

    void setup ()
      {
      Serial.begin (115200);
      } // end of setup

    // here to process incoming serial data after a terminator received
    void process_data (const char * data)
      {
      // for now just display it
      // (but you could compare it to some value, convert to an integer, etc.)
      Serial.println (data);
      }  // end of process_data

    void processIncomingByte (const byte inByte)
      {
      static char input_line [MAX_INPUT];
      static unsigned int input_pos = 0;

      switch (inByte)
        {

        case '\n':   // end of text
          input_line [input_pos] = 0;  // terminating null byte

          // terminator reached! process input_line here ...
          process_data (input_line);

          // reset buffer for next time
          input_pos = 0;
          break;

        case '\r':   // discard carriage return
          break;

        default:
          // keep adding if not full ... allow for terminating null byte
          if (input_pos < (MAX_INPUT - 1))
            input_line [input_pos++] = inByte;
          break;

        }  // end of switch

      } // end of processIncomingByte

    void loop()
      {
      // if serial data available, process it
      while (Serial.available () > 0)
        processIncomingByte (Serial.read ());

      // do other stuff here like testing digital input (button presses) ...

      }  // end of loop

In this example, the function `process_data` is called when there is a complete number to be handled.

body:
You can use `Serial.parseInt()` to read a number sent from Serial Monitor. [parseInt][1] waits for all numeric characters of the sent text, so it blocks the execution of your sketch for a very short time until all characters are received. At higher baud rate it will be faster. If your sketch doesn't need to loop as fast as possible, then you can use it. `parseInt` stops at first character that is not a digit (for example a newline character) and returns the received number as long.

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

    void loop() {
      if (Serial.available() > 0) {
        long number = Serial.parseInt();
        Serial.println(number);
      }
    }

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/parseint/


body:
I wanted to move most functionality of my sketch into different classes, to keep things better organized. One class worked just fine, but when I had to use multiple classes and pass information between then things stopped working.

I have two classes, my main Remote class, and my RemoteDisplay class. The main class takes care of fx, measuring battery voltage and I want to display this through the RemoteDisplay class. To do so I initiate the Display class with a pointer to the Remote class, so I can access the voltage function. This, however, doesn't work, even though I forward declare the Remote class in the Display class.

**Remote.ino**

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

    #include "Remote.h"

    Remote Remote;

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

    void loop() {
      Remote.display.showBattery();
    }

**Remote.h**

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

    #include "RemoteDisplay.h"
    class Remote
    {

    public:

   RemoteDisplay display;

   Remote( void );

   float voltage;

    };

**Remote.cpp**

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

    #include "Remote.h"

    Remote::Remote(void)
    {
      display.initiate(this);
    }

**RemoteDisplay.h**

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

    class Remote;

    class RemoteDisplay
    {

    public:

   RemoteDisplay(void);

   void initiate( Remote * _pointer );

      void showBattery( void );

    private:

   /* Reference to the remote class */
   Remote * pointer;
    };

**RemoteDisplay.cpp**

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

    #include "RemoteDisplay.h"

    void RemoteDisplay::initiate( Remote * _pointer )
    {
      pointer = _pointer;
    }

    void RemoteDisplay::showBattery( void )
    {
      Serial.println( pointer->voltage );
    }

I get the errors:

    error: invalid use of incomplete type 'class Remote'
    showBattery( pointer->voltage() );

    note: forward declaration of 'class Remote'
    class Remote;

Why is it so? Any help is much appreciated.

title: Sketch with multiple classes (.h and .cpp) - how to interconnect classes

Answers: 1

body:
In RemoteDisplay.cc you are using Remote in the Initiate method.

Also, since you use the voltage property, you need to include "Remote.h" within (as first line normally) in RemoteDisplay.cpp.

Also it is advised to use within every header file the following pattern (example for RemoteDisplay.h):

    #ifndef REMOTE_DISPLAY_H
    #define REMOTE_DISPLAY_H
    ...
    ...
    #endif // REMOTE_DISPLAY_H

This prevents problems that two include header files forever include each other.


body:
i'm study the Low-Power library to better undertand how it works.
In [this][1] part of code i have some question.

Sometime he uses commands like:

    power_timer1_disable();
    power_timer0_disable();

but in other part of code, example "TIMER2_OFF":

    if (TCCR2B & CS22) clockSource |= (1 << CS22);
    if (TCCR2B & CS21) clockSource |= (1 << CS21);
    if (TCCR2B & CS20) clockSource |= (1 << CS20);

    // Remove the clock source to shutdown Timer2
    TCCR2B &= ~(1 << CS22);
    TCCR2B &= ~(1 << CS21);
    TCCR2B &= ~(1 << CS20);

    power_timer2_disable();

he uses the register code and, in the end, the function.

Someone can explain to me why?

  [1]: https://goo.gl/tdofMP

title: Low-Power library question

Answers: 1

body:
It's doing basically this:

    clockSource = TCCR2B & (_BV(CS22) | _BV(CS21) | _BV(CS20)); // store prescaler
    TCCR2B &= ~(_BV(CS22) | _BV(CS21) | _BV(CS20));             // select "no source" - disable clock source
    power_timer2_disable(); // disable whole timer2 in Power Reduction Register

Definition of power_timer2_disable macro is:

    #define power_timer2_disable()  (PRR |= (uint8_t)(1 << PRTIM2))

In short, you have to turn off the clock source before the power gets cut off by PRR register (to avoid unexpected behaviour).

> **Power Reduction Register**
>
> The Power Reduction Register (PRR), provides a method to stop the
> clock to individual peripherals to reduce power consumption. The
> current state of the peripheral is frozen and the I/O registers can
> not be read or written. ***Resources used by the peripheral when stopping
> the clock will remain occupied, hence the peripheral should in most
> cases be disabled before stopping the clock.*** Waking up a module, which
> is done by clearing the bit in PRR, puts the module in the same state
> as before shutdown. Module shutdown can be used in Idle mode and
> Active mode to significantly reduce the overall power consumption. In
> all other sleep modes, the clock is already stopped.


body:
I don't have any code for this yet but I would like some ideas on coding it.
I have a directional antenna that is rotating at a slow speed and a ham radio connected to the antenna.  I have an output port on the radio that will put a voltage out from 0 to 5 volts for signal strength.  I also have the rotational degree data that is captured.  The question I have is do I try to do a long if then else statement to capture the 3 highest voltages and directions as variables for later processing or is there a better way.   An example would go a long way as well.

title: Sorting voltage data from pin A0 to 3 variables (ranked)

Answers: 1

body:
It needs a bit more work but I would suggest using arrays to store the signal and positions something like this..
From (G7WJD) EXPIRED!

    #define signalPin A0
    #define degreePin A1
    int signalStrength;
    // STORE DATA IN ARRAY
    // 0 [strength, direction]
    // 1 [strength, direction]
    // 2 [strength, direction]
    int signals[3][3];
    int degree;
    bool positionSavedFlag = false;
    void setup() {

    }

    void loop() {
     signalStrength = analogRead(signalPin);
     degree = analogRead(degreePin);
     // comapare with previous data
     for (int x = 0; x < 3; x++) {
      // have we saved data for this position before?
      if (degree == signals[x][1]) {
        // yes
        positionSavedFlag = true;
        // is it stronger than previous signal at this position
        if (signalStrength > signals[x][0]) {
          // yes so save / update it
          signals[x][0] = signalStrength;
        }
      }
     }
     // now since position not already stored , store it

     }


body:
I have a device that outputs a TX RX RS232 serial string. Is there a way I can take this locally to an Arduino and send over Wi-Fi to another Arduino?

I'm relatively new to all of this so any advice will be greatly appreciated!

title: Transmitting serial data over Wi-Fi

Answers: 1

body:
Yes, and there are many tutorials how to do it.
Most popular one uses ESP8266 module. What is even more interesting you can use ESP module as an Arduino (and yes, you can program it using Arduino IDE).


body:
I am trying to obtain Quaternion values from a BNO055 connected to ESP32-PoE board by Olimex.

## Code

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BNO055.h>
    #include <utility/imumaths.h>

    Adafruit_BNO055 bno = Adafruit_BNO055(55);

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

      if (!bno.begin()) {
        Serial.println("No BNO055 Detected!");
        while(1);
      }
      delay(100);
      bno.setMode(Adafruit_BNO055::OPERATION_MODE_NDOF_FMC_OFF);
      bno.setExtCrystalUse(true);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      imu::Quaternion quat = bno.getQuat();
      imu::Vector<3> euler = quat.toEuler();

      Serial.print("W: ");
      Serial.print(quat.w());
      Serial.print(F(" "));

      Serial.print("x: ");
      Serial.print(quat.x());
      Serial.print(F(" "));

      Serial.print("y: ");
      Serial.print(quat.y());
      Serial.print(F(" "));

      Serial.print("z: ");
      Serial.print(quat.z());
      Serial.print(F(" "));

      Serial.print("X: ");
      Serial.print((float)euler.x());
      Serial.print(F(" "));
      Serial.print("Y: ");
      Serial.print((float)euler.y());
      Serial.print(F(" "));
      Serial.print("Z: ");
      Serial.print(float(euler.z()));
      Serial.print(F(" "));
      Serial.println("");
      delay(200);
    }

### output

    W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
    W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
    W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
    W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
    W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
    W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
    W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
    W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
    W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
    W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00

The sensor seems to be working since I tried a simple script and the values are avaiable.

Is there some specific setting missing during `setup()` in order to obtain Quaternions.

### Purpose

For Absolute orientation, the Quaternion values need to be converted to Euler .

title: Quaternion values from BNO055 not available

Answers: 1

body:
Apparently in the `setup()` it is preferable to have a `delay(1000)` as opposed to `delay(100)`.

### Code

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BNO055.h>
    #include <utility/imumaths.h>
    #include <math.h>

    #define DEG (180/M_PI)

    Adafruit_BNO055 bno = Adafruit_BNO055(55);

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

      if (!bno.begin()) {
        Serial.println("No BNO055 Detected!");
        while(1);
      }
      delay(1000);
      bno.setMode(Adafruit_BNO055::OPERATION_MODE_NDOF_FMC_OFF);
      bno.setExtCrystalUse(true);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      imu::Quaternion quat = bno.getQuat();
      imu::Vector<3> euler = quat.toEuler();

    //  Serial.print("W: ");
    //  Serial.print(quat.w());
    //  Serial.print(F(" "));
    //
    //  Serial.print("x: ");
    //  Serial.print(quat.x());
    //  Serial.print(F(" "));
    //
    //  Serial.print("y: ");
    //  Serial.print(quat.y());
    //  Serial.print(F(" "));
    //
    //  Serial.print("z: ");
    //  Serial.print(quat.z());
    //  Serial.print(F(" "));

      Serial.print("Yaw: ");
      Serial.print(euler[0] * DEG);
      Serial.print(F(" "));
      Serial.print("Pitch: ");
      Serial.print(euler[1] * DEG);
      Serial.print(F(" "));
      Serial.print("Roll: ");
      Serial.print(euler[2] * DEG);
      Serial.print(F(" "));
      Serial.println("");
      delay(200);
    }


body:
After using int to display text in serial monitor, now i am trying to use string but there is something wrong.
The expected reslut is "Led1 is on" in serial monitor but what i get is "285".
This is the code involving strings.

    String(ledPin1="Led1 is on");
    Serial.println(ledPin1);

while this is the full code

    int numledPin1Blinks=5;
    int ledPin1Blinks=2;
    int i;
    int j;
    int waiTtimeoff2=1000;
    int waitTimeOn2=1000;
    int ledPin2=10;
    int ledPin1=13;
    int waiTtimeOn1=1000;
    int waiTtimeOff1=1000;
    void setup()
    {pinMode(10,OUTPUT);
    pinMode(13,OUTPUT);
    Serial.begin(9600);
    String(ledPin1="Led1 is on");

    }

    void loop()
    {Serial.println(ledPin1);
    for (i=1;i<=3;i=i+1){
    Serial.print("   You are on blink
    no#:  ");
    Serial.println(i);
    digitalWrite(ledPin1,HIGH);
    delay(waiTtimeOn1);
    digitalWrite(ledPin1,LOW);
    delay(waiTtimeOff1);}
    Serial.println(" ");

    Serial.println("Led 2 is on!");
    for (j=1;j<=4;j=j+1){
    Serial.print(" You are on blink no
    #:");
    Serial.println(j);
    digitalWrite (ledPin2,HIGH);
    delay(waitTimeOn2);
    digitalWrite (ledPin2,LOW);
    delay(waiTtimeoff2);}
    Serial.println(" ");

    }

title: using string to display text on serial monitor

Answers: 1

body:
Your syntax is incorrect. You are assigning the address of a static string literal to an integer, then using the results of that assignment (the address of the string literal, as it "falls through" to the left) to create a new String object. That `String` object is then being thrown away.

You need to create a *new* `String` variable (not re-use one that you actively use for another part of your program) and assign a string literal to it:

    String led1Message = "LED 1 is on";

Then you can print *that* variable instead:

    Serial.println(led1Message);

**HOWEVER** `String` objects are very very fragile on the Arduino and should be avoided. Forget trying to learn to use them, since you will only have to un-learn them at a later date.  Skip them and start straight away with C-strings (NULL-terminated `char` arrays).  Also learn about [`PROGMEM`](https://www.arduino.cc/reference/en/language/variables/utilities/progmem/).

For instance, the above could be written as:

    const char led1Message[] PROGMEM = "LED 1 is on";

And then use a casting to get `println` to grab it from flash:

    Serial.println((__FlashStringHelper*)led1Message);

This uses pretty much zero RAM, which on an Arduino is very important. Even more important it doesn't cause heap [fragmentation](https://en.wikipedia.org/wiki/Fragmentation_(computing)) which can cause your program to crash randomly.


body:
When I assign a global var to a certain value inside an if-block it has been changed to another value in the next statement. Somehow the address of the var is overwritten by some other process. It also does not stop at 1 value, this happens to the next vars that are assigned another value too. The vars are not defined in a row but should be close.
I already installed a newer version of Arduino IDE, no change.
Example:

    menuActive=1;
    Serial.print(menuActive);

 gives results in the range 40 to 57 as far as I have seen till now. Further actions assign always the SAME value to next vars I assign after this.
Anyone some idea what could cause this? Am I low on memory for local vars?
This is compile message:

    Sketch uses 21790 bytes (70%) of program storage space. Maximum is 30720 bytes.
    Global variables use 1454 bytes (70%) of dynamic memory, leaving 594 bytes for local variables. Maximum is 2048 bytes.

edit:

As I already said, it is 21k of code. But I show you the part of the code that mishaves:

    while ((digitalRead(rotSwPin) == 0) && lpress <= 200) {
        delay(10);
        lpress++;
        if (lpress > 200) {
            menuActive++;
            menuLvl=0;
            menuPos=0;
            subPos=0;
        }
    }

Normally I use menuActive=1. Within the braces, it is still 1, out of that it changes. Maybe change from byte to bool.

title: Nano V3 values "overwritten" randomly

Answers: 1

body:
I found the problem. I could see that the false value is the character code of the minute I am displaying. I display hours and minutes and there was a declaration that was 3 characters short for the string I got as a result for hours added to minutes. Yes, it was memory corruption. So be very careful to dimension enough places for your C-strings including 1 extra for 0. If you are not so short on RAM then a few more characters will do no harm, the end of the string will be the character before the 0 in memory.
When strange things happen start looking at this matter!


body: I'm using the [Motor Shield v2](https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/library-reference) and I'm looking for a way to automatically discover the addresses of attached motor shields.

title: How can I discover attached motor shields in code?

Answers: 1

body:
If you configure each I2C device to have a unique address, then it's easy to determine which ones are connected.

This sketch is derived from the I2C Scanner sketch found here: [I2cScanner][1]

    // This sketch tests the standard 7-bit addresses.
    // Devices with higher bit address might not be seen properly.
    #include <Wire.h>
    byte shieldOneAddress = 0x27;
    byte shieldTwoAddress = 0x32;
    byte error, address;

    void setup(){

      Wire.begin();
      Serial.begin(9600);
      Serial.println("Scanning for shields...");

      for(address = 1; address < 127; address++){

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

        if(error == 0){
          if(address == shieldOneAddress){
            Serial.println("Shield One is connected.");
          }
          if(address == shieldTwoAddress){
            Serial.println("Shield Two is connected.");
          }
        }

      }
      Serial.println("Scan complete.\n");
    }

    void loop(){}

  [1]: https://playground.arduino.cc/Main/I2cScanner


body:
I'm absolutely new to arduino, so please excuse me if this is a noob question.
I want to use a ESP8266 esp-03 Wifi module with a HC-05 bluetooth module together with my arduino uno.
Unfortunately both use the TX and RX pins on the board.
Is there a way to use both, the wifi and the bluetooth modules?
Or do I have to purchase a wifi board?

title: ESP8266 + HC-05 on same arduino

Answers: 1

body:
You can (just about) use any combination of two of:

* Serial to PC,
* HC-05
* ESP-03

You have, basically, a *hardware* UART (pins 0/1), and a *software* UART (any pins of your choice).

Only the hardware UART can be used for communication with the PC, and you can only reliably use one instance of SoftwareSerial.

So, you could:

* Use Serial to the PC (0/1) and HC-05 (SoftwareSerial, your choice of pins), or
* Use Serial to the PC (0/1) and ESP-03 (SoftwareSerial, your choice of pins), or
* Hardware Serial for ESP-03 (0/1) and SoftwareSerial for HC-05 (your choice of pins), or
* Hardware Serial for HC-05 (0/1) and SoftwareSerial for ESP-03 (your choice of pins)

If you want anything more complex than that then you need to use a board with more than one hardware Serial port (such as a Mega2560).


body:
Arduino claims to be a "language," not just an "application framework," and Arduino files have their own extension, `.ino`.  The language is obviously C++, but not quite.  My understanding is that Arduino has some sort of special preprocessor which converts `.ino` files into C++ files before compiling them.

My question is: What *exactly* does this preprocessor do?  What exactly are the differences between "Arduino language" and real C++?  The Arduino documentation seems to gloss over this.

In particular, I've had weird things happen when I try to define my own classes in my sketch.  It's hard to figure out what I'm doing wrong when the language doesn't seem to be specified anywhere.

title: What exactly does the Arduino preprocessor do?

Answers: 2

body:
It does four things, basically:

1. It adds `#include <Arduino.h>` to the top of your file, which gives you access to all the classes, functions and defined variables/macros of the API.
2. It joins together all the INO files together into a single monolithic file (in the same order as the tabs in the window),
3. It matches `#include` entries with libraries and adds the files in those libraries to the list of files to compile, and
4. It scans through the ino file(s) looking for functions and adds prototypes to them to the top of your file.

It's the latter that can cause problems. Historically it never got the prototypes in the right place, and if you ever passed a structure of your own devising to a function it would break horribly.  It does a better job these days, but it's still not 100% perfect.

It basically means that you don't have to adhere to the "You must define it before you use it" rule of C/C++.  Which of course makes for lazy programmers.

body:
See [my answer: How the IDE organizes things](https://arduino.stackexchange.com/a/13182/10794)

I'm not sure if link-only answers which refer to a Stack Exchange link are OK. In case they are not, here is the first part of that answer:

## This is how the IDE organizes your "sketch":

* The main `.ino` file is the one of the same name as the folder it is in. So, for `foobar.ino` in `foobar` folder - the main file is foobar.ino.
* Any other `.ino` files in that folder are concatenated together, in alphabetic order, at the end of the main file (regardless of where the main file is, alphabetically).
* This concatenated file becomes a `.cpp` file (eg. `foobar.cpp`) - it is placed in a temporary compilation folder.
* The preprocessor "helpfully" generates function prototypes for functions it finds in that file.
* The main file is scanned for `#include <libraryname>` directives. This triggers the IDE to also copy all relevant files from each (mentioned) library into the temporary folder, and generate instructions to compile them.
* Any `.c`, `.cpp` or `.asm` files in the sketch folder are added to the build process as separate compilation units (that is, they are compiled in the usual way as separate files)
* Any `.h` files are also copied into the temporary compilation folder, so they can be referred to by your .c or .cpp files.
* The compiler adds into the build process standard files (like `main.cpp`)
* The build process then compiles all the above files into object files.
* If the compilation phase succeeds they are linked together along with the AVR standard libraries (eg. giving you `strcpy` etc.)

A side-effect of all this is that you can consider the main sketch (the .ino files) to be C++ to all intents and purposes. The function prototype generation however can lead to obscure error messages if you are not careful.


body:
I am making an alarm clock using a 4x20 lcd display, rtc, and Arduino Pro Mini 3.3v. I have implemented a menu system for setting the time/date that blinks the text on the lcd display to indicate that I have it selected, but the blinking randomly stops and the Arduino stops printing to the serial after about ten seconds.

After much head scratching and Googling I came to the conclusion that all my lcd.print() lines were using up all my ram. I tried to create PROGMEM variables to use in the print commands, but I couldn't get it to work so I ended up just adding the F() macro to every print statement (there's a lot). This now prints everything as expected, but the Arduino still freezes up after the same amount of time. Am I using F() wrong or is the problem something else like power???

Visual Studio code says I am using 643/2048 bytes of data/ram and 14960/30720 bytes of flash when I upload the code. (that is with the F() macro implemented)

--------------EDIT----------------

So I've created a small test sketch to use with the same circut, and now I'm really confused. I've been running it for about an hour now and it is still not freezing. The script blinks a full screen of number signs every 200ms. The backlight is on and everything is still powered the same way. This, in theory, rules out both running out of ram and not providing enough power. Any other ideas?

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

    LiquidCrystal_I2C lcd(0x27,20,4);
    RTC_DS3231 clock;

    void setup() {
        Serial.begin (9600);
        lcd.init();
        clock.begin();
        clock.adjust (DateTime (__DATE__, __TIME__));
        lcd.backlight();
    }

    bool on = true;

    void loop() {
        lcd.setCursor (0, 0);

        if (on) {
            for (int i = 0; i < 4; i++) {
                lcd.setCursor (0, i);
                for (int j = 0; j < 20; j++) {
                    lcd.print ("#");
                }
            }
        }
        else {
            for (int i = 0; i < 4; i++) {
                lcd.setCursor (0, i);
                for (int j = 0; j < 20; j++) {
                    lcd.print (" ");
                }
            }
        }

        on = !on;
        delay (200);
    }

title: LDC paired with Arduino locks up and freezes. Out of SPRAM?

Answers: 1

body: I found the problem! it was specific to my code and didn't turn out to have anything to do with ram or power. The problem was I hadn't detached the interrupt from the rtc when I woke it up with a button. It would freeze seemingly randomly because the rtc would fire an interrupt signal when the next minute ticked, while the arduino was awake. I guess it causes problems when you try to interrupt arduino's sleep and it's not actually sleeping. All I had to do was detach both interrupts when the button is clicked. Thank you all for your help :)


body:
Assume you have an Arduino Uno board, the board is connected to some sensors, maybe a stepper motor or something, it does not matter.

How to get feedback or diagnostics or something that all the things are working, or if not then get feedback that are not working?

title: How to get a feedback that something connected to an Arduino is working?

Answers: 2

body:
To expand on Juraj's answers, tackle this question from the user's point of view. What does *all things are working* mean for them? Does the temperature you read from a sensor have to be within .2C of a reference value? The stepper has to move a thing from defined positions A to B?

Based on the answers to questions like this, which is sort of a [black-box testing](https://en.wikipedia.org/wiki/Black-box_testing) approach, think about how to obtain reference values, then write tests in your Arduino to check if they are met. You might have to move your system into a defined testing stage first, like move the steppers to a defined starting point, then go test.

body:
There is no general mean of error detection in microcontrollers, so also not for an Arduino. Problems can occur at many points, extremely depending on how your project works. Think about a sensor, that is connected over some network bus; the sensor itself may fail, but also the network bus, so that you are not able to connect to the sensor anymore. Also the Arduino has no possibility to report errors to you, that you didn't anticipated in your sketch (like the log files on a PC would do). So there is not one answer for it. Here are some possibilities (some of them already described in previous answers):

- Check the output of library functions for error messages. Many (but not all) libraries return status codes from their important functions. For example: The `Wire.endTransmission()` function will return a status code, with which you can determine, if the transmission succeded and what might have gone wrong.
- Check sensors for expected values. If the values go out of range (for example a temperature of -20°C where you would expect room temperature) you can be pretty sure, that something is wrong with the sensor (assuming it worked properly before).
- Add sensors to your project, to sense, if it is working as expected, and program the Arduino to do the corresponding actions on failure (for example an alarm)

The first two options are simple, the third can get very complex and expensive and is normally only used, if the project really demands sensing malfunction electronically (like for a robot, that could hurt humans, when moving in the wrong direction).


body:
Currently I am trying to access a rest API from NodeMCU. The API is hosted on my local LAN on a Raspberry pi 3 b. The Raspberry pi is accessible on LAN using the raspberrypi.local domain address.
But the problem is I am unable to access the raspberrypi.local address form NodeMCU.
It is unable to just resolve the address.
Can anyone please help me resolve this issue?

title: Accessing raspberrypi.local from Nodemcu

Answers: 1

body:
In order to access the API, your NodeMCU needs to know the IP address your Pi has at this time. There are several ways to resolve `raspberrypi.local` to the actual IP. Assuming the NodeMCU got its IP assigned by your WiFi hotspot, it also received a DNS server IP. This is where the NodeMCU would ask first. However, if this DNS server is hosted by your internet provider, it obviously would not know what to respond when asked for your `raspberrypi.local`.

Another way, especially for `.local` domains, is [mDNS](https://en.wikipedia.org/wiki/Multicast_DNS). NodeMCU has a [module](https://nodemcu.readthedocs.io/en/master/en/modules/mdns/) to do that.

If you work with this a lot, consider running a local development network with your own DHCP/DNS combo. [dnsmasq](http://www.thekelleys.org.uk/dnsmasq/doc.html) is a good place to start. Lots of tutorials online. The Pi can host that for you.


body:
I would like to make a connection from **Arduino Uno to Microsoft SQL Server** for storing student attendance records into a table from my database.

So, what is the best way to do that? I need a suggestion or useful references and links.

I have written a web application on Visual Studio using C# language. What Arduino does is getting fingerprint through sensor, then I would like to store the attendance records of a student into database. So the attendance records can be retrieved from database to the web application and display to teachers.

This is just for project purpose only and the connectivity between Visual & SQL Server using these two lines below:

    SqlConnection con = new SqlConnection();
    con.ConnectionString = "Data Source=DESKTOP-H7KQUT1;Initial Catalog=SAOS1;Integrated Security=True";

title: Connection from Arduino Uno to Microsoft SQL Server Database

Answers: 1

body:
Using a layer between Arduino and MSSQL might give you the least headache. Would you like to do this on-premise or in the cloud?

For an easy cloud approach, look at [AWS Lambda](https://aws.amazon.com/lambda/). Write a Lambda function that inserts into your MSSQL database, possibly running on AWS too. Your choice of Java, Node.js, C#, or Python. Hook it up with incoming MQTT messages from your Arduino.
https://stackoverflow.com/questions/33165045/aws-lambda-and-sql-server-integration
 could help.

For a cloud-free approach, you could run your own local MQTT server (broker, to be exact, [Mosquitto](https://mosquitto.org/) being the most popular), and have your C# subscribe as an MQTT client. When the Arduino publishes a fingerprint signature, your C# script can do the database work.


body:
I am new to electronics and I'm having a problem when creating my project. I have created a Bluetooth controlled rover using HC-06, Dual H-bridge motor driver and 4 DC motors.
However, only two of the DC Motors are moving and the other two remain still.

Could you please suggest what happened?

Attached is the wiring of the motors and code.

    char t;

    void setup() {
      pinMode(9,OUTPUT);
      pinMode(10,OUTPUT);
      pinMode(11,OUTPUT);
      pinMode(12,OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      if(Serial.available()) {
        t = Serial.read();
        Serial.println(t);
      }

      if(t == '1') {
        digitalWrite(9,HIGH);
        digitalWrite(10,LOW);
        digitalWrite(11,HIGH);
        digitalWrite(12,LOW);
      }

      else if(t == '2') {
        digitalWrite(9,LOW);
        digitalWrite(10,HIGH);
        digitalWrite(11,LOW);
        digitalWrite(12,HIGH);
      }

      else if(t == '3') {
        digitalWrite(9,LOW);
        digitalWrite(10,LOW);
        digitalWrite(11,HIGH);
        digitalWrite(12,LOW);
      }

      else if(t == '4'){
        digitalWrite(9,HIGH);
        digitalWrite(10,LOW);
        digitalWrite(11,LOW);
        digitalWrite(12,LOW);
      }

      else if(t == '5') {
        digitalWrite(9,LOW);
        digitalWrite(10,LOW);
        digitalWrite(11,LOW);
        digitalWrite(12,LOW);
      }

      delay(100);
    }

[![Wiring diagram][1]][1]

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

title: Beginner problem with DC motor

Answers: 1

body:
To analyze your problem:

1. Switch two wires between two motors (and repeat this to get all combinations), to find out if the code/wiring until the motors is wrong, or there is a problem with the motors.
2. Print out the values of pins 9, 10, 11 and 12 and the value of t/input to see if the pins are controlled as you expect.
3. Remove all but one motors, for all motors one at a time, to see if there is no influence between them.

Below is not an answer to your question, but I can only align the code as answer.

It is better coding style to use the following form:

    void loop() {
      if(Serial.available()){
        t = Serial.read();
        Serial.println(t);
      }

      if ((t >= '1') && (t <= '5'))
      {
        int input = (int) t - (int)'0';

        digitalWrite( 9, (input == 1) || (input == 4) ? HIGH : LOW);
        digitalWrite(10, (input == 2)                 ? HIGH : LOW);
        digitalWrite(11, (input == 1) || (input == 3) ? HIGH : LOW);
        digitalWrite(12, (input == 2)                 ? HIGH : LOW);
      }

      delay(100);
    }

Note: ? : is a ternary operator which means : a ? b : c => if a then b else c.

Instead of using 9, 10, 11, 12 define pin numbers (e.g. PIN_MOTOR_X), and for 1, 2, 3, 4, 5 input numbers define LEFT, RIGHT, UP/FORWARD, DOWN/BACKWARD, STOP.


body:
i have a Arduino screwshield from sparkfun that I purchased: https://www.sparkfun.com/products/9729 which I used to put between my arduino uno and my 2.8" TFT LCD touch shield so that I am able to use the unused pins. I have to make an I2C connection between 2 Arduino Unos which I understand will require the A4 and A5 pins however the TFT currently uses both pins. also, my tft screen is from here: https://www.sgbotic.com/index.php?dispatch=products.view&product_id=2756

The schematics of my tft are: http://www.sgbotic.com/products/datasheets/development/02756-schematic.jpg .

I am wondering if I can just use the A4 and A5 pins using the screw shield anyway since according to the schematics, the A4 pin is connected to the LCD_RST or is the pin necessary for displaying images taken from the SD card?
If that isn't the way, how should I go about doing it, does anyone know?

title: How to do I2C on Arduino with SDA and SCL pin already used

Answers: 3

body:
No, you can't just use it. While I2C itself *may* work, the screen will keep resetting itself all the time and will be useless.

You may be able to get some luck with a [software bit-banged I2C ](https://playground.arduino.cc/Main/SoftwareI2CLibrary) on other pins. However I would personally choose to modify the TFT screen's PCB and cut the LCD_RST signal from the A4 pin and connect a 10kΩ resistor to +5V, or re-route it to another pin. That way you can then use I2C.

body: If the LCD is using A4/A5 for something besides I2C, than no you cannot.

body:
As I have very little knowledge about Prototype connection.But to avoid the soldering problems,

You May use [I2C adapters][1] as well as [I2C cable joiners][2] will be much useful and are specially designed for expansion of more than 1 I2C modules at the same time.

Hope These Sheilds and Adapters will be helpful for you.

  [1]: https://store.ncd.io/product/i2c-shield-for-arduino-uno/
  [2]: https://store.ncd.io/product/i2c-extension-cable-adapter-i2c-cable-joiner/


body:
I'm playing around with context switching, and my first idea is to play with SP and see how it changes.  However, Sp doesn't do what I expect.  The sketch is below. I'm using an Uno R3.  What I expect to see is that SP should first print out some value, then it should be 4 integers further along (4x2 bytes?) when printed the second time.  But that doesn't happen, and both times I see the exact same value for SP.  What could the problem be?

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

      Serial.begin(9600);

      Serial.print("X = ");
      Serial.println(SP,HEX);
    }
    void loop() {
      // put your main code here, to run repeatedly:
    Serial.print("BEFORE: ");
    Serial.println(SP,HEX);
    int y = 15;
    int z = y;
    int g = z + y;
    int dsf = z-y;
      Serial.println(dsf+g); //this should make these variables DO something...
      Serial.print(" After = ");
      Serial.println(SP,HEX);
      delay(1000);
    }

title: Why isn't the stack pointer changing in this simple sketch?

Answers: 2

body:
It's impossible to second-guess the compiler like that. There's a couple of things you need to realise:

* The compiler will optimize out any variables that just get assigned to other variables as part of calculations and have no further use
* The AVR CPU has 32 registers. More than enough to not *need* to use RAM to store values for a simple sketch like that.

Making the variables `volatile` will certainly help, since that forces the compiler to place them in memory. However you really should examine the assembly code the compiler produces to know exactly what it's doing.

body:
Another way the compiler can optimize is to compile small or single-use functions inline. What you expected would get wrapped inside a call and return sequence, may not.

Inserting `__attribute__ ((noinline))` ahead of the function definition can suppress that optimization:

    __attribute__ ((noinline)) void foo(int bar)
    {
       // do something
    }

suppresses the inlining for function foo(). Inlining has frustrated my investigations more than once, so I created this easier to remember macro. (The keyword is just `__NOINLINE`; the #else-clause is there so that, umm, "someone", doesn't unwittingly try to use the "__attribute..." declarator with another compiler that doesn't recognize it).

    // Don't compile this function inline
    //   '__NOINLINE void foo(void){ ... }'
    #ifdef __GNUC__
    #define __NOINLINE  __attribute__ ((noinline))
    #else
    #define NOINLINE error 'NOINLINE' not defined for this compiler
    #endif


body:
I've been working on using an ethernet shield for my Arduino Uno for a couple weeks now. I've been going through the problems one by one and now realise that there seems to be nothing transmitting. Running code similar to DHCPAddressPrinter results in nothing, and any web server I set up does not work at all. Can anyone please help? Running the code below results in an output of "Baud rate set!" and nothing else. One thing to note is that the MAC address I am using is from going into the command prompt and using the MAC address listed from ipconfig /all, as there is no sticker on the ethernet shield itself.

        /*
        DHCP-based IP printer

         This sketch uses the DHCP extensions to the Ethernet library
         to get an IP address via DHCP and print the address obtained.
         using an Arduino Wiznet Ethernet shield.

         Circuit:
         * Ethernet shield attached to pins 10, 11, 12, 13

         created 12 April 2011
         modified 9 Apr 2012
         by Tom Igoe

         */

        #include <SPI.h>
        #include <EthernetV2_0.h>

        // Enter a MAC address for your controller below.
        // Newer Ethernet shields have a MAC address printed on a sticker on         the shield
        byte mac[] = {
          /*MAC Address here*/ };

        // Initialize the Ethernet client library
        // with the IP address and port of the server
        // that you want to connect to (port 80 is default for HTTP):
        EthernetClient client;

        void setup() {
         // Open serial communications and wait for port to open:
          Serial.begin(9600);
          Serial.println("Baud rate set!");

          // start the Ethernet connection:
          if (Ethernet.begin(mac) == 0) {
            Serial.println("Failed to configure Ethernet using DHCP");
            // no point in carrying on, so do nothing forevermore:
            for(;;)
            Serial.println("FAIL");
              ;
          }
          // print your local IP address:
          Serial.print("My IP address: ");
          for (byte thisByte = 0; thisByte < 4; thisByte++) {
            // print the value of each byte of the IP address:
            Serial.print(Ethernet.localIP()[thisByte], DEC);
            Serial.print(".");
          }
          Serial.println();
          Serial.println("Loop");
        }

        void loop() {

        }

title: DF Robot W5200 Ethernet Shield for an Arduino Uno not working?

Answers: 1

body:
Don't use the MAC address of your computer read from ipconfig output. It creates a conflict on LAN. Use the MAC address from examples.

To troubleshoot Ethernet shield, use the Ethernet library newest version 2.00. It supports W5100, W5200 and W5500 and has better diagnostic in examples.

And to troubleshoot, always connect the LAN cable to router or switch, not to computer, because direct connection to computer requires manual setup of addresses (no DHCP).


body:
Referring to post: https://electronics.stackexchange.com/questions/211069/lcd-data-read-and-show-on-computer
It was not clear what the final code is. Could you post the code and schema again, and if possible, an explanation of how it works?

My problem:

I need to read the information of a lcd 20x4 display, which is controlled by a PLC (which has the protected hex code), and send the data through the serial port.

For this I am using an arduino one to do the reading. I connected the arduino in parallel with the display data bus, to try to read the bits and convert later.

This is the schematic I'm using:
[![enter image description here][1]][1]

Note: I have placed 1k resistors to make the pulldown on each pin, to avoid reading errors.

With this code:

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

The problem is that I'm having these results in reading:
[![enter image description here][4]][4]

No matter what appears on the screen, they are always invalid characters.
If someone identifies where my problem is, I'll be very grateful.

  [1]: https://i.stack.imgur.com/iZEvF.png
  [2]: https://i.stack.imgur.com/hX1PF.png
  [3]: https://i.stack.imgur.com/ZbaMn.png
  [4]: https://i.stack.imgur.com/hmrIb.png

title: How to read data directly from lcd display

Answers: 2

body:
I would recommend ditching the the digitalRead in this case - it is performed sequentially, and is rather slow.
As you only need to read 8 input lines, consider using Port register: The Arduino Uno comes with a total of three Ports which "hold" all of the I/O pins.
Those are

 - PORTB = Digital Pins 8 through 13 plus the crystal pins
 - PORTC = Analog Input 0 through 5, reset pin
 - PORTD = Digital Pin 0 through 7

Since you need the RX and TX lines (Digital pin 0 and 1) for your serial communication, you will have to split the signal onto two registers.

I would recommend connecting D0 through D3 to Digital Pins 8 through 11 for the first four bits (meaning they'll go to bits 3 to 0 of Port B), and D4 through D7 to Analog Pins 0 To 3 (meaning they'll go to bits 3 to 0 of Port C).
RW goes to Pin 7, RS to Pin 6, E to Pin 5.

The code you would then use to read the data would be this:
    uint8_t byte_displaydata = 0x00;
    uint8_t RW = 7;
    uint8_t RS = 6;
    uint8_t E = 5;

    void setup() {
      Serial.begin(1200); //perhaps increase this a bit
      pinMode(RW, INPUT); //some speed is lost compared to register manipulation, but that is likely insignificant
      pinMode(RS, INPUT);
      pinMode(E,INPUT);
      DDRB &= ~((1 << DDRB0) | (1 << DDRB1) | (1 << DDRB2) | (1 << DDRB3)); //technical not necessary since they're initialized with 0
      DDRC &= ~((1 << DDRC0) | (1 << DDRC1) | (1 << DDRC2) | (1 << DDRC3));
      PORTB &= ~((1 << PORTB0) | (1 << PORTB1) | (1 << PORTB2) | (1 << PORTB3)); //disable internal pullups
      PORTC &= ~((1 << PORTC0) | (1 << PORTC1) | (1 << PORTC2) | (1 << PORTC3));

    }

    void loop() {
      if(digitalRead(RS) == HIGH && digitalRead(E) == HIGH){
        byte_displaydata = 0x00; //reset byte_displaydata
        byte_displaydata = PINB << 4; //push PINB bits 3 to 0 to bits 7 to 4
        byte_displaydata |= (PINC & 0x0F); //filter PINC bits 3 to 0 and OR them into result bits 3 to 0
        Serial.println(byte_displaydata,BIN);
      }
    }
Please note that I have not tested this, and only recently have gotten started in AVR / Arduino.
If anyone can look this over, I'd greatly appreciate it.

Source: Microchip ATmega328P datasheet, [Arduino pin mapping][1]

  [1]: https://www.arduino.cc/en/Hacking/PinMapping168

body:
It is probably too late for the OP but there is a protocol sniffer for such LCD screens which use the HD44780 series LCD driver as, for example, the common LCD1602 does.
The code is published here:

https://forum.arduino.cc/t/lcd-1602-and-similar-databus-sniffer/675769/11

The data rate would be too fast for Serial.print() to print each character received in real time so a queue is used to consolidate the data.


body:
I have a 3.3 V Pro Mini connected to nRF24l01 as xmtr. The nRF24L01 does not respond to the Pro Mini. Any help will be appreciated.

I have attached the print detail output:

    Transmitter 2  Started
    STATUS   = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
    RX_ADDR_P0-1  = 0xffffffffff 0xffffffffff
    RX_ADDR_P2-5  = 0xff 0xff 0xff 0xff
    TX_ADDR   = 0xffffffffff
    RX_PW_P0-6  = 0xff 0xff 0xff 0xff 0xff 0xff
    EN_AA   = 0xff
    EN_RXADDR  = 0xff
    RF_CH   = 0xff
    RF_SETUP  = 0xff
    CONFIG   = 0xff
    DYNPD/FEATURE  = 0xff 0xff
    Data Rate  = 1MBPS
    Model   = nRF24L01
    CRC Length  = 16 bits
    PA Power  = PA_MAX

    Transmitter 2 Started
    STATUS   = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
    RX_ADDR_P0-1  = 0xe8e8f0f0e2 0xc2c2c2c2c2
    RX_ADDR_P2-5  = 0xc3 0xc4 0xc5 0xc6
    TX_ADDR   = 0xe8e8f0f0e2
    RX_PW_P0-6  = 0x20 0x00 0x00 0x00 0x00 0x00
    EN_AA   = 0x3f
    EN_RXADDR  = 0x03
    RF_CH   = 0x73
    RF_SETUP  = 0x07
    CONFIG   = 0x0e
    DYNPD/FEATURE  = 0x03 0x06
    Data Rate  = 1MBPS
    Model   = nRF24L01+
    CRC Length  = 16 bits
    PA Power  = PA_MAX
    voltage = 3.97 V
    0
    RSLT (1 = success) 0
    Data Sent 3.00  0.00  3.97
    voltage = 3.85 V
    voltage = 3.79 V
    voltage = 3.75 V
    voltage = 3.73 V
    0
    RSLT (1 = success) 0
    Data Sent 3.00  0.00  3.73
    voltage = 3.70 V
    voltage = 3.68 V
    voltage = 3.65 V
    voltage = 3.62 V
    0
    RSLT (1 = success) 0
    Data Sent 3.00  0.00  3.62
    voltage = 3.58 V
    voltage = 3.54 V
    voltage = 3.50 V
    voltage = 3.45 V
    0

The top transmitter output is before I changed the nRF24L01 module which appeared to be bad.
The second transmitter started output. Module is good but nRF24L01 would not connect to receiver with 3.3 V Pro Mini. It connects if I use a Nano.

title: 3.3 V Arduino Pro Mini and nRF24L01 issues

Answers: 3

body:
> voltage = 3.97 V 0 RSLT (1 = success) 0 Data Sent 3.00 0.00

nrf24l01 is a 3.3V device, Where'd that come from?

body: Promini 3.3V regulator is also only good for 150mA. I think the nrf24L01 needs more current than that.

body:
LM317T set to 3.25 Volts and 220uF tantalum on the nrf24L01.

Pro mini and nrf24L01 powered by 3.25V works a treat. :-)

Problem with arduino nano is that the USB from laptop is 5V and that is a killer for the nrf24L01!
If using serial.write to send data to a serial monitor through the nano's USB insure that the power and levels are not 5V on the nrf24L01.


body:
I recently bought a STM32F103C8T6 board (blue pill)
I programming to it using the USB to Serial TTL I bought (CP2102).

I'm still taking very first steps and trying to figure out how to operate the component.
I was able to burn a basic script to STM32F103C8T6 that causes the P13(LED) to blink.

Now I'm trying to add basic printing that I can see over the serial interface
Which I am already connected to (CP2102).

Here's what my code looks like:

    void setup() {
    // initialize digital pin PC13 as an output.
    pinMode(PC13, OUTPUT);
    Serial.print("finish setup function \r\n"); // try to print something using serial
    }

    void loop() {
    digitalWrite(PC13, HIGH);
    delay(500);

    digitalWrite(PC13, LOW);
    delay(500);

    Serial.print("loop throgh loop function \r\n"); // try to print something using serial
    }

Everything is compiled and loaded fine (I work through ARDUINO IDE), but it is not clear to me where I can see these prints.

I tried to see them in Tools-> serial monitor (in the arduino ide tool)
But I didn't see any printing ...

(I know that my code got loaded successfully because I play with the speed of the LED blinks and I see that it is responding to the change at the speed of the flicker).

It feels like it's a really stupid question but where can I see my prints?

title: How can I read the serial output of STM32F103C8T6 from USB to Serial TTL?

Answers: 0


body:
I'm trying to switch on bulb via 4 channel 5V optocoupler relay controller from ESP8266 using WIFI Access point. All my connections looking fine and i can able to connect WIFI SoftAP and send signal to ESP8266 01. Even i can able to switch the Relay from NO to NC or other way around. Only when a connect 240V AC current to relay for powering the bulb, i'm getting following error from ESP

    21:11:34.312 ->  ets Jan  8 2013,rst cause:4, boot mode:(1,7)
    21:11:34.312 ->
    21:11:34.312 -> wdt reset

If i use 12V DC power to light the led via relay its working fine. if again use 240V power to relay to light bulb i'm get same error again.

I have already tried using ceramic capacitor for decoupling to avoid noise from AC. Still no luck. Please advice. I'm very new and naive at handling electronics.

Adding the circuit as well.

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

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

Update: After further testing, I can see following behaviour,
If i connect AC bulb to relay and turn it on. Then by provide a long gap before turning it off makes the ESP stable for longer time.

Even better, if i turn off/on my mobile wifi between each time i turn on or off the AC bulb then ESP is always stable.

Adding my code as well.

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>

    /* Set these to your desired credentials. */
    const char *ssid = "*****";
    const char *password = "*********";

    ESP8266WebServer server(80);

    const int led = 2;  //GPIO2

    /* Just a little test message.  Go to http://192.168.4.1 in a web browser
     * connected to this access point to see it.
     */
    void handleRoot() {

      int size=1000;
      char temp[size];

      int sec = millis() / 1000;
      int min = sec / 60;
      int hr = min / 60;

      snprintf ( temp, size,

    "\

Status: Light ON

\

Turn ON

\

\

Turn OFF

\
      \
      ",

        hr, min % 60, sec % 60
      );
      server.send ( 200, "text/html", temp );

    }

    void setup() {
     delay(1000);
     Serial.begin(115200);
     Serial.println();
     Serial.print("Configuring access point...");

     /* You can remove the password parameter if you want the AP to be open. */
     WiFi.softAP(ssid, password);

     IPAddress myIP = WiFi.softAPIP();
     Serial.print("AP IP address: ");
     Serial.println(myIP);

      pinMode(led, OUTPUT);
      digitalWrite ( led, HIGH );

      //URLs available to query
     server.on("/", handleRoot);
      server.on ( "/on", turnON );
      server.on ( "/off", turnOFF );
     server.begin();
     Serial.println("HTTP server started");

    }

    void turnON(){

      digitalWrite ( led, HIGH );

      int size=1000;
      char temp[size];

      int sec = millis() / 1000;
      int min = sec / 60;
      int hr = min / 60;

      snprintf ( temp, size,

    "

Turn OFF

",

        hr, min % 60, sec % 60
      );

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

    }

    void turnOFF(){

      digitalWrite ( led, LOW );

      int size=1000;
      char temp[size];

      int sec = millis() / 1000;
      int min = sec / 60;
      int hr = min / 60;

      snprintf ( temp, size,

    "

Turn ON

",

        hr, min % 60, sec % 60
      );

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

    }

    void loop() {
     server.handleClient();
    }

title: esp8266 + octocoupler relay: WDT reset when using AC current

Answers: 1

body:
Before running to dark magic of EMI problems - let's try isolate all our parameters that can cause or affect (and perhaps is is not only one):

 1. make a **test code** as simple as possible for switching a relay periodically on/off. At start make a 5 second delay between changing states, and down to 500 millis- This way you check both EMI interference and power issues inside you circuit (sometimes the relay consumes power more that the MCU can give, and that can cause resets. Problem can be MCU's power issue or Relay, mechanical or electrical issues).
 2. **Components** - try to replace with others, especially MCUs, and relays, to make sure it is not a malfunctioned or degraded components. For example - a Wemos mini with is Relay shield can easily isolate any "EMI"- related issue.
3. From you diagram (and in contrast to your question's title) - an Uno is used for switching ? and not the ESP-01' right? did you make sure that the relay's vcc is correct for its MCU? (you said 5v relay, which is not correct for ESP8266).
4. **Load** - make sure to choose a simple resistive load (AC light bulb), rather that an AC motor (which cause a massive EMI interference).
5. **EMI** - if all above did not help (I doubt) or it solved for that "bulb case" only, EMI affect are distance related. Try to use a long AC wires that will take you MCUs and relay far from that source. 1m will be enough.

To sum up, I will be very surprised to know that it is EMI (and I dealt with AC motors with WEMOS and a dual relay module successfully).

Please update.

Guy


body:
I started to play around with the [ArduinoJson library](https://arduinojson.org) to parse data I got from one of my APIs (the format of the JSON data I get from my API can be improved for sure, but the software I had to implement the API with is rather limited in formatting JSON strings). The data is formatted as an array of arrays like this:

    [["P101","1.2345","bar(a)"],["P102","1234.567","mbar"],["P103","2345.678","mbar"],["P104","2.3456","bar(a)"]]

In order to get a first impression about how much memory is needed I used [ArduinoJSON's Assistant](https://arduinojson.org/v5/assistant/) to analyse my dataset, calculate memory requirements and get a very basic code snippet for parsing the data. Code snippet generated by the assistant is as follows:

    const size_t bufferSize = 4*JSON_ARRAY_SIZE(3) + JSON_ARRAY_SIZE(4) + 90;
    DynamicJsonBuffer jsonBuffer(bufferSize);

    const char* json = "[[\"P101\",\"1.2345\",\"bar(a)\"],[\"P102\",\"1234.567\",\"mbar\"],[\"P103\",\"2345.678\",\"mbar\"],[\"P104\",\"2.3456\",\"bar(a)\"]]";

    JsonArray& root = jsonBuffer.parseArray(json);

    JsonArray& root_ = root;

    JsonArray& root_0 = root_[0];
    const char* root_00 = root_0[0]; // "P101"
    const char* root_01 = root_0[1]; // "1.2345"
    const char* root_02 = root_0[2]; // "bar(a)"

    JsonArray& root_1 = root_[1];
    const char* root_10 = root_1[0]; // "P102"
    const char* root_11 = root_1[1]; // "1234.567"
    const char* root_12 = root_1[2]; // "mbar"

    JsonArray& root_2 = root_[2];
    const char* root_20 = root_2[0]; // "P103"
    const char* root_21 = root_2[1]; // "2345.678"
    const char* root_22 = root_2[2]; // "mbar"

    JsonArray& root_3 = root_[3];
    const char* root_30 = root_3[0]; // "P104"
    const char* root_31 = root_3[1]; // "2.3456"
    const char* root_32 = root_3[2]; // "bar(a)"

I did not test this, yet but had a look at the produced snippet and stumbled upon these lines:

    JsonArray& root = jsonBuffer.parseArray(json);

    JsonArray& root_ = root;

What is the exact advantage of using [address-references](http://www.cplusplus.com/doc/tutorial/pointers/) `root`, `root_` and e.g. `root_1` here? Those should, as far as I understood the code, reference to the same data at the end. Is it for better readability only?

title: ArduinoJSON: Using a reference to a reference when parsing array of arrays

Answers: 2

body:
The advantage of reference above pointers:

- References cannot be NULL, so it's much safer to use them
- Address of a reference cannot be acquired, this means a calling function cannot mess up anything outside the type (value) being passed.

For passing a reference to an address the same advantages applies (cannot be NULL, address cannot be changed).

Also, address arithmetic (address + xxx or address - xxx) cannot be used, which prevents tricky programming errors where values outside a variable's memory space can be changed.

body:
It is not a reference to reference. It is a copy of the reference.

The generator must handle more difficult JSON inputs then yours and to make output readable it has a strategy, which in simple case can look as unnecessary. Yes, it could use `root[n][m]`.


body:
***As I learnt so far is that Arduino UNO board has a socket for power input. The available power input range is between 7V - 20V, but the optimal usage range is 7V-12V.***

Here I am wondering:
  ---> if there is a USB port for power supply, why do we need a power input socket?
  ---> Or there is a battery on-board to charge?

title: Arduino UNO socket

Answers: 2

body: Many projects (robots, drones, 3D printers, light control, art) made with Arduino have actuators (relays, motors), lights and displays which require a 9 or 12 V power supply. To use this power supply for the Arduino too, you need a voltage regulator which converts the voltage level and filters the noise and fluctuations created for example by that actuators.

body:
The Arduino Uno has no on-board battery. The dc barrel jack is provided to give you more options to power the Uno, which is handy for stand-alone applications (without USB-connection to a computer) and/or battery powered applications. It can also supply more current than the USB-connection, which can be necessary when using shields.

The current taken from the usb port is limited to 500 mA by by an auto resettable fuse on the Uno (the voltage is not regulated by the Uno). This is the same amount of current as the USB 2.0 standard specifies that a standard down stream port (computer USB port) should be capable to deliver (for USB 3.0 this is 900 mA).

The power taken from the barrel jack is regulated to 5 V by a voltage regulator, the NCP1117ST50T3G. To work properly, this regulator needs a voltage difference (dV) between input and output of 1.2 V (depending on output current and ambient temperature). This means that the minimum voltage on the barrel jack is 6.2 V.

The regulator has an internal thermal limiting circuit that limits the junction temperature to ca. 175°C. This determines the maximum power dissipation (= output current times dV) the regulator can handle at a given ambient temperature. The maximum allowable power dissipation also depends on the size of the copper pad under the cooling tab of the regulator. As I don't know this size it is difficult to calculate de maximum power dissipation precisely, but my guess is that at 25°C and 6.2 V a power dissipation of 1 Watt should be possible. This gives a maximum output current of 1/(6.2-5.0)=0.833A=833 mA. Of course, at higher input voltages the maximum output current is lower. For example at 12 V: 1/(12.0-5.0)=0.143A=143mA.


body:
I am making a Smart Cart using RFID. The user will
have a RFID card. As soon as he swipes the card on
the RFID Reader it will identify the user and will create
a linked list for that particular user. The linked list will
contain the unique Rfid based Ids of the items purchased by the user. In my code
the problem is that after the detection of the user it is
not creating any linked list for the items/it is not detecting the items bought by the user. Both the user and items are identified by their unique ids (ie RFID tags).It is detecting the user but once the user is being detected it is not mapping the items bought with that user.

the code for the same is :

    int count = 0; // count = 0
    int i;
    char input[12];                                   // character array of size 12
    boolean flag = 0;
    // flag =0

    boolean comparetag(char x[12], char bb[12]) {
      boolean ff = false;
      int fg = 0;
      for (int cc = 0; cc < 12; cc++) {
        if (x[cc] == bb[cc]) {
          fg++;
        }
      }
      if (fg == 12) {
        ff = true;
      }
      return ff;
    }

    struct Node {
      char x[12];
      struct Node *next;
    };

    struct Node* X;
    struct Node* point;

    void printList(struct Node *n) {
      while (n != NULL) {
        Serial.print(n->x);
        n = n->next;
      }
    }

    struct Node* Shopping(char[]) {

      Serial.print(input);
      // Print RFID tag number
      Serial.print("Welcome User");
      Serial.println();

      Serial.print("Start Shopping ");

      struct Node* head = NULL;
      head = (struct Node*) malloc(sizeof(struct Node));

      return head;

    }

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

    void loop() {

      if (flag == 0) {
        if (Serial.available()) {
          count = 0;
          while (Serial.available() && count < 12) // Read 12 characters and store them in input array
          {
            input[count] = Serial.read();
            count++;
            delay(5);
          }

          if (comparetag(input, "1B006AFA9F14")) {
            flag = 1;

            point, X = Shopping(input);
          } else {
            Serial.println("not Registered User");
          }
        }
      } else {
        int c = 0;
        if (Serial.available()) {
          while (Serial.available() && c < 12) // Read 12 characters and store them in input array
          {
            Serial.print("Taking Input");
            X->x[c] = Serial.read();
            c++;
            delay(5);
          }
          struct Node* second = NULL;
          second = (struct Node*) malloc(sizeof(struct Node));
          second = NULL;

          X->next = second;
          X = second;

        }
      }
      printList(point);
    }

title: Linked List based question

Answers: 1

body:
I don't see any code for making new nodes or linking them into a list. A linked-list needs a root (a known variable that points to the first member of the list); a way to make or acquire new nodes and link them onto the list as the number of items grows; and a way to unlink a node and "discard" it - return its memory - once it is no longer useful.

I'll offer a couple of suggestions for linked-lists, especially in processors like the Uno with limited memory:

1. Don't be tempted to use `malloc()` and `free()` or `new` and `delete` for a system that must run continuously. Allocating and deallocating small pieces of memory, especially when interspersed with other allocation & deallocations, will lead to fragmentation of the heap (that portion of memory used for allocating memory at run-time). The result is that the heap will end up with lots of separate pieces of memory that are free but too small for other allocation requests, so the heap has to acquire more memory to satisfy the larger allocations. It does this by reducing the stack space! Eventually the stack will grow into the heap space, and the program will fail.

My solution is to define a global array of node structs; enough of them for the program's greatest conceivable need, plus a few more for safety; link them into a list of free nodes; and give new nodes to the application by deallocating one from the free list. A You need link() and unlink() functions for a linked-list anyway, so it takes very little more code to do this.

2. Because we're talking about memory limited processors, If I don't need more than 255 nodes, I link with array indices instead of pointers, saving one byte per node. This costs a little bit more code to index into an array than to de-reference a pointer but compilers have gotten pretty smart about minimizing even that overhead.


body:
There is **blink project** consisting 3 sections:

***1 - regulation of the led brightness using a potentiometer***

***2 - whenever: the button is pressed - the led is on***

   ***-   the button is released - the led is off***

***3 - change state of a led statically***

The question is that:

May I make this project on-board?
I am curious that, if I will try making this project on-board (Arduino UNO) will the Arduino damaged?

title: How to regulate a led on-board?

Answers: 1

body: Pin 13, which is the on-board LED, is not a pwm pin. So you cannot Control the brightness of that LED on-board. You will have to use another LED and a PWM pin.


body:
I have a Leonardo board and I want to set up my pins to input in one shot using a for loop but the problem is with the analog pins I can't see how to set up a mixed alphanumeric array it gives me some errors.

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

    // including keyboard.h library for the keyboard functions
    #include <Keyboard.h>

    // setting Arrays for looping later
       int myIntPins[12] = {2,3,4,5,6,7,8,9,10,11,12,13};
       int myChar[12] = {97, 98, 99, 100, 101,102,103,104,105,106,107,108};
      int myChar2[6] = {109,110,111,112,113,114};
     myCharPins[6] = {"A0","A1","A2","A3","A4","A5"};
      int a;
      int x;
      int i;

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

     //Setting up Digital Pins
    for (int i=0; i <= 11; i=i+a){
      pinMode(myIntPins[i],INPUT);
      }

    //pinMode(2, INPUT);
    //pinMode(3, INPUT);
    //pinMode(4, INPUT);
    //pinMode(5, INPUT);
    //pinMode(6, INPUT);
    //pinMode(7, INPUT);
    //pinMode(8, INPUT);
    //pinMode(9, INPUT);
    //pinMode(10, INPUT);
    //pinMode(11, INPUT);
    //pinMode(12, INPUT);
    //pinMode(13, INPUT);

    //------------------------------------------------------------------------------
    //------------------------------------------------------------------------------

    // setting up Analog Pins to Digital
    for (int x=0; x <= 5; x=x+a){
      pinMode(myCharPins[x],INPUT);
      }
    //pinMode(A0,INPUT);
    //pinMode(A1,INPUT);
    //pinMode(A2,INPUT);
    //pinMode(A3,INPUT);
    //pinMode(A4,INPUT);
    //pinMode(A5,INPUT);

    // starting keyboard
    Keyboard.begin();

    }

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

      //if pin 2 is pressed then send the a key/char
     // if (digitalRead(2) == LOW) {Keyboard.write(97);}

    // instead of doing an if one by one doing a loop all in one shot
    // this loop for regular digital pins
    a=1;
      for (int i=0; i <= 11; i=i+a){
        if (digitalRead(myIntPins[i]) == LOW){
          Keyboard.write(myChar[i]);
          }
          }
    a=1;
      // this loop for the analog pins now working as digital pins
      for (int x=0; x <= 5; x=x+a){
        if (digitalRead(myCharPins[x]) == LOW){
          Keyboard.write(myChar2[x]);
          }
          }

      delay(10);

      }

Error:

        Arduino: 1.8.7 (Windows 10), Board: "Arduino Leonardo"

    Mandar_Keyboard_Key_1:10:2: error: 'myCharPins' does not name a type

      myCharPins[6] = {"A0","A1","A2","A3","A4","A5"};

      ^

    C:\Users\manue\OneDrive\Documents\Arduino\Mandar_Keyboard_Key_1\Mandar_Keyboard_Key_1.ino: In function 'void setup()':

    Mandar_Keyboard_Key_1:45:11: error: 'myCharPins' was not declared in this scope

       pinMode(myCharPins[x],INPUT);

               ^

    C:\Users\manue\OneDrive\Documents\Arduino\Mandar_Keyboard_Key_1\Mandar_Keyboard_Key_1.ino: In function 'void loop()':

    Mandar_Keyboard_Key_1:77:21: error: 'myCharPins' was not declared in this scope

         if (digitalRead(myCharPins[x]) == LOW){

                         ^

    exit status 1
    'myCharPins' does not name a type

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

If I change my code I to this, I get a different error.

Code:

    // including keyboard.h library for the keyboard functions
    #include <Keyboard.h>

    // setting Arrays for looping later
       int myIntPins[12] = {2,3,4,5,6,7,8,9,10,11,12,13};
       int myChar[12] = {97, 98, 99, 100, 101,102,103,104,105,106,107,108};
      int myChar2[6] = {109,110,111,112,113,114};
      char myCharPins[6] = {"A0","A1","A2","A3","A4","A5"};
      int a;
      int x;
      int i;

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

     //Setting up Digital Pins
     a=1;
    for (i=0; i <= 11; i+=a){pinMode(myIntPins[i],INPUT);}

    //pinMode(2, INPUT);
    //pinMode(3, INPUT);
    //pinMode(4, INPUT);
    //pinMode(5, INPUT);
    //pinMode(6, INPUT);
    //pinMode(7, INPUT);
    //pinMode(8, INPUT);
    //pinMode(9, INPUT);
    //pinMode(10, INPUT);
    //pinMode(11, INPUT);
    //pinMode(12, INPUT);
    //pinMode(13, INPUT);

    //------------------------------------------------------------------------------
    //------------------------------------------------------------------------------

    // setting up Analog Pins to Digital
    for (x=0; x <= 5; x+=a){pinMode(myCharPins[x],INPUT);}
    //pinMode(A0,INPUT);
    //pinMode(A1,INPUT);
    //pinMode(A2,INPUT);
    //pinMode(A3,INPUT);
    //pinMode(A4,INPUT);
    //pinMode(A5,INPUT);

    // starting keyboard
    Keyboard.begin();

    }

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

      //if pin 2 is pressed then send the a key/char
     // if (digitalRead(2) == LOW) {Keyboard.write(97);}

    // instead of doing an if one by one doing a loop all in one shot
    // this loop for regular digital pins
    for (i=0; i <= 11; i+=a){if (digitalRead(myIntPins[i]) == LOW){Keyboard.write(myChar[i]);}}

      // this loop for the analog pins now working as digital pins
      for (x=0; x <= 5; x+=a){if (digitalRead(myCharPins[x]) == LOW){Keyboard.write(myChar2[x]);}}

      delay(10);

      }

Error:

        Arduino: 1.8.7 (Windows 10), Board: "Arduino Leonardo"

    Mandar_Keyboard_Key_1:10:54: error: too many initializers for 'char [6]'

       char myCharPins[6] = {"A0","A1","A2","A3","A4","A5"};

                                                          ^

    exit status 1
    too many initializers for 'char [6]'

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

title: Help with AlphaNumeric array

Answers: 1

body:
All of those "A1" "A2" pins have other numbers that go with them.  The A1 or A2 is #defined in the core to be some number.  You can just use A1 or A2 and it will work.

For example, try this line and see what it prints:

    Serial.println(A0);

And for your pins, just put A0, A1, etc. in your int array and leave the quotes off.  Those symbols are being replaced by numbers because they're defined constants.

    int myIntPins[12] = {2,3,4,5,6,7,8,9,10,11,12,13, A0, A1, A2};


body:
I want to modify my code to move a servo motor only for the duration of time that the sensor is touched and stop moving immediately when the sensor is no longer touched. The code I have moves the sensor from 0 to 90 and back.  That motion is completed even when you remove your finger. I want it to be such that if you remove your finger before the servo reaches 90 degrees the servo stops.  And the servo starts up again toward 90 when touch resumes. This is the code I currently have:

    //when signal output is high the sensor is being pressed

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
    int pos = 0;    // variable to store the servo position
    int sensor=11; //initialises component to arduino digital pins
    led=13;

    void setup() {
            myservo.attach(9);
            pinMode(led,OUTPUT);
            pinMode(sensor,INPUT);
            Serial.begin(9600);
    }

    void loop() {

            int value=digitalRead(sensor);
            if(value == HIGH){
                    digitalWrite(led, HIGH);
                    for (pos = 0; pos <= 90; pos += 1) {
                            myservo.write(pos);              // tell servo to go to position in
                            variable 'pos'
                                    delay(15);                       // waits 15ms for the servo to reach the
                            position
                    }
                    for (pos = 90; pos >= 0; pos -= 1) { // goes from 90 degrees to 0 degrees
                            myservo.write(pos);              // tell servo to go to position in
                            variable 'pos'
                                    delay(15);
                    }
                    Serial.println("TOUCHED ");
            }else{
                    digitalWrite(led, LOW);

                    Serial.println("NOT TOUCHED ");
                    delay(500);
            }
    }

title: Controlling a servo motor with a touch sensor

Answers: 1

body:
To solve your problem, you need to take a tiny step into real time programming.  Most Arduino programs deal with one issue or action at a time.  Your simple twist to interrupt and action "i want it to be such that if you remove your finger before the servo reaches 90 degrees that's where the servo stops" requires you to continuously monitor your input (touch switch) while changing your output (next servo position).

You can go about this 2 ways.  You can use [interrupts][1] to inform you when the state of the touch switch changes. This is challenging.  Many find it difficult to conceive of what might happen if their program were to be interrupted at any and all possible points in its execution.  A mistake here can lead to unexpected results.

Or you could take turns polling the state of the touch switch then making a small adjustment in the position of the servo.  When the state of the touch switch changes from active to not-active, exit the loop you are using to change the servo position.

  [1]: http://playground.arduino.cc/code/interrupts


body: I wanted to find out if is possible to write programs into a micro controller using the Arduino and use the micro controller independent of the Arduino board?

title: Can an IC be programmed by an Arduino and then be removed, to be used in an external breadboard?

Answers: 2

body:
Yes. The compiles code will is burned in the Arduino ROM. You can then take the Atmel chip (the Arduino microprocessor) and use it. You only need a few extra component for a chip like the 328p (Arduino Uno).

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

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

body: For another example, using another method, an Uno can program another MCU without the target needing any bootloader, thus enabling your code to occupy the entire Flash memory of the target devices. Here is a link describing how to program an Attiny using an Uno and the ArduinoISP example program. An Attiny85, for example, has 8K of flash, all of which is usable by your application, using this technique. For comparison, a bootloader in an Attiny85 takes about 2.5K, or 30% of the Flash space! And it only gets worse with the smaller Attinys.


body:
I have a problem with my Arduino project and I tried everything to fix it but nothing helps.

I am trying to rotate my DC motor with two buttons:

 -  one button is to stop/start rotating on left side, and;
 - the second one is for stop/start rotating on the right side.

I can't switch the states and if the motor is rotating I can't stop it. The speed is controlled by the potentiometer and works fine, just the buttons are the problem. I hope somebody can help me.

    int enablePin = 11;
    int in1Pin = 10;
    int in2Pin = 9;
    int switchPin = 7;
    int switchPin1 = 6;
    int potPin = 0;
    int statusPin= 13;
    boolean status;

    void setup()
    {
      pinMode(in1Pin, OUTPUT);
      pinMode(in2Pin, OUTPUT);
      pinMode(enablePin, OUTPUT);

      pinMode(switchPin, INPUT_PULLUP);
      pinMode(switchPin1, INPUT_PULLUP);

      pinMode(statusPin,OUTPUT);
      Serial.begin(9600);
    }

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

      int speed = analogRead(potPin) / 4;

      boolean reverse = digitalRead(switchPin);
      boolean reverse1 = digitalRead(switchPin1);

      if(reverse == false){
        status = true;
      }
      if(reverse1 == false){
        status == false;
      }

      setMotor(speed, status);
    }

    void setMotor(int speed, boolean reverse)
    {
      analogWrite(enablePin, speed);

      digitalWrite(in1Pin, ! reverse);
      digitalWrite(in2Pin, reverse);
    }

I just added the second button with paint, so don't get confused.

[![Fritzing diagram][1]][1]

  [1]: https://i.stack.imgur.com/bGxNX.jpg "Fritzing diagram"

title: Arduino DC motor with 2 buttons

Answers: 1

body:
In your code the buttons only control the direction, but are not turning the motor on or off. This is only be done with the potentiometer, which can be set to zero speed.

To really enable the motor with the buttons, you have add some logic for the enable pin. For example change the `setMotor()` function and give it also a boolean as parameter, which indicates the enabling of the motor:

    void setMotor(int speed, boolean enabled, boolean reverse)
    {
        if(enabled) analogWrite(enablePin, speed);
        else        analogWrite(enablePin, 0);
        digitalWrite(in1Pin, ! reverse);
        digitalWrite(in2Pin, reverse);
    }

You can set a corresponding boolean variable in the `loop()` function like you did with the `status` variable. Set this new variable to `true` in both if-statement of the buttons. Alternatively you can do this inline with the `setMotor()` call by writing:

    setMotor(speed, reverse || reverse1, status);

The `||` is a logical OR operation. It returns `true` if any of both operands are true. In a similar way you can ditch the other if-statement with the `status` variable:

    setMotor(speed, reverse || reverse1, !reverse && reverse1);

`!` negates the value of `reverse` and `&&` does a logical AND. You can decide yourself, if you want to use if-statements (which are a bit easier to read or these logical statements (which are more compact).

---

Also you should use better variable names. `reverse` and `reverse1` are not really good to distinguish. Better would be `reverse` and `forward`.


body:
I have an Arduino Uno, 12V WS2811 RGB LEDs (from Mokungit), a 5V power source, and DC power connector. I do not have a breadboard and hope I don't need one.

This is almost exactly what I need to follow [this tutorial][1] to build a Stranger Things wall. The LED strip listed shares the same name as the one I have, but the wiring is different.

Here's a photo from the Instructables site:
[![enter image description here][2]][2]

However, the wires coming from my strip don't match up to the instructions, and I can't seem to figure out how to get these bad boys burning.

[![enter image description here][3]][3]
[![enter image description here][4]][4]
[![enter image description here][5]][5]
[![enter image description here][6]][6]

Thanks to anyone who can help me get started!

  [1]: https://www.instructables.com/id/Arduino-Based-Stranger-Things-Lights/
  [2]: https://i.stack.imgur.com/Vy9iB.jpg
  [3]: https://i.stack.imgur.com/DOVEu.jpg
  [4]: https://i.stack.imgur.com/ZDXQf.jpg
  [5]: https://i.stack.imgur.com/o9Qub.jpg
  [6]: https://i.stack.imgur.com/inp05.jpg

title: Connecting 12V WS2811 RGB LEDs to Arduino Uno & 5V Power Source (Breadboard needed?)

Answers: 3

body:
The signals are clear on the bulb pcb. Take a multimeter in continuity mode and probe to see which pins on the round connector is DI, GND and +12v.

Then connect DI to the arduino. +12v to the strip. GND from the Arduino, LED strip and your +12v source should all be conected together.

body:
This image, from [here][1], shows which pins are what:

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

Note the flat *key* next to the 12 V and GND pins. In addition:

 - the GND wire has a black broken line printed along it;
 - the data line is in the middle.

If you trust the image then you should be able to wire them up correctly.

  [1]: http://MOKUNGIT WS2811 Diffused Digital RGB LED Pixels Light Individually Addressable Round LED Pixels Module 25.6ft DC12V 12mm Waterproof IP68 100pcs/set (Black)
  [2]: https://i.stack.imgur.com/4fK25.jpg

body: That picture is for a 5 Volt rgb led strip. You have to use a 12 Volt power supply for your led and power the uno with another 5volt source. A computer power supply would be great for supplying power both 5 Volt and 12 Volt.