body:
I can get PB4 to work but not PB3 on my ATtinny85.  I'm just lighting up an led (with 150 ohm resistor) (using internal 16mhz)
```
void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);

}
void loop() {
  analogWrite(3, 15);//does not work
  analogWrite(4, 15);//works
  delay(500);
  analogWrite(3, 0);//does not work
  analogWrite(4, 0);//works
  delay(500);
}
```
[![enter image description here][1]][1]

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

title: Attiny85 PB4 works for analog output but not PB3?

Answers: 1

body:
The hardware `PWM` is only suported on pins with output compare altenate function on it. The pinout in your question shows `Attiny13` but the rest of your question is about `Attiny85`, which has different capabilities from `Attiny13`

[![Attiny85 pinout][1]][1]

As you can see, only pins with `PWM` capability are `PB0`, `PB1` and `PB4`

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


body: Need help to see if I can get an Arduino due to receive and send 9-bit com as already implemented on AVRs like Uno, Mega and even teensy boards, by modifying hardware serial cores. Have not found any similar references for this for the due? Is the due capable of 9-bit com?

title: Arduino Due 9-bit serial - Can core Due Libraries be modified to get this functionality similar to Mega and Uno?

Answers: 0


body:
I am trying to define multiple serial ports (multiple BMS management boards) and select via a global variable the port which one is active, this is the sketch I am trying to modify.

https://github.com/bres55/Smart-BMS-arduino-Reader/blob/master/smart_bms_reader_Mega_v11.ino

The function I want to write could be called "MySerialSwitch"

The smart_bms_reader_Mega_v11.ino has 19 calls to serial in a number of different functions. I want to be able to define the "active" MySerial in a variable that can be changed on the fly.

Something like this.

    #include <SoftwareSerial.h>
    SoftwareSerial MySoftSerial1(10, 11); // RX, TX
    SoftwareSerial MySoftSerial2(12, 13); // RX, TX

    #define MySerial1 MySoftSerial1
    #define MySerial2 MySoftSerial2
    #define MySerial3 Serial3

    char MySerialPort[] = "MySerial1";

    void setup()

    {
    MySoftSerial1.begin(9600);
    MySoftSerial2.begin(9600);
    Serial3.begin(9600);
    }

This function would be modified

    void call_get_cells_v()
    {
      flush(); // flush first
      uint8_t data[7] = {221, 165, 4, 0, 255, 252, 119};
      MySerial.write(data, 7);
    }

 to read.

    void call_get_cells_v()
    {
      flush(); // flush first
      uint8_t data[7] = {221, 165, 4, 0, 255, 252, 119};
      MySerialSwitch.write(data, 7);
    }

I have been researching this post

https://arduino.stackexchange.com/questions/22211/how-to-define-a-softwareserial-object-inside-a-class?newreg=b3b214527df54d7ea3152d0c6edd21df

And this post

https://arduino.stackexchange.com/questions/935/writing-first-library-serial-stream-object

It’s my first attempt at creating a library, I think this is kind of what I am trying to achieve, I've done the reading on stream, references and pointers. I'm not quite clear yet. I would really appreciate some assistance.

    class MySerialSwitch {
        private:
            Stream *_dev;

        public:
            MySerialSwitch(Stream *dev) : _dev(dev) {}
            MySerialSwitch(Stream &dev) : _dev(&dev) {}
            (char MySerialPort);
    };

        (int pos) {
        _dev->write(char MySerialPort);
    }

title: Multiple Serial Ports Stream Switch

Answers: 1

body:
I found this post, I don't think it will switch between hardware serial and software serial but it certainly works for just software.

    #include <SoftwareSerial.h>
    SoftwareSerial MySoftSerial1(10, 11); // RX, TX
    SoftwareSerial MySoftSerial2(12, 13); // RX, TX
    SoftwareSerial *MySerial;

    void setup()
        {

       Serial.begin(115200);
       MySoftSerial1.begin(9600);
       MySoftSerial2.begin(9600);
        }

        void loop()
        {
          MySerial = &MySoftSerial1; //Query the 1st BMS
          //or change port
          MySerial = &MySoftSerial2; //Query the 2nd BMS

          // I had to all instances of MySerial.write to MySerial->write
        }

I'll keep reading to figure out what I've done but if anyone would like to explain, I'd be very appreciative.

This is the post I got the method from.

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

Thanks


body:
This is a somewhat tricky question dealing with implementation and best-practices of the ESP8266. I'd ideally hope that it's answered by people with in-depth knowledge on the problem.

As you are hopefully aware, the Arduino (AVR) platform requires the use of the PROGMEM or F() instructions to avoid copying all strings to RAM. The ESP8266 platform also provides a PROGMEM instruction, but is memory-mapped.

I thus have several questions about what the PROGMEM instruction actually does on the ESP8266.

For the next few questions, until otherwise marked, I am referring to character-array-style C strings, not the Arduino String type.

 1. Storage of constant strings: If I were to declare a string (global, for now) on the ESP8266, would it be read from flash only when it's accessed, or will it always take up RAM (like it would on the AVR. Assume that in this case I do NOT declare it as PROGMEM; I wish to find out what the default behavior is on the ESP8266)?

 2. Local Constant Strings: What happens with strings that are used inside a function? I am fairly sure that they ALSO exist in RAM, at least in AVR. Does the ESP8266 do this too, or does it (potentially) store it in flash until it is read (it is fine if it ends up inside a cache somewhere, as long as it can be evicted if needed)?

 3. Use of String(F("mystring")): If I wrap a PROGMEM string in this manner, does this truly convert the string into a RAM-based string only when this line is reached, or does this for some reason initialize the String() early (and consume the RAM anyway)? Do the systems differ in this behavior?

 4. If I define several instances of the above (as in, the identical wrapped string shown above appears several times, perhaps in different functions), do all of them point to the SAME F() instance (since they are identical) or does it get duplicated since it's part of code rather than a referenced variable? On ESP8266? On AVR?

 5. On the ESP8266, I discovered that the server.on() function for the built-in webserver read F()'d constant strings just fine, but failed to work once the file grew beyond the size of the RAM. It was clearly *stored* correctly, but it could not be *read*. I thus conjecture that the method was making a local copy to RAM, even if the file was stored in Flash. There was also a on_P version that worked after that point (I believe I used PSTR rather than F at this point as well, since -- correct me if I am wrong -- the two are not compatible). Is this the real point of PROGMEM on ESP8266? That the data **is** only stored in Flash, but it also tells the function reading it to make as few copies as possible or chunk it?

----------

I am also curious what happens with large strings that *aren't* constant. The web server can return data that was passed via querystring, for instance, which in my case can be quite large. If I copy that data to a string (and then into a function), does it pass the heap pointer directly, or does each String make a new copy? I am concerned about fragmentation or other fun ways of running out of RAM even if one copy should in theory fit.

