body:
I am trying to make a game where there are arrows going towards an object (in this case I printed x) and you have to evade the arrows. When you press the button it is supposed to print x on the top row and clear the bottom row with printing nothing and if you don't press the button its supposed to print x on the bottom row and nothing on the top. Then the for loop is supposed to print arrows randomly going from right to left.

**Problem: When I actually run the code I only see the x every time the arrow hits the (0,1) or (0,0) position.**

**I want the x to be there all the time.**

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

    #include <LiquidCrystal.h>
    // init the lcd display according to the circuit
    LiquidCrystal lcd(12, 11, 6, 5, 4, 3);

    String line2 = " x ";
    int xPosition;
    int yPosition;
    int yConstant;

    void setup()  {
      lcd.begin(16, 2);
      // put your setup code here, to run once:
      int switchState = 0;
      pinMode(7, INPUT);
      int leftjump = 0;
      pinMode(8, INPUT);
    }

    void loop() {
      ///////////////////////////////
      //supose tp print arrow randomly going from right to left
      xPosition = 15;
      yPosition = random(0, 10);
      if (yPosition > 5) {
        yConstant = 1;
      }
      else yConstant = 0;
      lcd.setCursor(xPosition, yConstant);
      for (int xPosition = 15; xPosition > 1; xPosition--) {
        lcd.print("<-");
        delay(100);
        lcd.clear();
        lcd.setCursor((xPosition), yConstant);
      }
      ////////////////////////////
      // suppose to print x on the top row and print nothing on buttom row
      //and otherwise when button is not pressed print x on bottom and
      //print nothing on top row
      int rightjump = 0;
      rightjump = digitalRead(7);
      if (rightjump == 1 ) {
        lcd.setCursor(0, 0);
        //delay(10);
        lcd.print(line2);
        //delay(200);
        lcd.setCursor(0, 1);
        lcd.print("  ");
      }
      else if ( rightjump == 0 ) {
        lcd.setCursor(0, 1);
        //delay(10);
        lcd.print(line2);
        //delay(200);
        lcd.setCursor(0, 0);
        lcd.print("  ");
      }
    }

title: Combing two codes to make it work on the same time but not affecting the other code?

Answers: 3

body:
> Combing two codes to make it work on the same time but not effecting the other code?

the simplest would be to have two arduino and run each piece on one of them.

body:
You have a nested loop. When your for loop is **finished** moving the arrow to column 0 then, and only then, the " x " is displayed, exactly as predicted. You can start by drawing the x from inside the for loop (before the delay) that will make it visible all the time.
It's a start anyways.

body:
There is one big problem with your program, and it is here:

> `delay(100);`

Using `delay()` is bad practice. The Arduino does _nothing_ useful while
delaying. Quite importantly, it cannot respond to user input. And to
make matters worse, you have this delay inside a loop. This means your
program will be stuck inside the loop for 1.4 seconds. And during
this time it will not take care of reading the button, nor drawing the
player on the screen.

The solution is to use `millis()` to manage your timings, and _never_
block your program while waiting for something. The approach is well
explained in the [Blink Without Delay][] Arduino tutorial. In a
nutshell: on every loop iteration, you check the clock and, if it's time
to do some particular task, you do it. If it's not time, well, you
simply don't do it. Most importantly: you don't wait. If you don't do
something on this loop iteration, no worries, you will do it on some
other iteration.

With this approach, there are some pieces of information (e.g. arrow
position) that will have to be remembered from one loop iteration to the
next. This can be done by storing that in global variables. I prefer to
to use `static` local variables though, to keep the information confined
to where it belongs.

Here is my try at your `loop()`. Notice that both the arrow and the
player are managed through the same pattern:
`if (it needs to be updated right now) { update it; }`

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

 void loop() {
  static uint32_t last_arrow_move;  // last time the arrow moved
  static int arrow_x, arrow_y;
  const int player_x = 0;
  static int player_y;

  // Update the arrow position every 100 ms.
  if (millis() - last_arrow_move >= 100) {
   last_arrow_move += 100;

   // Erase the arrow at its old position.
   lcd.setCursor(arrow_x, arrow_y);
   lcd.print("  ");

   // Move one cell to the left.
   arrow_x--;

   // If too far left, then send a brand new arrow.
   if (arrow_x < 2) {
    arrow_x = 15;
    arrow_y = random(0, 2);
   }

   // Draw the arrow at its new position.
   lcd.setCursor(arrow_x, arrow_y);
   lcd.print("<-");
  }

  // Get the updated player position.
  int new_player_y;
  if (digitalRead(7) == HIGH) {  // "jump" button pressed
   new_player_y = 0;
  } else {
   new_player_y = 1;
  }

  // Update the player if he moved.
  if (new_player_y != player_y) {

   // Erase the player at its old position.
   lcd.setCursor(player_x, player_y);
   lcd.print(" ");

   // Move.
   player_y = new_player_y;

   // Redraw at the updated position.
   lcd.setCursor(player_x, player_y);
   lcd.print("x");
  }
 }

[Blink Without Delay]: https://www.arduino.cc/en/tutorial/BlinkWithoutDelay


body:
I try to use [this][1] *ArduinoThread* library. In the Arduino I go *Sketch->Import Library->ArduinoThread*. After that I have the following line in the beginning of the sketch:

    #include <ThreadController.h>
    #include <Thread.h>
    #include <StaticThreadController.h>

I leave `setup()` and `loop()` empty and try to verify or upload the sketch on my Arduino board. But I get the following errors:
[![enter image description here][2]][2]

Is this about the library or I do something wrong?

  [1]: https://github.com/ivanseidel/ArduinoThread
  [2]: https://i.stack.imgur.com/ZMPUn.png

title: Error: `nullptr` was not declared in this scope. Arduino IDE

Answers: 1

body:
I installed Arduino IDE in two different ways (only god knows why). The first one was via using of manager `apt-get` and other was manually via downloading, unzipping and installation through the `install.sh` file.
It seems that on Ubuntu 14.04 the

    sudo apt-get install arduino

command provides an installation of an old version of Arduino IDE.
So eventually I was launching Arduino IDE by `arduino` command in my terminal (actually I was using d-menu in i3). No surprise it ran the old one installed by `apt-get`. I just removed that version by

    sudo apt-get remove arduino

And now I am using executable `arduino` inside unzipped folder. Actually, I am not using Arduino IDE explicitly at all. I am using a Makefile from [here][1].

  [1]: https://github.com/sudar/Arduino-Makefile


body:
# Problem
I'm stuck on triggering different switch. I'll explain what each of  my switch should do. Output of this setup : No output from `relayPin`

`mainPin`

 - Main power of the switch to control `relayPin` — keeps on/off
 - Override `reedPin` state
 - Let `SecondState`

`reedPin`

 - Secondary power switch to control `relayPin` — depends on `mainPin` on/off state
 - Overridden by `mainPin`
 - Let `FirstState`

*another explanation in comment

Is it caused by coding or hardware? Pardon my ignorance, it is my beginner code. I would appreciate any help, thank you.

# Code

    const int reedPin = 8; // Reed Switch
    const int mainPin = 9; // Main Switch
    const int relayPin = 6; // Relay

    int FirstState = 0;
    int SecondState = 0;

    void setup() {
        pinMode(relayPin, OUTPUT);
        pinMode(reedPin, INPUT);
        pinMode(mainPin, INPUT);

    }

    void loop() {
        FirstState = digitalRead(reedPin);
        SecondState = digitalRead(mainPin);
        if (FirstState == HIGH) {
            digitalWrite(relayPin, LOW);
        }
        else if (SecondState == HIGH) {
            digitalWrite(relayPin, HIGH);
        }
        else {
            digitalWrite(relayPin, HIGH);
        }
    }

Only `else if (SecondState == HIGH) {` works in output.

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

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

title: Help: Using if-else on two switch state

Answers: 1

body:
Draw a truth table and look at it from there.  From your words, it is confusing.  From your code it looks like this:

    mainPin    reedPin   relayPin
    HIGH        LOW      LOW
    HIGH        HIGH     LOW
    LOW         LOW      HIGH
    LOW         HIGH     HIGH

So:

    void loop() {
          digitalWrite(relayPin, !digitalRead(mainPin));
    }

If you want:

    mainPin    reedPin   relayPin
    HIGH        LOW      LOW
    HIGH        HIGH     LOW
    LOW         LOW      HIGH
    LOW         HIGH     LOW

then:

    void loop() {
          digitalWrite(relayPin, !(digitalRead(mainPin) || digitalRead(reedPin)));
    }


body:
Does anyone know what the I/O line voltage level is on the Tinyduino?

[Tinyduino][1]

I want to run a MAX7219 LED array with it, like this one:

[LED Array][2]

  [1]: https://tinycircuits.com/collections/processors/products/tinyduino-processor-board?variant=14479557959
  [2]: https://www.ebay.com/itm/MAX7219-Dot-led-matrix-MCU-control-LED-Display-module-for-Arduino-Raspberry-Pi/272583013958

title: Tinyduino I/O line voltage level

Answers: 1

body: Whatever your power supply voltage is. If you run it from 5V you get 5V IO. If you run it from a 3V coin cell you get 3V IO.


body: I was working on an Arduino Uno and while carrying it to my teacher the wire's pin got stuck into the Vcc of 5 V. Can I set Vcc to other inputs? If so, then how?

title: Can I change Vcc to some other pin?

Answers: 2

body: No, you can't. Well, you can if all you want is a few mA (just set a pin to OUTPUT and HIGH), but chances are you need more than that. So no.

body:
The VCC pin is not programmable.

However, both ICSP buses have a pin that connects to the 5V VCC line. See the diagram here: https://i.stack.imgur.com/wKz2l.png
 These are both male headers while the pin marked 5V is a female header so you will need to use a different connector than what you used previously.

If you choose to go this route, you should use the bottom ICSP header (opposite side of the board from the USB) as it is wired directly to the ATEMEGA328 chip. For this same reason, you should be very careful if you are trying to apply or draw power from any of the 5V pins as they are not protected by a fuse.


body:
I am using an Arduino Uno R3 to control my Christmas lights (a strand of 665 WS2812B LEDs).

I am using the Pololu library that can be found here:
https://github.com/pololu/pololu-led-strip-arduino
This library has been the most memory efficient one of its kind that I have found. It is the only one with which I could run my entire strand. I have been able to run it with up to 670 LEDs when compiling the code from my Windows PC.

The Arduino, while driving the LEDs, is not accessible from my PC, so I am attempting to use a Raspberry Pi with VNC installed to control it remotely, and update the Arduino code on demand. However, when compiling the exact same code (the LedStripXmas example from the Pololu library) on the Raspberry Pi, I am only able to get 650 LEDs working. If I try upload a code with more than that, the program will not run. The Raspberry Pi Arduino software also does not show the message:
"Global variables use 2,012 bytes (98%) of dynamic memory, leaving 36 bytes for local variables. Maximum is 2,048 bytes."

Is there a way to display this information from the Raspberry Pi?
Is there a difference in the PC and Raspberry Pi compilers?

Edit:
I uninstalled the IDE from the standard repository and installed the ARM version from the website. Now with the exact same code as from my PC, I am getting a ton of Narrowing warnings and the code does not run with any number of LEDs.

title: Compiling SRAM intensive code from Raspberry Pi 3

Answers: 0


body:
I would like to see the definition of CLKPR. I guess that similarly to PORTB and other registers, it should be defined by the toolchain? (see https://arduino.stackexchange.com/questions/34639/where-is-portb-defined )

- Am I right?
- Where should I look for this toolchain on Ubuntu 16.04? I tried *locate* and *find* commands in terminal with various strings relating to the toolchain expected path / files, but could not find it (tips and tricks on how I may look for such paths in the future would be welcome ;) ).

