message:
'Serial1' was not declared in this scope

Trying to do serial communication between 2 Arduino Unos.

Code:

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

    #include <SoftwareSerial.h>

    int ledPin = 13;
    int board;   // 1 = Uno. 2 = Mega.
    int on_off;  // 1 = On. 0 = Off.
    int buzzerPin = 9;
    int Ack_tx = 2; //Acknowledgement tx.
    int rec;

    void setup()
    {
      Serial.begin(9600);      // start serial communication at 9600bps
      Serial1.begin(9600);     // start serial1 communication at 9600bps

      pinMode(ledPin, OUTPUT);
      pinMode(buzzerPin, OUTPUT);

      Serial.flush();
      Serial1.flush();

    } // End Setup

    void loop()
    {

      Serial.println("Enter Uno=1/Mega=0 ...");  //Select board
      //  if(!Serial){ board = Serial.read();}
      while(Serial.available()==0) { // Wait for User to Input Data
      }
      board = Serial.parseInt();  //Read the data the user has input

      Serial.println("Enter LED On=1/Off=0 ...");  //Select On or Off
      while (Serial.available()==0) { // Wait for User to Input Data
      }
      on_off = Serial.parseInt();

      Serial.println();

      switch (board) {

      case 0:  //Mega board
        if (on_off == 1) digitalWrite(ledPin, HIGH); //Select Uno LED On
        else digitalWrite(ledPin, LOW);              //Select Uno LED Off
        break;  //End Case

      case 1:  //Uno board
        //Serial.println("Off to Uno...");
        //Send on_off info to Uno
        Serial1.write(on_off/256); //Send the Quotient or "how many times" value
        Serial1.write(on_off%6); //Send the Modulo or Remainder.
        delay(50); //Wait for the serial port.

        while(Serial1.available()<2) //Wait for 2 bytes to arrive
         {
          //do nothing
         } //End While

      byte b1=Serial1.read();  //Read Upper byte
      byte b2=Serial1.read();  //Read Lower byte
      rec=(b1*256)+b2;

        if (rec == Ack_tx) tone(buzzerPin, 300, 300); //Ack_tx from Uno
        break;
      } //End Switch Case

    }

Error:

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

    Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

    C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void setup()':

    sketch_mar06a:13: error: 'Serial1' was not declared in this scope

       Serial1.begin(9600);     // start serial1 communication at 9600bps

       ^

    C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void loop()':

    sketch_mar06a:51: error: 'Serial1' was not declared in this scope

         Serial1.write(on_off/256); //Send the Quotient or "how many times" value

         ^

    Multiple libraries were found for "SoftwareSerial.h"
     Used: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial
     Not used: C:\Program Files (x86)\Arduino\libraries\SoftwareSerial
    exit status 1
    'Serial1' was not declared in this scope

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

This is a very basic problem I know, but nothing on the internet is helping.

body: The Uno has no `Serial1`. It only has one serial port, called `Serial`. To use `Serial1` you will need a bigger board such as a Mega2560, or define it as a `SoftwareSerial` port and use two other IO pins of your choice for it, though at lower baud rates than `Serial` can run at.


sender: user

sender: assistant

body:
You import the `SoftwareSerial` library but you however never instance an object of the `SoftwareSerial` class.

You just need to add the line

     SoftwareSerial Serial1(10, 11); // RX, TX

after including the library header (taken from [here][1])

This now creates an object `Serial1` on which the operations down there should work the same as with a real hardware serial (API-wise).

Side note: Careful with the wiring. You are using this `Serial1` emulated UART to communicate between the boards, so if you're using above pin numbers (D10 = RX, D11 =TX) then you must connected D10 (Board1) -> D11 (Board2), D11 (Board1) -> D10 (Board2), i.e. RX->TX, TX->RX.

  [1]: https://www.arduino.cc/en/Tutorial/SoftwareSerialExample


message:
Trouble uploading sketch / error in sketch

I am following [this tutorial][1] of a very basic serial communication between 2 arduino unos.

I have made the connections as given and connected the arduino unos to 2 separate laptops via USB.

Code1:

    char mystr[3] = "Hello"; //String data

    void setup() {
      // Begin the Serial at 9600 Baud
      Serial.begin(9600);
    }

    void loop() {
      Serial.write(mystr,5); //Write the serial data
      delay(1000);
    }

Code 2:

    char mystr[5]; //Initialized variable to store recieved data

    void setup() {
      // Begin the Serial at 9600 Baud
      Serial.begin(9600);
    }

    void loop() {
      Serial.readBytes(mystr,5); //Read the serial data and store in var
      delay(1000);
    }

Error on arduino following code 1:

    Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

    Sketch uses 1602 bytes (4%) of program storage space. Maximum is 32256 bytes.
    Global variables use 188 bytes (9%) of dynamic memory, leaving 1860 bytes for local variables. Maximum is 2048 bytes.
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
    An error occurred while uploading the sketch

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

Arduino running code 2 is stuck on the uploading and does not fininsh uploading.

The solutions on the internet only talk of the scenarios where the arduino is having trouble communication with the computer and so the solutions given are:

check com port

check that correct board is selected

do not insert the arduinos in usb 3

press reset button

None of these is my problem as I have checked them all. The arduinos themselves are working fine. I have a very strong feeling that there is a problem with the pins 0 and 1, i.e. with serial comm.

Please help.

  [1]: https://create.arduino.cc/projecthub/harshmangukiya/serial-communication-between-two-arduino-boards-d423e9

body:
I am guessing you have connected 2 arduinos together using their hardware serial ports while uploading. This cause uploading to fail as those ports are getting two signals at the same time.

Break this connection before upload and then it should work. You can reconnect them after upload.

If you want to avoid this you can use different pins with software serials for communication.

Also consider using Serial.available() on the reading end to see if there is data to be read.


message:
KY-022 IR receiver, LED always on, no output

I've been trying to use a KY-022 to read IR signals. However no output is being produced and the LED on the board is constantly on.

Board: Arduino Uno R3

I followed the procedure found [here][1].

The code:

    #include <IRremote.h>

    int RECV_PIN = 11;

    IRrecv irrecv(RECV_PIN);

    decode_results results;

    void setup() {
      Serial.begin(9600);
      // In case the interrupt driver crashes on setup, give a clue
      // to the user what's going on.
      Serial.println("Enabling IRin");
      irrecv.enableIRIn(); // Start the receiver
      Serial.println("Enabled IRin");
    }

    void loop() {
      if (irrecv.decode(&results)) {
        Serial.println(results.value, HEX);
        irrecv.resume(); // Receive the next value
      }
      delay(100);
    }

The output:

    Enabling IRin
    Enabled IRin

The LED is constantly on, it should come on when there's a signal received. However this is not shown in the output. :/ I don't know what to do.

Pictures:

[![Board!][2]][2]
[![Board-upside-down, top-row corresponding to Signal!][3]][3]
[![Setup][4]][4]

  [1]: https://arduinomodules.info/ky-022-infrared-receiver-module/
  [2]: https://i.stack.imgur.com/Mxkt2.jpg
  [3]: https://i.stack.imgur.com/o4XLf.jpg
  [4]: https://i.stack.imgur.com/4alhh.jpg

body:
The first thing to look at is the circuit board. Are they using the resistor and LED to indicate the board is receiving power? The data sheet has a schematic showing several passive components in the "3. ApplicationCircuit" section. Here is a copy of the schematic I have used that worked with the IRremote library (Version 0.1 July, 2009 - Copyright 2009 Ken Shirriff).

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

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


body:
This happened to me when I "fried" my IR receiver.

Everything was fine and working until I accidentally reversed ground and +5v when putting my project back together after a tear down.
After correcting the wiring, the LED stayed on, and no reading was coming out.

Did you ever get any pins wrong?

This video show the correct wiring.
https://www.youtube.com/watch?v=iFpAqG90zY0


message:
Only getting error from ESP8266 AT commands

I am trying to get the ESP8266 work with Arduino AT commands. I am using the due. How do I get the ESP8266 to respond with anything other than ERROR?

Here is the current serial output:

    AT
    ERROR

Here is my code:

<!-- language: lang-C -->

    void setup() {
        Serial.begin(9600);
        Serial3.begin(115200); //Manufacture said this is the correct baud rate
    }

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

        if ( Serial.available() )  {  Serial3.write( Serial.read() );  }
    }
Here are my pin connections:

    RX3  -> ESP TX
    TX3  -> ESP RX
    GND  -> GND
    3.3V -> CH_PD + VCC

body:
The AT firmware responded with ERROR because it received data, but timed out waiting for the CR/LF line ending.

AT commands must be terminated with Carriage Return '\r' and Line Feed '\n' control bytes/characters.


message:
Is a variable declaration inside a loop static declaration or dynamic?

while(condition){
        Object object = new Object();
    }

So my question is, will each iteration would create a different object in different memory location or it will overwrite the once created object every iteration.

body:
It will be created every iteration.

Assuming, you are not using it to add to a list (e.g. to use in later loops), what you better can do is make it in a global, you also don't need to use 'new', thus:

    Object object;

Also, if you do not delete/remove the object at the end of each while condition (with the *delete* keyword), you will lose the memory (and this is a memory leak). Also, you run the risk of memory shortage (the Uno has only a few KB of memory).

What I also miss in your code is the pointer (*, because the *new* keyword creates a pointer), and also Obj and Object are inconsistent types (they should be equal), so:

    Object* object = new Object();

If you only need the object within the condition and it can be removed in the next while, than you don't need to use new, so just declare it as a vaiable

    Object object;

This also has the benefit that the (local) variable will be destroyed at the end of scope (which is at the end of the while).


body:
**Dynamic** object creation is using operator `new`. Operator `new` creates object on *heap* and the object exits until you delete it with operator `delete`.

`Object object` creates object on *stack*. It will be removed from stack when the variable goes out of scope on the end of the block.

**Some classes have copy constructors. If your `Object object = new Object()` compiles, then the class Object has copy constructor. The code creates an object on stack, then creates an object on heap and then copies it's content into object on stack. The object on heap stays and you have no pointer to it to delete it. The program soon crashes on low memory.**

**Static** variables have keyword static. If you would have `static Object* object = new Object()`, then the pointer is created on global level and the object on heap is created and assigned only ones.

EDIT:
I tested this. Class String has a copy constructor, but the Arduino compiler doesn't allow `String s = new String(a)`. It can be misleaded with `String s = *(new String(a))` (`a` is some variable).


message:
Not getting pure color while using the FastLED with WS2812b

I am working with the LED strip **WS2812b** and **FastLED** library, currently I have only 3 LEDs connected in such a way that the first 2 receive a color *(say green)* and the last one receives another one *(say blue)*.