Does doing something like `bool myFunction(String &str){...}` help? Some sort of way to actually ensure that it's the same string, rather than copying (and can I do `String &myStr=server.arg(...)` -- is a return value different from an assignment)? It's confusing for me, since strings are clearly passed by value, despite being a complex datatype with dynamic memory somewhere in there. So, did they override the assignment operator (and/or the one that handles reference passing, since I think there's more than one) to duplicate the string as pass-by-value of a basic type would normally do, or do they share pointers (and thus memory) as a *class* passed-by-value would normally do?

title: Use of progmem in ESP8266 vs AVR and also how to handle large dynamic strings

Answers: 1

body:
On the ESP8266 flash is a very special case. Because the ESP8266 itself does not have any flash, but instead uses an external SPI-connected flash chip, accessing it is not an easy or technically obvious operation.

Reading from the flash chip is slow. Very very slow (by comparison to reading RAM).  Because of this where possible certain things are copied into RAM. Also, there are different sections of RAM that are dedicated to different purposes.

* `dram0` - This is your "Data" RAM. It's where your variables and such are stored (80kB total).
* `iram1` - Instruction RAM. It's here that interrupt routines need to be stored for rapid execution (32kB).
* `icache` - Instruction cache. 16kB of data that is cached when reading from the flash chip. Executed code usually gets copied here.

Normally when you execute code the block of code that the instructions you are executing are copied from flash into the `icache` memory block and then executed. This is reasonably fast (reasonably in that there may be brief delays while copying the data from flash, but fast when actually executing. I don't know how efficient the cache is, whether it's split into different blocks that are loaded in the background by the memory controller as needed, but it seems to be a pretty efficient system that is used in practice).

Because of this disassociation of the CPU and flash string constants, unless specified otherwise, will be copied into `dram0` during startup. This makes it very fast and simple to get at the data. Anything that you don't specify as `PROGMEM` will get copied into `dram0`. Note that you don't get all 80kB of the RAM to play with since the SDK uses a portion of it. You only get about 50kB at most (station mode - softap mode will use more).

Now... what *does* `PROGMEM` do on the ESP8266 then?  Well, it adds an *attribute* to the definition that tells the linker to place the data in a specific section in flash (`.irom.text.<filename>.<line>.<number>`). This prevents it being copied into `dram0` at startup.

So how do you get at it? That's where the `*_P` variants of the string functions (and certain overloaded functions in the Arduino core) come into play.

The whole of the flash chip is mapped (or can be, depending on register settings) into the ESP8266's memory map (address 0x40200000). Which means that it's possible to get directly at the data. However since this access doesn't go through the `icache` RAM block it's slow. Very very slow. About 12x slower by some accounts. Also because data can be in different locations within the chip the addresses of your string data can't be directly hard coded. There has to be some form of "it's over there" redirection when reading the data (for example if you use OTA updates you get two distinct blocks of flash where your code can be stored - the currently executing code and the previously executing version). The `*_P` variants of the string functions take that into account and look up where in flash the current code is located before reading from it.

So to summarise: Not using `PROGMEM` gives you fast access to your string data at the cost of RAM, and limits the size of the data you can use. Using `PROGMEM` removes the size restriction, doesn't use RAM, but is considerably slower.

To specifically answer your questions:

1. The string data gets copied to RAM at startup.
2. The string data gets copied to RAM at startup.
3. The string data gets loaded from flash (using `*_P` variants of functions) when the `String` object is constructed (RAM is allocated on the heap at that moment in time). The RAM is freed when the `String` object is destroyed (goes out of scope).
4. The compiler has recently had an update that will deduplicate constant PROGMEM strings.
5. As mentioned above `*_P` copies directly from flash and is slow, but has no size limitation.


body:
I want to make a serial program with input from the serial monitor and show each character with its binary and ASCII codes.

At the end of the program, I want to show the whole message sent from the serial monitor but I don't know how to stop the loop. Can someone help me please?

Here's my program:

    String dataST;

    void setup() {
      Serial.begin(9600);
      Serial.println("Message sent by serial monitor : ");
    }

    void loop() {
      for (int i = 0; i < 400 ; i++) {
        if (Serial.available()) {
          char dataOK = Serial.read();
          dataST += dataOK;
          Serial.print(dataOK);
          Serial.print(" = ");
          delay(200);
          for (int i = 7; i >= 0; i--) {
            byte bytes = bitRead(dataOK, i);
            Serial.print(bytes, BIN);
          }
          Serial.print(" = ");
          int dataAS = dataOK;
          Serial.print(dataAS);
          Serial.println(" ");
          Serial.println(" ");
        }
      }
      Serial.println("Message : ");
      Serial.print(dataST);
      dataST = "";
    }

The result from the program above is:

    Message sent by serial monitor :
    Message :
    Message :
    Message :

And the result I want is:

    Message sent by serial monitor:
    H = 01001000 = 72

    e = 01100101 = 101

    y = 01111001 = 121

    Message :
    Hey

Please help me.

title: How to stop loop in the serial monitor?

Answers: 2

body:
Please take a look at the documentation of [SerialEvent][1].

This might be exactly what you are looking for (after several small tweaks)

Code from the example:
```c++
/*
  Serial Event example

  When new serial data arrives, this sketch adds it to a String.
  When a newline is received, the loop prints the string and clears it.

  A good test for this is to try it with a GPS receiver that sends out
  NMEA 0183 sentences.

  NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or
  other ATmega32U4 based boards.

  created 9 May 2011
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/SerialEvent
*/

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

void loop() {
  // print the string when a newline arrives:
  if (stringComplete) {
    Serial.println(inputString);
    // clear the string:
    inputString = "";
    stringComplete = false;
  }
}

/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}
```

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

body:
An embedded system is never meant to stop. If/when your `loop()` function exits (returns), it will be immediately called again.

If you need a process that runs to some state of completion and than stops, you're better off to leave `loop()` empty and write your own function that does what you need it to do, and call it at the end of `setup()`.

You can either put an infinite loop at the bottom of your function:

    for(;;);

is one way to do it, or just let it return to setup(). Then `setup()` will exit, your empty `loop()` function will be called (infinitely), which accomplishes the same thing.


body:
    void setup() {
      Serial.begin(9600);
      setupPWM16();
    }

    uint16_t icr = 0xffff;

    void loop() {
      analogWrite16(9, 0);
    }
    void setupPWM16() {
      DDRB  |= _BV(PB1) | _BV(PB2);       /* set pins as outputs */
      TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
            | _BV(WGM11);                 /* mode 14: fast PWM, TOP=ICR1 */
      TCCR1B = _BV(WGM13) | _BV(WGM12)
            | _BV(CS10);                  /* prescaler 1 */
      ICR1 = icr;                         /* TOP counter value (freeing OCR1A*/
    }

    /* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
    void analogWrite16(uint8_t pin, uint16_t val)
    {
      switch (pin) {
        case  9: OCR1A = val; break;
        case 10: OCR1B = val; break;
      }
    }

Using the code above I can achieve 16 bit PWM signal, but when writing 0 in `analogWrite16` it output ~33mV. I know that I can set the PWM pin low but yet again it don't output 0V.

I'm guessing beside the ATMEGA offset the Arduino UNO board it self ground is raised either because it's being fed from USB or the board circuitry and PCB traces resistance. or both?

because ~33mV offset is a lot, is it normal?

How can I make Arduino to start at 0V or at least reduce that 33mV offset to 1-2mV?

title: 16 bit PWM doesn't go to absolute 0V

Answers: 1

body:
You've got two possibilities:

 1. You can't have full off in "non-inverting PWM" mode
 2. You can't have full on in "inverting PWM" mode

In the Arduino core it's solved by turning off the PWM output and setting logical 0 or 1 for corner values.

And if you need full off but you don't need full on, you can use inverted PWM mode.


body:
I am currently trying to connect my Arduino Uno to my computer and let them communicate via UART. I started using a project from Github ([here](https://github.com/bertrandom/snowball-thrower)), which I'm trying to modify to get the next step via UART. Because of that, I'm not able to switch programming languages and also need to override the bootloader.

However, I can't get the serial connection to work.
```
#include "Joystick.h"
#include <avr/io.h>
#include <util/delay.h>
#include <Arduino.h>
```
These are the `#include` statements at the top, but `<Arduino.h>` can't be found...

If I remove these statements, `Serial` can't be found (from the `main`-Method: `Serial.begin(9600);`)

It's my first time to program with C, did I overlook a stupid mistake? Thanks for any help...

title: Using serial communication in .c-files

Answers: 1

body:
I would consider using [HoodLoader2](https://github.com/NicoHood/HoodLoader2) instead of that LUFA project. If you can't do that, you can compile parts of the Arduino Core together with the LUFA project.

The main steps:

- Add the necessary Arduino source files to the `SRC` variable in the Makefile.
- Add the Arduino core folder to the include path by appending to the `CC_FLAGS` and `CXX_FLAGS` variables.
- Move the main function to a new `main.cpp` file and add it to the Makefile `SRC` as well.
- Include the `Joystick.h` file in your main file in an `extern "C"` block.
- Include the `HardwareSerial.h` file in your main file as well.

My files after these changes:

**Makefile**

```Makefile
# Set the MCU accordingly to your device (e.g. at90usb1286 for a Teensy 2.0++, or atmega16u2 for an Arduino UNO R3)
MCU          = atmega16u2
ARCH         = AVR8
F_CPU        = 16000000
F_USB        = $(F_CPU)
OPTIMIZATION = s
TARGET       = Joystick
SRC          = $(TARGET).c Descriptors.c main.cpp $(LUFA_SRC_USB)
LUFA_PATH    = ./lufa/LUFA
CC_FLAGS     = -DUSE_LUFA_CONFIG_HEADER -IConfig/
LD_FLAGS     =

ARDUINO_PATH = ${HOME}/.arduino15/packages/arduino/hardware/avr/1.8.1/cores/arduino
SRC         += $(ARDUINO_PATH)/HardwareSerial.cpp
SRC         += $(ARDUINO_PATH)/HardwareSerial1.cpp
SRC         += $(ARDUINO_PATH)/Print.cpp
CXX_FLAGS   += -I$(ARDUINO_PATH) -I./HoodLoader2/avr/variants/HoodLoader2
CC_FLAGS    += -I$(ARDUINO_PATH) -I./HoodLoader2/avr/variants/HoodLoader2

...
```

**main.cpp**

```cpp
extern "C" {
#include "Joystick.h"
}

#include <HardwareSerial.h>

// Main entry point.
int main(void) {
 // We'll start by performing hardware and peripheral setup.
 SetupHardware();
 // We'll then enable global interrupts for our use.
 GlobalInterruptEnable();
    // Initialize the UART
    Serial1.begin(115200);
    Serial1.println(F("Hello, world"));
 // Once that's done, we'll enter an infinite loop.
 for (;;)
 {
  // We need to run our task to process and deliver data for our IN and OUT endpoints.
  HID_Task();
  // We also need to run the main USB management task.
  USB_USBTask();
 }
}
```

**Joystick.c**
Deleted the `main` function.

To get it to compile after these changes:

```sh
# (inside of the snowball-thrower folder)
git submodule add https://github.com/NicoHood/HoodLoader2.git HoodLoader2
make
```

This compiles without problems for me, but I have no idea if it actually works.

**Edit**:

You'll notice that the program uses more RAM than the ATmeg16U2 has available. You could solve this by moving the `step` array to `PROGMEM`, or by shrinking the Serial buffers.

```
avr-size --mcu=atmega16u2 --format=avr Joystick.elf
AVR Memory Usage
----------------
Device: atmega16u2

Program:    5076 bytes (31.0% Full)
(.text + .data + .bootloader)

Data:        527 bytes (102.9% Full)
(.data + .bss + .noinit)

 [INFO]    : Finished building project "Joystick".
```


body:
I just bought a new Adafruit Flora board, and I haven't been able to get it working successfully. When I plug it into a USB port, the board seems to be getting power (the green PWR LED is illuminated), but there is no other output from the board. The Arduino IDE also does not recognize the board (the "port" menu under "Tools" is grayed out), and I have tried to connect to it on both Windows and Linux (Ubuntu) systems with the appropriate drivers/packages installed (including the Windows drivers and the board manager add-on in both installations of the Arduino IDE). I've also verified that the USB cable I'm using can handle data.

Previously, I was able to at least get the board to be recognized in the IDE on my Linux machine, and the red LED did light up, but after disconnecting it doesn't light up anymore (unless I try to reset the board, which makes the red LED pulse a few times).

Anything that I can try to get it recognized in the IDE?

Edit: I'm able to see the board pop up under "ports" in the IDE immediately after I hit the reset button on the board. However, as soon as the red LED stops pulsing (I think this means that the board is finished rebooting), it disappears from the list of available ports. It's also mounting under /dev/ttyACM0, not the usual /dev/ttyUSB0.

title: Issues with connecting to an Adafruit FLORA board

Answers: 1

body: Seems like whatever code was running on the Flora was corrupted. As soon as I hit the reset button, the board would momentarily pop up in the Arduino IDE, and after doing this a few times, I managed to upload the "Blink" sketch while the board was visible to my system. After that the board started working normally. It reports its name as "Adafruit FLORA" under "get board info", and the serial monitor/onboard LED work just fine.


body:
I am trying to reproduce the side-channel power analysis attack described in this paper: https://pdfs.semanticscholar.org/7946/a8ee82658e2ffb017270331f220a55f5ace6.pdf for educational purposes.

The attack (on the HCS3xx family of chips) requires measuring the power consumption (i.e. current) that the chip is using in order to reveal its cryptographic key.

In the paper, they describe their setup as attaching a shunt resistor in the ground path and using a digital oscilloscope (with a sampling rate greater than 1MHz) to measure the voltage drop across this resistor.

I have reproduced this setup to the best of my abilities (pictured in the schematic below), but the problem is I don't have an oscilloscope.

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

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

<!-- End schematic -->

Therefore, I've decided to use an Arduino Uno I have lying around as a poor man's oscilloscope.

Besides the fact that the Arduino ADC has a *much* lower sampling rate (~77KHz vs. the ideal 20MHz described in the paper), I have been having an issue getting a reliable voltage reading across the shunt.

While trying to use the full 10-bit ADC, and producing samples as `(ADCH << 8) | ADCL` in my ADC ISR, I do not get any samples that are greater than 0.

However, when I left-align the ADC to only use 8-bit precision (with `ADMUX |= 1 << ADLAR` and read with just `ADCH`, I get non-zero values but none with a value greater than one.

Could it be that the amount of power that the chip consumes is so small that the Arduino does not have enough precision to read it? Or could it be that my shunt has too large of a resistance and is causing a reduced current throughout the circuit?

title: Measure current across shunt resistor (Power Analysis)

Answers: 1

body:
In the graphs they've got `2.5mA` tops, so you've got about `2mV` on that `1.2R` shunt resistor.

And Uno's default ADC reference is `5V` divided into `1024` steps each of them roughly `5mV`. That's more than peak value of measured voltage.

And with such small sampling frequency you won't be even able to spot fast changes as you'll be measuring much slower that it needs to be.

ADC step precision can be better by using internal 1V1 reference, but it's still way too big step. And there is no other option on UNO. The Mega on the other side has also possibility to configure diferential ADC inputs and with 1x, 20x or 200x gain. But it's not supported by Arduino core, so you'll have to do it directly. However it won't help much if it's sampling too slow.


body:
I'am making a temperature monitor using an IC2 Interface and a dht11 sensor connected to an arduino uno, it works great when it´s plugged to the computer but whenever i plug it to a 9v battery the humidity goes to "0" and the temperature to "2", it only works when i resend the code through the ide to the arduino.

What could be the problem?

Code :
```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
DHT dht;

void setup()
{
  lcd.begin(16,2);
  lcd.clear();
  dht.setup(7); // Pino 7

}

void loop(){

  float humidade = dht.getHumidity();
  float temperatura = dht.getTemperature();

  lcd.setCursor(0,0);
  lcd.print("Humidade: ");
  lcd.print(humidade);
  lcd.print("%");

  lcd.setCursor(0,1);
  lcd.print("Temp: ");
  lcd.print(temperatura);
  lcd.print("C");

  delay(1000);

}
```

title: Arduino problem

Answers: 2

body: The 9v sort of "cube shaped" batteries have a notoriously limited current output, resulting in falling voltage as the current demand rises. The Arduino's voltage regulator is not very effecient either, plus the battery gives only 2v of "headroom" over the minimum Vin voltage of 7v. Your system is probably starving. Try a different source.

body: Fixed it by clicking the red button on the arduino uno.


body:
Why has Adafruit ImageReader Library v2.3.5 recently added six dependencies on other libraries for hardware I'm not using?

I used the v2.3.2 of the Adafruit ImageReader Library successfully two months ago. An example sketch worked fine with my ILI9341 3.2" display and its SD card.

Now there is an updated v2.3.5 available but the library manager wants to add six more "dependency" libraries:
- Adafruit ST7735 and ST7789 Library
- Adafruit seeswaw Library
- Adafruit HX8357 Library
- Adafruit SSD1351 library
- Adafruit SSD1331 OLED Driver Library for Arduino
- Adafruit EPD

As far as I know, the ILI9341 uses none of the hardware that corresponds to the six libraries it's trying to drag in. I don't want unneeded dependencies and don't want the code bloat.

If I don't accept the additional libraries, my sketch fails to compile. The error message is "C:\Users\barry\Documents\Arduino\libraries\Adafruit_ImageReader_Library\Adafruit_ImageReader_EPD.h:18:10: fatal error: Adafruit_EPD.h: No such file or directory"

However, EPD code is for "e-paper displays" which does not apply to my ILI9341 which is a TFT display. I don't think EPD code should be a real dependency.

Kindly redirect me if there's a better place to ask.

title: Adafruit ImageReader Library 2.3.5 added several library dependencies

Answers: 1

body:
If you don't use the functions of the ImageReader library, which use the additional libraries, your compiled code will not contain code from the additional libraries.

The Adafruit ImageReader library may have functions which use other libraries and the libraries are required for compilation. But at linking the compiled units which are not used by your code and even parts of the compiled units which are not used by your code are not put in the resulting hex or bin file.


body:
Is there a way I can have my arduino uno differentiate between pushbuttons that are wired through a shift register and detect when each are pressed or not? I found [this][1] tutorial for the 74HC165 but I'm not sure it's applicable to the 74HC595.

  [1]: https://infectedbytes.com/2016/07/arduino-shiftin.html

title: How to detect button presses with a 74HC595 shift register?

Answers: 1

body:
The [74HC595](http://www.ti.com/lit/ds/scls041i/scls041i.pdf) is a *deserializer* while the 74HC165 is a *serializer*. This means the former consumes a serial datastream and provides all data bits in parallel on dedicated data lines. While the latter consumes parallel data and converts it to a serial datastream.

To scan buttons you want to have parallel input data, where each switch is attached to a single data line. Then you serialize the data to reduce the amount of required Arduino inputs. This method is well explained in the mentioned tutorial.

As the 74HC595 is a deserializer it is not really applicable here. Instead you could use it to drive multiple outputs through a serial interface (see https://www.arduino.cc/en/tutorial/ShiftOut as an example).


body:
I have made an LED cube that is a 3x3x3 design and was wondering if there is way to make a function in the Arduino IDE where each the layers of LEDs can be represented by a list with 1 being on and 0 being off:
```{1, 0, 1, 0, 1, 0, 0, 1, 0}``` with the first number of the list being the first column, then the second column, etc. and the same for the rows which would be something like ```{0, 1, 0}```. Does this make sense? If so, is there an idea for a function that could take these inputs and transform them into digitalWrite outputs? I am using an Arduino Nano for this, with pins 2, 3, 4, 5, 6, 7, 8, 9, and 11 used for the columns with A0, A1, and A2 being the rows of the cube.

title: What is the best way to assign pins to an LED Cube?

Answers: 1

body:
Well, learning bit manipulations and using three `uint16_t` (as 9 bits won't fit into `uint8_t`) to store state for a whole cube is much better. Then you hust have to setup timer `ISR` and each time it fires just display one "floor". The multiplexing can be done even in loop, but it's usualy flickering as you can't do almost perfect timing as in the `ISR`.

And for example, I was using two `2x4x4` segments to build up `4x4x4` cube and single `MAX7219` to drive it, so I don't have to handle whole multiplexing and so.

My another aproach was using individually addressable LEDs like `WS2812B`, so I needed only one pin to drive it all. Or by using `ARM` and `DMA` transfers, I could drive 8 or 16 lines simultaneously.


body:
since an Arduino cannot run two programs simultaneously, I have been struggling a lot to get my project working - basically it is a motorized desk which is supposed to take input either from a BLE controller app or a pushbutton in order to move the linear actuators. However these inputs should work SIMULTANEOUSLY, I have failed to make both of them work together, after countless hours of prototyping, code provided below, please help me out.

```c++
    #include <AFMotor.h>

    AF_DCMotor motor1(1, MOTOR12_64KHZ);

    AF_DCMotor motor2(2, MOTOR12_64KHZ);

    int command;

    int forwardButton = A3;

    int backwardButton = A4;

    void setup() {

      Serial.begin(9600);

      pinMode(forwardButton, INPUT_PULLUP);

      pinMode(backwardButton,INPUT_PULLUP);

      motor1.setSpeed(255);

      motor2.setSpeed(255);

    }

    void forward(){

       motor1.run(FORWARD);

       motor2.run(FORWARD);
    }

    void backward(){

       motor1.run(BACKWARD);

       motor2.run(BACKWARD);
    }

    void stopMotor(){

       motor1.run(RELEASE);

       motor2.run(RELEASE);
    }

    void loop() {

      if (Serial.available() > 0) {

        command = Serial.read();

        stopMotor();

        switch (command) {

          case 'a':
            forward();
            break;
          case 'c':
            backward();
            break;
          case 'e':
            forward();
            break;
          case 'g':
            backward();
            break;
          case 'b':
            forward();
            break;
          case 'd':
            backward();
            break;
          case 'f':
            forward();
            break;
          case 'h':
            backward();
            break;
        }

      }
        else {

          stopMotor();

      }

    while(digitalRead(forwardButton) == LOW)

    {

      forward();

    }

    while(digitalRead(backwardButton) == LOW)

    {

      backward();

    }

    if(digitalRead(backwardButton)== HIGH)

    {

      stopMotor();

    }

    if(digitalRead(forwardButton) == HIGH)

    {

      stopMotor();

    }

    }
```

title: Using two input methods to control one motor shield (bluetooth and pushbuttons)

Answers: 0


body:
When I try to compile my code it says "stray '\342' in program

My code:
```
#include <IRremote2.h>
#include <IRremoteInt.h>

#define pinIN 11

uint32_t val;
uint32_t prev;
int fre = 0;

IRrecv remote(pinIN);
decode_results result;

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

  remote.enableIRIn();
  pinMode(2, OUTPUT);
}

void loop() {
  if (remote.decode(&result)) {
    val = result.value;
    if (val == 0xFFFFFFFF) {
      val = prev;
    }
    prev = val;
    detekceKlaves();

    remote.resume();
  }
}

void detekceKlaves() {

  switch (val, HEX) {

    case 0x807FB24D:
      Serial.println("Stisknuto PLAY");
      tone(2, fre);
      break;
    case 0x807FB04F:
      Serial.println("Stisknuto STOP");
      noTone(2);
      break;
    case 0x807F18E7:
      Serial.println("Stisknuto VOL+");
      fre += 10;
      break;
    case 0x807F906F:
      Serial.println("Stisknuto VOL-");
      fre -= 10;
      break;
    case 0x807F9867:
      Serial.println("Stisknuto OFF/ON");
      fre = 0;
      break;
    default:
      Serial.println("Stisknuta jina klavesa");

  }
}
```

Error code:
```
Arduino: 1.8.10 (Windows 10), Board: "Arduino Uno"

irTEST:43:20: error: stray '\342' in program

     case 0x807FB24D:

                    ^

irTEST:43:21: error: stray '\200' in program

     case 0x807FB24D:

                     ^

irTEST:43:22: error: stray '\254' in program

     case 0x807FB24D:

                      ^

irTEST:47:10: error: stray '\342' in program

     case 0x807FB04F:

          ^

irTEST:47:11: error: stray '\200' in program

     case 0x807FB04F:

           ^

irTEST:47:12: error: stray '\255' in program

     case 0x807FB04F:

            ^

irTEST:47:23: error: stray '\342' in program

     case 0x807FB04F:

                       ^

irTEST:47:24: error: stray '\200' in program

     case 0x807FB04F:

                        ^

irTEST:47:25: error: stray '\254' in program

     case 0x807FB04F:

                         ^

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino: In function 'void detekceKlaves()':

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:43:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807FB24D:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:47:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807FB04F:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:51:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F18E7:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:55:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F906F:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:59:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F9867:

     ^~~~

Multiple libraries were found for "IRremote2.h"
 Used: C:\Users\maxim\Documents\Arduino\libraries\IRremote2
exit status 1
stray '\342' in program

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

```

Please help

title: stray \342 in program

Answers: 1

body:
If I copy your provided code in a vim-editor you can see some strange characters. `<202c>`

    switch (val, HEX) {
      4
      5     case 0x807FB24D<202c>:
      6       Serial.println("Stisknuto PLAY");
      7       tone(2, fre);
      8       break;
      9     case <202d>0x807FB04F<202c>:

I've removed them for you:

    #include <IRremote2.h>
    #include <IRremoteInt.h>

    #define pinIN 11

    uint32_t val;
    uint32_t prev;
    int fre = 0;

    IRrecv remote(pinIN);
    decode_results result;

    void setup()
    {
      Serial.begin(9600);
      remote.enableIRIn();
      pinMode(2, OUTPUT);
    }

    void loop()
    {
      if (remote.decode(&result))
      {
        val = result.value;
        if (val == 0xFFFFFFFF)
        {
          val = prev;
        }
        prev = val;
        detekceKlaves();
        remote.resume();
      }
    }

    void detekceKlaves()
    {
      switch (val, HEX)
      {
        case 0x807FB24D:
          Serial.println("Stisknuto PLAY");
          tone(2, fre);
          break;
        case 0x807FB04F:
          Serial.println("Stisknuto STOP");
          noTone(2);
          break;
        case 0x807F18E7:
          Serial.println("Stisknuto VOL+");
          fre += 10;
          break;
        case 0x807F906F:
          Serial.println("Stisknuto VOL-");
          fre -= 10;
          break;
        case 0x807F9867:
          Serial.println("Stisknuto OFF/ON");
          fre = 0;
          break;
        default:
          Serial.println("Stisknuta jina klavesa");
      }
    }


body:
this is my first post here, though I have been following this forum for a while (pun intended). I am trying to write a program for a machine that will drill holes in a metal rail, and cut the rail to the desired length. This is a home project, but I am starting to think that it is a bit much for the arduino. I hope I'm wrong.
Case 1 is used to enter the length of the rail. Case 2 is used to enter the number of big holes that need to be drilled in a rail, after that it goes to Case 3 where it should, for each hole, ask the user to enter the distance, that means that this part will be in a loop, with a condition that the counter is less or equal to the number of holes. When this is done it should go to Case 4. But the problem appears with Case 3. It seems that the loop (while loop) is creating some troubles. I've tried the program without the while loop ( so basically it only asks once to enter the distance) and it works. I think that maybe the part where I need to print the message "enter the value" and then print the keypad values creates some trouble with the while loop, maybe it slows it down.

I forgot to add, when I upload the program, and I start entering the values with a keypad, as soon as it goes to Case 3, the display prints a bunch of ones (the display fills up with 1s)

Could it be that this is too much for Arduino? Should i try to program it like a regular microcontroller, using arduino IDE but not using arduino commands? What do you think? Please ask if you need some clarification about the code. And thank you in advance.

    #include<Wire.h>
    #include<LiquidCrystal_I2C.h>
    #include<Encoder.h>
    #include<Keypad.h>

    //definisanje tastera za tastaturu
    LiquidCrystal_I2C lcd1(0x27, 16, 2);
    LiquidCrystal_I2C lcd2(0x23, 16, 2);
    const byte ROWS=4;
    const byte COLS=4;
    char hexaKeys [ROWS][COLS]={
      {'1', '2', '3', 'A'},
      {'4', '5', '6', 'B'},
      {'7', '8', '9', 'C'},
      {'*', '0', '#', 'D'}
    };
    byte rowPins[ROWS] = {4, 5, 6, 7};
    byte colPins[COLS] = {8, 9, 10, 11};
    Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
    Encoder myEnc(2,3);

    unsigned long currentTime;
    unsigned long previousTime2=0;
    unsigned long previousTime3=0;
    unsigned long previousTime4=0;
    unsigned long previousTime5=0;
    unsigned long oldTime=0;
    int loopTime=5;
    String niz1="";
    String niz2="";
    String niz3="";
    String niz4="";
    String niz5="";
    int duzina;
    int br_Vrupa, br_Mrupa;
    int state=1;
    int debounce=400;
    int i=1;
    int m=1;
    int j,k,n;
    int zad_vrV [30], zad_vrM [30];
    int start_taster, previous_state; //button that signals the start
    int encoder_reading;
    int prev_vr;
    int zbir;
    int error=5;
    bool testRange1=true;
    bool testRange2=true;
    bool testRange3=true;
    int machine_start=14; //relay that moves the rail
    int relay1=15;  //relay for big holes
    int relay2=16;  //relay for small holes
    int relay3=17;  //relay for cutting the rail
    int dt=2000;

    void setup(){
      lcd1.init();  //printing values from the encoder
      lcd2.init();  //printing values from the keypad
      lcd1.backlight();
      lcd2.backlight();
      pinMode(12,INPUT_PULLUP);
      pinMode(machine_start,OUTPUT);
      pinMode(relay1, OUTPUT);
      pinMode(relay2, OUTPUT);
      pinMode(relay3, OUTPUT);
    }

    void loop(){
      char keyin=customKeypad.getKey();
      lcd1.setCursor(0,0);
      lcd2.setCursor(0,0);
      currentTime=millis();
      switch (state) {
        case 1:
        lcd2.print("Uneti duzinu:");
        if(keyin){
          if(isDigit(keyin)){   //proverava da li je uneta vrednost neka cifra
          niz1 += (char)keyin;    //od unetih cifara kreira niz
          lcd2.clear();
          lcd2.setCursor(0,1);
          delay(10);
          lcd2.print(niz1);
          duzina=niz1.toInt();     //konvertuje dobijeni niz u broj (int)
          }
          else if (keyin=='#'){
          niz1.remove(0);
          duzina=niz1.toInt();
          lcd2.clear();
          delay(10);
          lcd2.print(duzina);
          }

          if(keyin=='A'){
            state=2;
            lcd2.clear();
            delay(10);
        }
      }
        break;

        case 2:

        lcd2.print("Uneti br V");  //enter the number of big holes
        if(keyin){
          if(isDigit(keyin)){
            niz2+=(char)keyin;
            lcd2.clear();
            delay(10);
            lcd2.setCursor(0,1);
            lcd2.print(niz2);
            br_Vrupa=niz2.toInt();
            }
          else if (keyin=='#'){
            niz2.remove(0);
            br_Vrupa=niz2.toInt();
            lcd2.clear();
            delay(10);
            lcd2.print(br_Vrupa);
        }

        if(keyin=='A'){
            state=3;
            lcd2.clear();
            delay(10);
          }
        }
        break;

        case 3: //this case is used to enter the length to the each big hole

        while(i<=br_Vrupa);{
          j=i-1;
          if(keyin){
            if(isDigit(keyin)){
             niz3+=(char)keyin;
             lcd2.print("enter length ");
             lcd2.print(i);
             delay(10);
             lcd2.print(niz3);
             zad_vrV[j]=niz3.toInt();
            }
            else if (keyin=='#'){
              niz3.remove(0);
              zad_vrV[j]=niz3.toInt();
              lcd2.clear();
              delay(10);
              lcd2.print(zad_vrV[j]);
            }
          }
           if(keyin=='A'){
             i++;
             }
          if(i==br_Vrupa){  //when counter i reaches the br_Vrupa value, switch to the next case
            state=4;
          }
        }

          break;

          case 4:
          lcd2.clear();
          delay(10);
          lcd2.print("Uneti br M"); //enter the number of small holes
          if(keyin){
            if(isDigit(keyin)){
            niz4+=(char)keyin;
            lcd2.clear();
            lcd2.setCursor(0,1);
            delay(10);
            lcd2.print(niz4);
            br_Mrupa=niz4.toInt();
            }
            else if (keyin=='#'){
            niz4.remove(0);
            br_Mrupa=niz4.toInt();
            lcd2.clear();
            delay(10);
            lcd2.print(br_Mrupa);
            }
           if(keyin=='A'){
            state=5;
            lcd2.clear();
            delay(10);
            }
           }
          break;

          case 5: //this case is used to enter the length to the each small hole
          lcd2.clear();
          delay(10);
          while(m <= br_Mrupa){
            lcd2.print("enter length ");
            lcd2.print(m);
            n=m-1;
            if(keyin){
              if(isDigit(keyin)){
              niz5+=(char)keyin;
              lcd2.clear();
              lcd2.setCursor(0,1);
              delay(10);
              lcd2.print(niz5);
              zad_vrM[n]=niz5.toInt();
            }
            else if (keyin=='#'){
              niz5.remove(0);
              zad_vrM[n]=niz5.toInt();
              lcd2.clear();
              delay(10);
              lcd2.print(zad_vrM[n]);
            }

           if(keyin=='A'){
             m++;
            lcd2.clear();
            ;
             }
            }
          break;
      }

    }
      start_taster=digitalRead(12);
      if(start_taster==LOW && previous_state==HIGH && currentTime-previousTime2 > debounce){
        previousTime2=currentTime;
        digitalWrite(machine_start,HIGH);
      }
      previous_state=start_taster;
      encoder_reading=(myEnc.read())*446/400;
      if(encoder_reading!=prev_vr){
        lcd1.clear();
        delay(10);
        prev_vr=encoder_reading;
      }
      lcd1.print(encoder_reading);

      zbir=br_Vrupa+br_Mrupa;
      for(k=0;k<zbir;k++){
        if(encoder_reading>=zad_vrV[k] && encoder_reading<zad_vrM[k]-tolerance && encoder_reading>zad_vrM[k]+tolerance && testRange1){
          digitalWrite(machine_start,LOW);
          digitalWrite(relay1,HIGH);
          previousTime3=currentTime;
          testRange1=false;
          if(currentTime-previousTime3 >= dt){
            previousTime3=currentTime;
            digitalWrite(relay1,LOW);
            digitalWrite(machine_start,HIGH);
          }
          if(encoder_reading<(zad_vrV[k]-error) || encoder_reading>=(zad_vrV[k]+error)){
            testRange1=true;
          }
        }
        else if(encoder_reading>=zad_vrM[k] && encoder_reading<zad_vrV[k]-tolerance && encoder_reading>zad_vrV[k]+tolerance && testRange2){
          digitalWrite(machine_start,LOW);
          digitalWrite(relay2,HIGH);
          previousTime4=currentTime;
          testRange2=false;
          if(currentTime-previousTime4 >= dt){
            previousTime4=currentTime;
            digitalWrite(relay2,LOW);
            digitalWrite(machine_start,HIGH);
          }
          if(encoder_reading<(zad_vrM[k]-error) || encoder_reading>=(zad_vrM[k]+error)){
            testRange2=true;
          }
        }
      }
      if(encoder_reading>=duzina && testRange3){
        digitalWrite(relay3,HIGH);
        previousTime5=currentTime;
        testRange3=false;
        if(currentTime-previousTime5>=dt){
          previousTime5=currentTime;
          digitalWrite(relay3,LOW);
        }
        if(encoder_reading<(duzina-error)){
          testRange3=true;
        }
      }
    }

title: Problem with printing keypad input to the LCD in a while loop

Answers: 0


body:
I have written this code working on SimpleHost example from ESP8266Ping library,

the code works,

    #include <ESP8266WiFi.h>
    #include <ESP8266Ping.h>
    #include <ESP8266WebServer.h>
    #include <ArduinoJson.h>

    #define HTTP_REST_PORT 80

    const char* ssid     = "usernaem";
    const char* password = "password";

    const char* remote_host = "10.10.10.12";

    ESP8266WebServer http_rest_server(HTTP_REST_PORT);

    void get_online_status() {
      StaticJsonBuffer<200> jsonBuffer;
      JsonObject& jsonObj = jsonBuffer.createObject();
      char JSONmessageBuffer[200];

      Serial.print("Pinging host ");
      Serial.println(remote_host);

      if(Ping.ping(remote_host)) {
        Serial.println("Success!!");
        jsonObj["roku_express"] = 1;
      } else {
        Serial.println("Error :-(");
        jsonObj["roku_express"] = 0;
      }
      jsonObj.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
      http_rest_server.send(200, "application/json", JSONmessageBuffer);
    }

    void config_rest_server_routing() {
        http_rest_server.on("/", HTTP_GET, []() {
            http_rest_server.send(200, "text/html",
                "Welcome to the ESP8266 REST Web Server");
        });
        http_rest_server.on("/ping", HTTP_GET, get_online_status);
    }

    void setup() {
      Serial.begin(115200);
      delay(10);

      // We start by connecting to a WiFi network

      Serial.println();
      Serial.println("Connecting to WiFi");

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(100);
        Serial.print(".");
      }

      Serial.println();
      Serial.print("WiFi connected with ip ");
      Serial.println(WiFi.localIP());
      config_rest_server_routing();
      http_rest_server.begin();
      get_online_status();
    }

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

if I try to access my wemos D1 Mini from web browser I get correct message :
if offline

    {
      "roku_express": 0
    }

if online

    {
      "roku_express": 1
    }

but if I try to get the REST URL from python code either using `requests` or `urllub3`

    import urllib3
    http = urllib3.PoolManager()
    url = "http://10.10.10.4/ping"
    response = http.request('GET', url)

I get below error

> MaxRetryError: HTTPConnectionPool(host='10.10.10.4', port=80): Max
> retries exceeded with url: /ping (Caused by
> NewConnectionError('<urllib3.connection.HTTPConnection object at
> 0x104293e10>: Failed to establish a new connection: [Errno -536870212]
> Unknown error: -536870212'))

title: Getting maxretry error when trying to ping using python requests or urllib3

Answers: 0


body:
I am new to arduino and lora technology and i have dragino lorashield for arduino Uno and dragino gateway. I have also MQ-3 gas sensor and I want to detect the alcohol value and to send it to the gateway using the lorashield after that the gateway should send the data to ThingSpeak platform.
Currently the code for my MQ-3 sensor is as below. I would like to ask you for some help as I dont know how to write the code for the dragino and to send it to the gateway. Thanks in advance!

`
void setup() {
 Serial.begin(9600);
}
void loop() {
 float sensor_volt;
 float RS_gas; // Get value of RS in a GAS
 float ratio; // Get ratio RS_GAS/RS_air
 int sensorValue = analogRead(A0);
 sensor_volt=(float)sensorValue/1024*5.0;
 RS_gas = (5.0-sensor_volt)/sensor_volt; // omit *RL
 /*-Replace the name "R0" with the value of R0 in the demo of First
Test -*/
 ratio = RS_gas/0.01; // ratio = RS/R0
 /*-------------------------------------------------------------------
----*/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 delay(1000);
}
`
The code is working fine when I am using only the arduino. How do I modify it to use lora and to send the data to the gateway?

title: Dragino Lora shield for Arduino sensor use

Answers: 0


body:
I got a C# WPF application wich communcates with my arduino uno over serial port. Everything works fine for 3 to 20 seconds then i can not send or receive anything from/to the arduino.

What im trying to archieve:
 Connected a arduino uno to an optical sensor of a mouse to read from its registers, now i want to process the data on my pc.

I tried using another arduino uno and also some other mouse optical sensor, wich did not change anything.
Opening and closing the serialport after each communication did not work for me.
I have seen a few questions here on stack exchange, i looked through everyone but they could not help me.
 `Serial.flush()` seems to be not working, or its some kind of overflow i cant figure out.

I would really appreciate it if someone could explain me what the root of this problem is.

For completeness, here is my C# code:

     public class SerialCommunication
        {
            public SerialPort serialPort = new SerialPort();

            public SerialCommunication()
            {
                string[] ports = SerialPort.GetPortNames();
                if (ports.Count() == 1)
                {
                    MessageBox.Show("No serialport is available");
                    return;
                }
                serialPort.PortName = ports[1];
                serialPort.BaudRate = 115200;
                serialPort.Parity = Parity.None;
                serialPort.DataBits = 8;
                serialPort.Handshake = Handshake.None;
                serialPort.StopBits = StopBits.One;
                serialPort.NewLine = "\r\n";
                serialPort.WriteTimeout = 2000;
                serialPort.ReadTimeout = -1;

                serialPort.Open();
            }
        }

    public partial class MainWindow : Window
        {
            public static readonly object _lock = new object();

            private SerialCommunication serialCommunication = new SerialCommunication();

            public MainWindow()
            {
                InitializeComponent();
                GetWindow(this).KeyDown += HandelKeyDown;

                serialCommunication.serialPort.DataReceived += (sender, args) =>
                {
                    string bufferstring = ((SerialPort)sender).ReadLine();
                    OnMessageReceived(bufferstring);
                    //serialCommunication.serialPort.DiscardOutBuffer();
                    //serialCommunication.serialPort.DiscardInBuffer();
                    //Thread.Sleep(3);
                    //byte[] buffer = new byte[15];
                    //((SerialPort)sender).Read(buffer, 0, buffer.Length);
                    //string bufferstring = Encoding.UTF8.GetString(buffer);
                };
                serialCommunication.serialPort.WriteLine("OK");
            }

            private void OnMessageReceived(string message)
            {
                if (message.Length != 15 || message.Contains('O') || message.Contains('K') || message.Contains('\n') || message.Contains('\r'))
                {
                    serialCommunication.serialPort.DiscardInBuffer();
                    serialCommunication.serialPort.DiscardOutBuffer();
                    serialCommunication.serialPort.WriteLine("OK");
                    return;
                }

                //Format: "y: 0xX,x: 0xX"
                string x = message.Substring(3, 4);
                string y = message.Substring(11, 4);

                int offsetX = (Convert.ToInt32(x, 16) - 128);
                int offsetY = (Convert.ToInt32(y, 16) - 128);

                // the next three lines only visualize the received data but do not change it
                MoveX(offsetX / 50);
                MoveY(offsetY / 50);
                ShowMessage(message);
                Thread.Sleep(2);
                serialCommunication.serialPort.WriteLine("OK");
            }
    }

Foto of how the application and data it receives look like:
[![On the right side is the data, at the top the current position][1]][1]

Here is my arduino code:

    #include <Arduino.h>

    // 5v
    #define POWER 13
    // Serial I/O
    #define SDIO 11
    // Serial clock
    #define SCK 12

    // Registers
    #define DELTAY 0x02
    #define DELTAX 0x03

    #define serialInputBufferSize 16
    char dataBuffer[serialInputBufferSize];
    unsigned short inputBufferLength = 0;

    bool sendPosition = true;

    char tmp[16];

    void InitMouse()
    {
      digitalWrite(SCK, HIGH);
      delayMicroseconds(5);
      digitalWrite(SCK, LOW);
      delayMicroseconds(1);
      digitalWrite(SCK, HIGH);

      // Wait for the serial transaction timer to time out:
      delay(1000);
    }

    byte readRegister(byte addr)
    {
      byte r = 0;

      // Set the dataline to output
      pinMode(SDIO, OUTPUT);
      for (int i = 7; i >= 0; i--)
      {
        digitalWrite(SCK, LOW);
        digitalWrite(SDIO, addr & (1 << i));
        digitalWrite(SCK, HIGH);
      }

      // Switch the dataline from output to input
      pinMode(SDIO, INPUT);
      // The datasheet mentions to wait at least 100 µsec
      // when switching from write to read operations.
      // This is needed for the chip to prepare the data
      delayMicroseconds(110);

      // Clock trough the register and read its data
      for (int i = 7; i >= 0; i--)
      {
        digitalWrite(SCK, LOW);
        digitalWrite(SCK, HIGH);
        r |= (digitalRead(SDIO) << i);
      }

      // Delay at the end guarantees >100 µsec before next transaction
      delayMicroseconds(110);

      return r;
    }

    byte y = 0;
    byte x = 0;

    void WaitForMovementThenSendPositionOffset()
    {
      x = 0;
      y = 0;

      while (((y == 0 && x == 0) || x == NULL || y == NULL) && sendPosition)
      {
        delay(1); // kann eigentlich weg
        y = readRegister(DELTAY);
        x = readRegister(DELTAX);
      }

      if (sprintf(tmp, "y: 0xX,x: 0xX", y, x) > 0)
      {
        tmp[16] = 0;
        if (!Serial.println(tmp))
        {
          // Serial.end();
          // Serial.begin(9600);
          // Serial.begin(115200);
          Serial.flush();
        }

        sendPosition = false;
      }
    }

    void serialEvent()
    {
      sendPosition = false;

      // Read serial data into the buffer
      while (Serial.available())
      {
        dataBuffer[inputBufferLength++] = Serial.read();
      }

      Serial.flush();

      if (strstr(dataBuffer, "OK"))
      {
        sendPosition = true;
        WaitForMovementThenSendPositionOffset();
      }
    }

    void setup()
    {
      pinMode(SCK, OUTPUT);
      pinMode(SDIO, INPUT);
      pinMode(POWER, OUTPUT);

      digitalWrite(POWER, HIGH);

      Serial.setTimeout(1000);
      // Serial.begin(9600);
      Serial.begin(115200);

      InitMouse();
    }

    void loop()
    {
    }

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

title: Arduino stops sending/receiving data over Serialport after random time

Answers: 2

body:
Every time you receives data, it tries to read a full line (SerialPort.ReadLine()).
If there's not a full line available, it will block the current thread until there is or until it times out.

These calls will stack up and eventually cause the application to fail.

body:
The problem was in the serialEvent() method. I did not rest the bufferindex where i red the received message so it allways stayed there until the arduino ran out of memory and also i did not gave the arduino enough time to receive the message so i added `delay(1)` there.

Here is my updated code:

    void serialEvent()
    {
      inputBufferLength = 0;
      sendPosition = false;
      delay(1);
      // Read serial data into the buffer
      while (Serial.available())
      {
        if (inputBufferLength < serialInputBufferSize)
        {
          dataBuffer[inputBufferLength++] = Serial.read();
        }
        else
        {
          Serial.read();
        }
      }

      Serial.flush();

      if (strstr(dataBuffer, "OK"))
      {
        sendPosition = true;
        WaitForMovementThenSendPositionOffset();
      }
    }


body:
I am working on a project with a 3-Wheel Car: 1 Custer Wheel, and 2 DC Motors. I need to steer the car playing with the speeds of these two dc motors. If I would supply a constant voltage and current to the DC motors, is there an equation or maybe a source to know the exact degree of turning by assigning PWM to a certain value? Let's say I want to turn the car 30 Degrees to the left from the straight direction. Can I do calculations to find all of the PWM values or it can only be got through experiments?
Thanks in Advance!

title: DC Motor Car Steering

Answers: 1

body: Basically you can't. PWM value required to turn to a specific degree will depend on motors, on voltage, on hardware, in the current velocity of the car and probably on the surface under the wheel. Also keep in mind that real cars don't turn like that (at a fixed angle). Instead, driver constantly adjusts the position of the steering wheel, while looking at the road (i.e.a feedback system). Same is for RC cars, operator smoothly deflects the joystick looking at the vehicle.


body:
I'm trying to use the [RF24][1] library for wireless communication.
However, it appeared that this library does not have "help" option.
There was a [keywords][2] file but it did not explain what it does.
I found couple of examples online, and in the library, but id did not explain things quite in detail.

Could you explain to me how those command works, and weather there's any help file for the library?

Especially, I have a question about the channel and address used in the library.

**A.** Does address take character or number as input?
The official example in the library used

    byte addresses[][6] = {"1Node","2Node"};
But I also say some example use

    byte addresses[][6] = {"00001","00002"};

The [byte][3] command was suppose to be a 8-bit unsigned number, from 0 to 255, but why they used string " " as input?

I found a sentence in RF24.h file: Addresses are assigned via a byte array, default is 5 byte address lengths. But why they wrote *byte addresses[][6]* instead of *byte addresses[][5]*?

**B.** From some other video I learned that RF24 have channel and address for communication, where channel can take value from 0 to 125; pin/port take value from 0,1-5; and the address.

    setChannel KEYWORD2

The pin was explained in RF24.h. However,

1. Can one open multiple channel at once?
2. If one use the same addresses in multiple channel at once, can the address being distinguished, or were they treated as the same address?
3. Is channel-pin/port(while writing)-address a tree structure?

**C.**
Can one open up more pin/port in transmitting and writing?

      openWritingPipe KEYWORD2
      openReadingPipe KEYWORD2

  [1]: https://github.com/nRF24/RF24
  [2]: https://github.com/nRF24/RF24/blob/master/keywords.txt
  [3]: https://www.arduino.cc/reference/tr/language/variables/data-types/byte/

title: RF24 library commands, channel, and address

Answers: 1

body:
> A. Does address take character or number as input?

The address is 5 bytes. In this library it is provided as an array. In C a string is merely an array of bytes. So it is possible to represent an array of bytes as a simple string. Internally the two representations:

    byte address[] = "123ab";

and

    byte address[] = { '1', '2', '3', 'a', 'b' };

and even:

    byte address[] = { 0x49, 0x50, 0x51, 0x97, 0x98 };

are all identical, except that the first one adds an extra `0x00` to the end of it to mark the end of the string (which the library completely ignores).

> B. From some other video I learned that RF24 have channel and address for communication, where channel can take value from 0 to 125; pin/port take value from 0,1-5; and the address.

It's helpful here that you have some understanding of basic radio communication terminology.

When you say that a device works at X frequency you are generally only referring to the "frequency band" that the device operates within (2.4GHz in this case). The device doesn't work *at* 2.4GHz - only "in the 2.4GHz band". That frequency band is then divided up into channels. Each channel is a specific frequency. Just like your television has channels you select one specific channel (and thus frequency) to tune into and communicate on.

Channel numbers are just used because it's far far easier to remember "channel 21" instead of 471.25MHz, for example.

For two devices to be able to communicate they both need to be tuned to the same frequency, and hence the same channel.

The "address" is more like the address your computer has on the network. Within the channel frequency you can have multiple devices communicating. The address identifies exactly which of the devices you want to send data to or are receiving data from.

> C. Can one open up more pin/port in transmitting and writing?

The nRF24L01 internally uses *pipes* as a method of separating data from different devices into distinct feeds that you can read from. It is merely for convenience. You can open up to 6 pipes at once, each one receiving from a different address. All pipes are in the same channel though since you can only tune to one channel at a time.

By the way - the `keywords.txt` file exists solely for the IDE to do highlighting of certain words. It's not meant for a human to read when working out how to use a library.


body: Well am asking this basically to know if it is possible to create a bootable flash drive that automatically uploads any source code onto the arduino just like creating a bootable flash drive when installing windows operating system on a computer. I will be happy to get some cool responses that would be helpful thanks.

title: Is there some hardware that can be used to upload sketch source code via USB flash disk (Automatically By plugging it in)

Answers: 2

body:
There is no specific piece of hardware that does what you ask.

There are various options though:

1. Write a new bootloader that uses the USB Host Shield to load data from a USB MSD device then flash it to the internal flash of the MCU (hard to do if you don't know low-level programming)
2. Use an embedded Linux computer (Raspberry Pi, etc) to run `avrdude` and flash your Arduino like it's a connected to a computer
3. Use an Arduino that has a Linux portion to it (such as the venerable Arduino Yun) or a shield that provides a similar function (Dragino Yun Shield) to flash the AVR chip from Linux
4. Don't use an Arduino at all, but use an embedded Linux computer for everything.

body:
There is a solution with SD card and SD bootloader. You put a bin file on SD card, insert it into the SD adapter and power up the Arduino. The bootloader loads the bin file to flash memory.

I use '[avr_boot][1]' SD bootloader by Zevero. It reads a file named firmware.bin from SD card if present and loads it into flash.

To generate a bin file for Arduino AVR boards add to platform.txt

    recipe.objcopy.bin.pattern="{compiler.path}{compiler.elf2hex.cmd}" -O binary {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.bin"

I use this with the ArduinoOTA library which uploads the bin file from IDE to the SD card over network and then resets the MCU for the bootloader to apply the bin.

btw: [the ArduinoOTA library][2] can use the upper half of the flash memory too to store the uploaded bin and then activate a modified Optiboot to copy the bin to run location and reset the MCU.

UPDATE 2022: new advanced example for my ArduinoOTA library: [load hex from SD card][3]

  [1]: https://github.com/zevero/avr_boot
  [2]: https://github.com/jandrassy/ArduinoOTA/blob/master/README.md#atmega-support
  [3]: https://github.com/JAndrassy/ArduinoOTA/tree/master/examples/Advanced/SD2Flash2BootAVRHex


body: Of course after developing a success full embedded product the next step would be making upgrades to compete favorably with new products in the market. Well making upgrades would require making adjustments in the sketch and Uploading it onto already made prototypes to cub the costs involved in by the hardware of a remotely located prototype. How can one upload a sketch from his location on to the prototype without going there psychically to upload through the port?

title: How can I upload a sketch remotely from a distant location onto an arduino that is power by a battery

Answers: 2

body:
First you have to establish communication between Arduino and your computer. This communication could be wire (ex. LAN) or wireless.

Like Juraj said, you could use [ArduinoOTA][1] with an additional WiFi or Ethernet module on your Arduino, as long as arduino is connected to the network and you know its address. I haven't tried it yet, so I don't know its reliability. Even so, it helps your problem

  [1]: https://github.com/jandrassy/ArduinoOTA

body:
Battery powered devices need a system where the device checks over Internet connection (WiFi, mobile) if a new firmware bin file is available on a specific location on a server. If the bin file is available the device can download it and apply.

One option how to apply the new bin is to use SD card and SD bootloader ([Zevero avr_boot][1]) The sketch saves the downloaded file on SD card and resets the MCU. The SD bootloader then loads the binary from the SD card to flash.

Other option if enough free flash memory is available is to use the InternalStorage object from [ArduinoOTA][2] library. It uses the upper half of the flash memory to store the uploaded bin and then activates a modified Optiboot to copy the bin to run location and reset the MCU.

  [1]: https://github.com/zevero/avr_boot
  [2]: https://github.com/jandrassy/ArduinoOTA


body:
Hi everyone I am hoping someone here can help me.
I am trying to make an arduino turn my project on and off.Using a relay.
I am looking for it to act like a computer power button.
A short press to turn on and them stay on and a long press (say 5 sec) to turn off and then stay off till button is pressed again.
I would like it so that the project can not be accidentally turned off
Can anyone please help.
Thanks

title: Press On Hold Off Power Switch

Answers: 2

body:
To clarify the problem, do you want to control ON OFF using Arduino? It is very simple. Please read this [simple][1] tutorial, and modify it according to your needs.

  [1]: https://www.electroschematics.com/arduino-control-relay/

body:
Here is a test sketch that I wrote for a different question. The other question's requirement was for a short press (minimum 100ms) to turn on an LED, and a long press (1 second) would turn it off. With a slight modification of this sketch, it may work for you. You will need to install the `Bounce2` library.
<!-- language-all: lang-cpp -->

    // Press and hold button for 100 ms to turn LED ON.
    // Press and hold button for 1000 ms to turn LED OFF.
    #include <Bounce2.h>

    byte buttonState = 0;
    const byte ledPin = 3;
    const byte buttonPin = 2;
    const unsigned long debouncerInterval = 50;
    unsigned long buttonPressedTime = 0;
    unsigned long currentMillis = 0;

    Bounce debouncer = Bounce();

    void setup(){
      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, LOW);
      debouncer.attach(buttonPin, INPUT_PULLUP);
      debouncer.interval(debouncerInterval);
    }

    void loop(){

      // Get the current time.
      currentMillis = millis();

      // Check if button was pressed or released.
      if(debouncer.update()){

        // Pressed.
        if(debouncer.read() == 0){
          if(buttonState == 0){
            buttonState = 1;
            buttonPressedTime = currentMillis;
          }
        }

        // Released.
        else{
          buttonState = 0;
        }
      }

      // Turn the LED ON or OFF.
      if(buttonState == 1){
        if(currentMillis - buttonPressedTime >= 1000){
          digitalWrite(ledPin, LOW);
          buttonState = 0;
        }
        else if(currentMillis - buttonPressedTime >= 100){
          digitalWrite(ledPin, HIGH);
        }
      }
    }


body:
Warning: I'm completely new to Arduino, and not even sure if it's the right solution here.

I'm trying to make a better digital picture frame. Got almost all the way there by just buying a nice flat-bezel 4k display, connecting a chromecast, and putting a picture frame on it. Voila!

But I want it to adjust its brightness in response to ambient light -- and turn itself off when the room is dark. So now I need something to check a light sensor and control screen brightness.

Is it possible (and does it make sense) to disassemble the monitor, wire up the LCD panel to a controller with arduino, add in a light sensor, and try to tackle it that way? Is there a better way?

Would greatly appreciate any recommendations / suggestions / ideas.

Thanks!

title: Dim 4k LCD panel in response to ambient light

Answers: 0


body:
I'm working on a audio-reactive lightinstallation with 16 LED lights.
In Max MSP I analyse my audio and split the frequencies in 16 'parts'.
I store these parts in a message of 16 ints, either 1 or 0 (on of off).
Every time a new frequency is detected the message updates and puts out a new int from 16 numbers (for exampe 1000100100110101).

I receive this number in my serial monitor of my Arduino Uno.
I want to put this 'incomingValues' in an array so I can check if a number/frequency is 0 or 1. When it's 1 I can turn on my relay/ light.
The 'incomingValues' is changing quite quickly but that shouldn't be a problem right?

I tried multiple things to create an array and update this every time a new serial message is coming in but I'm not used to work with Arduino so I could need some help.

Thanks! :)

Here is my code:

    int counter;
    int incomingValues = 0;
    int lights[16];

    void setup() {
      Serial.begin(9600);
      counter = 0;
      pinMode(13, OUTPUT);
    }

    void loop() {

      boolean newValue = false;

      while (Serial.available() > 0) {

        incomingValues = Serial.read();
        Serial.print(incomingValues);
        counter = counter + 1;

        newValue = true;
      }

      if (newValue) {
    //    delay(50);
    //    lights[counter] = incomingValues;
    //
    //
    //    Serial.print(lights[0]);
    //
    //    for (int i = 0 ; i < 16 ; i ++) {
    //      Serial.print(lights[i]);
    //    }
    //    Serial.println("");
    //    newValue = false;
      }

      if (counter > 15) {
        counter = 0;
        Serial.print("\n");
      }

      if (incomingValues == 1) {
        digitalWrite(13, HIGH);
      } else if (incomingValues == 0) {
        digitalWrite(13, LOW);
      }
    }

title: How to create an array from serial.read?

Answers: 2

body:
If you are able to send the message as 16 chars, followed by a newline, then here is a test sketch that might work for you. Use the Serial Monitor to send the `1000100100110101` data. Please ensure you have the Serial Monitor set to send a `Newline Only`.
<!-- language-all: lang-cpp -->

    // Valid input data from serial is 16 chars followed by a newline.
    // 1000100100110101
    const byte bufferSize = 17;
    char inputBuffer[bufferSize + 1];

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

    void loop(){

      if(Serial.available() > 0){
        byte bytesRead = Serial.readBytesUntil('\n', inputBuffer, bufferSize);
        if(bytesRead == 16){
          for(byte i = 0; i < 16; i++){
            if(inputBuffer[i] == '1'){
              Serial.print("on ");
            }
            else{
              Serial.print("off ");
            }
          }
          Serial.println();
        }
        else{
          Serial.println("Invalid data length.");
        }
      }
    }

body:
Thanks @VE7JRO, it does the job :)

    const byte bufferSize = 16;
    char inputBuffer[bufferSize + 1];
    int myDelay = 20;

    void setup(){
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);

    }

    void loop(){

      if(Serial.available() > 0){
        byte bytesRead = Serial.readBytesUntil('\n', inputBuffer, bufferSize);
        if(bytesRead == 16){
          for(byte i = 0; i < 16; i++){
            if(inputBuffer[0] == 1){
              digitalWrite(13, HIGH);
              delay(myDelay);
            }
            else{
              digitalWrite(13, LOW);
            }
            if(inputBuffer[1] == 1){
              digitalWrite(12, HIGH);
              delay(myDelay);
            }
            else{
              digitalWrite(12, LOW);
            }
          }
          Serial.println();
        }
        else{
          Serial.println("Invalid data length.");
        }
      }
    }


body:
Programming Questions / L298N Driver - Code Issuing - " expected primary-expression before '=' token"
Today at 07:20 pm
Hello Arduino Community,

*Code is shown at bottom - please read below*

I've been working on a little project that uses the L298N Dual Motor Driver to run a single motor.

Using this link I set up my project (disregard Using the L298N with PIC Section) :

https://www.teachmemicro.com/use-l298n-motor-driver/.

1.  I connected my wires and checked them and their connections for any problems.

2. I am using 1 motor instead of two

3. I am using two 'C' Duracell Alkaline Batteries, connected them together in a series circuit. I've tested the batteries and they run my Small Round Electric Motor with 12000 RPM + 3 to 6V DC perfectly when I don't connect the battery and motor to the L298N Driver.

4. The two, 'C' batteries are 1.5 volts each (connecting them together in series give me 3 volts)

5. I am connecting my arduino uno to a newly purchase laptop - I've compiled codes from this computer that have worked fine.

I copied and pasted the code from the website at the link at the top. I checked device manager and chose the correct port with the correct board, so I am starting to believe there is something wrong with the code on the website.

Once I compile the program, errors pop up stating, "expected primary-expression before '=' token" for every line of code that has a #defined variable (mentioned on the top lines of the program).

It would be helpful to please comment your thoughts and solutions for this issue.

Please see link at the top for code.

Thank you.

title: L298N Motor Driver - Code issuing "expected primary-expression before '=' token"

Answers: 1

body:
Definitions via `#define` don't use equal signs. The following is wrong

    #define EN = 1