title: Where is CLKPR located on Ubuntu 16.04 with Arduino 1.8.3

Answers: 1

body:
`grep` is the command you want:

    foo@bar:~/arduino-1.8.2$ grep -r CLKPR .
    Binary file ./hardware/tools/avr/avr/lib/avr35/crtattiny167.o matches
    Binary file ./hardware/tools/avr/avr/lib/avr35/crtat90usb82.o matches
    Binary file ./hardware/tools/avr/avr/lib/avr35/crtatmega8u2.o matches
    ...
    Binary file ./hardware/tools/avr/avr/lib/avr5/crtat90pwm161.o matches
    Binary file ./hardware/tools/avr/avr/lib/avr5/crtatmega649p.o matches
    Binary file ./hardware/tools/avr/avr/lib/avr5/crtatmega168pa.o matches
    ./hardware/tools/avr/avr/include/avr/io90pwm216.h:#define CLKPR   _SFR_MEM8(0x61)
    ./hardware/tools/avr/avr/include/avr/iom329.h:#define CLKPR   _SFR_MEM8(0x61)
    ./hardware/tools/avr/avr/include/avr/iom165p.h:#define CLKPR   _SFR_MEM8(0x61)
    ...
    ./hardware/tools/avr/avr/include/avr/iom48p.h:#define CLKPR _SFR_MEM8(0x61)
    ./hardware/tools/avr/avr/include/avr/iom644pa.h:#define CLKPR _SFR_MEM8(0x61)
    ./hardware/tools/avr/avr/include/avr/ioa6289.h:#define CLKPR _SFR_IO8(0x3C)
    ./hardware/arduino/avr/bootloaders/caterina-Arduino_Robot/Caterina.h:  #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))
    ./hardware/arduino/avr/bootloaders/caterina-LilyPadUSB/Caterina.h:  #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))
    ./hardware/arduino/avr/bootloaders/caterina/Caterina.h:  #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))

So it's defined in the IO header for the chip you are using (`hardware/tools/avr/avr/include/avr/io[chip].h`). So for the '328p that's `hardware/tools/avr/avr/include/avr/iom328p.h`.


body:
I want to use an Arduino Mega at 8MHz because my power supply is bad and I have only 4.3V (no way I can fix that), which is outside the operation range of the ATMega1280 at 16MHz. I think the right way to do it is to put a pre-factor 2 on CLKPR (tell me if I am wrong)? I know that several pages explain how to do so in a sketch: see https://arduino.stackexchange.com/questions/25591/how-can-you-reduce-the-clock-frequency-of-an-arduino-mega , https://playground.arduino.cc/Code/Prescaler .

However, both those methods reduce the Mega frequency at run time, by setting the CLKPR register during the setup loop or another function, mess up with the *millis()*, *delay()*, *Serial* etc, and in addition I guess this means that the Mega is running at an out-of-spec 16MHz until the prefactor is set in the setup loop (?). So my question (I searched for it but found no answer) is:

- Can one set the clock prefactor at compile time, so that:
 - the compiler knows about it,
 - the *millis()*, *delay()*, *Serial* and similar are not disturbed
 - the register is set immediately at boot (i.e. no need to change the registers in the setup)

?

title: How to add prefactor to clock frequency at compile time?

Answers: 2

body:
1 and 3 can be solved by putting it in one of the initialization sections. 2 can be solved by creating and using a board.txt entry with the appropriate FCPU.

    #include <avr/power.h>

    void __attribute__((naked, section(".init1"))) preprescale(void)
    {
      clock_prescale_set(clock_div_2);
    }

body:
Clock speed is controlled by fuse settings and as such can be set at compile time - whether that will conflict with your bootloader is anyone's guess.

Gcc-avr allows fuse settings but you will need to burn it separately. F_CPU needs to be changed accordingly.


body:
In my current project I am measuring temperature using K-type thermocouple and MAX31855 breakout board and Arduino uno.

I have used Adafruit-max31855 library and example code from that library. But monitoring on serial monitor after some reading it is giving **NaN**.

Here is the code I have used:

    #include "Adafruit_MAX31855.h"

    int thermoDO = 5;
    int thermoCS = 6;
    int thermoCLK = 7;

    Adafruit_MAX31855 thermocouple(thermoCLK, thermoCS, thermoDO);

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

      Serial.println("MAX31855 test");
      // wait for MAX chip to stabilize
      delay(500);
    }

    void loop() {
      // basic readout test, just print the current temp
       Serial.print("Internal Temp = ");
       Serial.println(thermocouple.readInternal());

       double c = thermocouple.readCelsius();
       if (isnan(c)) {
         Serial.println("Something wrong with thermocouple!");
       } else {
         Serial.print("C = ");
         Serial.println(c);
       }
       //Serial.print("F = ");
       //Serial.println(thermocouple.readFarenheit());

       delay(1000);
    }

Circuit Diagram:

[![max31855 arduino][1]][1]

Output:

[![output][2]][2]

What could be the possible error for this and how can I solve this?

  [1]: https://i.stack.imgur.com/fh63x.jpg
  [2]: https://i.stack.imgur.com/2MvKI.png

title: MAX31855 giving NaN after some readings

Answers: 1

body:
Try to `Serial.println(thermocouple.readError())`. It will give you an
error code, which is a bit field:

* 1 = open circuit
* 2 = short to ground
* 4 = short to Vcc