The problem is that by putting the color *(blue)* on the last LED, the other two (currently only in *green*) also take a portion of *blue*, preventing it from being a pure (*green*) color. It happens with any combination of color.

I leave the piece of my code referring to the LED strip:

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

    #include "FastLED.h"
    #define NUM_LEDS 3
    #define DATA_PIN 2

    //Variables declaration...
    ....

    void setup() {
      FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
    .....

      }

    void loop() {
      ReadMySerial();       //This function take data from serial port and set the color for the leds
      FastLED.setBrightness(brigth);

      for (int pinNo = 0; pinNo <= 2; pinNo++){
        leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
        FastLED.show();
          if (digitalRead(pinNo+3) == HIGH){
            leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
               FastLED.show();
                }
            }

      }

I already change the pin for where I put the signal for the LED strip, I try to change the type of LED strip

- `FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS)`
- `FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS)`
- `FastLED.addLeds<WS2812, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS)`

without any success...

Can anyone point me in the rigth direction?

Edit: actually, the first LED of the strip is flashing, not in the way of the **Blinking** example, but I can see a little flashing.

body:
I can see what the problem is, I put `FastLED.show();` where it should not, that's also why I saw the flash ... fix it and here's the result:

    void loop() {
      ReadMySerial();       //This function take data from serial port and set the color for the leds
      FastLED.setBrightness(brigth);

      for (int pinNo = 0; pinNo <= 2; pinNo++){
        leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
        FastLED.show();
        if (digitalRead(pinNo+3) == HIGH){
          leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
        }
      }

      FastLED.show(); //NOW IS IN THE RIGHT POSITION
    }


message:
Attiny85 not able to understand data from 433Mhz using VirtualWire.h

The basic plan is to have a Attiny85 pass information from a 433Mhz RF module to another chip/Arduino via I2C using VirtualWire and Wire libraries. I have been able to make this system work on their own using Arudino Nano's to debug, but the Attiny85 (A85) seems unable to grab the data from the RF 433 Mhz.

So have spent a few days doing some more research, and basically putting each component separate, to make sure what is being sent is correct.

 1. 433 Mhz transmitter is working by sending a 9 digit number, using VirtualWire.h.
 2. Nano with a 433 Mhz receiver is receiving 9 digit
    number, VirtualWire.h.
 3. Attiny85 is sending either a no data, or the 9 digit number, to another Nano using Wire.h.
 4. The Nano is getting only No Data, so the I2C is working between A85 and Nano.

Attiny85, on Pin 1 (pin 6 on chip) is not getting any data from the 433 Mhz, which works on (2). I connect the GND of the 433 RX to the chip.

Here is the **Receiver** code:

    #include <VirtualWire.h>
    #include <Wire.h>
    void setup() {
      pinMode(A3, OUTPUT);
      Wire.begin(); // join i2c bus (address optional for master)
      vw_set_ptt_inverted(true); // Required for DR3100
      vw_setup(4000);   // Bits per sec
      vw_set_rx_pin(1);
      vw_rx_start();       // Start the receiver PLL running
    }
    void loop() {
      uint8_t buf[15];
      uint8_t buflen = 15;
      if (vw_get_message(buf, &buflen)) // Non-blocking
        {
          digitalWrite(A3, LOW);
          Wire.beginTransmission(8); // transmit to device #8
          for (int i = 0; i < buflen; i++) {
            Wire.write(buf[i]);
          }
          Wire.endTransmission();    // stop transmitting
        } else {
          digitalWrite(A3, HIGH);
          Wire.beginTransmission(8); // transmit to device #8
          Wire.write("no DATA");
          Wire.endTransmission();    // stop transmitting
         }
    }