Instead it should be

    #define EN 1


body:
I'm just lighting up an LED through a TIP31C, pin 0 goes through a 560kohm resistor to the tip's input pin
pin 1 goes through a 750 ohm resistor to the tip's input pin
^i'm not sure this information is really relevant

The reason I am doing this is so i can sleep the attiny85 while having pin 0 set to HIGH to have the led at a very low brightness, kind of like a standby function

```
void setup() {

}

void loop() {
  digitalWrite(0, HIGH);//works ONLY the first time
  delay(500);
  digitalWrite(0, LOW);
  delay(500);

  analogWrite(1, 15);//always works
  delay(500);
  analogWrite(1, 0);
  delay(500);
  /*it's like as soon as i've used an analogWrite, i can no
    longer output with digitalWrite
  */

  //pinMode(0, OUTPUT);//didn't help
  digitalWrite(0, HIGH);//never works
  delay(500);
  digitalWrite(0, LOW);
  delay(500);
}
```

title: Attiny85 simple analog and digital output problem

Answers: 1

body:
There are a number of issues here:

1. You state you have a 560kohm resistor, this is too high a value. With 5V it will restrict the current to 8.9uA.
  - This is too low to drive the LED, which probably requires up to 20mA (5V / 0.02A = 250Ohm at least)
  - This is also too low for for the base of the transistor (I'm not completely sure if my understanding of transistor gain is correct, but I think if you feed 1mA into the base of the TIP31C, it's gain of 25 will allow upto 25mA between the collector and emitter.) Based on this, 5V / 0.001A = 5kOhm.