C.f. the
[datasheet](https://cdn-shop.adafruit.com/datasheets/MAX31855.pdf#page=10).


body:
I have an Arduino (Pro Mini) connected to an HMI display over serial. When the user pushes a button on the HMI screen, it activates a relay attached to one of the digital pins on the Arduino.

For safety reasons, if the Arduino loses communications with the HMI, I want it to turn off the relay. So, when the button has been pushed, it triggers a polling sequence to verify that the button is still being pushed (I'm not relying on the button release event, again for safety).

The following code works perfectly if I disconnect either of the signal lines (tx or rx) or ground from the HMI. If I disconnect the +5 volts, however, the Arduino freezes completely, and therefore never shuts down the relay.

What could be causing this, and what can I do to overcome the problem?

The code is as follows, however, it works as expected if the data lines or ground are severed.

    int getNumber(const char *reqString)
    {
      sendString(reqString);

      long startTime = currentMillis;
      long waitTimer = currentMillis - startTime;

      bool responded = false;
      int endcount = 0;
      byte inbyte;
      byte bytebuffer[80];
      int bytecount = 0;

      while (waitTimer < 100 && !responded)
      {

          if (HMI.available())
          {
            inbyte = HMI.read();

            if (inbyte == 0xFF)
            {
              endcount++;
              if (endcount == 3)
              {
                responded = true;
                endcount = 0;
              }
            }
            else
            {
              endcount = 0;
            }

            bytebuffer[bytecount] = inbyte;
            bytecount++;
          }

          // Update the wait Timer.
          waitTimer = millis() - startTime;
      }

      // If we received a response, return the first data byte. If not, return 0
      if (responded)
       {
         Serial.println("Received response");
         return bytebuffer[1];
       }
       else
       {
     Serial.println("No response");
         return 0;
       }
    }

title: My Arduino freezes if power removed from the HMI

Answers: 1

body:
It seems that Software Serial is waiting for "high" on RX

Only a hardware solution comes to my mind

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/ACqxL.png)

<!-- End schematic -->

This way Arduino RX will be released on HMI power loss

Later edit

You can also use the watchdog timer to unfreeze your code when unresponsive. It will reset the Arduino if wdt_reset() is not called in a given amount of time and you can make the cleaning you need before using Software Serial again. [Here is a useful tutorial][1].

  [1]: https://circuits4you.com/2018/01/24/tutorial-on-arduino-watchdog-timer-setup/


body:
I'm working on a project for a robot and I'm trying to make a menu that can run on start up where the user can calibrate the mid-point for the servos (so they're stationary) and the ldrs so it can tell between black lines and white paper. So, I've made the menu a switch case where it calls the calibration when user enters a value, the calibration routines are their own functions.

What I want to know how to do is how to make it so when the user is finished with a calibrator it will go back to the menu function and also how to get the menu to exit on user input. So far when the menu calls a function it will just loop on it.

The menu:

    void Menu(){

      Serial.println("|****************************|");
      Serial.println("|**|Ardnoid Configuration |**|");
      Serial.println("|**|        Menu          |**|");
      Serial.println("|****************************|");
      Serial.println("");
      Serial.println("Select one of the following options:");
      Serial.println("1 LDR configuration");
      Serial.println("2 Servo calibration");
      Serial.println("3 Exit configuration menu");

      while(!Serial.available()){}
      int i = Serial.parseInt();

      switch(i){

      case 1:
        break;
      case 2:
        while(srvConOn == true){
          srvConfig();
          }
        break;strong text
      case 3:
        Serial.println("Leaving configuration menu");
        break;
      default:
        Serial.println("Unrecognized command, try again!");
        }
     }

and the servo calibration:

    void srvConfig(){

    Serial.println("");
    Serial.println("Begin servo stop calibration routine");

    int x = 0;

      while(x == 0){

        Serial.println("Enter values for servos until both are stationary");
        delay(100);

        Serial.println("Enter value for left servo");
        while (!Serial.available()) {;}
        left = Serial.parseInt();
        Serial.println(left);
        delay(100);

        Serial.println("Enter value for right servo");
        while (!Serial.available()) {;}
        right = Serial.parseInt();
        Serial.println(right);
        delay(100);

        srvR.write(right);
        srvL.write(left);

        Serial.println("have both servos stopped?");
        Serial.println("1 = Yes | 2 = No");

        int j;
        while (!Serial.available()) {;}
        j = Serial.parseInt();

        if (j == 1) {
          Serial.println("Saving calibration");
          EEPROM.write(leftMid, left);
          EEPROM.write(rightMid, right);
          srvConOn == false;
          x == 1;
          } else if (j == 2) {
            Serial.println("Try again");
            Serial.println();
            }
      }
    }

title: Making a menu through serial

Answers: 1

body:
You could put your switch/case inside an infinite loop, and return from
the `Menu()` function when the user presses '3'. E.g.:

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

    void Menu() {
        Serial.println(menu_banner);
        for (;;) {
            switch (Serial.read()) {
                case '1': ldrConfig(); break;
                case '2': srvConfig(); break;
                case '3': return;
                default: continue;  // includes the case 'no input'
            }
        }
    }


body:
I tried to write a simple program. Press button 1 servo goes to position 1, press button 2 servo goes to position 2.

But when I hook everything up my Servo goes full Crazy mode. It starts to jiggle back and forth like a madman. Even when I unhook the buttons.

What is the mistake I made? Any help is appreciated :D

Thanks in advance

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

    /* Sweep
         by BARRAGAN <http://barraganstudio.com>
         This example code is in the public domain.

         modified 8 Nov 2013
         by Scott Fitzgerald
         http://www.arduino.cc/en/Tutorial/Sweep

        modified 5-12-2017
    */

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo

    int buttonState = 0;         // variable for reading the pushbutton status
    int buttonState2 = 0;        // variable for reading the pushbutton status
    const int buttonPin = 4;     // the number of the pushbutton pin
    const int buttonPin2 = 5;    // the number of the pushbutton pin

    void setup() {
      myservo.attach(9);         // attaches the servo on pin 9 to the servo object
      pinMode(buttonPin, INPUT);
      pinMode(buttonPin2, INPUT);
    }

    void loop() {
      buttonState = digitalRead(buttonPin);
      buttonState2 = digitalRead(buttonPin2);
      if (buttonState == HIGH) {
        myservo.write(173);        // tell servo to go to position
        delay(25);                 // waits 25ms for the servo to reach the position
      }
      if (buttonState2 == HIGH) {
        myservo.write(97);         // tell servo to go to position
        delay(25);                 // waits 25ms for the servo to reach the position
      }
    }

[![photo][1]][1]

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

title: Servo start to turn like madman with simple if statement

Answers: 1

body:
Please, connect the buttons to the ground and change the code:
<!-- language-all: lang-c -->

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo

    int buttonState = 0;         // variable for reading the pushbutton status
    int buttonState2 = 0;        // variable for reading the pushbutton status
    const int buttonPin = 4;     // the number of the pushbutton pin
    const int buttonPin2 = 5;    // the number of the pushbutton pin

    void setup() {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode(buttonPin2, INPUT_PULLUP);
    }

    void loop() {
      buttonState = digitalRead(buttonPin);
      buttonState2 = digitalRead(buttonPin2);
      if (buttonState == LOW) {
        myservo.write(173);              // tell servo to go to position
        delay(300);                       // waits 25ms for the servo to reach the position
      }
      if (buttonState2 == LOW) {
        myservo.write(97);              // tell servo to go to position
        delay(300);                       // waits 25ms for the servo to reach the position
      }
    }

Pull-up resistors get a high input level when the buttons are open. Otherwise, electromagnetic interference may occur.


body:
I even rewrote the code and it still didn't work. How can I fix this?

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

    #include "pitches.h"
    void setup() {
        // put your setup code here, to run once:
        pinMode(4, OUTPUT);
    }

    void loop() {
        // put your main code here, to run repeatedly:
      tone(4, NOTE_D4, 500);
      digitalWrite(dayOne, HIGH);
      digitalWrite(Shamash, HIGH);
      delay(700);
      tone(4, NOTE_A4, 250);
      digitalWrite(dayOne, LOW);
      digitalWrite(Shamash, LOW);
      delay(350);
      tone(4, NOTE_A4, 250);
      delay(350);
      digitalWrite(dayOne, HIGH);
      digitalWrite(dayTwo, HIGH);
      digitalWrite(Shamash, HIGH);
      tone(4, NOTE_A4, 250);
      delay(350);
      tone(4, NOTE_A4, 250);
      delay(350);
      digitalWrite(dayOne, LOW);
      digitalWrite(dayTwo, LOW);
      digitalWrite(Shamash, LOW);
      tone(4, NOTE_D5, 500);
      delay(700);
      tone(4, NOTE_A4, 250);
      digitalWrite(dayOne, HIGH);
      digitalWrite(dayTwo, HIGH);
      digitalWrite(dayThree, HIGH);
      digitalWrite(Shamash, HIGH);
      delay(350);
      tone(4, NOTE_A4, 250);
      delay (350);
      tone(4, NOTE_A4, 500);
      digitalWrite(dayOne, LOW);
      digitalWrite(dayTwo, LOW);
      digitalWrite(dayThree, LOW);
      digitalWrite(Shamash, LOW);
      delay (700);
      tone(4, NOTE_G4, 250);
      digitalWrite(dayOne, HIGH);
      digitalWrite(dayTwo, HIGH);
      digitalWrite(dayThree, HIGH);
      digitalWrite(dayFour, HIGH);
      digitalWrite(Shamash, HIGH);
      delay (350);
      tone(4, NOTE_F4, 250);
      delay (350);
      tone(4, NOTE_G4, 500);
      digitalWrite(dayOne, LOW);
      digitalWrite(dayTwo, LOW);
      digitalWrite(dayThree, LOW);
      digitalWrite(dayFour, LOW);
      digitalWrite(Shamash, LOW);
      delay (700);
      tone(4, NOTE_F4, 250); //Oh chanukah oh chanuka come light the meora
      digitalWrite(dayOne, HIGH);
      digitalWrite(dayTwo, HIGH);
      digitalWrite(dayThree, HIGH);
      digitalWrite(dayFour, HIGH);
      digitalWrite(dayFive, HIGH);
      digitalWrite(Shamash, HIGH);
      delay (350);
      tone(4, NOTE_F4, 250); //Oh chanukah oh chanuka come light the meora
      delay (350);
      tone(4, NOTE_A4, 500);
      digitalWrite(dayOne, LOW);
      digitalWrite(dayTwo, LOW);
      digitalWrite(dayThree, LOW);
      digitalWrite(dayFour, LOW);
      digitalWrite(dayFive, LOW);
      digitalWrite(Shamash, LOW);
      delay(700);
      tone(4, NOTE_A4, 250);
      digitalWrite(dayOne, HIGH);
      digitalWrite(dayTwo, HIGH);
      digitalWrite(dayThree, HIGH);
      digitalWrite(dayFour, HIGH);
      digitalWrite(dayFive, HIGH);
      digitalWrite(daySix, HIGH);
      digitalWrite(Shamash, HIGH);
      delay(350);
      tone(4, NOTE_A4, 250);
      delay(350);
      tone(4, NOTE_D5, 500);
      digitalWrite(dayOne, LOW);
      digitalWrite(dayTwo, LOW);
      digitalWrite(dayThree, LOW);
      digitalWrite(dayFour, LOW);
      digitalWrite(dayFive, LOW);
      digitalWrite(daySix, LOW);
      digitalWrite(Shamash, LOW);
      delay(700);
      tone(4, NOTE_A4, 250);
      digitalWrite(dayOne, HIGH);
      digitalWrite(dayTwo, HIGH);
      digitalWrite(dayThree, HIGH);
      digitalWrite(dayFour, HIGH);
      digitalWrite(dayFive, HIGH);
      digitalWrite(daySix, HIGH);
      digitalWrite(daySeven, HIGH);
      digitalWrite(Shamash, HIGH);
      delay(350);
      tone(4, NOTE_A4, 250);
      delay (350);
      tone(4, NOTE_A4, 500);
      digitalWrite(dayOne, LOW);
      digitalWrite(dayTwo, LOW);
      digitalWrite(dayThree, LOW);
      digitalWrite(dayFour, LOW);
      digitalWrite(dayFive, LOW);
      digitalWrite(daySix, LOW);
      digitalWrite(daySeven, LOW);
      digitalWrite(Shamash, LOW);
      delay (700);
      tone(4, NOTE_G4, 250);
      digitalWrite(dayOne, HIGH);
      digitalWrite(dayTwo, HIGH);
      digitalWrite(dayThree, HIGH);
      digitalWrite(dayFour, HIGH);
      digitalWrite(dayFive, HIGH);
      digitalWrite(daySix, HIGH);
      digitalWrite(daySeven, HIGH);
      digitalWrite(dayEight, HIGH);
      digitalWrite(Shamash, HIGH);
      delay (350);
      tone(4, NOTE_F4, 250);
      delay (350);
      tone(4, NOTE_G4, 500);
      digitalWrite(dayOne, LOW);
      digitalWrite(dayTwo, LOW);
      digitalWrite(dayThree, LOW);
      digitalWrite(dayFour, LOW);
      digitalWrite(dayFive, LOW);
      digitalWrite(daySix, LOW);
      digitalWrite(daySeven, LOW);
      digitalWrite(dayEight, LOW);
      digitalWrite(Shamash, LOW);
      delay (700);
      tone(4, NOTE_F4, 500); //Oh chanukah oh chanuka come light the meora
      delay (700);

      tone(4, NOTE_F4, 250);
      digitalWrite(dayOne, HIGH);
      delay (50);
      tone(4, NOTE_F4, 250);
      digitalWrite(dayTwo, HIGH);
      delay (50);
      tone(4, NOTE_F4, 250);
      digitalWrite(dayThree, HIGH);
      delay (50);
      tone(4, NOTE_F4, 250);
      digitalWrite(dayFour, HIGH);
      delay (50);
      tone(4, NOTE_F4, 250);
      digitalWrite(Shamash, HIGH);
      delay (50);
      tone(4, NOTE_F4, 250);
      digitalWrite(dayFive, HIGH);
      delay (50);
      tone(4, NOTE_F4, 250);
      digitalWrite(daySix, HIGH);
      delay (50);

      tone(4, NOTE_G4, 250);
      digitalWrite(daySEVEN, HIGH);
      delay (50);
      tone(4, NOTE_G4, 250);
      digitalWrite(dayEIGHT, HIGH);
      delay (50);
      tone(4, NOTE_G4, 250);
      delay(250);

      tone(4, NOTE_A4, 250);
      digitalWrite(dayEight, HIGH);
      delay (50);
      tone(4, NOTE_A4, 250);
      digitalWrite(daySeven, HIGH);
      delay (50);
      tone(4, NOTE_A4, 250);
      digitalWrite(daySix, HIGH);
      delay (50);
      tone(4, NOTE_A4, 250);
      digitalWrite(dayFive, HIGH);
      delay (50);
      tone(4, NOTE_A4, 250);
      digitalWrite(Shamash, HIGH);
      delay (50);
      tone(4, NOTE_A4, 250);
      digitalWrite(dayFour, HIGH);
      delay (50);
      tone(4, NOTE_A4, 250);
      digitalWrite(dayThree, HIGH);
      delay (50);

      tone(4, NOTE_G4, 250);
      digitalWrite(dayTwo, HIGH);
      delay(50);
      tone(4, NOTE_G4, 250);
      digitalWrite(dayOne, HIGH);
      delay(50);
      tone(4, NOTE_G4, 250);
      delay(250);

      delay (300);
      tone(4, NOTE_F4, 500);
      delay (700);
      tone(4, NOTE_F4, 250);
      delay (350);
      tone(4, NOTE_F4, 250);
      delay (350);
      tone(4, NOTE_G4, 500);
      delay (700);
      tone(4, NOTE_F4, 250);
      delay (350);
      tone(4, NOTE_E4, 250);
      delay (350);
      tone(4, NOTE_F4, 750);
      delay (1000);

      tone(4, NOTE_F4, 250);
      delay (350);
      tone(4, NOTE_G4, 250);
      delay (350);
      tone(4, NOTE_A4, 250);
      delay (350);
      tone(4, NOTE_G4, 250);
      delay (350);
      tone(4, NOTE_F4, 500);
      delay (700);
      tone(4, NOTE_F4, 500);
      delay (700);
      tone(4, NOTE_G4, 500);
      delay (700);
      tone(4, NOTE_F4, 250);
      delay (350);
      tone(4, NOTE_E4, 250);
      delay (350);
      tone(4, NOTE_D4, 500);
      delay (700);
      delay (2000);
    }

title: I keep getting stray '/302'.

Answers: 1

body: The Stray /302 is saying that the compiler found some random unicode character that it didn't understand.  You should put your code into some text editor that will allow you to see the unicode characters and go find it.  It will probably be a lot easier if you'll format that code instead of trying to cram it all in one line.


body:
I am using an Arduino to read information from an EEPROM chip over I2C with the code I found here:
https://playground.arduino.cc/Code/I2CEEPROM

It works great for *int* and *char* values but I also need to read *short*, *long*, and *float* values.

They are stored in this order:  1510543923
is stored as: 01011010 00001001 00010010 00110011

How can I read multiple bytes into a single variable of these types?

I tried the following but it gives me a 16 bit number:

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

    i2c_eeprom_read_buffer(0x50, 25, (byte *)bytes, 4);
    long j = (bytes[3] << 0) + (bytes[2] << 8) + (bytes[1] << 16) + (bytes[0] << 24);

title: Read float and long from external EEPROM chip

Answers: 4

body:
> How can I read multiple bytes into a single variable of these types?

use a pointer to read each byte of a multi-byte type and save it into eeprom;

then do the same in reading them back: use a pointer to re-assemble the data (in bytes).

sizeof() comes in handy here.

Edit: lots of wonderfully complex answers for something this simple. When I get sometime I will pin my approach down.

Btw, many i2c libraries allow blocked read or write. So take that into your coding consideration.

edit2:

so here is what I have, to demonstrate how pointers can be used to write / read data.

    //simulated write to buffer
    //write n bytes of data from *ptr to address starting with addr
    void mem_write(char addr, char *ptr, char n) {
     do {buffer[addr++] = *ptr++;} while (n--);
    }

    //simulated read from buffer
    void mem_read(char addr, char *ptr, char n) {
     do {*ptr++ = buffer[addr++];} while (n--);
    }

in this particular example, mem_write() writes n bytes of data, from source pointer ptr, into buffer[] starting at address addr. the read does the same.

you can port in your i2c byte read / write routines here, or use block read/write routines for more efficiency.

to confirm that it works, I wrote the following:

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

     dat.x = 1; dat.z = 3.0;  //initialize dat
     dat_ptr = (uint8_t *)&dat; //initialize pointers
     dat_ptr1= (uint8_t *)&dat1;

     //print serial
     Serial.print("line 0: size = "); Serial.print(sizeof dat); Serial.print(", x = "); Serial.print(dat.x); Serial.print(", z = "); Serial.println(dat.z);

     //round 1: similated eeprom write/read
     mem_write(0, dat_ptr, sizeof dat);     //write to buffer
     dat1.x = 0; dat1.z = 0;        //initialize dat1
     mem_read(0, dat_ptr1, sizeof dat1);     //read from buffer
     //now, dat1 contains the same data as dat
     //print dat1 on serial -> it should read identical to line 0
     Serial.print("line 1: size = "); Serial.print(sizeof dat1); Serial.print(", x = "); Serial.print(dat1.x); Serial.print(", z = "); Serial.println(dat1.z);

     //round 2: similated eeprom write/read
     //slightly different way of doing the same
     dat.x +=1; dat.z +=10.0;       //x=2, z=13.0
     mem_write(0, (char *)&dat, sizeof dat);    //write to buffer
     dat1.x = 0; dat1.z = 0;        //initialize dat1
     mem_read(0, (char *)&dat1, sizeof dat1);   //read from buffer
     //now dat1.x = 1+1=2, dat1.z = 3.0+10.0 = 13.0
     //print dat1 on serial
     Serial.print("line 2: size = "); Serial.print(sizeof dat1); Serial.print(", x = "); Serial.print(dat1.x); Serial.print(", z = "); Serial.println(dat1.z);

    }

it essentially writes one data element "dat" into the buffer, and read it back into "dat1"; both items are printed over serial to confirm that the write / read are successful.

then I incremented on dat, and wrote it to buffer and read it back to dat1. again, printed dat1 on the serial monitor to confirm that we have the right result.

here is what I got:
[![enter image description here][1]][1]

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

so we have the expected result.

the approach here is fairly standard. Obviously, experts usually come up with far more complex ways of doing simple things, as shown earlier answers, :)