Here is the **Transmitter** code:

    #include <VirtualWire.h>
    int xPin = A7;
    int yPin = A6;
    int buttonPin = 2;

    int xPosition = 0;
    int yPosition = 0;
    int buttonState = 0;
    const char *controller;
    void setup() {
      Serial.begin(9600);
      pinMode(12,OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(yPin, INPUT);
      pinMode(xPin, INPUT);
      pinMode(buttonPin, INPUT_PULLUP);
      vw_set_ptt_inverted(true); //
      vw_set_tx_pin(12);
      vw_setup(4000);// speed of data transfer Kbps
    }

    void loop(){
       xPosition = analogRead(xPin);
       yPosition = analogRead(yPin);
       buttonState = digitalRead(buttonPin);
    if(xPosition > 0 || yPosition > 0) {
      String Data = (xPosition + yPosition);
      controller = Data;
      vw_send((uint8_t *)controller, strlen(controller));
      vw_wait_tx(); // Wait until the whole message is gone

    } else {
      digitalWrite(13, 0);
      digitalWrite(4, 1);
      controller = "#s0_0";
      vw_send((uint8_t *)controller, strlen(controller));
      vw_wait_tx(); // Wait until the whole message is gone
    }

    Serial.println(controller);

    }

So basically the A85 is not getting past if (vw_get_message(buf, &buflen)) { on pin 1. But does when using the Nano on pin D2, from the same transmitter, but not at the same-time of-course.

Am I using the wrong Pin on the A85? Chip pin 5 and 7 are used for the I2C so it only leaves analog pins so not sure they would work either. I also tried 8 Mhz and 1 Mhz when loading the A85.

I  have tried different Cores as suggested from Google, different versions of VirtualWire and clocked the Attiny 1Mhz, 8Mhz and 16Mhz. None of have worked.

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

Not sure what else I am missing?

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

body:
Have you tried using the <a href="http://www.airspayce.com/mikem/arduino/RadioHead">Radiohead </a> library? I know you said you tried different versions of Virtual Wire. The RH_ASK class works on a 328p and a nano for sure and they claim a simple Rx program can run on a ATTiny85. They have documentation under RH_ASK regarding the changes you need make to the library.
Another possible fix is to edit the Virtual Wire library files, they might have variables like "Max_payload" (Radiohead does) whose size can be decreased.
I haven't actually read the Virtual wire library, but I am sure Radiohead should fix your problems.

If this doesn't work, do you have an oscilloscope? Maybe we can try debugging it like that.

Edit: Maybe try commenting out the `vw_set_ptt_inverted` line first. I don't think you are using the DR3100. Might not make a difference because you haven't actually set a pin for ptt.
Next thing you can try is just connecting the data pin of the Tx to the Rx. You should be able to check if the module is actually connected to the ATTiny with this.


message:
How to count the voltage pulses of a digital temperature sensor using Arduino Mega Atmega2560?

I have a digital temperature sensor which gives digital output in the form of current pulses. The number of pulses corresponds to a particular temperature.

I have converted the current pulses to voltage pulses using transistor as a level shifter. I want to count the number of pulses for a time interval of 50ms each time.

Please help me with the algo and the code.

body:
There are function called [pulseIn][1] which probably need exactly what you want.

Just set a variable with the current 'time' ([millis][2], start counting until the current time reaches 50 ms later.

So something like (not checked):

    unsigned long timer = millis();
    unsigned pulses = 0;
    while (timer + 50 < millis())
    {
      pulseIn(PIN, LOW);
      pulses++;
    }

PIN is a constant or variable that defines the pin number to check, LOW is to check low pulses, you also can use high, and optionally you can add a timeout. For example, you can use the timeout to check the last timeout is within the 50 ms region. Or to be more precise, check if the pulse was within the same 50 ms:

    unsigned long timer = millis();
    unsigned pulses = 0;
    while (timer + 50 < millis())
    {
      pulseIn(PIN, LOW);
      if (timer + 50 < millis())
      {
        pulses++;
      }
    }

  [1]: https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/
  [2]: http:// millis()


message:
ESP8266(01) doesn't work when servo connected to GPIO-2

the wiki here says http://www.esp8266.com/wiki/doku.php?id=esp8266_gpio_pin_allocations

    0 Low
    1 High
    x floating
    MODE                 GPIO15  GPIO0  GPIO2
    SDIO (BootSDCard)      1      x       x
    UART (UploadCode)      0      0       x or 1
    FLASH (NormalRunning)  0      1       x or 1

Can connecting my GPIO 2 to a servo Signal Wire cause it to go LOW? because some how my ESP8266 doen't boot when I have a servo hooked up to it.
I tried to change it to RX (which is GPIO3 on ESP8266) and everything seems to work fine. But I wanna know the reason why GPIO2 didn't work.

Thank you.

p/s:http://www.goodluckbuy.com/ld-1501mg-metal-gear-digital-servo-17kg-for-rc-robot.html this is the servo, if it matters. Also GPIO-2 works when I use another servo of different type instead (I don't know its name though)

body:
It's what Juraj said.

> add external pull-up to io 2 -Juraj

sovled it


message:
What is a safe way to power arduino nano with 7.4V Lipo battery?

I'm trying to power Arduino Nano with 7.4V LiPo battery and use it to run 2 DC motor using L293D. I have figured out how power it with the connection just like in the figure below(the diagram uses Uno and the battery is 9V but try to imagine it as Nano and 7.4V).[![figure][1]][1]  I also found another way to power it by connecting the red wire from battery to Vin on the Arduino instead of connecting it to the positive power rail.

So, my question is which is a safer way to power it and what is the difference and risk of one the way I mention.

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

body:
Connect it via the Vin pin. That way the 6-8.4 volt of the battery will go through the voltage regulator on the Nano, giving you a stable 5v.

What you show in your diagram is the wrong way of connecting the battery. The absolute maximum you can supply to the Arduino's 5V pin is 6 Volt. Atmel recommends no more than 5.5V. So your battery exceeds this when it's full.


message:
Arduino UNO reset using SIM800L

I'm using the **SIM800L** module but i've problems. I'm triying to connect it to the **Elegoo UNO** i've, but it restarts at all times. Also the led of signal strengh blink every second, so i dont get signal.

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

I also upload a video to Youtube to explain the problem, [this is the link.][2]

Thanks in advance!

  [1]: https://i.stack.imgur.com/5zlC2.jpg
  [2]: https://www.youtube.com/watch?v=0XL_CzWNUik

body:
When the reset pin of Uno is connected to ground, the Uno resets. That is what the reset button does.

You connected the reset pin of Uno to other device's reset pin. If the reset pin of the other device grounds the reset pin of Uno (grounds or has lower then required voltage), then Uno resets.

The reset pin of a peripheral device is intended to reinitialize the device by program running in microcontroler by setting a connected GPIO pin to required state.

If you have a library for the device, that library will take care of the GPIO pin controlling the reset of the device.

If you plan to use the device without library, then you should take care of the reset pin in your sketch. Setting the selected pin to OUTPUT and initializing it to required state.

The usual required state for reset is LOW so the output must be HIGH for the device to work.

[Some tutorials and libraries][1] require connecting the reset pin of gsm800l to a selected Uno GPIO pin with a transistor, and then reset is HIGH and LOW is for normal operation.

  [1]: https://cristiansteib.github.io/Sim800l


body:
Besides the RST pin situation that the others pointed out, you're not going to do much with the way you're powering the module. It might turn on, but you will never be able to register on the network.
You have to power the module with an external power source and common the ground.

Also, if the module you're using is the one on the image, you might need a logic level shifter to use the Tx-Rx connection.


message:
Splitting SCL and SDA pins

For a robotics project I am using an MCP23017 I/O Port Expander in order to have more pins available, and I am also using a PS2 controller for input. Both of these require pins 4 and 5 (because these are the data and clock pins). I was wondering if I can use a breadboard to simply connect these two pins to both devices in order to provide both of them with data and clock pins.

I am using an Arduino UNO and a playstation 2 controller with the following guide:
http://www.techmonkeybusiness.com/using-a-playstation-2-controller-with-your-arduino-project.html

body:
An I2C bus can be connected to many slaves at the same time, since in the I2C protocol every slave has an address.

But, as Majenko wrote in the comments, the library for the PS2 controller doesn't use I2C. The communication with the controller is bit banged, meaning that every part of the communication is done by software. This can be done with every digital pin on the Arduino. In your setup you have to usw the function `ps2x.config_gamepad()`.  In it's parameters you can set the pins that the library will use.


body:
You are confusing pins here. In the library you mention there is a function call to set up the gamepad:

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

     ps2x.config_gamepad(5,4,3,2, false, false);
     //setup pins and settings: GamePad(clock, command, attention, data, Pressures, Rumble)

That is **digital** pins 5, 4, 3 and 2.

I2C uses **analog** input pins A4 and A5 on the other side of your Uno board.


message:
What is better approach for non blocking pid algorithm?

I'm developing software side for 3 axes robot where are 360° continuous rotating servos used [Documentation here][1]

these servos have its own feedback system so it's possible to control it's position via pid system, when im using only one PID algorithm in clear sketch just for this pid everything working OK but when I want to use multiple PIDs there are problem with delays and every next function that is used in the sketch will result in bigger delays that make these servos flicking because it's executed in main function

 int pinFeedback = pin_comes_here;

 float tHigh = 0;
 float tLow = 0;
 int tCycle = 0;
 float dc = 0;
 float angle = 0;
 float dcMin = 2.9;
 float dcMax = 97.1;

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

 void loop() {
  while(1) //From Parallax spec sheet
  {          //There is core of the problem
    tHigh = pulseIn(pinFeedback, HIGH);
    tLow = pulseIn(pinFeedback, LOW);
    tCycle = tHigh + tLow;
    if ( tCycle > 1000 && tCycle < 1200)
   {
     break; //valid tCycle;
   }
  }

   dc = (100 * tHigh) / tCycle; //From Parallax spec sheet, determine the percentage of the HIGH in the pulse

   angle = ((dc - dcMin) * 360) / (dcMax - dcMin + 1); //From Parallax spec sheet

   if (angle < 0)
   {
  angle = 0;
   }
   else if(angle > 359)
   {
  angle = 359;
   }

  //This is just angle calculation part, we have angle as output value from this algorithm so its possible to calculate error how much to left or right value from out target angle value and adjust servo position via standard servo library

 }

Reason why i need non blocking angle calculating is that because with everything this, i need to be able to control angles from firmata protocol and not just firmata but there can't be anything else done in sketch and i mentioned everything else causing bigger delays between reading signal, calculating angle, adjusting position, and every next function that could be placed in main loop.

So i came to the point that i need to use timer and interrupts like servo library uses by creating something like basic servo library wraper where i create PID class that inherit Servo class members for sake of accesing servo members from one object (attach, write) and two different approaches came to my mind

 1. This PID class could instead of waiting in while loop for pulseIn sacrifices another one Timer that could divide feedback signal period which is long 1,1millisecond (see documentation, heading: feedback signal) by checking if it's up or down every several microseconds and counting total signal uptime for period and then calculate angle and error and adjust position with inherited write() member for every object from one timer

 2. Using attachInterrupt that could behave similar like pulseIn but outside of main loop for every object(with same approach with PID class with inherted servo class)

  [1]: https://www.parallax.com/sites/default/files/downloads/900-00360-Feedback-360-HS-Servo-v1.2.pdf

body:
The main issue you have is that `pulseIn()` is completely blocking - and your `while` loop doesn't help much either.

The "proper" (or what I would consider the "proper") way of dealing with this is to use a timer in *gated* mode. Actually you need two timers, but the Arduino already provides you `micros()` that will do for one of them.

Basically your pulsed signal is input into the gate input of a timer. That timer, when the gate input is HIGH, will count the number of ticks from whatever clock source you configure it for (system clock, etc, with or without prescaler, etc). It also needs to be configured so that the timer triggers an interrupt at the falling edge of the gate.

That interrupt reads the count from the timer and resets the count to 0 ready for the next pulse. It also uses `micros()` to work out the time between successive falling edges (should be about 1100us).  A little bit of maths is needed to calculate the time from the count.

It's not something I have ever done with an Arduino - I have only used a PIC32 for it - though I assume that AVR timers have a gated mode (they should have; they are fairly comprehensive timers). Check the datasheet to be sure - as well as for how to configure it.  On the PIC32 I used two timers both running at the same speed from the same clock source - one in gated mode to count the HIGH time and one in free-running mode to count the full period time. The duty % is then the ratio of the two counts and you don't care about the actual time in human-created units.

Of course, it goes without saying that you need a gated timer for each servo you want to sense...


message:
Trying to make sense of the coding style in Arduino libraries. (Particularly the Radiohead library)

I've been using the Arduino IDE for some time now, and I want to shift to coding for the bare AVR microcontroller. So I wanted to begin by porting required arduino libraries to C/C++.
I started with the Radiohead library, but I've noticed a lot of variables/tokens that are directly used without a definition for them. For example:

        // path :RadioHead/RH_ASK.cpp
    #if (RH_PLATFORM == RH_PLATFORM_GENERIC_AVR8)
     #ifdef RH_ASK_PTT_PIN
        RH_ASK_PTT_DDR  |=  (1<<RH_ASK_PTT_PIN);
        RH_ASK_TX_DDR   |=  (1<<RH_ASK_TX_PIN);
        RH_ASK_RX_DDR   &= ~(1<<RH_ASK_RX_PIN);
     #else
        RH_ASK_TX_DDR   |=  (1<<RH_ASK_TX_PIN);
        RH_ASK_RX_DDR   &= ~(1<<RH_ASK_RX_PIN);
     #endif
    #else
        // Set up digital IO pins for arduino
        pinMode(_txPin, OUTPUT);
        pinMode(_rxPin, INPUT);
        pinMode(_pttPin, OUTPUT);
    #endif
None of the tokens in this snippet like "RH_ASK_PTT_PIN" or  "RH_ASK_TX_PIN" were mentioned anywhere in the code before or any other file that was included.

I understand what the code does, but how does the compiler know what these tokens mean? I tried to compile this code using Atmel Studio but it gives me an error (As it should):
`"RH_ASK_PTT_PIN" not declared in this scope`
So how does this library work with the Arduino IDE?

Link to the library : https://github.com/PaulStoffregen/RadioHead

Also can someone suggest tags for this post? Its my first post here.

body:
They're not defined. If you notice that whole block is wrapped in a `#ifdef` which will be false unless you're on some specific platform, where the platform defines those macros.

Everything else uses the last little bit:

    pinMode(_txPin, OUTPUT);
    pinMode(_rxPin, INPUT);
    pinMode(_pttPin, OUTPUT);

You only need to care about that bit - nothing else is of any concern unless you're using a "RH_PLATFORM_GENERIC_AVR8" (whatever that is).


message:
What do I have to change to make this code functional?

I have a joystick, an I2C 16x2 character display, and an Arduino. I want to move the joystick and get an on-screen character (specifically, the letter h) to move in the direction that I pushed the joystick. Here is the Arduino code.

    #include <LiquidCrystal_I2C.h>
    int xVal;
    LiquidCrystal_I2C lcd(0x27, 16, 2);
    int yVal;

    int blockPos[]= {8, 0};
    int blockPosBack[]= {8, 0};

    int ycal;
    int xcal;
    void setup() {

        lcd.begin();
        lcd.clear();
        lcd.backlight();
    Serial.begin(9600);

    pinMode(A0, INPUT);

    pinMode(A2, INPUT);
    lcd.setCursor(blockPos[0], blockPos[1]);
    //lcd.print("h");

    ycal = 500;
    xcal = 514;
    }

    void loop() {

    xVal = analogRead(A0);

    yVal = analogRead(A2);

    Serial.print(" Y is...");

    Serial.print(yVal);

    Serial.print(" X is...");

    Serial.println(xVal);

    blockPosBack[0] = blockPos[0];
    blockPosBack[1] = blockPos[1];

    if(xVal < (xcal - 150)){
      if(blockPos[0] > 0){
        blockPos[0] - 1;
        }
      }

      if(xVal > (xcal + 150)){
      if(blockPos[0] < 15){
        blockPos[0] + 1;
        }
      }

      if(yVal < (ycal - 150)){
      if(blockPos[1] > 0){
        blockPos[1] -1;
        }
      }

      if(yVal > (ycal + 150)){
      if(blockPos[1] < 1){
        blockPos[0] +1;
        }
      }
    if(((blockPosBack[0]) != (blockPos[0])) && ((blockPosBack[1]) != (blockPos[1])){
      lcd.clear();}
      lcd.setCursor(blockPos[0], blockPos[1]);
      lcd.print("h");
    }

The problem is, I get a message saying that "expected ')' before '!' token". How do I solve this, and how do I change the code to make it functional?

Edit: I learnt that '!' is not the same as 'not equal to', which is '!='. I tried this, but now the h just sits at the initial position but doesn't move when I move the joystick. What do I have to change in the code to make it work?

body:
!! is not a valid logical operator, you probably meant || for locical OR?

Did you verify that the condition to change the blockpos value is actually fulfilled? Means are you sure one of your if blocks is actually executed?


body:
Like stated in my comment, to have proper condition for clearing the display, the condition you should want to meet are:

`if ( (newX != previousX) OR (newY != previousY)) {
    clearLCD()
}`

EDIT: Or else, what you're saying is that you're only clearing the display when you have changed both X and Y _at the same time_

And to adress your problem with the 'h' not moving, you need to change the lines
`blockPos[0] - 1;` etc

into

`blockPos[0] = blockPos[0] -1;`

or

`blockPos[0]--;`

or else, you're not really assigning the new value to the variable containing the position to use in the display.


message:
Elegant solution for refreshing TFT display content?

I'm currently drawing black boxes over old content before displaying constantly refreshing content on my display, so for instance to display temperature:

    if (sensorTemp != nowTemp){
        nowTemp = sensorTemp;
        tft.fillRect(0,52,88,21,ILI9341_BLACK);
        return nowTemp;
    }

If I don't do this the display will just overlay content until it becomes a white blob.

However, this solution leaves me with a black flickering on the display and I can't control exactly what is refreshed where. So for instance when I want to display the current time or date it has to refresh the date all the time, even though nothing changed.

    void loop() {
      tft.setTextSize(2);
      tft.setCursor(0,0);
      tft.print(rtc.getDateStr());
      tft.fillRect(144,0,199,15,ILI9341_BLACK); //Black box drawn over 'old' time data
      tft.setCursor(144,0);
      tft.print(rtc.getTimeStr());  //Draw new time
      tft.setCursor(0,52);
      tft.print(tempCall());  //call function to check on temperature and draw new data if necessary
    }

Is there a more elegant solution to this problem?

body:
The Adafruit GFX library has two functions for setting the text colour:

    setTextColor(uint16_t c)
    setTextColor(uint16_t c, uint16_t bg)

The first sets both the foreground and background to the same colour, and the second to two different colours.  You may ask why you would want the foreground and background to be the same - well, the library handles that situation as a special case: it makes the background transparent.

By setting the foreground and background to different colours you force the library to draw that background colour in over whatever is already on the screen.

    tft.setTextColor(ILI93481_WHITE, ILI9341_BLACK);

With that any background pixels in the text string will be coloured black and the text itself white.  As long as the string you are printing is the same length as the text that is already there it will be replaced completely.


body:
If you look in the "Adafruit_GFX.cpp" you will see the following.

    void Adafruit_GFX::setTextColor(uint16_t c) {
     // For 'transparent' background, we'll set the bg
     // to the same as fg instead of using a flag
     textcolor = textbgcolor = c;
    }

    void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) {
     textcolor   = c;
     textbgcolor = b;
    }

If you only want to Draw the Character with a transparent background meaning you only write the character setTextColor in the prescribed pixels changing none of the surrounding pixels in the character block defined by x, y, setTextSize.

    TFT.setTextColor(GREEN); //With Transparent Text Background not updating surrounding pixels.

If you want to Draw the Character with your background color, replace app pixels in the character block defined by x, y, setTextSize with your chosen text color and your background to be the same as your chosen background. This will overwrite all pixels with old character that are no longer used with the background color all at the same time preventing mess of pixels, and character flashing.

    TFT.setTextColor(GREEN, BLACK); //With Text Background Color updating surrounding pixels.


body:
Hmm the solution is how the code is written...no fancy stuff...the KIWI way

    //in setup function add tft.fillScreen(ST7735_GREEN);

    void loop(){

      int lightIntensity = myBH1750.getLux();
      tft.setTextSize(3);
      tft.setCursor(10,10);
      tft.setTextColor(ST7735_RED);
      tft.print(lightIntensity);
      delay(3000);
      tft.setTextColor(ST7735_GREEN);
      tft.setCursor(10,10);
      tft.print(lightIntensity);
      tft.setCursor(10,50);
      tft.setTextColor(ST7735_BLUE);
      tft.print("LUX");
    }


body:
This code works well and accounts for values of different length.

    void textValue() {
      float newValue = @your input@;
      int numChars = String(newValue).length(); // Get the number of characters
      int valueWidth = numChars * 6 * 2.5;

      if (valueWidth != previousValue) {
        tft.fillRect(0, 55, previousValue, 30, ST77XX_BLACK);
        previousValue = valueWidth;
      }
      tft.setCursor(3,60);
      tft.setTextColor(ST77XX_WHITE, ST77XX_BLACK);
      tft.setTextSize(2.5);
      tft.print(newValue);
    }


message:
Lag in fetching serial data from Arduino

I am working on a project based on **Arduino** and **python3.6**,two HC-SR04 sense the distance of palms and process the data using Arduino and send it through serial port to python3.6 ,python3.6 with the help of **pyserial** ,**pyautogui** based on data from arduino controls a game named **supertuxcart**,a racing game,basically the thought behind this is  controlling game with palms instead of keyboard or mouse .But the problem am facing is Arduino takes the distance measurement data from two HC-SR04(one for each hand) ultrasonic sensors, processes according and sends processed data through serial port to python3.6 ,there while running the my python script i open the game to check if its working ,it works, but there is lag in data received from arduino thus turn the game messy.

here is **arduino** code am using with **NewPing** library

    #include <NewPing.h>
    int trig1=9;
    int echo1=6;
    int trig2=7;
    int echo2=5;
    int R;
    int L;
    NewPing right(9,6,100);
    NewPing left(7,5,100);
    void setup() {

      pinMode(9,OUTPUT);
      pinMode(8,OUTPUT);
      pinMode(6,INPUT);
      pinMode(5,INPUT);

    }

    void loop() {
      Serial.begin(9600);
      //Serial.println("hi,am arduino");
      R=right.ping_cm();
      L=left.ping_cm();
      //Serial.println(R);
      //Serial.println(L);
      delay(0000);
     if (R==0 && L==0){
        Serial.println('0');
      }
      else if(R<L&&L-R>5){
        Serial.println('1');
      }
      else if(R>L&&R-L>5){
        Serial.println('2');

    delay(3000);

      }

    }

Here is **python3.6** code am using

    import serial
    import pyautogui
    import time

    Arduino = serial.Serial('/dev/ttyACM0', 9600)
    time.sleep(0)
    print(Arduino.readline())
    pyautogui.keyDown('up')
    while 1:
        Data = Arduino.readline()
        print(Arduino.readline())

        if Data == b'0\r\n':
            pyautogui.keyUp('up')
            pyautogui.keyUp('right')
            pyautogui.keyUp('left')
            break
        elif Data == b'1\r\n':
            pyautogui.keyUp('left')
            pyautogui.keyDown('right')
        elif Data == b'2\r\n':
            pyautogui.keyUp('right')
            pyautogui.keyDown('left')

body:
A couple of things jump out at me:

1. You only need to run `Serial.begin(9600)` once in `setup()` - never in `loop()` like that.
2. Your `delay(3000)` will be causing a 3 second delay when `R>L&&R-L>5`.
3. You don't need to constantly send the data over and over again. You just need to send it once and once only when the state changes.

At the moment you're sending something like:

    0000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000000000000000002222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222200000000000000000000000000000000000000000000000000000000000000

when all you really need to do is send `01020`. Remember what the state is and only send anything when that state changes from one iteration to the next. And never ever use `delay()`.


message:
Point-to-point Communication of Arduinos with RFM LoRa Shield

In [this tutorial][1], it sends a string from a node to the other node. But if I want to send an integer instead of a string, how should I change the code?

    Serial.println("Sending to rf95_server");
    // Send a message to rf95_server

    String radiopacket = "Hello World #";
    radiopacket += String(packetnum++);
    radiopacket += " from ";
    radiopacket += node_id;

    Serial.print("Sending "); Serial.println(radiopacket); delay(10);
    rf95.send((uint8_t*)radiopacket.c_str(), radiopacket.length()+1);

    Serial.println("Waiting for packet to complete..."); delay(10);
    rf95.waitPacketSent();

  [1]: https://cytrontechnologies.github.io/RFM-LoRa-Shield-Examples/Arduino-Sketches-Overview/

body:
The simplest way is to just cast the integer into an array of 2 bytes and send that.  Assuming `int temperature`:

    rf95.send((uint8_t *)&temperature, 2);

To make it more portable you can use the size of an integer instead of 2:

    rf95.send((uint8_t *)&temperature, sizeof(int));

Reading back, you just cast the buffer you have received as an integer, or combine the data manually (which may be safer since the buffer may be misaligned on a more powerful system than an 8 bit Arduino):

    int temperature = buf[0] | (buf[1] << 8);

(Assuming it was sent from a *little-endian* 8-bit system).

If you want to send the number as plain text, so it can be easily read by a human, you want to print it to a string:

    char temp[6];
    sprintf(temp, "%d", temperature);
    rf95.send((uint8_t *)temp, strlen(temp));


body:
Just cast the integer to a String before sending and convert the String back to an int when you received. May not be memory friendly considering you are using Strings, but its very easy.

    int a = 10;
    String s = String(a);

You can then send the String as you would a normal string. Then on the receiving end you cast back to an int.

Assuming you received a String s.

    int b = s.toInt();


message:
ESP8266/NodeMCU unable to communicate with MFRC522 RFID reader

I am trying to use the 'DumpInfo.ino' example file to dump an rfid tag, the only changes i have made to the example is changing the pin settings.

    #define RST_PIN         3          // Configurable, see typical pin layout above
    #define SS_PIN          4         // Configurable, see typical pin layout above

i have wired it based on [this guide](https://github.com/Jorgen-VikingGod/ESP8266-MFRC522) (tried using the pins shown on here as well) when i run the code i get this error from `mfrc522.PCD_DumpVersionToSerial();`

    WARNING: Communication failure, is the MFRC522 properly connected?

Ive also tried printing the version and i get 0xFF which along with 0x00 seems to mean it isnt connected.

The only light that is on during the test is D1 on the RFID reader which you can see in the first wiring pic.

[Pictures of wiring here](https://i.stack.imgur.com/4D1hD.jpg)

Edit: I've changed the pins to D3 and D4 but i still get the same error

body:
change the pins to Dx constants, to match your connections

    #define RST_PIN         D3
    #define SS_PIN          D4
because pin D3 is not io 3 and pin D4 is not io 4. see [pins_arduino.h][1]

  [1]: https://github.com/esp8266/Arduino/blob/master/variants/nodemcu/pins_arduino.h


body:
ok i got it working with this pinlayout:

D1 (GPIO 5)-- RC522 - RST

D2 (GPIO 4)-- RC522 - SDA/SS

D3 (GPIO 0)

D5 (GPIO 14)-- RC522 - SCK

D6 (GPIO 12)-- RC522 - MISO

D7 (GPIO 13)-- RC522 - MOSI

D8 (GPIO 15)

also i used this tutorials code and i posted a serial.println after each piece of code to see where it is/or fails:
http://www.instructables.com/id/MFRC522-RFID-Reader-Interfaced-With-NodeMCU/


message:
IO with port manipulation while not interfering with i2c

I'm using an Attiny84 with the Tiny Core.
I'm try to use port manipulation to write the lower four bits of port A. I'm using i2c which occupies bits 5 and 7.

How can I write only to the lower 4 bits to avoid interfering with the i2c?

body:
I don't think you need to worry. A simple piece of code:

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

    void setup()
    {
     PORTA |= bit (0);
    }

    void loop() { }

Generates:

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

    00000044 <setup>:
      44: d8 9a        sbi 0x1b, 0 ; 27
      46: 08 95        ret

In other words, the compiler generates code to set that bit, ignoring all the other bits.


message:
Getting 3.3v on 5v pin in Arduino Uno

When interfacing my Arduino Uno with a relay I was facing reliability issues, and while investigating it with a multimeter, I found something strange.

I noticed that in the 5V power pin (with which I was powering my circuit) is producing only 3.3V when using the power adapter. However, when connected via the USB-A port, the 5V pin was producing the expected 5V voltage.

I tried powering it in many ways - computer-to-USB-A, computer-to-barrel-jack, phone-charger-to-USB-A, phone-charger-to-barrel-jack and an external 5V DC power supply. In all cases, the above observation held true - powering the board through the barrel jack made the 5V power pins produce only 3.3V.

Question: Why is this happening? Does that mean my board is faulty? Is there any way to fix this?

body:
>  and an external 5V DC power supply

OK, assuming you are putting 5V into the barrel jack this is exactly what you expect to happen.

From the [Arduino Uno specifications](https://store.arduino.cc/usa/arduino-uno-rev3) you are supposed to supply a *recommended* 7V to 12V. Your supply of 5V is too low.

The barrel jack first goes through a M7 protection diode which would have about a 0.7V forward voltage drop, and then through a NCP1117ST50T3G voltage regulator which has a dropout voltage of (typically) 0.95V at 100 mA.

Thus you have:

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

    5V input - 0.7V - 0.95V = 3.35V

That is what you are finding.

---

## Solutions

* If you have a proper, regulated, 5V DC supply you can put that directly onto the 5V pin of the Arduino. Better get the wires around the right way because you are bypassing the protection diode!

* Get a DC supply in the range 7V to 12V and put that into the barrel jack.

* Another simple idea is to just get a wall-wart that is used for charging phones via USB and run a USB cable into the Arduino USB port.

---

## Empirical test

I put 5V into the barrel jack of my Uno and read 3.33V on the 5V pin, which is pretty-much what you got. I measured a 0.77V drop over the M7 diode.


body:
While Nick's answer is 100% (technically) correct.
Functionally, it's a much easier story (given you feed 5V into the barrel jack).

Check the Arduino's [product page][1].

    Microcontroller ATmega328P
    Operating Voltage 5V
    Input Voltage (recommended) 7-12V

So yes, while the Arduino runs on 5V (and does so over USB). The recommended input voltage is 7-12V. You're simply not supplying a high enough voltage.

The difference, as per Nick's answer, is the protection circuit and regulator snooping off a few volts (which is bypassed when using USB).

  [1]: https://store.arduino.cc/arduino-uno-rev3


message:
Adadfruit Trinket software not running on ATtiny85

I have an application that uses a pair of nRF24L01+ as a simple RF link between a camera PC sync output and a set of LED flashes. The important factors are power and low latency - hence the 2.4GHz.

I developed both ends using UNOs and then moved to Trinket 3 V. The system works very well with Trinkets.
My next step was to strip this down further to ATtiny85 at least at the receiver end.
I overcame the programming challenges and a day's worth of board installation in Arduino IDE and can not now program the ATtiny85 as well as the Trinket.

I will share the code lower down, but let me explain the difference in result.

With the Trinket the trigger output from the receiver is a simple pulse the width of the transmitted pulse (as is the goal.

               __________________________________
 _____________|                                  |__________________________

The pulse is anywhere from 5 ms to 50 ms.

On the ATtiny85 the link is clearly operational from transmitter to receiver but the output is ugly. Something like this:

                 _____      _____            _____
________________|     |____|     |__________|     |___________

The pulses appear (not always the same number) for the duration of the transmitted pulse and the interval is variable. The pulses themselves are of 8 MHz duration.

**The code:**

    #include "RF24.h"

    // Note: these includes looked necessary when I started but during debugging I
    // removed them with not change in functionality - strange!
    //#include <Mirf85.h>
    //#include <MirfHardwareSpiDriver85.h>
    //#include <MirfSpiDriver85.h>
    //#include <nRF24L0185.h>
    //#include <SPI85.h>

    /*    **ATtiny25/45/85 Pin map with CE_PIN 3 and CSN_PIN 4**
          nRF24L01 CE oins is tied high and pin3 is used as the trigger output.

                                       +-\/-+
                         NC      PB5  1|o   |8  Vcc --- nRF24L01  VCC, pin2 --- LED --- 5V
          nRF24L01  CE, pin3 --- PB3  2|    |7  PB2 --- nRF24L01  SCK, pin5
          nRF24L01 CSN, pin4 --- PB4  3|    |6  PB1 --- nRF24L01 MOSI, pin6
          nRF24L01 GND, pin1 --- GND  4|    |5  PB0 --- nRF24L01 MISO, pin7
                                       +----+
    */
    *    **Trinket 3V Pin map with CE_PIN 3 and CSN_PIN 4 **
    * @code
    *                                 + -\ / - +
    *                   NC      PB5  1 | o   | 8  Vcc -- - nRF24L01  VCC, pin2 -- - LED -- - 5V
    *    nRF24L01  CE, pin3 -- - PB3  2 |    | 7  PB2 -- - nRF24L01  SCK, pin5
    *    nRF24L01 CSN, pin4 -- - PB4  3 |    | 6  PB1 -- - nRF24L01 MOSI, pin6
    *    nRF24L01 GND, pin1 -- - GND  4 |    | 5  PB0 -- - nRF24L01 MISO, pin7
    *                                 +---- +

    // (Create an instance of a radio, specifying the CE and CS pins. )
    RF24 myRadio (3, 4); // "myRadio" is the identifier you will use in following methods
    /*-----( Declare Variables )-----*/
    byte addresses[][6] = {"1Node"}; // Create address for 1 pipe.
    int dataReceived;  // Data that will be received from the transmitter
    int flashPin = 3;
    int flashValue = 0;
    long flashStartMicros = micros();

    void setup()
    {
      pinMode (flashPin, OUTPUT);

      myRadio.begin();  // Start up the physical nRF24L01 Radio
      myRadio.setChannel(108);  // Above most Wifi Channels
      // Set the PA Level low to prevent power supply related issues since this is a
      // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
      myRadio.setPALevel(RF24_PA_MIN);
      //  myRadio.setPALevel(RF24_PA_MAX);  // Uncomment for more power

      myRadio.openReadingPipe(1, addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now)
      myRadio.startListening();

      digitalWrite(flashPin, 0);
    }//--(end setup )---

    void loop()
    {
      if ( myRadio.available()) // Check for incoming data from transmitter
      {
        flashStartMicros = micros();
        while (myRadio.available())  // While there is data ready
        {
          myRadio.read( &dataReceived, sizeof(dataReceived) ); // Get the data payload (You must have defined that already!)
        }
        if (dataReceived == 8) {
          flashValue = 1;
          digitalWrite(flashPin, flashValue);
        }
      }
      if ( micros() - flashStartMicros > 1500) {
        flashValue = 0;
        digitalWrite(flashPin, flashValue);
      } //END Radio available
    }//--(end main loop )---

Simply - I send a character, received it and set trigger high. Then time out and set it low. There is only one statement setting pin 3 (`flashPin`) low.

I have spent 2 days trying to find the difference.

body:
My debugging effort was in an endless DO loop because I was trying to see why the ATtiny was not acting on the received data like the Trinket. Thanks to some simple questions from #jsotola I looked at what the Trinket signals looked like to compare.
Turns out, my transmitted was broken and that both receivers were dealing with the same garbage. Now I do not have a difference between the 2 receivers and I can go back and make the TX do what I need it to do.
“When you eliminate the impossible, whatever remains, however improbable, must be the truth.”


message:
powering arduino with a voltage divider to increase lifespan

I have a chinese arduino nano that I'm planning to use to open a door using a numeric keypad.

My power source is 12V and I want it running 24/7. I have read that the first thing to fail on an arduino is the voltage regulator due to the heat of lowering the voltage to something the arduino can use.

I have think of buying two big resistors of around 1W each to build a voltage divider and only feed 7V to the Vin pin of the arduino, so it will increase its lifespan.

Is this a good idea?

body:
Terminating voltage by dropping it over large power resistors is a bad idea, efficiency wise. There are better options.

Switch-mode Buck (=step down) converters are usually far more efficient than linear regulators. A linear regulator dumps the excess voltage in a resistor which converts the energy mainly into heat. A switch-mode converter works by switching on/off an inductance at the right time, which is far more efficient.

For step-up/step-down DC-DC converter theory look [here][1], [here][2] and [here][3]. For a comparison for switch-mode against linear regulators look [here][4].

A step-down converter module like the ones with a LM2596 should be good enough for you. See [here on ebay][5].

  [1]: https://www.youtube.com/watch?v=m8rK9gU30v4
  [2]: https://www.youtube.com/watch?v=QnUhjnbZ0T8
  [3]: https://www.youtube.com/watch?v=CEhBN5_fO5o
  [4]: https://www.youtube.com/watch?v=giGRrODKJSE
  [5]: https://www.ebay.com/itm/LM2596-DC-DC-4V-35V-to-1-23V-30V-Step-Down-Power-Module-Voltage-Regulator-3A-/251066005460


message:
Burning the Bootloader on Adafruit Feather 32u4

So, the default bootloader in Arduino is oddly set to erase EEPROM with every reboot, rendering the EEPROM, well, useless.

I found where the fuses are set in the boards.txt file, but getting this configuration change into the chip requires burning an updated booloader.

In the Arduino IDE, there is an option to "Burn Bootloader", but that would be way too easy, and of course, doesn't seem to work.

I can't find any clue on the Internet about how to actually get the bootloader updated in these devices.

So, is it possible to reprogram the bootloader on the Adafruit Feather 32u4 devices?

If so, what's the trick to do it?

body:
"Burn Bootloader" only works if you have a programmer connected to the device. The onboard bootloader in your Feather cannot change the fuses, even though the process may indicate it has done so.

You would have to connect an ICSP (In-Circuit Serial Programmer) to the correct pins (`MOSI`, `MISO`, `SCK`, `RESET`, `VCC`, `GND`). You can use another Arduino as a programmer by uploading a specific sketch to the Arduino to make it an [Arduino as ISP](https://www.arduino.cc/en/Tutorial/ArduinoISP).

The normal bootloader on an Arduino emulates this kind of device to allow programming by serial/USB port, but it has limitations. The ICSP process is the native way to get a program onto the AVR chip, and is the only way to set fuses.

**EDIT:**

This [AVR USB Bootloader Datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/doc7618.pdf) states on page 3:

> • Boot Reset Fuse The Boot Reset Fuse (BOOTRST) can be programmed so
> that the Reset Vector points to the Boot Flash section start address
> after reset. Once the user code is loaded, a bootloader command
> (“start application”) can start executing the application code. Note
> that the fuses cannot be changed by the MCU itself. This means that
> once the Boot Reset Fuse is programmed, the Reset Vector will always
> point to the Bootloader Reset and **the fuse can only be changed through
> the serial or parallel programming interface.** The BOOTRST fuse is not
> active in the default factory configuration.

That document also references [AVR282: “USB Firmware Upgrade for AT90USB”](http://docplayer.net/21589219-8-bit-application-note-microcontrollers-avr282-usb-firmware-upgrade-for-at90usb.html) (Note, I could not find this on the Atmel website.) This document details the FLIP program, at Atmel tool for uploading firmware over the USB DFU interface and setting configuration settings, etc.

This doc has a FAQ section which states:

> 3. Can I modify the fuse bits using Flip? • No, Flip cannot modify the fuse bits. To modify the fuse bit you can use either the JTAG ICE
> MKII, the AVRISP MKII, or parallel programming

So, while this may not be a definitive answer, it appears at this time that "burning fuses" cannot be done over USB on the `32u4`. If that's not the case, I'm sure the site would welcome the new info.


body:
In my case the 32u4 (Lora32u4II) failed after uploading big firmware. Not responsive.

Fortunately I have the buspirate 4 with firmware 7.0. And during this time I discovered that the BusPirate is not able to power the board to reflash the firmware. But if I connect the board over USB and then the cabling as described:

    BUS PIRATE - LORA32U4II
    MISO              MISO
    MOSI               MOSI
    CLK                SCK
    GND                GND
    CS                 RST

And I use arduino ide to upload a new bootloader it starts to work again. So. I wonder why the firmware update locked the board while there's enough space. And why powering over 5v doesn't get it to work on buspirate + arduino ide.

I leave info for others that have same problem.

I discovered that using this method, even if slower, I can skip bootloader, leaving more room for my firmware...


message:
Weird multiplication result

Here's come Arduino code.

    #define M(x, y) x * y;
    void setup() {
      Serial.begin(9600);
      Serial.println(M(3 + 2, 4 + 2));
    }
    void loop() {
    }

Why is the result 13?

body:
Because `M(3 + 2, 4 + 2)` gets replaced to `3 + 2 * 4 + 2` and then the normal priority of operations does the multiply before the addition.

This is one of the many reasons why you should prefer functions over macros. The inliner of the compiler will negate any call overhead.

If you truly want to use a macro then surround each use of the macro arguments in parenthesis, surround the macro itself in parenthesis as well.

    #define M(x, y) ((x) * (y))


message:
LMT 84 temperature sensor measurement error

I want to measure atomospheric temperature with arduino sensor i am using is LMT84.
 data sheet :http://www.ti.com/lit/ds/symlink/lmt84.pdf
 After uploading following code to arduino board i am getting very high temperature in serial window .I m new in electronics field so i am unable to understand what is error in my code .Ive connected0.1uf cap between vcc and ground,data pin is connected toA1 of arduino.

Plz check following code:
==============================================================================

    const int sensor = A1; // Assigning analog pin A1 to variable 'sensor'
    float tempc;  //variable to store temperature in degree Celsius
    float vout;  //temporary variable to hold sensor reading
    float vout1;  //temporary variable to hold sensor reading

    void setup()
    {
      Serial.begin(9600);
      pinMode(sensor, INPUT); // Configuring pin A1 as input
    }

    void loop()
    {
     vout = analogRead(sensor);
      vout1 = (vout * 500) / 1023;
      tempc = vout1; // Storing value in Degree Celsius
       Serial.print("LMT84 temp=");
      Serial.print(tempc);
      Serial.println();

    delay(1000);
    }

Serial window showing this values::

    LMT84 temp=168.13
    LMT84 temp=168.13
    LMT84 temp=168.64
    LMT84 temp=168.89
    LMT84 temp=168.13

body:
The Arduino uses an analog voltage as reference. It is default set to the Vcc of the microcontroller, which is about 5 V for an Arduino Uno. The function [analogReference][1] can be used to set something else as reference.

When that reference is not precisely 5.0 V, it is impossible to measure a voltage in a accurate way. It is almost never precisely 5.0 V. When using the USB connector to power the Arduino board, it might be somewhere between 4.5 and 5.0 V.

The Arduino Uno has an internal voltage reference of 1.1 V. That is better than using the default 5 V. The actual voltage can be 1.0 to 1.2 V, you have to put the actual value in your sketch.

The LMT84 has an output of 1034 mV at 0°C and 476 mV at 100°C. That means your calculation is not correct. In the datasheet are two ways to calculate the temperature, an accurate formula and a simple calculation.

You can avoid all these problems with a temperature sensor that has a digital interface to the Arduino board. For example the DS18B20. That is a cheap and accurate temperature sensor.

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


message:
State machine doesn't function

My goal is to make a logic controller for a cassette tape mechanism, right now I'm simply trying to get the mechanism to engage and disengage the pinchroller arm which is motorized, spin the reels/capstan to advance the tape for playback; and stop the process by stopping the capstan motor, and retracting the pinchroller arm.

Currently this code doesn't respond to any of the button inputs, and I'm unsure as to why that is. I have another program that allows manual control of the motors, and that works fine, this however does not.

Can someone point out/correct what is the mistake? Because I can't seem to find what is wrong. Thank you in advance!

Here is my current full code:

    const int motor1Pin = 5; //If motor1 is HIGH and motor2 is LOW,  the motor will spin one way, if motor1 is LOW and motor2 HIGH then the motor will spin in the opposite direction.
    const int motor2Pin = 4;
    const int motor3Pin = 2;
    const int motor4Pin = 1;
    const int enablePin = 6; //turns pinch roller arm motor on or off
    const int enablePin2 = 3; //turns capstan motor on or off
    const int limitswitch1Pin = 7; // end of top travel limit switch
    const int limitswitch2Pin = 9; // end of bottom travel limit switch
    const int cyclePin = 8; //switch that cycles the pinch roller arm depending on limit switches
    const int reversePin = 10;
    const int forwardPin = 11;
    const int stopPin = 12;

    int state;
    int buttonState;
    int limit1State;
    int lastlimit1State;
    int limit2State;
    int lastlimit2State;
    int reverseState;
    int forwardState;
    int stopState;

    enum State_enum {STOP,PLAY};

    bool enableState = false;
    bool enable2State = false;

    void setup() {

      pinMode(motor1Pin, OUTPUT);
      pinMode(motor2Pin, OUTPUT);
      pinMode(motor3Pin, OUTPUT);
      pinMode(motor4Pin, OUTPUT);
      pinMode(enablePin, OUTPUT);
      pinMode(enablePin2, OUTPUT);
      pinMode(reversePin, INPUT_PULLUP);
      pinMode(forwardPin, INPUT_PULLUP);
      pinMode(stopPin, INPUT_PULLUP);
      pinMode(limitswitch1Pin, INPUT_PULLUP);
      pinMode(limitswitch2Pin, INPUT_PULLUP);
      pinMode(cyclePin, INPUT_PULLUP);
      pinMode(A0, INPUT);

      buttonState = digitalRead(cyclePin);
      limit1State = digitalRead(limitswitch1Pin);
      limit2State = digitalRead(limitswitch2Pin);
      reverseState = digitalRead(reversePin);
      forwardState = digitalRead(forwardPin);
      stopState = digitalRead(stopPin);

    }

    void loop() {

      if (buttonState == LOW) int state = PLAY;
      if (stopState == LOW) int state = STOP;

      switch (state) {
      case PLAY: //Plays the cassette
        if (stopState == LOW) {
          state = STOP;
        }
        if (limit1State == LOW) { //running the pinchroller arm clockwise from the top to bottom

          digitalWrite(motor1Pin, HIGH); // set leg 1 of the pinchroller motor H-bridge high
          digitalWrite(motor2Pin, LOW); // set leg 2 of the pinchrooler motor H-bridge low
          analogWrite(enablePin, 176); //set pinchroller motor speed

        } else if (limit2State == LOW) { //pinchroller arm is fully down (at bottom)
          digitalWrite(enablePin, LOW); //disable pinch roller motor
          digitalWrite(motor3Pin, LOW); // set leg 3 of the capstan motor H-bridge low
          digitalWrite(motor4Pin, HIGH); // set leg 4 of the capstan motor H-bridge high
          analogWrite(enablePin2, 200); // set capstan motor speed
          digitalWrite(enable2State, true);
        }
        break;

      case STOP: //Stops the cassette
        if (enable2State == true && limit2State == LOW) {
          digitalWrite(enablePin2, LOW);
          digitalWrite(enable2State, false);

        } else if (enable2State == false && limit2State == LOW) {
          //running the pinchroller arm counter-clockwise from the bottom to top

          digitalWrite(motor1Pin, LOW); // set leg 1 of the motor H-bridge high
          digitalWrite(motor2Pin, HIGH); // set leg 2 of the motor H-bridge low
          analogWrite(enablePin, 176); //set pincroller motor speed

          if (limit1State == LOW) {
            digitalWrite(enablePin, LOW);
          }
        }
        break;

      }
    }

body:
I don't know enough about how tapes work to comment on the sense of what you're doing, but some problems with the code:

You are reading the input and setting `buttonstate` once only in `setup() `. You need to read it repeatedly, by putting it in `loop()`.

You also have three variables called `state`: one global which is never set, and two with very restricted scope which are set but never used - they go out of scope immediately. Remove the `int`s where you set `state` in your `loop()`.

This part is useless because you've already done it just above, but probably not hurting anything:

    if (stopState == LOW) {
        state = STOP;
    }

That's as far as I got. If that doesn't fix it, consider adding trace: you'd have found these two problems pretty quickly if you'd printed out the variables to check your assumptions.


message:
Unknown USB Device (Device Descriptor Request Failed) - Win 10

I am posting a possible solution here for any online searches happening upon this exact issue.

So I have a third party board (Mega 2560) and I was plagued with my board intermittently working, on some rare occasions it worked but in most cases it just threw me the "USB device not recognized" after plugging it into my pc.

Upon closer inspection I have noticed the following[![Not the best of jobs eh?][1]][1]

The one coupling capacitor (Blocks DC but allows AC and signal to pass) was poorly soldered, barely making contact!

So if your pc intermittently connects to your arduino, maybe check what the physical signal path looks like, you might find something like this.

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

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

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

SMD soldering is not easy but here is the fix. Continuity achieved!


message:
Reading RAM from SH1106 OLED Controller through I2C

*Summary: I'm having trouble with writing a program to get RAM data from an SH1106 OLED controller via i2c. In the first part of the question I've written the assumptions I've made to get informations I couldn't find in the datasheet, in the second part I've posted a program which should read that data but doesn't (obviously, since I'm writing here...).*

I'm working on a program to control an SH1106 OLED display. I read the datasheet to find out how to send commands to it and it works, I can write to my display.

Now in the datasheet there is one thing I don't understand: how can I read the RAM?

Consider the picture below, taken from the command table at pages 30 and 31 of the [SH1106 datasheet](http://www.allshore.com/pdf/SH1106.pdf); the last line is the one about reading RAM.

This chip can be connected to a microcontroller through different interfaces: 6800 and 8800 8-bit parallel, 3 and 4 wire SPI and i2c. Since I'm using SPI I don't have any `A0`, `RD` or `WR` pin, and I didn't found anywhere in the datasheet a "translation" of the boolean value given to those signals in the command table to some i2c signal. I assume that WR corresponds with the lsb of the i2c address, since it is 0 for writing and 1 for reading. And my assumption seems to be true since I can read the status (line 25).

Then I assumed that `A0` should match `DC` (Data/Command, see second screenshot), a bit of the Control byte. The control byte is a byte that has to be sent before each byte or group of bytes to tell the chip how to interpret it (command or data). But I tried to send it before an i2c reading with different values and I always get the status byte (never the RAM data).

How could I read the memory of an SH1106 chip through i2c? The datasheet doesn't states that it is impossible (neither that it is possible...), maybe I simply can't?

**Command table**
[![Command table][1]][1]
(I removed lines 1-16, which contain commands like those at lines 17-23)

**Control byte**
[![Control byte][2]][2]

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

----------

**EDIT**

Here is the shortest working program I could write which shows the problem (i.e. which contains my implementation errors). I tested it on an Arduino UNO.

    #define ADDR  0x78

    void i2c_start() {
      TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
      while (!(TWCR & (1 << TWINT)));
    }

    void i2c_stop() {
      TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
    }

    void i2c_send(uint8_t data) {
      TWDR = data;
      TWCR = (1 << TWINT) | (1 << TWEN);
      while (!(TWCR & (1 << TWINT)));

    }

    uint8_t i2c_read(bool isLastByte) {

      if (isLastByte) TWCR = (1 << TWINT) | (1 << TWEN);
      else TWCR = (1 << TWEA) | (1 << TWINT) | (1 << TWEN);
      while (!(TWCR & (1 << TWINT)));
      return TWDR;
    }

    void display_init() {
      i2c_start();
      i2c_send(ADDR);
      i2c_send(0x00); //................ control byte
      i2c_send(0xAE); //................ displayOff
      i2c_send(0x8D); //................   *
      i2c_send(0xD5); i2c_send(0x80); // clockFrequency
      i2c_send(0x32); //................ pumpVoltage0123
      i2c_send(0xA1); //................ segmentRemap
      i2c_send(0xC8); //................ flipVertically
      i2c_send(0xDA); i2c_send(0x12); // comConfiguration
      i2c_send(0xA8); i2c_send(0x3F); // multiplex
      i2c_send(0xD3); i2c_send(0x3F); // displayOffest
      i2c_send(0x10); i2c_send(0x00); // columnAddr
      i2c_send(0x40); //................ startLine
      i2c_send(0xB0); //................ pageAddr
      i2c_send(0xAF); //................ displayOn
      i2c_stop();
    }

    void setup() {

      // Initialization
      Serial.begin(115200);
      display_init();

      // Request RAM data
      i2c_start();
      i2c_send(ADDR);
      i2c_send(0x80); //   control byte
      i2c_send(0xB0); // page address
      i2c_send(0x80); //   control byte
      i2c_send(0x10); // column address high
      i2c_send(0x80); //   control byte
      i2c_send(0x00); // column address low
      i2c_send(0x40); //   control byte
      i2c_send(0xE3); // nop
      i2c_stop();

      // get RAM data
      uint8_t a[10];
      i2c_start();
      i2c_send(ADDR + 1);
      for (int i = 0; i < 9; i++) a[i] = i2c_read(false);
      a[9] = i2c_read(false);
      i2c_stop();

      // print results
      for (int i = 0; i < 10; i++) {
        Serial.print("0x");
        Serial.println(a[i], HEX);
      }

    }

    void loop() {}

I've tried as many possibilities as I could imagine in the `// Request RAM data` section. To avoid confusion I leave only the posted one to your kind analysis, but of course if someone would like to see them just write it in a comment and I'll post all the (unsuccessful) test I have made.

The output on the serial monitor is always a list of `0x3`s.

I've not reduced the initialisation routine I use in my code because maybe the issue comes from there. BTW, I have no idea about what the `i2c_send(0x8D); //................   *` line does, I've added it because all the others SH1106 libraries I found had it, but I didn't found it in my datasheet. Maybe there are multiple versions of the chip or of the datasheet?

body:
It's slightly tricky understanding the protocol with I2C.  The bit to watch is:

> If the R/ W bit is set to one in the slave-address, the chip will output data immediately after the slave-address according to the D/C bit, **which was sent during the last write access.** If no acknowledge is generated by the master after a byte, the driver stops transferring data to the master.

So you have to set the D/C bit in the transaction *before* you want to access the RAM.

It's unclear from the datasheet if you have to send a data byte after the control byte for it to be accepted, but if you do you can use the NOP command.

So you do a write of NOP with D/C (which, yes, corresponds to A0 in the other interfaces) set to 1 in the control byte (i.e., write the bytes 0x40 0xE3) and then you can do a read which should return the RAM contents at the current page/column address, which will auto-increment for each subsequent byte.

It's quite an unclear datasheet when it comes to explaining how I2C reading works...


body:
My version of the data sheet has a flowchart (Figure 10) for doing a "read-modify-write".  In there is a clue - there has to be a dummy read before the actual read is done.  Here is my function for plotting a pixel, which requires a read-modify-write to add a pixel to the existing data.  It's not clear dummy read is needed before every byte read, or just on the first of a sequence of bytes, but that's easy enough to test.
```
#define CTRL_LAST_CMD 0x00
#define CTRL_NEXT_CMD 0x80
#define CTRL_LAST_RAM 0x40
#define CTRL_NEXT_RAM 0xC0

void MySH1106_PlotPixel(char x, char y, char on) {
  unsigned char curDisp;
  MySH1106_SetPage(y/8);
  MySH1106_SetCol(x);

  Wire.beginTransmission(SLAVE_ADDR);
  Wire.write(CTRL_LAST_CMD);
  Wire.write(0xE0); //R-M-W enable
  Wire.endTransmission(1);

  Wire.beginTransmission(SLAVE_ADDR);
  Wire.write(CTRL_LAST_RAM);
  Wire.endTransmission(1);

  Wire.requestFrom(SLAVE_ADDR, 2, 1);
  while(Wire.available()<2);
  curDisp = Wire.read(); //dummy read
  curDisp = Wire.read(); //real read.

  Wire.beginTransmission(SLAVE_ADDR);
  Wire.write(CTRL_LAST_RAM);
  if (on) {
    Wire.write((0x1<<(y%8)) | curDisp);
  } else {
    Wire.write(~(0x1<<(y%8)) & curDisp);
  }
  Wire.beginTransmission(SLAVE_ADDR);
  Wire.write(CTRL_LAST_CMD);
  Wire.write(0xEE);//end R-M-W
  Wire.endTransmission(1);

}
```
This is woefully inefficient for plotting one pixel, but it's a start.

Edit: I've subsequently confirmed that only 1 byte of dummy read is needed, even if the reads are stopped/restarted.  As long as you're only doing RAM reads, no further dummy reads are needed.


message:
RS422 interfacing with the Arduino

Good day,
I have a sensor which supports serial data output using RS422 which has 4 wires (RX+, RX-, TX+, TX-)
my question is how can I connect this sensor to the Arduino.
I read that i can use 2 max485 chips to do this but uncertain of the exact procedure.
Thanks in advance.

body:
The MAX490 chip consists of DI (pin 3) and RO (pin 2) pins that connect to the Arduino TX and RX respectively. the rs-422 side of the chip consists of pin 5 (Y / T+), Pin 6 (Z / T-), pin 7 (B / R-) and pin 8 (A / R+)

[http://arduinotronics.blogspot.com/2018/09/long-distance-serial-with-rs-422.html][1]

  [1]: http://arduinotronics.blogspot.com/2018/09/long-distance-serial-with-rs-422.html


body:
  There are pre-made and very inexpensive Arduino RS-485 modules available on Ebay or Amazon.  Much simpler than building your own circuit.

They look like this:

[![RS-485 Module][1]][1]

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


message:
Modbus RTU controller monitoring with arduino and RS485 module

[![enter image description here][1]][1]I'm a medium user in Arduino. I baught a pHmeter controller with RS485 output (MODBUS RTU protocol).
I want to get pH value read by the controller over RS485 module and Arduino.
According the controller's manufacturer, we should operate as bellow:
Sent by computer : 00 03 00 00 00 01 85 DB
Return from controller : 00 03 02 02 AE 05 58.

#include SoftwareSerial.h

#define SSerialRX        10  //Serial Receive pin
#define SSerialTX        11  //Serial Transmit pin
#define SSerialTxControl 3   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW
#define Pin13LED         13

SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
byte byteSend;

void setup()
{
  // Start the built-in serial port, probably to Serial Monitor
  Serial.begin(9600);
  Serial.println("SerialRemote");  // Can be ignored

  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);

  digitalWrite(SSerialTxControl, RS485Receive);  // Init Transceiver

  RS485Serial.begin(9600);
  delay(2000);
  digitalWrite(SSerialTxControl, RS485Transmit);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x03);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x01);
   RS485Serial.write((byte)0x85);
   RS485Serial.write((byte)0xDB);
   Serial.println(" ");

   digitalWrite(Pin13LED, LOW);
   delay(10);
   digitalWrite(SSerialTxControl, RS485Receive);

}
void loop()
{

  if (RS485Serial.available())
  {
    byteSend = RS485Serial.read();   // Read the byte
    Serial.print(byteSend, HEX);
    Serial.print(" ");
  }
}

I tried this following sketch who does not work.
I would like to know if it is the good way to send request to the controller?

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

body:
To send series of bytes over Serial or any other Stream (Print) implementation use the "write buffer" method `size_t write(const uint8_t *buffer, size_t size)`

For the case in question:

    byte request[] = {0, 0x03, 0, 0, 0, 0x01, 0x85, 0xDB};
    RS485Serial.write(request, sizeof(request));

If someone is curios about the Modbus RTU request bytes. They are:

 - station address
 - function - 0x03 Read Multiple Holding Registers
 - register address - 2 bytes
 - number of registers to read - 2 bytes
 - checksum - 2 bytes

The response:

 - station address return
 - function or error code
 - data length
 - data - length bytes
 - checksum - 2 bytes


message:
Problems bluetoothing float values

I have two Arduino Unos, one of which is connected to a HC-05 bluetooth device and a temperature reader, the other has just a HC-05 bluetooth and is expected to output temperature readings in serial monitor.

This is first device:

    #include <SoftwareSerial.h>
    const int tempPin = 1;
    SoftwareSerial BTSerial(10, 11);

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

    }

    void loop() {
    int value = analogRead(tempPin);
    float mv = value * (3300/1024);
    float x = (mv - 500)/100;
    Serial.print("Temperature is: ");
    Serial.println(x);
    BTSerial.print(x);
    delay(5000);
    }
This is the second device:

    #include<SoftwareSerial.h>
    void setup() {
    BTSerial.begin(38400);
    Serial.begin(9600);
    }
    void loop() {
    if(BTSerial.available())
    {
    float x = BTSerial.read();
    Serial.println(x);
    }
    }
The first program is able to give me accurate readings (around (15 degress Celsius) but the second program gives readings between 40 - 60 *C (as well as that it spits out 5 different readings between delay intervals). Why is that? How should I change this so both devices output the same readings

body:
Two problems:

Your first program sends an ASCII representation of the temperature with no line ending.  So after a few readings you get something like:

    20.2520.2520.5021.0021.25

etc.  You need some line endings in there to break them up.

Secondly your second program reads one byte at a time as a number (float) and prints it - so would get something like:

    50.00
    48.00
    46.00
    50.00
    53.00
    50.00
    48.00
    ... etc ...

You need to, in association with sending line endings in your first program, read each character of a single line either into a string and then parse that as a float (with `dtostrf()`) or directly into a float using a state machine.

You can read more about working with serial [here](https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/) and working with a number reading state machine [here](https://www.gammon.com.au/serial).


message:
Missing arduino bootloader problem?

I have a arduino clone that is not being assigned a /dev/tty by Debian Stretch (Stable).  It does have the ch340g chip.  I have tried the driver from the manufactures site with no joy.  Would the lack of a bootloader cause this problem?

Thanks.

body:
No.  On Arduino-style boards which use distinct chips for the main processor (ATmega328p) and Serial interface (CH34x/ATmega8u2/ATmega16u2/FT2232 etc) the presence or absence of a bootloader on the main processor has no bearing on the recognition of a USB/Virtual Serial device by a host.

However on ATmega32u4 and some ARM-based boards it can.

Since you are describing a classic board with distinct chips, whatever your actual issue is, it is something else.


message:
Need help with understanding the CapacitiveSensor circuit diagram

Hey guys I need help with understanding the circuit diagram from this link: https://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense

As of now, this is the schematic I drew from what I understand:

[![https://imgur.com/YBvBupJ][1]][1]

I know it is wrong since they make use of 2 capacitors, but I do not know where should the other capacitor be connected to.

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

body:
The other capacitor shown in the article is the ambient capacitance (that is, the capacitance between the pin and the things around it). There is no actual capacitor.

What it is saying is that there is a RC circuit (the supplied resistor and the capacitance in the air) which will change the charging time of the RC circuit as the capacitance changes, when you move your hand near it.

---

From a comment:

> and the other capacitor with a value of 20-400pF

Yes, it **does** say that:

> Adding small capacitor (20 - 400 pF) in parallel with the body capacitance, is highly desirable too, as it stabilizes the sensed readings.

However that doesn't make any sense to me. How do you add a capacitor in parallel with your body? Do you carry one around with really long wires? And how do you hold it? I would ignore that part.


body:
This question appears to get posted every week!
There is NOT 2 capacitors.
The Csensed capacitor in dotted lines is the capacitance added when you touch the plate.
The Cpin capacitor is suggested to stabilise the readings and is not required.
So in the circuit NO capacitors are used.
All you need is a high value resistor between the Send Pin and Receive Pin and put your plate on the Receive Pin.


message:
Switch between timer2 and manually setting output of pin 3

I have a 62.5 kHz square wave created by timer2 on the pin 3. I would like to be able to use digitalWrite(3, HIGH) to force pin 3 high for several clock cycles, but then I would like it to return the 62.5 kHz square wave. Is there a way to reset a single output without resetting the entire program?

    void setup() {
      Serial.begin(9600);
      pinMode(3, OUTPUT); //Output for OCR2B (Timer 2)
      //The following block allows sets the Timer2 properties for PWM
      TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
      TCCR2B = _BV(WGM22) | _BV(CS20);
      OCR2A = 255; //Sets the period to 16us (62.5kHz)
      OCR2B = 0; //Sets the duty cycle of the signal (8-bit(255) resolution)
    }

    void loop() {
      int pot = analogRead(A0);
      int duty = map(pot, 0, 1023, 0, 255); //scale to duty cycle resolution
      OCR2B = duty; //set duty cycle
      delay(10000); //arbitrary wait time
      digitalWrite(3, HIGH);
      delay(10000); //arbitrary wait time
      //undo the digitalWrite to continue the pulse train here
    }

body: If you clear the clock select bits in `TCCR2B`, then the PWM stops and you can control the port normally. To re-start the PWM, set the `CS20` bit just as you did in `setup()`.


message:
Can Arduino control 8 solenoids?

I know very little about Arduino and even less about programming one. Before I purchase a board, and learn how to program it, I was wondering if my idea is feasible.

I want to program the Arduino to sequentially open one after another irrigation valve. There would be approximately eight 24 volt solenoid valves. Each one would need to be open for approximately 15 minutes, then open the next valve in sequence and finally close the previous valve. Similar to a multi-zone irrigation controller.

I see that I may need to use a transistor in the power circuit of the solenoid. But it is not clear to me if the Arduino can control eight solenoids and if so, does each solenoid require its own transistor?

body:
An Arduino can control (at least) 8 devices. Instead of a transistor, it might be much easier to use an 8 way relay controller, something like this:

[8 relay module][1]

Just connect all 8 valves to the relays, you power the relay with a separate source for the valves, and connect the pins to the Arduino.

These ones have opto couplers, which give an extra security between the valves and the Arduino.

[8 relay module with opto couplers][2]
(note I just put the first entry I found, you might find better/cheaper similar items, e.g. at AliExpress for $4).

As Andre said in a comment below, you can use an Arduino Mega if you need more outputs. Or if you want a challenge you can use use a multiplexer IC like 74HC595 (plenty of examples to be found with Arduino).

For controlling one relay with an Arduino enough examples can be found, for 8 it's similar (just use 8 GPIOs), or a multiplexer IC.

  [1]: https://www.amazon.com/SainSmart-101-70-102-8-Channel-Relay-Module/dp/B0057OC5WK
  [2]: https://www.elegoo.com/product/elegoo-8-channel-dc-5v-relay-module-with-optocoupler/


body:
Yes, Arduino can control eight transistors.

Each solenoid will need a transistor.

Ideal would be to use logic level N-channel MOSFETs that the Arduino 0/5V output can drive directly.  IRFL540 is mentioned a lot, you can get them at digikey.com.
Drive the gate thru a 150 ohm resistor, and have a 10K resistor from the gate to Gnd so the transistor is off while the Arduino is reset (and the IO pins all revert to Inputs).

Depending on the current draw, you may able to use a shift register with Open Drain outputs. TPIC6C595, 100mA. TPIC6B595, 150mA. TPIC6595, and TPIC6A595 are even higher current capable parts.

Add a diode with the same current rating across the solenoid coil, cathode to +24V, so the burst of current generated by the coil when the transistor closes has somewhere to dissipate. (current in a coil wants to keep flowing as the magnetic field in the coil collapses, it can't go thru the turned-off transistor, so it goes thru the coil and dissipates in the coil's wire-resistance).


body:
Yes, you will need something to drive 24 volt solenoids, because the Arduino cannot do it alone.

My preferred method would be to use a ULN2803 device, which will allow you to drive all those eight solenoids (assuming they take less than 500mA or current) and has inbuilt protection against the voltage spike when the solenoid switches off.

http://www.ti.com/lit/ds/symlink/uln2803a.pdf

These devices are available on eBay.

The software will be quite simple for this application and should be well within the capabilities of anyone who reads an Arduino tutorial.


body:
An Arduino board is merely a microcontroller with the stuff around it that is necessary to keep it running. By stufff, I mean thinks such as the voltage regulator that provides the power, the oscillator that provides the frequency for the controller, the GPIO pin connectors, and so on.

This is a very simple application and could easily be done by an Arduino. The programming doesn't have to run quickly. You are only doing one thing at a time.

I found an [8-channel relay module](https://www.amazon.com/dp/B01ARS8OVQ) that should do what you need. You would need four of them, but they are only about $11 apiece. I have never used this device before, so I don't know how well it works, but the specifications seem right. They can be controlled by almost any computer with output pins that have 5 volts. So you'd need to use an Arduino with 5V output pins.

You will probably need more output pins than a standard Arduino, but that is easy enough to do with the Mega version.


body:
There are 2 wires to a solenoid, and 2 ways to operate them:

1- Closing a relay sends 24V out, with return wires going to 0 volts.

2- 24V Always goes out, and a relay can short the return wire to 0 volts.

Either way, test 2 by running the wires to a control board, and manually activating solenoids. When that works, add Arduino relay control as other suggest.

Keeping the switches will help, if you want to operate a solenoid manually OR you suspect you have a broken relay / solenoid.


body: Most irrigation valves are AC operated, typically using 24VAC at about 250mA (Double that to 500mA for the inrush current).  The best way to drive these is via a triac.  If you want isolation between your controller and the valve voltage an opto coupler with a triac output is the best way to go.  A good choice given the typical irrigation valve is the Vishay VO3023:  5mA LED input current and 1A output current and only about $0.50 per unit.  Triacs are pretty tough devices and have no moving parts like relays so they are quite reliable.


body: An alternative method is to use an I2c port expander such as a PCF8574.  These are available as break out boards.  By selecting a different I2C address on each break out board up to 64 relays can be controlled using opto isolated relay modules.  Thus 64 0utputs or inputs with just two Arduino pins.


message:
Getting a truly random number in Arduino

What is the best method to get a truly (as opposed to pseudo) random number in Arduino, or at least the best possible approximation? From my understanding, the function randomSeed(analogRead(x)) it's not random enough.

If possible the method should leverage the basic Arduino setup alone (no additional sensors). Solutions with external sensors are welcome if they improve significantly the randomness over the basic setup.

body:
The [Entropy library](https://sites.google.com/site/astudyofentropy/project-definition/timer-jitter-entropy-sources/entropy-library) uses:

>the watchdog timer's natural jitter to produce a reliable stream of true random numbers

I like this solution because it doesn't use up any pins of your microcontroller and doesn't require any external circuitry. This also makes it less subject to external failures.

In addition to a library, they also provide a sketch that demonstrates the use of the same technique used to generate a random seed for the microcontroller's PRNG without the library:
https://sites.google.com/site/astudyofentropy/project-definition/timer-jitter-entropy-sources/entropy-library/arduino-random-seed