2. You do need `pinMode(0, OUTPUT);` and `pinMode(A1, OUTPUT);` in setup. It will work, except you won't notice the effect with your 560kOhm resistor.

3. You also need to check the pins of the atTiny85. [![AtTiny85 pinout][1]][1]

  [1]: https://i.stack.imgur.com/GeP8s.png
As you can see, the only analog outputs are on physical pins 2, 3 and 7. You need to refer to these (for connection to pin 7) as:

    pinMode(A1, OUTPUT);
    analogWrite(A1, 15);

Below is a rough idea of what the schematic should look like

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

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

<!-- End schematic -->

And below is an (untested) example of the code:

    void setup() {
      pinMode(A1, OUTPUT);
    }

    void loop() {
      analogWrite(A1, 15);
      delay(500);
      analogWrite(A1, 0);
      delay(500);
    }


body:
My situation:

- I am able to communicate over i2c with my MPU6050 IMU
- I can get accelerometer and gyro data
- I can compute the sensor's orientation using my accelerometer

Issue:

- when trying to compute the sensor's orientation using my gyroscope my values seem to be totally incorrect. I am computing the orientation using a [complementary filter](https://www.pieter-jan.com/node/11).

This is the code I use https://paste.ubuntu.com/p/vZmbnc23gj/