body:
It gives you a 16-bit integer because the compiler automatically makes casts. In particular:

 - `byte << int` returns `int`
 - `int + int` returns `int`

So your `(bytes[1] << 16)` is converted to an `int`, and consequently gets zeroed.

I tried to simulate this code; the results are shown as comments

    int a = 0x1234;
    long b = a << 8;
    long c = a << 8L;
    long d = ((long)a) << 8;
    Serial.println(a); // a is 0x1234
    Serial.println(b); // b is 0x3400
    Serial.println(c); // c is 0x3400
    Serial.println(d); // d is 0x123400

Personally I'd bet that `int << long` would result in a `long`, but apparently I'm wrong.

In any case, you should write

    long j= (bytes[3] << 0) + (bytes[2] << 8) + (((unsigned long)bytes[1]) << 16) + (((unsigned long)bytes[0]) << 24);

This should fix your error. In any case, you can also simply write

    long write_value;
    i2c_eeprom_write_page(0x50, 25, (byte *)&write_value, sizeof(write_value));
    long read_value;
    i2c_eeprom_read_buffer(0x50, 25, (byte *)&read_value, sizeof(read_value));

Please note that accessing directly the pointers, like in this case, will respect the endianness of the compiler. In the case of a big endian implementation, the long with value `0x12345678` will be saved as `12 34 56 78`, while with a little endian implementation it will be saved as `78 56 34 12`. This is not a problem if you always use the same platform, but if you are trying to transfer information over a network you will have to ensure that all the devices have the same endianness or manually correct it

body:
>  1510543923 is stored as: 01011010 00001001 00010010 00110011

This is known as “big endian”, or “MSB first”, because the most
significant byte (MSB, here 01011010) comes first.

I recommend against this order. If you can, swap all the bytes and store
the value LSB first, i.e. with the least significant byte first, and the
most significant byte last. This will make your life easier since it's
the order used internally in the Arduino. If you can go little endian,
then you will be able to read the data straight into the required
variable, with no conversion needed, as in:

    i2c_eeprom_read_buffer(0x50, 25, (byte *) &j, sizeof j);

and it will work identically with any data type.

If you cannot choose the byte order (maybe you cannot control what is
inside the EEPROM), then you will have to reverse all the bytes. You can
do this either with bit shifts or by explicitly moving bytes.

> `bytes[1] << 16`

This will not work. Per the rules of the C++ language, `bytes[1]` is
implicitly promoted to `int` type before the shift, then it is shifted
as an `int`. But on your Arduino an `int` is 16-bits long, thus by
shifting it 16 positions you are dropping off _all_ of the bits.
Actually, this is even worse: you are invoking what is known as
_undefined behavior_, meaning that it is considered nonsense and the
compiler is free to interpret however it wants.

To do this properly, you first have to _explicitly_ cast `bytes[i]` to
`unsigned long`. It has to be unsigned because changing the sign bit on
a `long` by bit shifting is also undefined behavior. Thus, the proper
way of reconstructing the number via bit shifts is:

    long j = ((unsigned long) bytes[3] << 0)
           | ((unsigned long) bytes[2] << 8)
           | ((unsigned long) bytes[1] << 16)
           | ((unsigned long) bytes[0] << 24);

This is portable (it should also work on big-endian architectures) but
only works with integral types, not with floats.

For reconstructing a float, my preferred option would be to use a
`union`, in order to access the bytes of the variable explicitly. Then
you just have to copy the bytes from the buffer to the `union` in
reverse order:

    union { float f; byte b[4]; } data;
    data.b[0] = bytes[3];
    data.b[1] = bytes[2];
    data.b[2] = bytes[1];
    data.b[3] = bytes[0];
    float x = data.f;

One nice thing about this approach is that it works with any data type.

body:
Using [template functions][1] this could be written as:

    template<class T> void i2c_read(uint16_t addr, T& x)
    {
      i2c_eeprom_read_buffer(0x50, addr, &x, sizeof(T));
    }

    template<class T> void i2c_write(uint16_t addr, T& x)
    {
      i2c_eeprom_write_buffer(0x50, addr, &x, sizeof(T));
    }

These two functions take the data type as template parameter. Some examples:

      long x = 0x12345;
      i2c_write<long>(0, x);

      long y = 0;
      i2c_read<long>(0, y);

With `auto` the functions could be written as:

    void i2c_read(uint16_t addr, auto& x)
    {
      i2c_eeprom_read_buffer(0x50, addr, &x, sizeof(x));
    }

    void i2c_write(uint16_t addr, auto& x)
    {
      i2c_eeprom_write_buffer(0x50, addr, &x, sizeof(x));
    }

With `auto` the compiler will determine the data type.

Cheers!

  [1]: https://playground.arduino.cc/Code/EEPROMWriteAnything


body:
I am working on an Arduino project, where I am transmitting GPS data between two Arduinos. This code can transmit the raw GPS data:

    int a = Serial1.available();
    if(a){
        uint8_t hej[a];
        for(int i=0; i<a; i++){
            hej[i] = Serial1.read();
        }

        rf95.send(hej, a);
    }

I need to be able to identify the device that's transmitting the data. This can be in form of an integer value. I have tried to add a value to the array, but that messes up the data when I receive it.
Is there a simple way to add an ID to the data I am transmitting?

title: Add id to raw data in an array

Answers: 3

body:
I would suggest:

1. Use a library (TinyGPS++ for example) to read the GPS data and extract just what you want.
2. Use a `struct` to craft a packet that you can send over bluetooth, or send the data as a textual representation, depending on your needs.

For a struct you can:

    struct packet {
        uint8_t id;
        float latitude;
        float longitude;
    };

    struct packet myPacket;
    myPacket.id = 32; // Unique ID
    myPacket.latitude = gps.getLatitude(); // Whatever function call here
    myPacket.longitude = gps.getLongitude(); // or whatever
    rf95.send((uint8_t *)&myPacket, sizeof(struct packet));

body:
Well, the main problem here is that you don't know when the string will enter from the serial port. For instance, let's see a sample communication:

    $GPGGA,154655,4328.1874,N,00340.5185,W,1,03,08.5,-00044.7,M,051.6,M,,*79
    $GPGSA,A,2,13,23,25,,,,,,,,,,08.5,08.5,00.9*0E
    $GPGSV,3,1,10,02,50,290,26,04,60,210,26,08,33,173,29,10,21,296,00*7E

Making a sample reading like this:

    int a = Serial1.available();
    if(a){
        uint8_t hej[a];
        for(int i=0; i<a; i++){
            hej[i] = Serial1.read();
        }

        Serial.print("Received \"");
        Serial.write(hej, a);
        Serial.println("\"");
    }

you will see something like

    Received "$GPG"
    Received "GA,1546"
    Received "5"
    Received "5,4"

or, most probably,

    Received "$"
    Received "G"
    Received "P"
    Received "G"
    Received "G"
    Received "A"

so it is difficult to detect where to insert your ID.

I have two solutions for you.

The simpler one is to use the fact that the GPS sends formatted sentences. According to the [NMEA specification][1], the message is at most 82 chars long and is terminated by a LF (0x10) char. This means that you can do something like this (I assume you want to use a 4-chars ID, and in this case the ID is `MYID`)

    #define ID_LENGHT 5 /* 4 chars and a separator */
    #define BUFFERSIZE ID_LENGHT+82 /* ID plus the max NMEA sentence*/
    byte recvBuffer[BUFFERSIZE];
    byte recvIdx;

    void setup()
    {
     // ... other initialization

     // Fill the ID at the beginning, and prepare to store data at the end of ID
     memcpy(recvBuffer, "MYID-", ID_LENGHT * sizeof(byte));
     recvIdx = ID_LENGHT;
    }

    void loop()
    {
     // ... other program

     while (Serial1.available())
     {
      byte ch = Serial1.read();
      if (recvIdx >= BUFFERSIZE)
       continue; // Should never arrive here, since the sentences are shorter
      recvBuffer[recvIdx++] = ch;
      if (ch == 0x10) // received LF, so end of sentence
      {
       // Send the buffer (plus the identifier)
       rf95.send(recvBuffer, recvIdx);
       // Reset the idx (and so you will overwrite previous buffer
       recvIdx = ID_LENGHT;
      }
     }

     // ... Other code
    }

This approach transfers a lot more thata then needed, since you want to only transfer the latitude and longitude. So the second (and best) approach in my opinion is to have a NMEA parser on the arduino that extracts the lat and long values you need and then sends a (formatted) message to the master, with ID, lat and long.

This is the best solution, but I don't have experience with NMEA parsers so you'd better try searching online for some library and, most important, have the necessary computational power and flash available to perform this computation

  [1]: https://en.wikipedia.org/wiki/NMEA_0183#Message_structure