This is the computed orientation, when the sensor is lying on a table: https:https://paste.ubuntu.com/p/W7DzVKR9c7/
Those measurements are totally incorrect, because when moving the senor randomly around its axis it never goes above 1.8. (even when I do an 180 degree turn)

Could somebody give me some hints or explanation on why my results are incorrect and drifting so much?

title: MPU6050 - Why is my gyro integration incorrect?

Answers: 1

body:
You need to perform offset calibration, otherwise you'll get large drift errors. The MPU6050 has a dedicated Digital Motion Processor (DMP) where data from the gyro and accelerometer are fused for you. I recommend grabbing the results of that fusion from the DMP. As far as I know the only libraries that do this are ones based on Jeff Rowberg's work. For a detailed guide please see:

https://youtu.be/k5i-vE5rZR0


body:
I have just got a new Arduino robot for Christmas and I have plugged my robot into my computer and I have read the instructions from the manual that the robot was provided with and told me to go to the device manager in the control panel and look under unknown devices, unfortunately I was unable to find it. However I looked under ports and I found that there were 3 ports, I eventually found out that if I took the Arduino plug in and out of my PC that port COM5 was the Arduino, the problem I am having now is to know how to get this port to recognise my Arduino

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

one error that always comes up when trying to upload the code onto COM5 is this:

    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xa1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xa1

This is what the arduino looks like
[![enter image description here][2]][2]

Link for where I brought the arduino kit from:
https://www.amazon.co.uk/ELEGOO-Tracking-Ultrasonic-Intelligent-Educational/dp/B01M6YHRJ4/ref=sr_1_1_sspa?keywords=elegoo+robot&qid=1577982862&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyVjVXTk9VMDlUTTg1JmVuY3J5cHRlZElkPUEwMjc4NjYwOEVGNEoxM1Y0QzIwJmVuY3J5cHRlZEFkSWQ9QTA4OTA1NzAzTTNBVFJMV09aVjJRJndpZGdldE5hbWU9c3BfYXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==

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

  [1]: https://i.stack.imgur.com/p8VWI.jpg
  [2]: https://i.stack.imgur.com/c31RA.jpg
  [3]: https://i.stack.imgur.com/gk2Ja.png

This is what shows up on the arduino IDE when I select COM5 (which should be my arduino)

title: Unable to find arduino on device manager

Answers: 1

body:
It seems your computer recognize the serial port of the Arduino device, but doesn't know how to 'talk to it'.

In most USB to TTL devices (that are included in Arduino and ESP8266 boards) you need to install their driver (like CH341 driver) BEFORE you plug in your device.

Please try to find/identify the 'USB to Serial' chip you have on the board, and install its drivers.