body:
You could try [NeoGPS](https://github.com/SlashDevin).  NeoGPS is smaller, faster, more reliable and more accurate than all other GPS libraries.  It packages all the GPS fields into a structure for you:

    #define gpsPort Serial1

    struct msg_t {
      uint8_t ID;   // A node's ID
      gps_fix fix;  // The NeoGPS structure containing all configured GPS fields
    };

    msg_t msg = { THIS_NODE_ID };

    void loop()
    {
      if (gps.available( gpsPort )) {  // parses characters
        msg.fix = gps.read();          // gets the struct when it's ready (once per second)

        rf95.send( (uint8_t *) &msg, sizeof(msg) );  // send the msg struct
      }
    }

The receiving side will similarly read into the same struct, something like:

        rf95.receive( (uint8_t *) &msg, sizeof(msg) );
        if ((msg.id == ROVER_ID) && msg.fix.valid.location) {
          // Check lat/lon against target location
           ...

This will also coordinate the RF transmission with the [GPS quiet time](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Troubleshooting.md#quiet-time-interval), helping to avoid losing GPS characters while the RF transmission is busy.

The `gps_fix` structure can be quite small, depending on what GPS fields you enable in the NeoGPS [configuration](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Configurations.md) files.  This structure is 10x to 80x smaller than the raw NMEA data, so it is transmitted very quickly.  The default configuration uses only 31 bytes; most GPS devices send about 400 bytes per second.

If you'd like to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu **Sketch -> Include Library -> Manage Libraries**.  You should also read about [Choosing a Serial Port](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Installing.md#2-choose-a-serial-port) and the [Troubleshooting](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Troubleshooting.md) tips.


body:
I am new to Arduino and Electronics and am thinking of making a 6 wheel drive all terrain platform similar to the MonsterBorg pi, but I want to use an Arduino instead of a Raspberry pi  to control the motors. The motors I intend to use need to be powerfull.
Any advice on what would be shield or motor controllers I should use would be a great help.

title: Can I use a ThunderBorg is a dual motor controller on an Arduino UNO R3

Answers: 1

body:
Hello,

You have many possibility for drive one or more motor.

 - Transistor(1 motor)
 - [L293D][1](2 motor backward and forward or 4 motor just forward)
 - [L298D ][2](like L293D but he support more Amp and Vol
 - [L293D Adafruit shield][3](4 motor)
 - ...

Here is an example for
[L293D][1]:

enable PWM(0-255), inputs digital(0-1).

Motor1 : Input1, Input2, Enable1,2

Motor2 : Input3, Input4, Enable3,4

    void motor1RotationDirection(int input1arg, int input2arg){
        digitaleWrite(input1, input1arg);//  LOW  |  HIGH
        digitaleWrite(input2, input2arg);//  HIGH |  LOW
                                         //Forward|Backward
    }

    void motor1speedRotation(int speed){
        analogWrite(enableMotor1, speed);
    }    //for motor2 is the same.

  [1]: https://www.engineersgarage.com/sites/default/files/L293D_1.jpg
  [2]: http://www.fixmasterelectronics.com.ph/wp-content/uploads/2016/06/L298-2-Channel-Motor-Driver.png
  [3]: https://playground.arduino.cc/uploads/Main/adafruit-motorshield2.jpg


body:
I am trying to work with the (new) sparkfun razor IMU 9dof, I wrote a silple sktetch to calibrate the magnetometer:

    #include <SparkFunMPU9250-DMP.h> // Include SparkFun MPU-9250-DMP library
    #include <Wire.h> // Depending on your Arduino version, you may need to include Wire.h
    MPU9250_DMP imu; // Create an instance of the MPU9250_DMP clas
    void setup() {
      Serial.begin(115200);

      Serial.println(F("Adafruit 10 DOF Board AHRS Calibration Example")); Serial.println("");

      if (imu.begin() != INV_SUCCESS){
        while (1) {
        Serial.println("Failed to initialize MPU-9250, loop forever");
       }

      }

     imu.setGyroFSR(2000); // Set gyro to 2000 dps

     imu.setAccelFSR(2); // Set accel to +/-2g

     imu.setLPF(5); // Set LPF corner frequency to 5Hz

     imu.setSampleRate(100); // Set sample rate to 10Hz

    imu.setCompassSampleRate(100); // Set mag rate to 10Hz
    }

    void loop(void){
      imu.update();

      // Print the sensor data
      Serial.print("Raw:");
      Serial.print(imu.ax);
      Serial.print(',');
      Serial.print(imu.ay);
      Serial.print(',');
      Serial.print(imu.az);
      Serial.print(',');
      Serial.print(imu.gx);
      Serial.print(',');
      Serial.print(imu.gy);
      Serial.print(',');
      Serial.print(imu.gz);
      Serial.print(',');
      Serial.print(imu.mx);
      Serial.print(',');
      Serial.print(imu.my);
      Serial.print(',');
      Serial.print(imu.mz);
      Serial.println();

      delay(50);
    }

To be sure the Arduino IDE can access to dev/ttcACM0, I did   sudo chmod 666 /dev/ttyACM0

I can dowload successfully but when I want to open the terminal I got the following error:

Erreur d'ouverture du port série « /dev/ttyACM0 ». (Port busy) (see attached screenshot)

More over when I entered dmesg on the console, I can see the following messages:

    [   94.133923] usb 3-2: USB disconnect, device number 2
    [   94.133978] cdc_acm 3-2:1.1: urb 12 failed submission with -19
    [   94.135862] cdc_acm 3-2:1.1: urb 13 failed submission with -19
    [   94.136059] cdc_acm 3-2:1.1: urb 14 failed submission with -19
    [   94.136257] cdc_acm 3-2:1.1: urb 15 failed submission with -19
    [   94.136457] cdc_acm 3-2:1.1: urb 2 failed submission with -19
    [   94.136656] cdc_acm 3-2:1.1: urb 3 failed submission with -19
    [   94.136852] cdc_acm 3-2:1.1: urb 5 failed submission with -19
    [   94.137048] cdc_acm 3-2:1.1: urb 6 failed submission with -19
    [   94.138841] xhci_hcd 0000:03:00.0: WARN Cannot submit Set TR Deq Ptr
    [   94.138843] xhci_hcd 0000:03:00.0: A Set TR Deq Ptr command is pending.
    [   94.931853] usb 3-2: new full-speed USB device number 3 using xhci_hcd
    [   95.316578] usb 3-2: New USB device found, idVendor=1b4f, idProduct=9d0f
    [   95.316581] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
    [   95.316582] usb 3-2: Product: SFE 9DOF-D21
    [   95.316584] usb 3-2: Manufacturer: SparkFun
    [   95.320306] cdc_acm 3-2:1.0: ttyACM0: USB ACM device
    [  858.774849] usb 3-2: USB disconnect, device number 3
    [  904.529058] TCP: wlp1s0: Driver has suspect GRO implementation, TCP performance may be compromised.

Does anyone outhere experienced such issue?

Thank you for your help

Fabrice

title: : Failed to open /dev/ttyACM0 (port busy)

Answers: 4

body:
`sudo apt-get purge modemmanager`
It helps me for linux user and for many other peoples.
Now I am playing with stm32f103 and opening port was painfull.
That  was problem only for stm32 chip. Arduino nano was working without problems.
Before I need reopened few times port to initiate communication.
That was painfull. After finding that solution now Arduino ID is working without problems.
 I am not sure if deleting modemmanager will have impact for my system.

body:
I solved following serial port related problems in ubuntu 18.04 as follows:

**Problem 1 :  Cannot open /dev/ttyACM0: Permission denied**
Solution  :  Grant permissions to read/write to the serial port with this terminal command --->  `sudo chmod a+rw /dev/ttyACM0`
Here replace tty port with your respective ubuntu port.

**Problem 2 : Failed to open /dev/ttyACM0 (port busy)**
Solution  : This problem appears when serial port is busy or already occupied. So kill the busy serial port with command ---> `fuser -k /dev/ttyACM0`. Here replace tty port with your respective ubuntu port.

**Problem 3 : Board at /dev/ttyACM0 is not available**
Solution : In this case, your serial port in tools menu will be greyed out. I googled a lot for this, but  none of  solution worked for me. Atlast I tried different arduino board and usb connector and it was working for me. So, if you are having old arduino board (can be solved using required drivers) or defected arduino board then only this problem arises.

body: When I had this problem I discovered that running `ps x` showed a lot of tasks involving temporary mount files. So I closed Arduino, ran `sudo rm -rf /tmp/.mount_arduin*` and restarted Arduino. The device attached successfully.

body:
You need to be part of the dial out group. Try this:
Type 'groups', is 'dialout' there ?
sudo usermod -a -G tty yourUserName
Example sudo usermod -a -G tty gil

Log off and log on again for the changes to take effect.
This has consistently worked for me and is now in some of the Arduino install packages.


body:
On the ESP8266 NodeMCU I have GPIO2 , GPIO3 , GPIO1 , GPIO9 free but when I assign them to a button they do not work. I assume it is because those pins have other function behind them. When I look at the schematic I found that they are TXD1, RXD0, TXD0, and SSD2. Is there a way to still use these pins as inputs?

If not, can I use an Arduino Uno for my inputs and send signals from there to the analog pin to my ESP8266 NodeMCU for the connection to the MQTT server?

For the record all my other pins are used so I can't use any other input pin than these 4.

title: Which input pins can I use on the ESP8266 NodeMCU

Answers: 1

body: GPIO2 is NodeMCU D4 which is U1TXD, transmit for the second UART, generally available. GPIO3 is NodeMCU U0RXD, receive for the first UART, generally available if you aren't using serial. GPIO1 is NodeMCU U0TXD, transmit for the first UART, generally available if you aren't using serial. GPIO9 is NodeMCU SPIHD and is NOT available, as it is required for the flash memory. All that is well documented in many places. You can easily use serial to move data between modules, or multiplex your input to the one module. Cannot provide much insight without more details.


body:
I'm trying to read a block of bytes from an AD5934 Impedance converter ([PDF][1]) using I2C.

This is my code so far

Preamble:

    #define AD5934_Address                    0xD
    #define AD5934_Start_Frequency            0x82
    #define AD5934_Block_Read                 0b10100001
    #define AD5934_Address_Pointer            0b10110000

Loop:

    void loop() {
      readAD5934(AD5934_Start_Frequency, test, 3);
    }

Read Function:

    byte readAD5934 (int address, long int  data, int len) {
      byte err = 0, counter;

      if (len > 32)
        return 0xFF;

      else if (len > 1) {
        // Part ONE
        Wire.beginTransmission(AD5934_Address);
        Wire.write((byte) AD5934_Address_Pointer);
        Wire.write((byte) address);

        err = Wire.endTransmission();

        // Part TWO
        Wire.beginTransmission(AD5934_Address);
        Wire.write((byte) AD5934_Block_Read);
        Wire.write(len);

        // Part THREE
        Wire.requestFrom(AD5934_Address, len);
        StartHigh = Wire.read();
        StartMed = Wire.read();
        StartLow = Wire.read();
        err = Wire.endTransmission();
      }
    return err;
    }

For some reason, the Arduino tries to read the three bytes before Part TWO is executed.

I'm aware that I'm ending the I2C transmission after the requestFrom. The datasheet for AD5934 describes how to read a block of bytes on page 26. It does not show a STOP CONDITION before the end.

The oscilloscope shows

START 0001101 WRITE ACK 10110000 ACK 10000010 ACK STOP **START 0001101 READ ACK 00000001 ACK 11000111 ACK 11111111 NACK STOP** START 0001101 WRITE ACK 10100001 ACK 00000011 ACK STOP

Short:
S 0x0D W A 0xB0 A 0x82 A P **S 0x0D R A 0x01 0xC7 0xFF NA P** S 0x0D W A 0xA1 A 0x03 A P

The highlighted part (requestFrom and three Wire.read()) should be at the end.

I've spent a long time trying to figure this out, any help would be very much appreciated.

PS. Working on a Sparkfun Pro Micro 5V

  [1]: https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjTneXr5fXXAhXIPxoKHVZdBqAQFggpMAA&url=http://www.analog.com/media/en/technical-documentation/data-sheets/AD5934.pdf&usg=AOvVaw0oxbzNHLdCt3tEmvhQ1jaS

title: Trying to read from AD5934 using Arduino on I2C

Answers: 1

body:
I think you should re-see [AD5934x datasheet][1].

To read data from AD5934, we have three ways:

- read single byte
- read block
- using pointer command

-------------------------------------------------------
If you want to read multi byte, you can refer to my way:

    unsigned long GetRegisterValue(unsigned char regAddr, unsigned char len)
    {
        unsigned long regValue = 0;
        unsigned char index;
        unsigned char wrData[2] = {0,0};
        unsigned char rdData[2] = {0,0};

        for (index = 0; index < len; index++)
        {
            wrData[0] = 0xB0; //assign pointer cmd
            wrData[1] = regAddr + index;
            I2C_Write(AD5934_ADDR, wrData, 2);
            rdData[0] = 0xff;
            I2C_Read(AD5934_ADDR, rdData, 1);
            regValue <<= 8;
            regValue += rdData[0];
        }

        return regValue;
    }

  [1]: http://www.analog.com/media/en/technical-documentation/data-sheets/AD5934.pdf


body:
I am trying to transmit serial data from terminal to Arduino and I want to reconfirm that its the same data. But I am not able to get the right answer. I want data to be HEX. I want to check only the third last and last bytes since they will be changing every time.

I tried to write it in 2 different ways but none worked.

First try:

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

    byte thisByte[]={0xAA, 0xBB, 0x06, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03};
    void setup()
    {
      // start serial port at 9600 bps:
      Serial.begin(9600);
    }

    void loop()
    {
      while (Serial.available())
      {
        delay(250);
        // get the new byte:
        byte thisByte = Serial.read();
        // add it to the inputString:
        //inputString += char(intChar);

        if(thisByte == 0x03 || thisByte == 0x03)
        {
          Serial.print(thisByte, 'Hello');
          //digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
          delay(50);             // wait for a second
          Serial.print(thisByte, 'Nothing');
          //digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
        }
        Serial.print(thisByte,HEX);
        Serial.print(" | ");
      }
    }

Second try:

    const byte message[]={0xAA, 0xBB, 0x06, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03};
    boolean found = false;

    byte byte1 = 0xAA;
    byte byte2 = 0xBB;
    byte byte3 = 0x06;
    byte byte4 = 0x00;
    byte byte5 = 0x00;
    byte byte6 = 0x00;
    byte byte7 = 0x01;
    byte byte8 = 0x01;
    byte byte9 = 0x03;
    byte byte10 = 0x03;

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

    void loop() {
      // put your main code here, to run repeatedly:
      // put your main code here, to run repeatedly:
      //int hexIn = Serial.read();
      //Serial.write(message,2);
      //Serial.write(message,sizeof(message));
      //delay(500000);
      while(Serial.available())
      {
        delay(10);  //small delay to allow input buffer to fill
        byte c = Serial.read();
        byte message = c;

        //Serial.print(c,HEX);
        //Serial.print(" | ");

        //if (c =!byte 0xAA && c =!byte 1 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA);

        if (c == message);
        //Serial.print("I received: ");
        Serial.println(c);

        // byte c = Serial.read();  //gets one byte from serial buffer
        // readmessage += c;
      } //makes the string readString
      //Serial.print(messsage);
      //readString=""; //clears variable for new input
    }

title: Receiving hex data from terminal

Answers: 1

body:
First, you have to understand what “hex” means. Basically, you are
representing binary data as _text_, where each byte is represented as
two characters. For example, the number 42 is represented as either “2A”
or “2a”. In C and C++, you can write this number as `0x2a`, but I assume
your serial stream sends the raw hex data, without the “0x” prefix.
Thus, on the serial stream you may receive the character “2” (character
code 0x32 = 50 in decimal) followed, some time later, by “a” (charcode
0x61 = 97).

What you need is a conversion routine that takes these characters and
reconstructs the binary data out of them. Here is one such routine I
use. You have to provide it with an input string `in` and an output
array `out` large enough to store the resulting binary data. The
function will return the number of bytes filled in `*size`:

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

    /*
     * Convert an hex string to binary. Spaces are allowed between bytes.
     * The output array is supposed to be large enough.
     * On return, *size is the size of the byte array.
     */
    static void hex2bin(uint8_t *out, const char *in, size_t *size)
    {
        size_t sz = 0;
        while (*in) {
            while (*in == ' ') in++;  // skip spaces
            if (!*in) break;
            uint8_t c = *in>='a' ? *in-'a'+10 : *in>='A' ? *in-'A'+10 : *in-'0';
            in++;
            c <<= 4;
            if (!*in) break;
            c |= *in>='a' ? *in-'a'+10 : *in>='A' ? *in-'A'+10 : *in-'0';
            in++;
            *out++ = c;
            sz++;
        }
        *size = sz;
    }

As a mere convenience, the function above accepts spaces within the
string, but only between bytes. Notice however that it does not attempt
to do any error checking. You may want to improve it in this respect.

Next, you have to devise a way to frame your messages on the serial
line. Serial does not provide any framing per se: it only transmits byte
one by one. When dealing with text, a common scheme is to send a
carriage return (`\r`) to indicate the end of a message. With this
convention, you sketch has to buffer the bytes it receives until it
sees a carriage return. Then it can process the whole message as a
whole. This approach is nicely explained in the blog post [Reading
Serial on the
Arduino](https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/),
by Majenko, a regular contributor to this site.

Here is an example that reads an hex string, converts it to binary, and
then sends it back as hex again:

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

    void loop()
    {
        static char buffer[1024];
        static size_t length = 0;

        if (Serial.available()) {
            char c = Serial.read();

            // On carriage return, process the received data.
            if (c == '\r') {
                Serial.println();  // echo

                // Properly terminate the string.
                buffer[length] = '\0';

                // Convert the hex data to a byte array.
                size_t byte_count = length/2;
                uint8_t data[byte_count];
                hex2bin(data, buffer, &byte_count);

                // Echo back the byte array in hex.
                for (size_t i = 0; i < byte_count; i++) {
                    Serial.print(data[i], HEX);
                    Serial.print(" ");
                }
                Serial.println();

                // Reset the buffer for next line.
                length = 0;
            }

            // Otherwise buffer the incoming byte.
            else if (length < sizeof buffer - 1) {
                Serial.write(c);  // echo
                buffer[length++] = c;
            }
        }
    }

Notice the lines with the comment “echo”: they are meant to help you see
in the terminal what you are typing. You can remove them if you do not
what the Arduino to echo your typing. I tested it by sending

<!-- language-all: lang-none -->

    AA bb06 000000 0101 03 03

and it replied

    AA BB 6 0 0 0 1 1 3 3


body:
The idea of this project is to open 3 valves one after the other for 5 minutes each, at a time like like 7am, 12pm, 4pm in a day.
The for loop should be executed at 7am, where valve 1 is open and water is pumped for 5 minutes, then valve 1 closes and valve 2 runs for 5 minutes, then valve 3 opens and runs for 5 minutes.
The program comes to a stop. Now at 12pm, the same cycle, or process repeats for the 3 valves.
The question is how do I Time the Arduino using the RTC that I can operate the valves at 7am, 12pm, and 4am?

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

    #include <SoftwareSerial.h>

    #include <DS3231.h>

    // intialise Valves for Each Vegetation Bed

    int valvePorts[] = { 4,5,6};

    int valveCount= 3;

    DS3231  rtc(SDA, SCL);

    Time t;
    const int OnHourOne = 12;   // assuming that one Tank- valve takes 5minutes each

    const int OnMinOne = 00;

    const int OffHourOne = 12;

    const int OffMinOne = 30;

    const int OnHourTwo = 16;

    const int OnMinTwo = 00;

    const int OffHourTwo = 16;

    const int OffMinTwo = 30;

    void setup()

    {

     for( int thisvalve=0; thisvalve<=valveCount; thisvalve++)

    {

     pinMode(valvePorts[thisvalve], OUTPUT);

    }

    pinMode(Waterpump,OUTPUT);             // Waterpump

      Serial.begin(9600);
    }

    void loop()

    {

       t = rtc.getTime();

      Serial.print(t.hour);

      Serial.print(" hour(s), ");

      Serial.print(t.min);

      Serial.print(" minute(s)");

      Serial.println(" ");

      delay (1000);

       if(t.hour == OnHour && t.min == OnMin)

    {

         Startwatering(1);

        }

        else if(t.hour == OffHour && t.min == OffMin)
    {
          Startwatering(0);

        }

    void Startwatering(int id)

     {

             if( id== 0)
                      {

                        return;

                      }

         //while(valvePorts[thisvalve],HIGH)

          if(id==1)

         {

       for( int thisvalve=0; thisvalve <=valveCount; thisvalve++)

    pinMode(valvePorts[thisvalve], OUTPUT);

       {

      digitalWrite(Waterpump,LOW);

     delay(5000)

      } // close for loop

         }// close if loop

     } // close for loop

title: How to Time the Arduino using RTC that I can operate the valves at 7am, 12pm, and 4 am?

Answers: 1

body:
Many ways of doing it.

1. Poll the rtc constantly until the set time is reached. Then operate the valves. Or

2. Set an alarm on the rtc for the next time to operate the valves. The rtc will interrupt the mcu when the time is up. The mcu can then operate the valves.

You don't have to use an rtc for this.


body:
What I want to do is to create a temperature measurement bracelet that you wear on your wrist.
So it takes data from the sensors and sends them to the PC.
What I am using to do that:

 - an Arduino Uno
 - a temperature sensor
 - a Bluetooth module to connect with Arduino Uno
 - a mobile phone
 - a PC

I will connect Arduino Uno with the Bluetooth module so it sends data to the mobile for example.
Since I am a beginner I do not have it very clear. Do I need a GPRS SIM (SIM900A for example or whatever) for this to function or just the Bluetooth connection is enough?

Specify that the question is very basic because I am a beginner.

title: Connecting my Arduino with Bluetooth

Answers: 2

body: Assuming the mobile device to which you are connected by bluetooth is always kept near the bracelet, you don't need a GPRS module. The mobile device, then, would use it's network connection (either GPRS, LTE, WiFi, etc.) to communicate the data to the PC for processing or storage.

body: You should only need the Bluetooth module, not a Sim card.  The HC-05 and HC-06 are Bluetooth modules that are commonly used with Arduinos, are relatively inexpensive, are fairly small, and there's quite a bit of documentation out there on how to use them.


body:
I am trying to use the [Adafruit Metro Mini][1] as Arduino (can be used the same way) to program an [IR Break Beam sensor][2] and a stepper motor. I connected the beam sensor to the breadboard and plugged the Arduino into my computer. But  my MAC pops up with the notification:

> "USB Device Disabled - Unplug the device using too much power to
> re-enable USB Devices."

What is the problem causing the issue? Did I short circuit something? I attached photos to my circuit to the post.

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

Thanks so much in advance.

  [1]: https://www.adafruit.com/product/2590
  [2]: https://learn.adafruit.com/ir-breakbeam-sensors
  [3]: https://i.stack.imgur.com/GxbPf.jpg
  [4]: https://i.stack.imgur.com/XOPTi.jpg

title: How to fix the Break Beam Sensor programming issue that says "USB Device Disabled"?

Answers: 1

body:
The stepper motor driver is installed with the error (shifted) to the breadboard.

The electrolytic capacitor at the output of the voltage stabilizer in reverse polarity.

Power to  Adafruit Metro Mini is put in inverse polarity ...


body:
I followed [this tutorial][1] to connect the ESP8266 to a wifi network using AT commands. I used the below schematics (without the connection between ESP's CPIO 0 and Arduino's Ground):

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

After that, I was able to follow through the tutorial and got this response in the Serial Monitor:

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

That means my ESP8266 has successfully connected to my Wifi named W3. However, I decided to switch the mode of my ESP8266 from Network Device (mode 1) to Both network device AND Access Point (mode 3) (at this point I called AT+CWJAP? and can still see that it's connected to W3 wifi). I then was able to see the ESP wifi in my wifi list as (AI-THINKER_4C8CF2) but when I connected to it, I cannot connect to the internet. I'm wondering what the problem is and would appreciate any help.

*Note:* **The reason why I switched to mode 3 is because I want to control an Arduino Pro Mini (instead of Arduino Pro) using NodeJS.** I followed [another tutorial][4] and I figured that I need to connect to an ESP8266 access point.

I uploaded the StandardFirmataSketchPlus to my Arduino Pro Mini, with the baud rate set to 115200 (which is the same baud rate with my ESP8266). The schematic I used is similar to the one below, except I used a 3.3V Pro Mini and a Lipo battery, instead of a 5V:

[![enter image description here][5]][5]

The nodejs code is below:

    var VirtualSerialPort = require('udp-serial').SerialPort;
    var firmata = require('firmata');
    var five = require("johnny-five");
    var sp = new VirtualSerialPort({
      host: '192.168.1.243' //I got this number from the AT command (STAIP above)
     });

    var io = new firmata.Board(sp);

    io.once('ready', function(){
        io.isReady = true;

        var board = new five.Board({io: io, repl: true});

        board.on('ready', function(){
            var led = new five.Led(12);
            led.blink(3000);
        });
    });

This code is to test the connection between Arduino and Nodejs and when I run this file, it doesn't work.

  [1]: https://www.agcross.com/2015/09/the-esp8266-wifi-chip-part-2-connecting-to-a-network/
  [2]: https://i.stack.imgur.com/nD18w.png
  [3]: https://i.stack.imgur.com/40WaU.png
  [4]: https://medium.com/@imkiran/connecting-johnny-five-arduino-raspberry-pi-etc-over-wifi-to-the-pc-using-esp8266-a10348fdb300
  [5]: https://i.stack.imgur.com/BxKjQ.jpg

title: ESP8266 cannot connect to an existing network after using AT command

Answers: 1

body:
you have Firmata in Atmega, AT firmware in ESP and the 'blink led' js on computer.

you did not follow [the tutorial][1] properly. it requires [jonny-five firmware][2] in esp8266

  [1]: https://medium.com/@imkiran/connecting-johnny-five-arduino-raspberry-pi-etc-over-wifi-to-the-pc-using-esp8266-a10348fdb300
  [2]: https://github.com/anaganisk/johnny-five-esp8266.git


body:
I have a DS18B20 temperature sensor that needs between 3v and 5.5v to work, as seen in its documentation.

What's the difference? Should it work better which 5.5v?

I know that a LED with more voltage will bright more but it will burn or a pump with more voltage will take water faster.  But what about the temperature sensor?

![DS18B20 temperature sensor](https://i.stack.imgur.com/tfjK3.jpg)

title: Which voltage should I use with a component that allows between 3v and 5.5v?

Answers: 3

body:
<p>It's the same thing for a measurement module. You can use the 5V of the arduino, but with a resistance of 4.7KΩ between "Data" and "5V".<p> Like this example [![enter image description here][1]][1]

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

body:
According to the datasheet the absolute maximum is -0.5 V to 6.0 V.

The normal voltage for which it works according to the specifications in the datasheet is 3.0 V to 5.5 V.

That means het DS18B20 works well with 3.3 V and just as well with 5.0 V. One voltage is not "better" than the other. There is not difference. You can use it with a 3.3 V Arduino board and with a 5 V Arduino board.

The power it uses when being active is 1 mA * 5.0 V = 5 mW. It is possible that it causes some self-heating. But let's not go there. That is something for nerds.

body:
When a sensor like this allows a range of power supply voltages it's not because one voltage is "better" than another. It's purely to allow it to work with a wider range of controllers.

The voltage you would use it with is more dictated by what it is you are using it with. If you are using it with a 5V microcontroller, such as the Arduino Uno then you would run the sensor at 5V, since that is the logic levels your MCU will be working at.  If you are using it with a 3.3V microcontroller, such as a Teensy, Due, or chipKIT board, then you would run the sensor at 3.3V to maintain the right logic levels for the board you are using.

By running both the MCU and the sensor at the same voltage you remove the need for any logic level translation between the two.


body:
I am making a project using arduino uno & A7 gsm+gps+gprs module.my circuit connection is like this:

    A7 UTXD -> arduino RX
    A7 RTXD -> arduino TX
    A7 GND -> arduino GND
    A7 pwr_key -> A7 VCC5.0

When i make call from my mobile to A7,it's ok.But i cannot get call/msg from A7.
Here is my code for making call:

    char phone_no[]="phone_no";

    void setup()
    {
    Serial.begin(9600);
    delay(200);
    Serial.println("AT");
    delay(1000);
    Serial.print("ATD");
    Serial.println(phone_no);
    //Serial.println(";");
    delay(10000);
    Serial.println("ATH");
    }

    void loop()
    {
    }

What can i do now??? Please help me to fix it.I apologize for my poor english.

title: Can't get call / message from A7 gsm+gprs+gps module

Answers: 1

body:
Increase your second delay to 2000 (ie. 2 seconds).

    delay(2000);


body:
I was studying the ISR for twi and I want to know how is it working.

I have two questions about the code handling for ISR and the other functions and what they do exactly:

1. My first question is about how ISR for twi is working? The following example shows a piece of the ISR for twi library. My concern here is how switch statement is working?

And probably I have to understand how TWSR works; for example, I think when twi module sends or receive an address, the TWSR is updated according to TWSR Status codes. But I really don't understand exactly what is happening?! Which happens first?

The programmer issue the twi operation; like, sending a start address. Then, the TWSR is updated with the code 0x08 which means according to the datasheet "A START condition has been transmitted". If that so, then why in the following ISR code. The status code is called as a switch result for twi operation, then it issue an action based on that??!! that what is confusing to me!
So, is the procedure of twi:
1. Send start address.
2. TWSR is updated with 0x08 as a confirmation for the start action.
3. Here the ISR issues another action based on the TWSR again? This is what I didn't understand.

    ISR(TWI_vect)
    {
      switch(TW_STATUS){
        // All Master
        case TW_START:     // sent start condition
        case TW_REP_START: // sent repeated start condition
          // copy device address and r/w bit to output register and ack
          TWDR = twi_slarw;
          twi_reply(1);
          break;

2. My second question is about the relationship between ISR and other functions. For example,

          if (true == twi_inRepStart) {
        twi_inRepStart = false;
        do {
          TWDR = twi_slarw;
        } while(TWCR & _BV(TWWC));
        TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE);
        }
        else
        TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE) | _BV(TWSTA);
        while(wait && (TWI_MTX == twi_state)){
        continue;
        }

Here is another start send address operation. So which one is the real one? The start send in the ISR or this one?

title: Difference between ISR and other functions in AVR twi library

Answers: 2

body:
The confusing thing is that there is only one interrupt, and it is called for a number of different reasons.

To make sense of why it's being called you also have to know what you have just done in order to know what to expect. In this case we have just sent a START bit, so we set the current status to "start sent". When the interrupt fires we know that it must be in response to the start bit we sent earlier having been completed, so it's time to then send the address.  It's just implementing a simple state machine.

To answer your second question: both are "real" and used.

When sending data to a slave it can be easily implemented with a non-blocking interrupt arrangement. This makes it fast and efficient, and you can get on with doing other things while the data is being sent. That uses the ISR.

When reading from a slave it's harder to implement it with an ISR and still fit into the Arduino ethos of "data is available immediately", so when using `requestFrom` a simpler blocking routine is called that doesn't use the ISR. This means that when the function is completed all the data has been received and you can get on with reading it from the buffer. If you used the ISR instead then data wouldn't have arrived until some unknown time after you have made the request - so you would have to implement either some kind of callback system to execute a user function when the data has arrived, or manually block waiting for the data to arrive polling a status set by the ISR, which is pretty pointless anyway. So it's just been implemented as a simple blocking routine.

It's crude, but like much of the Arduino API it "gets the job done with the minimum of fuss" - sacrificing efficiency for simplicity and ease of use.

----

To break it down for you further:

1. When using `Wire.beginTransmission(...)` the ISR is used to empty the buffer onto the physical wires. Your sketch can continue while that is happening.
2. When using `Wire.requestFrom(...)` the ISR is *not* used. Your sketch cannot continue until the whole buffer has been received (or it times out).

When using `Wire.beginTransmission(...)` you first fill the buffer (32 bytes maximum) with your data to send. Calling `Wire.endTransmission(...)` then starts the sending of the data from the buffer using the ISR.

When you use `Wire.requestFrom(...)` a call to the `Wire.beginTransmission(...)` and `Wire.endTransmission(...)` functions are called to send the address. This uses the ISR.  Following that the `twi_readFrom(...)` function is called to receive the data in a blocking fashion. That first blocks itself waiting for the ISR to signal that the I2C bus is available and it has finished sending the address. The `twi_readFrom(...)` function then, if it's using *repeated start*, sends the start bit again. If it's not using *repeated start* then it just gets on with the task of reading the data into the buffer.  The actual reception of the data triggers an interrupt which copies the data into the incoming RX buffer from the FIFO, but that's pretty much all the interrupt does when receiving.

Much of the confusion (and it's confusing even to me) comes because the Wire library is written in two layers - an Arduino API wrapper class which implements the Wire object that you are familiar with, and a pure C set of helper functions which most likely were ported over from some other Atmel application library originally. This makes it quite hard to follow what is going on, since the two programming styles and ways of working are very different. Following the thought processes of two different parties working in different ways with different goals in mind is tricky at best.

To better understand how it all fits together you want to sit down with a couple of example transactions (both read and write) and a copy of the datasheet and trace exactly how the program would flow and respond to the different events and sequences within those transactions. Have the transaction waveforms on paper in front of you and mark on them where the different interrupts trigger. Follow that through in the code and work out what exactly gets called when and why it gets called. Quite an arduous task, but essential if you want to fully understand exactly what is going on in the code.

body:
ISRs are triggered by status (more precisely status changes). For example, once the device address is sent, the hardware will set a flag, which will be serviced by the isr; if the data is sent, the hardware will set another flag, triggering the isr....

It is through this process that the transmission is carried out in an orderly fashion, without tying up the mcu.

For a more detailed description of how avr i2c modules work, check out datasheet for older lpc/nxp mcus.

The other approach is for the mcu to poll the hardware and process the flags accordingly.

Hope it helps.


body:
Whenever I use multiple devices on SPI, [TFT Screen][1], and the BME280 breakout board from Adafruit, the Arduino fails to detect the devices.

Code of the screen separately (works)

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

    // include the necessary libraries
    #include <SPI.h>
    #include <SD.h>
    #include <TFT.h>  // Arduino LCD library

    // pin definitions
    #define sd_cs  7
    #define lcd_cs 10
    #define dc     9
    #define rst    8

    // Define screen pins
    TFT TFTscreen = TFT(lcd_cs, dc, rst);

    //Define variables
    char sensorPrintout[4];
    char sensorPrintout2[4];

    // this variable represents the image to be drawn on screen
    PImage logo;

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

      Serial.print("Initializing SD card...");
      if (!SD.begin(sd_cs)) {
        Serial.println("failed!");
        return;
      } else {
        Serial.println("OK!");
      }

      // Start and clear TFT screen
      TFTscreen.begin();
      TFTscreen.background(0, 0, 0);

      // Lookup image on TFT screen
      logo = TFTscreen.loadImage("Logo.bmp");
      if (!logo.isValid()) {
        Serial.println("error while loading Logo.bmp");
      }
      if (logo.isValid() == false) {
        return;
      }

      //Draw logo on the screen
      Serial.println("drawing image");
      TFTscreen.image(logo, 0, 0);

      // Change textcolor to white
      TFTscreen.stroke(255,255,255);

      //Write some text
      TFTscreen.setCursor(0,25);
      TFTscreen.print("Schuif 1: ");
      TFTscreen.setCursor(75,25);
      TFTscreen.print((char)247);
      TFTscreen.print("C");

      //Write some text
      TFTscreen.setCursor(0,50);
      TFTscreen.print("Schuif 2: ");
      TFTscreen.setCursor(75,50);
      TFTscreen.print((char)247);
      TFTscreen.print("C");
    }

    void loop() {
      // Read value of A0
      int value = analogRead(A0);
      Serial.println(value);
      float voltage = value * (5.0/1023.0);
      Serial.println(voltage);
      String sensorVal = String(analogRead(A0));
      String sensorVal2 = String(voltage);

      // Change sensor value to a character array
      sensorVal.toCharArray(sensorPrintout, 4);
      sensorVal2.toCharArray(sensorPrintout2, 4);

      // Change text color to white
      TFTscreen.stroke(255,255,255);

      // Write value of sensor 1
      TFTscreen.setCursor(55,25);
      TFTscreen.print(sensorPrintout);

      // Write value of sensor 2
      TFTscreen.setCursor(55,50);
      TFTscreen.print(sensorPrintout2);

      // wait  500ms
      delay(1000);

      // Change text color to black
      TFTscreen.stroke(0,0,0);

      // Write value of sensor 1
      TFTscreen.setCursor(55,25);
      TFTscreen.print(sensorPrintout);

      // Write value of sensor 2
      TFTscreen.setCursor(55,50);
      TFTscreen.print(sensorPrintout2);
    }

Code of the BME280 separately (works)

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

    #include <Wire.h>
    #include <SPI.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BME280.h>

    #define BME_SCK 13
    #define BME_MISO 12
    #define BME_MOSI 11
    #define BME_CS 6

    #define SEALEVELPRESSURE_HPA (1013.25)

    Adafruit_BME280 bme(BME_CS); // hardware SPI

    unsigned long delayTime;

    void setup() {
      Serial.begin(9600);
      Serial.println(F("BME280 test"));

      bool status;

      // default settings
      // (you can also pass in a Wire library object like &Wire2)
      status = bme.begin();
      if (!status) {
        Serial.println("Could not find a valid BME280 sensor, check wiring!");
        while (1);
      }
      Serial.println("-- Default Test --");
      delayTime = 1000;
      Serial.println();
      delay(100); // let sensor boot up
    }

    void loop() {
      printValues();
      delay(delayTime);
    }

    void printValues() {
      Serial.print("Temperature = ");
      Serial.print(bme.readTemperature());
      Serial.println(" *C");

      Serial.print("Pressure = ");
      Serial.print(bme.readPressure() / 100.0F);
      Serial.println(" hPa");

      Serial.print("Approx. Altitude = ");
      Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
      Serial.println(" m");

      Serial.print("Humidity = ");
      Serial.print(bme.readHumidity());
      Serial.println(" %");
      Serial.println();
    }

Code of the TFT screen with the BME280 (doesn't work)

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

    // include the necessary libraries
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BME280.h>
    #include <SPI.h>
    #include <SD.h>
    #include <TFT.h>   // Arduino LCD library
    #include <Wire.h>

    // pin definitions
    #define bme_cs  6
    #define sd_cs   7
    #define rst     8
    #define dc      9
    #define lcd_cs 10
    #define mosi   11
    #define miso   12
    #define sck    13

    //var definitions
    #define SEALEVELPRESSURE_HPA (1013.25)

    //Define hardware SPI connection with BME280
    Adafruit_BME280 bme(bme_cs); // hardware SPI

    // Define screen pins
    TFT TFTscreen = TFT(lcd_cs, dc, rst);

    //Define variables
    char sensorPrintout1[6];
    char sensorPrintout2[6];
    unsigned long delayTime;

    // this variable represents the image to be drawn on screen
    PImage logo;

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

      bool status;

      // Initializing SD card
      Serial.print("Initializing SD card...");
      if (!SD.begin(sd_cs)) {
        Serial.println("failed!");
        //while (1);
      } else {
        Serial.println("OK!");
      }

      //Initializing BME280
      Serial.print("Initializing BME280");
      status = bme.begin();
      if (!status) {
        Serial.println("Could not find a valid BME280 sensor, check wiring!");
        while (1);
      } else {
        Serial.println("BME 280 sensor found");
      }

      // Start and clear TFT screen
      TFTscreen.begin();
      TFTscreen.background(0, 0, 0);

      // Lookup image on TFT screen
      logo = TFTscreen.loadImage("Logo.bmp");
      if (!logo.isValid()) {
        Serial.println("error while loading Logo.bmp");
      }
      if (logo.isValid() == false) {
        return;
      }

      //Draw logo on the screen
      Serial.println("drawing image");
      TFTscreen.image(logo, 0, 0);

      // Change text color to white
      TFTscreen.stroke(255,255,255);

      //Write some text
      TFTscreen.setCursor(0,25);
      TFTscreen.print("temperatuur 1: ");
      TFTscreen.setCursor(100,25);
      TFTscreen.print((char)247);
      TFTscreen.print("C");

      //write some text
      TFTscreen.setCursor(0,50);
      TFTscreen.print("luchtvochtigheid 2: ");
      TFTscreen.setCursor(100,50);
      TFTscreen.print((char)37);
      TFTscreen.print("C");
    }

    void loop() {
      // Read value of temperature
      int value1 = bme.readTemperature();
      int value2 = bme.readHumidity();
      String sensorVal1 = String(value1);
      String sensorVal2 = String(value2);

      // Change sensor value to a character array
      sensorVal1.toCharArray(sensorPrintout1, 6);
      sensorVal2.toCharArray(sensorPrintout2, 6);

      // Change text color to white
      TFTscreen.stroke(255,255,255);

      // Write value of temperature sensor
      TFTscreen.setCursor(55,25);
      TFTscreen.print(sensorPrintout1);

      // Write value of humidity sensor
      TFTscreen.setCursor(55,50);
      TFTscreen.print(sensorPrintout2);

      // wait  500ms
      delay(1000);

      // Change text color to black (aka overwrite text)
      TFTscreen.stroke(0,0,0);

      // Write value of temperature sensor
      TFTscreen.setCursor(55,25);
      TFTscreen.print(sensorPrintout1);

      // Write value of humidity sensor
      TFTscreen.setCursor(55,50);
      TFTscreen.print(sensorPrintout2);
    }

Now this is the serial output:

    Initializing SD card...failed!
    Initializing BME280Could not find a valid BME280 sensor, check wiring!

At first it only showed the first line, then it stopped because of the `while(1)` loop. So I put it in comment to see if the BME initializes on its own.

I also tested the screen+SDcard and the BME280 separately, which worked just fine.

**Update**

I tried to test the programs with the complete circuit. The program of the TFT screen works fine that way but when I try the program of the BME280 it doesn't work. I have to remove the TFT screen from the breadboard to make it work.

**Update 2**

After some measurements with the scope I determined that the MOSI is pulled to 0V when I connect the 5V to the TFT screen. I also saw that the MOSI output on the BME280 board is 3.3V instead of 5V.

Could it be that the conflict in voltages is the cause for all my troubles?

 [![Circuit][2]][2]

  [1]: https://www.arduino.cc/en/Guide/TFT
  [2]: https://i.stack.imgur.com/TAIIy.png

title: Multiple devices on SPI

Answers: 2

body: Connect the BME280 board by I2C, it cannot be used in a multi-SPI setup. The problem is that the MISO line it not decoupled from the bus if CS is HIGH but constantly pulled HIGH. This will disturb other bus members.

body:
Please check [my blog post about this issue][1] exactly.

The main idea is that the different SPI components do not respect the chip select and interfere with each other on the SPI bus. The way I solved it was to toggle between the different components using an array of switches- transistors in a way that in any given time only one component is connected to my Arduino (or any other master) through the SPI.

# How to use multiple SPI devices with Arduino

While building my SmartHomeDIY project I encountered a problem trying to use multiple SPI devices connected to the same Arduino. Although the SPI bus should support multiple devices at the same time (toggling the Chip-Select line), this does not always work (mostly due to the part using the bus not respecting the chip select or other configuration issues). So after reading for some time and experimenting I came up with the following solution.

The above station is an IR recorder and sransmitter station. It can be set into recording state, which then saves the recorded IR-in data into and SDCard connected over SPI. But when not in recording mode it will listen over the RF24 (also connected via SPI) for commands. Once a command is given it will try to send the IR code request (for example turn TV on). To do that it will again have to move to SDCard mode and read the previously recorded data and retransmit it over the IR out LED.

So to solve this I have connected the SPI lines to couple of transistors/switches, then just CUT the lines of the part not being used at the moment and there for prevent the SPI lines collision.

Attached is the code and hardware layout to do just that.

Note that it does not matter which type of project you have. You can always do the same transistor-switch trick to cut of the problematic SPI lines while using the others.

A special note for the transistor configurations. It will not work if you pass as usually suggested, which means to set a logic level by design at the output of the transistor so that the base will toggle the out voltage (same as an amplifier).

Instead I set the signal to go trough the transistor, which is needed, so testing to select the transistor, which does not affect the actual signal (it will depend on the transistor type, spec and configuration...). So it took me some time to figure out the right transistor values and configuration.

For trial and error I used a logic analyzer with 8 logic lines or an oscilloscope.

I inspected the incoming signal and the outgoing signal to make sure the transistor does not temper with the incoming signal, so everything will continue to work as expected (the transistor is transparent to the actual data).

You could also use this logic multiplexer [8 Channel Logic Level Converter Convert TTL Bi-directional] to do the same job, which I have not tested yet. But I think my way is more fun! :)

  [1]: https://www.2bitornot2bit.com/blog/how-to-use-multiple-spi-devices-with-arduino


body:
I am newbie on Arduino and TFT Screens. But I am a semi-professional on programming and I decided to develop a device that can be controlled by Arduino via capacitive touch screen (there will be 2 buttons on the screen and while one of them will increase the current of a device, other will decrease). To do that, I've bought a complete solution (Arduino Mega + 5" TFT LCD + Arduino Shiled but without Resistive touch screen - [this one][1]), instead of resistive touch screen, I've bought [this one][2] and I've bought a separate PSU.

At the end, I have an Arduino Mega, 5 inch TFT Display, 5 inch Multi Touch Screen Panel with Controller GSL1680F (assembled to the Display) and Arduino Shield which is produced for this system. But I don't know how to communicate these three devices with each other. I know that, Arduino has built-in storage for the codes, and both TFT Display and Shield have micro-sd storage slots for placing codes. E.g. I don't know what is the aim of micro-sd storage slot on the shield.

As a result, is there any code samples / tutorials / video that I can follow to develop with this system? Thanks.

  [1]: http://www.buydisplay.com/default/display-5-inch-tft-arduino-touch-shield-ssd1963-for-mega-due
  [2]: http://www.buydisplay.com/default/5-inch-capacitive-touch-panel-screen-with-controller-gsl1680f

title: Programming 5 inch TFT Display + Arduino Mega with Touch Shield (w/SSD1963)

Answers: 0