Good Luck!


body: please anyone help me build my project, i want to connect multiple smart phones to arduino mega using blutooth module hc-05 , I am working on real life home automation project and i don't have idea that can i use 4 Bluetooth modules with arduino mega . Requirement is max 4 smart phone connect to system , please anyone knowing about arduino please help ,i will be grateful . if u have any other suggestions tell me .

title: using multiple hc-05 with one arduino mega

Answers: 1

body: HC-05 modules use Serial (UART) for communication with the Arduino. Thus you need 4 Serial interfaces for 4 HC-05 modules. The Arduino Mega has 4 hardware Serial interfaces, so just connect once HC-05 to each Serial interface. Then handle each module in your code the same just with a different Serial interface. If you already know, how to use one HC-05, then it should be rather easy to implement the same with all 4 modules.


body:
Getting an audio signal from a 3.5mm jack amplified (non-inverted) and fed into analog in pin on a Mega 2560. I am having problems using a potentiometer as a variable resistor to adjust gain. I'm also getting a lot of noise (+/-10 units on the 0-1023 scale)

Circuit:
- The audio is from a mono 3.5mm jack, playing from my laptop (with audio split to my speakers).
- Audio goes through an op amp TL071, single sourced shared with arduino 5V
- The potentiometer is wired with 2 pins as a variable resistor. The pins are connected to ground and the inverting input (VCC-)
- Output signal from the op-amp is biased by 2.5V and seems to work fine.

[![modified circuit][1]][1]

I'm closely following the instructions here (https://www.instructables.com/id/Arduino-Audio-Input/) but with a TL071 op amp as a single sourced from the Arduino 5V power supply.

The potentiometer doesn't seem to make much difference; I can even unplug it and I still get some readings on A0. I'm misunderstanding how to 'rewire' the op-amp for a single supply, but I can't figure out what else I can do.

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

title: op amp circuit single sourced from arduino power

Answers: 2

body:
The TLO series don't work with 5v supply. They have also a reversal phase : that meens, when used in follower, it's output will go high when intut is lower than 3v...
One can use an old LM324 or LM358, but output is not going up to VCC...
OPA140 is a correct choice.
Also, may be a link capacitor of 100µF between input and potentiometer is necessary : this avoids amplification of DC, gives a centered output, and will reduce noise due to DC paht in potentiometer.

body:
In case anyone is looking for a solution, I followed the TL071 manual (texas instruments) for an op-amp instead of using the diagram posted above. That signal then links into a bias.

The noise was coming from having 5V shared with the LED lights (WS2812B). Once I put them on a different circuit (shared ground) it was ok.


body:
I have been using the Ticker to blink a led successfully.
However, now I am fetching temperature from a DS18B20 in the main loop (which is using the OneWire library) and the blink is now erratic.

Is the Ticker suspended by the DallasTemperature/OneWire library?

It this suspending interrupts or something?

Maybe using the same interrupt?

title: Arduino ESP8266 Ticker interrupted by DallasTemperature/OneWire?

Answers: 2

body:
Ticker does not interrupt your code. It is a OS-timer and will call your function once the time is elapsed.

The Tiker callback can be interrupted by a "real" interrupt or another Task with higher priority and does not provide any reliability - it will just be called.

A solution (not the best) would be to disable manually all interrupts, if you can't solve it in another way.

If you just want a blinking led, you should use a Timer interrupt as your callback is short and fast. Maybe with the `ICACHE_RAM_ATTR` attribute.

body: I ran into a problem using libraries with sensor DS18B20 in ticker. If I request the temperature through millis(), then everything is fine. When I request the temperature in the ticker, I get "Panic core_esp8266_main.cpp:137 __yield". Unfortunately I can't explain it.


body:
I have a little project at the university where I have to use the timers to generate a pwm signal and get it into a piezo buzzer when something else turns over a certain value by using the registers, the thing is that we have worked on some other microcontrollers so I don't really know the libraries for arduino uno with atmega328p and I would require some help on that. Also I have to use the registers instead of the function analogRead() that is reading from a temperature sensor.

Having the following code that works for my setup:

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //Digital pins to which you connect the LCD
    const int inPin = 0;
    const int buzzer=9;// A0 is the sensor
    void setup()
    {
      pinMode(buzzer,OUTPUT); // DDRA=0b00000001;
      lcd.begin(16,2);
    }
    void loop()
    {
      int value = analogRead(inPin); // read the value from the sensor <= to be written on registers
      lcd.setCursor(0,1);
      float millivolts = (value / 1024.0) * 5;
      float celsius = (millivolts-0.5)*100;
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print(celsius);
      lcd.print("C");
      lcd.setCursor(0,1);
      lcd.print((celsius * 9)/5 + 32); //turning the celsius into fahrehait
      lcd.print("F");
      delay(1000);
      if(celsius>30.0){tone(buzzer,1000);delay(1000);noTone(buzzer);delay(1000);} //<= on registers
    }

title: Piezo buzzer with PWM on arduino uno with atmega328p in C on registers + analogRead on registers

Answers: 1

body:
In fact all the mentioned function calls are using the Special Function Registers (SFR) and thus the hardware peripherals of the Arduino in the background to work. But I guess this is an exercise to learn how to configure and use these peripherals yourself. Doing this for the whole code is a rather big task for a single question on this site. So I will give you hints and will point you to the corresponding registers. Then the [datasheet of the Atmega328P][1] (the microcontroller on the Arduino Uno) is a must read for you. It contains detailed descriptions for almost every function and SFR of the microcontroller.

1. **PWM:** I think you want to use PWM for creating a tone from your buzzer. This is not the classical PWM use case (as you don't need to change the duty cycle but the frequency to get different tones). Nonetheless you reach it with the same hardware. For hardware PWM you need to configure a Timer. The Uno has 3 Timers, where Timer0 is already configured by the Arduino IDE for functions like `delay()`, `millis()` and such. So I suggest you use Timer1. It has 3 control registers called `TCCR1A` to `TCCR1C`. You want the timer to be in CTC Mode (Clear Timer on Compare Match)(Waveform Generation Mode Bits set to 4, CTC mode for OCR1A). The timer will count up with the set frequency (will describe this later) until it gets to the value, that you wrote into the `OCR1A` register (Compare Match). Then it will reset. If you have set the `COM1Ax` bits in the `TCCR1A` register to the correct values, you can set it up to toggle the OC1A pin on a Compare Match).

    So in this mode, the timer will reset at a counter value that you set and will toggle the OC1A output pin for you. Thus it generates a square wave with variable frequency, that you can control by writing different values to the `OCR1A` register.

    But we also need to configure the frequency with which the timer will count up. This is done by the clock selection bits `CS10` to `CS12` in the `TCCR1B` register. A value of 0 for all bits means the timer is stopped. Look at the corresponding table in the Timer1 register descriptions in the datasheet. You want to connect the timer to the internal system clock. With these bits you can set the prescaler. This determines how many clock pulses it needs to let the timer count 1 up. With no prescaler the timer will count at every clock pulse. With the bit values 0 1 1 you will get a prescaler of 64, so the timer will count up 1 every 64 clock pulses. This sets the frequency range, that you have with the counter. The internal system clock runs at 16MHz on the Uno (you can do the math with the prescaler to calculate for the wanted frequency).

2. **analogRead aka ADC:** For reading an analog voltage the ADC (Analog Digital Converter) is used. It has the SFRs `ADMUX`, `ADCSRA`, the convertion result registers `ADCL` and `ADCH`, and `ADCSRB`. First we want to set the reference voltage for our conversion. When we set the `REFS1` and `REFS0` bits in the `ADMUX` register to 01 we use Vcc as voltage reference, which is sufficient most of the time. The bits `MUX3` to `MUX0` in the same register select one of the ADC pins for AD Conversion (We have only 1 ADC in the Atmega328P, but we can connect it to multiple ADC pins one after another). Now on the `ADCSRA` register: The `ADEN` bit will enable the ADC, with `ADSC` we can start a conversion. With the bits `ADPS2` to `ADPS0` we can select a clock prescaler for the ADC. This determines how fast the ADC runs. For maximum resolution you should keep the frequency between 50 and 200kHz.

    You can start a conversion by writing 1 to the `ADSC`. Then you can poll the `ADIF` bit in the same register. It will be set to 1, when the ADC has completed the conversion. Then you can read the conversion result from the `ADCL` and `ADCH` registers (for the Low byte and the High byte of the 10bit result). You should reset the `ADIF` bit after that by writing a 1 to it.

3. **LCD:** I don't know, if you also need to replace the LiquidCrystal library by your own code, since it does not use special peripherals (just digital pins). Digital pins are controlled via the `DDRx`, `PORTx` and `PINx` registers. Google "arduino port manipulation" for more information. And then you can resemble the functions from the library with it.

  [1]: http://TB6600


body:
I have a 5V arduino pro micro. I want to power it with a 3.7V lipo.

- Should I use a step up module to convert it to 5V?

I also want to measure the voltage of the battery.

- How can I do this?

Because I read that the power source also the reference voltage is so I cant measure it with an analog pin right?

I also use a lipo charging module to charge the battery.

Thanks for helping!

title: Read battery voltage from battery which is powering arduino

Answers: 2

body: You can read the Arduino's supply voltage see here [How to measure the supply voltage of Arduino without using an analog pin](https://arduino.stackexchange.com/a/50771/521) Alternatively use the internal 1.1V reference and a suitable voltage divider to read the lipo's voltage

body:
Yes, you should use a boost converter to convert the 3.7V from your battery to the 5V that the Arduino requires.

As I understand it, measuring voltage to determine charge level does not work well with lithium chemistry batteries since they hold a nearly constant voltage until they are almost completely depleted. Generally lithium batteries include a chip that measures current in and out and lets you query their charge level.