body:
I have a USB mouse which I am using to measure distance travelled by my bot for a project. I followed [this blog][1] to get the optical sensor from the mouse from the arduino and interface it with the arduino. In that blog, the USB wire has been removed and the 4 pins (VCC,GND and 2 data) are connected to the arduino

However,I found the code to not be very robust as the mouse doesn't always establish Serial communication with the arduino.

I have a USB host shield for the arduino. Is there any library which will let me get the x and y coordinates of the mouse using the USB protocol?

And if not, then is there a more stable library which will be more robust than the one used in thr blog linked above?

  [1]: https://www.instructables.com/id/Optical-Mouse-Odometer-for-Arduino-Robot/

title: Interfacing optical mouse with arduino

Answers: 0


body:
Yesterday I asked a question about de-bouncing this rotary encoder and Jsotola suggested that I should use a method like [This][1] to detect the previous state and then do the counting. using that method each turn is counting twice in one turn so I came up with my version of de-bouncing the rotary encoder:

    int s1, s2;
    int count = 0;
    boolean right = 0;
    boolean left = 0;
    int rotary = 0;
    unsigned long timer = 0;
    unsigned int bounce = 50;

    void setup() {
      Serial.begin(9600);
      pinMode(6, INPUT);
      pinMode(7, INPUT);

    }

    void loop() {

      s1 = digitalRead(6);
      s2 = digitalRead(7);
      if (s1 == 1 && s2 == 1) {
        right = 0;
        left = 0;
        rotary = 0;
      }
      if (s1 == 0 && s2 == 1) {
        left = 1;
      }
      if (left == 1 && (s1 == 0 && s2 == 0)) {
        rotary = 2;
      }
      if (s1 == 1 && s2 == 0) {
        right = 1;
      }
      if (right == 1 && (s1 == 0 && s2 == 0)) {
        rotary = 1;
      }

      if (rotary == 1) {
        if ((millis() - timer) > bounce) {
          count++;
        }
        right = 0;
        left = 0;
        timer = millis();
      }
      if (rotary == 2) {
        if ((millis() - timer) > bounce) {
          count--;
        }
        right = 0;
        left = 0;
        timer = millis();
      }
      Serial.print(s1);
      Serial.print(s2);
      Serial.print(", ");
      Serial.print(count);
      Serial.println(" ");
      delay(15);
    }

The code is working just fine. When turning the rotary this are the steps that I get:

`10-00-01 < (11) > 10-00-01`

problem is if I turn the knob quickly rotary encoder will skip one or two steps like: `01-01-01 < (11)` or `10-00-00 < (11)`.

This problem exist in all methods/libraries (I tested them all), is there anyway to fix this with software/hardware or this rotary encoder is just junk and I should get a better one?

_________________________________

Another method of de-bouncing as Jsotola requested:

     int pinA = 3;  // Connected to CLK on KY-040
     int pinB = 4;  // Connected to DT on KY-040
     int encoderPosCount = 0;
     int pinALast;
     int aVal;
     boolean bCW;

     void setup() {
       pinMode (pinA,INPUT);
       pinMode (pinB,INPUT);
       /* Read Pin A
       Whatever state it's in will reflect the last position
       */
       pinALast = digitalRead(pinA);
       Serial.begin (9600);
     }

     void loop() {
       aVal = digitalRead(pinA);
       if (aVal != pinALast){ // Means the knob is rotating
         // if the knob is rotating, we need to determine direction
         // We do that by reading pin B.
         if (digitalRead(pinB) != aVal) {  // Means pin A Changed first - We're Rotating Clockwise
           encoderPosCount ++;
           bCW = true;
         } else {// Otherwise B changed first and we're moving CCW
           bCW = false;
           encoderPosCount--;
         }
         Serial.print ("Rotated: ");
         if (bCW){
           Serial.println ("clockwise");
         }else{
           Serial.println("counterclockwise");
         }
         Serial.print("Encoder Position: ");
         Serial.println(encoderPosCount);

       }
       pinALast = aVal;
     }

  [1]: http://henrysbench.capnfatz.com/henrys-bench/arduino-sensors-and-input/keyes-ky-040-arduino-rotary-encoder-user-manual/

title: KY-040 rotary encoder skipping steps

Answers: 1

body:
I applaud you for your tenacity with the "debouncing" idea, but there is an excellent library for this rotary encoder, and the author has also written an article about it: [Ben Buxton - rotary encoders done properly][1]. Here is a link to his library: [GitHub - buxtronix][2].

I’ve used an older version of the library before with interrupts, and it worked perfectly for my application. I see the author has updated the library and has 2 example sketches; one uses interrupts, and the other uses polling. I tried both of them today on an Uno and I was very impressed with the polling sketch’s performance. It seemed to equal that of the interrupt method.

If you take the important bits out of the library files, then add them to a sketch, you can see how little code it takes for this "method" of processing the encoder’s output. Here is a test sketch with the library bits in it.
<!-- language-all: lang-cpp -->

    #define R_START 0x0
    #define R_CW_FINAL 0x1
    #define R_CW_BEGIN 0x2
    #define R_CW_NEXT 0x3
    #define R_CCW_BEGIN 0x4
    #define R_CCW_FINAL 0x5
    #define R_CCW_NEXT 0x6
    #define DIR_NONE 0x0
    #define DIR_CW 0x10
    #define DIR_CCW 0x20

    const byte pin1 = 5;  // DT
    const byte pin2 = 6;  // CLK
    int state = R_START;
    int counter = 0;

    const unsigned char ttable[7][4] = {
      // R_START
      {R_START,    R_CW_BEGIN,  R_CCW_BEGIN, R_START},
      // R_CW_FINAL
      {R_CW_NEXT,  R_START,     R_CW_FINAL,  R_START | DIR_CW},
      // R_CW_BEGIN
      {R_CW_NEXT,  R_CW_BEGIN,  R_START,     R_START},
      // R_CW_NEXT
      {R_CW_NEXT,  R_CW_BEGIN,  R_CW_FINAL,  R_START},
      // R_CCW_BEGIN
      {R_CCW_NEXT, R_START,     R_CCW_BEGIN, R_START},
      // R_CCW_FINAL
      {R_CCW_NEXT, R_CCW_FINAL, R_START,     R_START | DIR_CCW},
      // R_CCW_NEXT
      {R_CCW_NEXT, R_CCW_FINAL, R_CCW_BEGIN, R_START},
    };

    unsigned char process(){

      // Grab state of input pins.
      unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

      // Determine new state from the pins and state table.
      state = ttable[state & 0xf][pinstate];

      // Return emit bits, ie the generated event.
      return state & 0x30;
    }

    void setup(){
      pinMode(pin1, INPUT_PULLUP);
      pinMode(pin2, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop(){
      unsigned char result = process();
      if(result == DIR_CW){
        counter++;
        Serial.println(counter);
      }
      else if(result == DIR_CCW){
        counter--;
        Serial.println(counter);
      }
    }

Heres a simplified sketch (It works the same but I didn't like the hex numbers and I don't use define):

    const byte pin1 = 5;  // Connected to DT on KY-040
    const byte pin2 = 6;  // Connected to CLK on KY-040
    int state = 0;
    int counter = 0;

    const unsigned char ttable[7][4] = {
      {0, 2, 4, 0},
      {3, 0, 1, 0 | 16},
      {3, 2, 0, 0},
      {3, 2, 1, 0},
      {6, 0, 4, 0},
      {6, 5, 0, 0 | 32},
      {6, 5, 4, 0},
    };

    void setup(){
      pinMode(pin1, INPUT_PULLUP);
      pinMode(pin2, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop(){

      unsigned char result = process();

      // Clockwise rotation.
      if(result == 16){
        counter++;
        Serial.println(counter);
      }

      // Counter clockwise rotation.
      else if(result == 32){
        counter--;
        Serial.println(counter);
      }

    }

    unsigned char process(){

      // Grab state of input pins.
      unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

      // Determine new state from the pins and state table.
      state = ttable[state & 0xf][pinstate];

      // Return emit bits, ie the generated event.
      return state & 48;
    }

  [1]: http://www.buxtronix.net/2011/10/rotary-encoders-done-properly.html
  [2]: https://github.com/buxtronix/arduino/tree/master/libraries/Rotary


body:
To preface, I am very new to Arduino and I watched [this video][1] on YouTube.

It shows how you can build a motion controlled car with Arduino and I decided to make this for my school project.

One thing I am having difficulty with is connecting the MPU6050 to the Lilypad. In the video he doesn't really show much of it and just sticks it onto the board.

However, do I need to solder the MPU6050? Where do I solder the pins the underside or the top. Do I need to align the pins with that of the Lilypad?

Sorry if it's a stupid question I genuinely don't know.

The current condition of our lilypad:
[![Our lilypad][2]][2]

What it's supposed to look like:
[![What it looks like in the video][3]][3]

If you see the images, in addition to the yellow light of the MPU 6050 and the red light of the HC 05, the red light of the Lilypad is also supposed to light up like the second picture, however in ours, only the MPU 6050 and the HC 05 lights up and not the Lilypad.

  [1]: https://m.youtube.com/watch?v=lVqAu-p6wq0&list=PLBxj6rgFwv2ts4rFV6_Rb2Kitxa-ZP4Ox&index=3&t=10s
  [2]: https://i.stack.imgur.com/lYOE6.png
  [3]: https://i.stack.imgur.com/65p4w.png

title: Connecting MPU6050 to Arduino Lilypad

Answers: 1

body:
Since you seem to need some orientation, I will explain a few things, to get you started.

The MPU6050 is a device, that communicates through the I2C interface. It uses 2 communication lines (SCL for the clock and SDA for the data). To use is with the Lilypad, you have to connect those two lines, Vcc (5V) and Ground. If you look at a pinout diagram, you can identify, which of the pads are SDA and SCL on the Lilypad.

It is up to you, if you connect the mentioned lines via soldering or by other means. Normally you would solder connecting wires between the MPU6050 and the Lilypad. If you want the MPU to be removable, you can solder a cable with a pin header (for example female) to the Lilypad and the according pins to the MPU (for example a male pin header). That way, you could also stick the MPU to the board and remove it again if necessary. How you are doing it is not important, as long as the electrical contact is good.

---

There are also a lot of tutorials and ready to use libraries for the MPU6050 on the net. newbie already posted a link to a tutorial. Also Adafruit has a library on [github][1] with examples, that explain how to use it. That way you should be able to get started with your project.

Good luck!

  [1]: https://github.com/adafruit/Adafruit_MPU6050


body:
I'm very new to this. I found [this tutorial][1].

But it don't explain how to read voltages higher than Arduino 5V. I have connected a 100K ohm resistor to positive and 10K ohm to negative of my 24V power supply.

I need some guidance for writing the code for this specific ADC, please.

  [1]: http://henrysbench.capnfatz.com/henrys-bench/arduino-voltage-measurements/arduino-ads1115-module-getting-started-tutorial/

title: How to read voltage using ADS1115

Answers: 1

body:
As KIIV mentioned you need to do the math:

Use [this][1] online voltage divider calculator to calculate your maximum input.

 - Keep in mind you shouldn't exceed Arduino 5V.
 - Use a multimeter to measure the resistors actual resistance.
 - Do the math for your example assuming R1 is exactly 100K and R2 10K you have to multiple the voltage by 11.
 - remember any error is going to multiple by 11 too, so make sure the first reading is accurate/stable.

ADS1115 is actually 15bit which will give you resolution of 32768, with default PGA setting you get:
`6.144 / 32768 = 0.0001875V` per bit.

    Voltage = (your ADC reading) * 0.0001875V;
    Voltage = Voltage * 11;

Take a look at [This][2] question/answer to see how I did reduced Arduino ADC noise, some steps can be done for ADS1115 as well.

  [1]: http://www.ohmslawcalculator.com/voltage-divider-calculator
  [2]: https://arduino.stackexchange.com/questions/69261/arduino-10bit-adc-is-not-accurate/69266


body: I have created a algorithm and using arduino harware, and I don't want that users of my hardware could read or copy the Program so is there any security code or something that I could use. But I must access it whenever I needed to. It should be like admin and users.

title: Privacy of a program

Answers: 1

body:
The code that's sent to Arduino is "compiled" which means it's changed from human readable form to a binary data that can be understood by the processor. The "code" you wrote remains on your computer only.

This itself is a way of encryption since it's impossible to retrieve the original source code from that binary data. That data can only be "decompiled". This is a process that takes the binary data and converts it automatically into a human readable code, but it's not the same code that you originally made. It doesn't have comments, and logical variable names. This makes it also hard to understand.

Decompilation is usually to difficult and time consuming to even bother doing that unless your hardware is a lock on a vault with million dollars inside. If that's the case don't use Arduino, but instead use a custom designed chip with cryptographic key built inside the hardware.


body:
I have old Sony amplifier (F117R) and CD player (CDP-590), both equipped with IR remote controls. The problem is that I bought them as vintage without remotes.

I have a rough idea how to build dedicated RC for both units but I'm missing the essential part - how is the signal encoded for the units?

I can find tutorials where the can be taught the codes from working remote control and how to build universal RC from that.

Is there any chance where to find IR codes for Hi-Fi units remote controls?

title: Using arduino as a remote control

Answers: 0


body: I am trying to do a project where I need to get data from multiple sensors simultaneously. I am planning to use a Arduino to get the readings from the sensors. I am thinking to control the Arduino using ESP8266 as I would finally like to have internet capabilities for my project. I have worked with Arduino before but this is my first time with ESP8266 and I don't know much about. What I would like to know is if its feasible? I read that I need to use SoftwareSerial library to achieve this. Am I correct? I have tried to google for similar examples but most of the results direct to using a single pin on the Arduino controlled by ESP8266 and the Blynk app. Apart from that I could not find much information. I would be very much grateful if you could point out some similar projects or examples. Thanks a lot for your time in advance.

title: Reading data from multiple sensors from Arduino with ESP8266

Answers: 0


body:
I’m using ESP8266 with Arduino code. Each device posts a ‘state’ and an ‘avail’ messages for a specific topic.

I wish to be able to read those retained messages and not only right after connecting and subscribe to MQTT broker.

**EDIT 1**  - Clarifications

1. I'm using Raspberry Pi Zero W as a MQTT Broker ( Local ).
2. When device boots, it changes its state from `offline` to `online`, but a different process checks periodically if state is `offline` or `online` for current device and **others** on the network.
3. it is not same as when subscribing to a retained topic, that you get the state at that specific time.
4. Storing chage of state in a variable, is one way to do it, but is there a different way ?

title: Obtain retained MQTT message

Answers: 1

body:
Once a message has passed through an [MQTT][1] [broker][2] there is not a way to retrieve it from the broker.

Consider instead deciding upon the action at the time the message is received by the subscriber.  If this decision needs to be made at a later time consider storing the state in the of the payload of the message on the subscriber.

Also consider running [Node-RED][3].  If the platform running the MQTT broker can support Node-RED (such as a Raspberry Pi), it turns out to be convenient to run both on the same computer.  Node-RED contains nodes (graphical programming blocks) which can [subscribe to and publish to MQTT topics][4].  By connecting other nodes to these, the topic and payload can be manipulated.  Of interest is an option within the Output MQTT node.  Here you can select Retain True.  [This page][5] explains how this option works:

> Once you have sent a retained message to a topic, all subscribers will
> receive that message when they subscribe.
>
> To clear a previously retained topic from the broker, send a blank
> message to that topic with the retain flag set.

  [1]: https://en.wikipedia.org/wiki/MQTT
  [2]: https://en.wikipedia.org/wiki/Message_broker
  [3]: https://en.wikipedia.org/wiki/Node-RED
  [4]: https://cookbook.nodered.org/mqtt/connect-to-broker
  [5]: https://cookbook.nodered.org/mqtt/publish-retained-message


body:
I'm using my Arduino DUE 5V pin to power a lot of sensors and I'm worried about the drop in current.

I'm powering the board using the USB port. Is this the correct way or is there a different way of powering the board to make sure the current drop is limited as much as possible?

Thanks in advance.

title: Running many devices on 5V pin. How to provide external power

Answers: 1

body:
There is a maximum current you can use from the 5V pin(s), so it is good to split the current going into the Arduino.

You can use a breakout board for a USB, connect the USB to the breakout board, connect it both to the Arduino, and in parallel to the sensors; meaning the current used for the sensors is not going through the Arduino. You might need 2 break out boards, one for the input USB, one for the output USB.

Note there is a maximum current for USB too.


body: I have been in internet for the past week looking for a way of programming a scrolling text (either left or right) using Adafruit_SSD1305 but I only find scrolling commands for Adafruit_SSD1306. Has anyone tried this before? I really need help on this

title: Using a scrolling text in OLED Adafruit_SSD1305

Answers: 1

body:
The SSD1305 hardware apparently *does* include scrolling support ([SDD1305 datasheet - see section 10][1]) but apparently the Adafruit driver didn't implement it. But The SSD1306 looks so similar to the SSD1305, that if the SSD1306 software driver won't work with it "out of the box" (worth a try!), you could probably compare the two software drivers and back-implement that feature into the the 1305 driver yourself.

  [1]: https://cdn-shop.adafruit.com/datasheets/SSD1305.pdf


body:
I want to send the voltage magnitude received on an analog pin of atmega328Pu to another arduino uno using Serial communication pins TX and RX and display the value on the receiver arduino's Serial monitor.

Transmitter Arduino Code:
```
void setup()
{

  Serial.begin(9600);

  pinMode(A0, INPUT);

}

void loop()

{

  int voltage=analogRead(A0);

  Serial.println(voltage);

}
```
Receiver Arduino Code:

```
void setup()

{

  Serial.begin(9600);

}
int incomingByte = 0;

void loop()
{
if (Serial.available() > 0) {
    incomingByte = Serial.read();
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
}

}
```

Problem: Now the Problem I am facing is that Serial Monitor of Receiver arduino does not shows anything, it remains blank. Please analyse this system help me in finding out the best way to get around this problem?
[![enter image description here][1]][1]

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

title: Serial Commmunication between two arduino

Answers: 2

body:
The problem is that a serial connection usually connects two devices, in your case it's three (sensor arduino, receiving arduino and your pc).

To get around this you have to use an additional software serial on different pins on the receiving arduino (unfortunately the atmega328 has only one hardware serial interface).
As long as you don't have to send anything from pc to the receiving arduino and from the receiving arduino to the sensing one you could try to simply disconnect the wire receiving-TX to sensing-RX and see if it works. In this latter case you could actually get rid of the receiving arduino at all.

Edit: another important point was mentioned in JRobert's answer: grounds of devices communicating with each other must **always** be connected!

body:
 1. Connect the grounds of the two Arduinos together. Their serial transmitters and receivers need the same voltage reference.

 2. `pinMode(A0, INPUT);` is not needed. pinMode() only affects the digital part of the pin driver. (But it probably isn't doing any harm, either).

 3. The transmitter Arduino will be sending 1, 2, 3, or 4 ASCII bytes - the digits 0-9, representing the D/A result, 0 - 1023. In decimal, those digits will look like 48, 49, ..., 57 (for a '0', '1', ... '9', respectively). So the receiving Arduino will be handling characters, not numbers. It needs to collect all of the characters, then repeat them onto it's terminal output.


body:
I've an arduino nano 33 iot and I'm working with the first time with bluetooth.
So far BLE is working fine, I can use an app on my smartphone to check the services and characteristics.
Is it possible to send data over serial via Bluetooth on this board ?

title: Arduino Nano 33 IOT - Bluetooth Classic (Serial)

Answers: 1

body:
This board has multiple processors on it.  The main processor (SAMD) rus your arduino code.  There is also an ESP32 based processor which runs the WIFI and the Bluetooth.  There is a pretty featured library for controlling the WIFI called WIFININA.  This library does NOT have any bluetooth functions though.  Therefore, until someone writes a library which lets you control the bluetooth functions of that ESP32 chip, I don't think you'll be able to send arbitrary serial data via bluetooth.  It is "possible" to do this but not without a lot of technical wizardry.

Here are some links to examples of what the code might look like if you were writing code directly to the ESP32 chip here https://github.com/espressif/arduino-esp32/blob/master/libraries/BluetoothSerial/examples/SerialToSerialBT/SerialToSerialBT.ino


body:
maybe this is a dumb question, but is there a way to test for wrong wifi password,

I know you can do WL_CONNECT to check if the password works, but is there a command for checking if the password is wrong? not just by waiting.

title: test for wrong wifi password?

Answers: 1

body:
The information is available on SDK level. If you include `#include "user_interface.h"`, you can use function `wifi_station_get_connect_status()`. It returns one of:

    STATION_GOT_IP
    STATION_NO_AP_FOUND
    STATION_CONNECT_FAIL
    STATION_WRONG_PASSWORD
    STATION_IDLE

The `WiFi.status()` function uses function `wifi_station_get_connect_status()`,  but returns WL_CONNECT_FAILED for STATION_WRONG_PASSWORD.


body:
Are there any documentation or whatsoever on what the 16U2 does when trying to program the Sam3X in Arduino Due?

I reallynwant to know what's wrong with my made up board but can't get pass the No Device Found problem.

Been searching it but I can't find any. I can't understand the hex file burned on the MCU.

title: Arduino Due 16U2 Programming Port Documentation

Answers: 1

body:
The 16u2 is merely acting as a usb to UART adapter. You can just as well use an ft232 or other serial adapter.

Of course the 16u2 needs firmware installing on it in order to function. That firmware is available (possibly bundled with the ide, or for download, not sure at the moment).


body:
I am new to **Arduino**. I just have my **Arduino UNO** kit and started to do some small projects with `node.js` and the `Johnny-five` library.

My question is why there not many content about `javascript`+**Arduino** in web, and the last news on `Johnny-five` website dated last year.

>Is js development still relevant for Arduino?

title: Is the johnny-five library and javascipt good for Arduino projects?

Answers: 0


body:
After looking through the internet, I coudln't find any document (not in the datasheet, no nice graphics on google image searches) that showed the mapping between the Arduino breakout board and the SAMD51. Does such a mapping exist?

I'm answering my own question below, but perhaps someone knows of a better table.

title: Pin Mappings from Arduino Metro M4 Express Board to SAMD51

Answers: 1

body:
Edit: Since writing my answer, I found this [Google Sheet](https://docs.google.com/spreadsheets/d/1hWHiM1Sk-gxcUmfgm5XQctqf9yaOnkmY66cwd_sRCiY/edit#gid=0) that does a much better job.

Arduino has some schematics on their website. [Here's an image](https://cdn-learn.adafruit.com/assets/assets/000/053/093/original/adafruit_products_schem.png?1524085993) I used to build the following list below.

There are in this format: Arduino Pin | SAMD51 Pin | SAMD51 Description

## Analog

    A0 3 PA02/EINT2/AIN0/VOUT0
    A1 14 PA05/I5/AIN5/VOUT1/SERCOM0.1
    A2 15 PA06/I6/VREFC/AIN6/SERCOM0.2
    A3 13 PA04/I4/VREFB/AIN4/SERCOM0.0
    A4 11 PB08/I8/AIN2/SERCOM4.0
    A5 12 PB09/I9/AIN3/SERCOM4.1

## Digital

    D0 44 PA23/I2C/I7/SERCOM3.1 +5/SOF/I2SFS1
    D1 43 PA22/I2C/116/SERCOM3.0+5.1/I2SDI
    D2 40 PB17/SERCOM5.1/I2SMCK0
    D3 39 PB16/I0/SERCOM5.0/I2SCK0
    D4 26 PB13/I13/SERCOM4.1/I2SMCK1
    D5 27 PB14/I14/SERCOM4.2/PCC8
    D6 28 PB15/I15/SERCOM4.3/PCC9
    D7 25 PB12/I12/SERCOM4.0/I2SCK1
    D8 42 PA21/I5/SERCOM3+5.3/I2SDO
    D9 41 PA20/I4/SERCOM3+5.2/I2SFS0
    D10 37 PA18/I2/SERCOM1+3.2
    D11 38 PA19/I3/SERCOM1+3.3
    D12 36 PA17/I2C/I1/SERCOM1.1+3.0
    D13 35 PA16/I2C/I0/SERCOM1.0+3.1
    GND
    AREF 4 PA03/I3/VREFA/AIN1
    SDA 63 PB02/I2/AIN14/SERCOM5.0
    SCL 64 PB03/I3/AIN15/SERCOM5.1

## SPI

    MOSI 29 PA12/I12/I2C/SERCOM2.0+4.1
    SCK 30 PA13/I13/I2C/SERCOM2.1+4.0
    MISO 31 PA14/I14/SERCOM2+4.2

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


body:
I am currently working on the elegoo uno r3 smart car kit that uses arduino. I have written some code and it works for the most part but I could use some help. I am trying to figure out what i need to do to get my square program to loop and continue to until the stop button is pressed. Can anyone help me out please? Also, I have 2 programs in it. One is for obstacle avoidance which is controlled by button 2 and the square program which is controlled by button 3. The stop button will be used to stop either program. I will put the code below.

    #include <Servo.h>

    //#include <ArduinoJson.h>

    //     Left motor truth table
    //Here are some handy tables to show the various modes of operation.
    //  ENB         IN1               IN2         Description
    //  LOW   Not Applicable    Not Applicable    Motor is off
    //  HIGH        LOW               LOW         Motor is stopped (brakes)
    //  HIGH        HIGH              LOW         Motor is on and turning forwards
    //  HIGH        LOW               HIGH        Motor is on and turning backwards
    //  HIGH        HIGH              HIGH        Motor is stopped (brakes)
    #include <IRremote.h>

    //#include <Servo.h>
    Servo myservo;      // create servo object to control servo
    //Servo servo;             //  Create a DC motor drive object
    //#include <stdio.h>

    //#include "HardwareSerial.h"

    int Echo = A4;
    int Trig = A5;

    //ir remote button values/ data sheet===========================
    #define f 16736925    // FORWARD
    #define b 16754775    // BACK
    #define l 16720605    // LEFT
    #define r 16761405    // RIGHT
    #define s 16712445    // STOP
    #define KEY2 16750695 //obstacle avoidance mode
    #define KEY3 16756815 //square mode

    #define KEY_STAR 16728765
    #define KEY_HASH 16732845

    // define IO pin
    #define ENB 5
    #define IN1 7
    #define IN2 8
    #define IN3 9
    #define IN4 11
    #define ENA 6
    #define RECV_PIN 12
    #define ECHO_PIN A4
    #define TRIG_PIN A5
    #define LED_Pin 13
    #define carSpeed 250
    int rightDistance = 0, leftDistance = 0, middleDistance = 0;

    IRrecv irrecv(RECV_PIN);

    decode_results results;

    void forward(){

      analogWrite(ENA, carSpeed);
      analogWrite(ENB, carSpeed);
      digitalWrite(IN1, HIGH);
      digitalWrite(IN2, LOW);
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, HIGH);
      Serial.println("Forward");
    }

    void stop_r() {
      digitalWrite(ENA, LOW);
      digitalWrite(ENB, LOW);
       /* digitalWrite(IN1, LOW);
      digitalWrite(IN2, LOW);
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, LOW);*/
      Serial.println("Stop!");
    }

    void back() {
      analogWrite(ENA, carSpeed);
      analogWrite(ENB, carSpeed);
      digitalWrite(IN1, LOW);
      digitalWrite(IN2, HIGH);
      digitalWrite(IN3, HIGH);
      digitalWrite(IN4, LOW);
      Serial.println("Back");
    }

    void left() {
      analogWrite(ENA, carSpeed);
      analogWrite(ENB, carSpeed);
      digitalWrite(IN1, LOW);
      digitalWrite(IN2, HIGH);
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, HIGH);
      Serial.println("Left");
    }

    void right() {
      analogWrite(ENA, carSpeed);
      analogWrite(ENB, carSpeed);
      digitalWrite(IN1, HIGH);
      digitalWrite(IN2, LOW);
      Serial.println("Right");
    }

    void stop_() {
      digitalWrite(ENA, LOW);
      digitalWrite(ENB, LOW);
       /* digitalWrite(IN1, LOW);
      digitalWrite(IN2, LOW);
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, LOW);*/
      Serial.println("Stop!");
    }

    //Ultrasonic distance measurement Sub function
    int getDistance() {
        digitalWrite(Trig, LOW);
        delayMicroseconds(2);
        digitalWrite(Trig, HIGH);
        delayMicroseconds(10);
        digitalWrite(Trig, LOW);
        return (int)pulseIn(Echo, HIGH) / 58;
    }

    //--------------------ZIG ZAG----------------------------------------------------

    //init the car
    void setup() {

      //pinMode(IN1, OUTPUT);     //set IO pin mode OUTPUT
      //pinMode(IN2, OUTPUT);
     // pinMode(ENB, OUTPUT);
     // digitalWrite(ENB, HIGH);  //Enable left motor

      myservo.attach(3);  // attach servo on pin 3 to servo object
      Serial.begin(9600);
      pinMode(Echo, INPUT);
      pinMode(Trig, OUTPUT);

      pinMode(IN1, OUTPUT);     //set IO pin mode OUTPUT
      pinMode(IN2, OUTPUT);
      pinMode(ENB, OUTPUT);
      digitalWrite(ENB, HIGH);  //Enable left motor

      pinMode(ENB, OUTPUT);
      pinMode(IN1, OUTPUT);
      pinMode(IN2, OUTPUT);
      pinMode(IN3, OUTPUT);
      pinMode(IN4, OUTPUT);
      pinMode(ENA, OUTPUT);
      digitalWrite(ENA, HIGH);//forward
      digitalWrite(ENB, HIGH);

      pinMode(IN3, OUTPUT);     //set IO pin mode OUTPUT
      pinMode(IN4, OUTPUT);
      pinMode(ENA, OUTPUT);
      digitalWrite(ENA, HIGH);  //Enable right motor

      //attachInterrupt(0,CHECK_IR,CHANGE);

      irrecv.enableIRIn(); // Start the receiver

      stop_r();

      //pinMode(IN3, OUTPUT);     //set IO pin mode OUTPUT
      //pinMode(IN4, OUTPUT);
      //pinMode(ENA, OUTPUT);
      //digitalWrite(ENA, HIGH);  //Enable right motor
    }

    //main loop============================================================================================================================
    void loop() {

      if(irrecv.decode(&results)){
        Serial.println(results.value);
        irrecv.resume();
      }
      delay(100);

      //square();

     if (results.value == KEY2){
         digitalWrite(ENA, HIGH);
         digitalWrite(ENB, HIGH);
        obstacleavoidance();
        //irrecv.resume();
      } else if (results.value == s){
        stop_r();
        results.value = 12;
        //irrecv.resume();
      }

      if(results.value == KEY3){
        digitalWrite(ENA, HIGH);
         digitalWrite(ENB, HIGH);
        square();
        //irrecv.resume();
      }else if (results.value == s){
        stop_r();
        results.value = 12;
        //irrecv.resume();
      }

     /* if(results.value == KEY3){
        square();
      } else if (results.value == s){
        stop_r();
      }*/

     /*if (key_pressed == KEY2){
        obstacleavoidance();
      }
      while (key_pressed == s){
        stop_r();
      }*/

    }

    void get_keys(){

    }

    void CHECK_IR(){
      if(irrecv.decode(&results)){
        Serial.println(results.value);
        //key_pressed = results.value;
        irrecv.resume();
      }
      delay(100);
    }

    void square (){
      Serial.println("square");
      digitalWrite(IN1, HIGH);
      digitalWrite(IN2, LOW);
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, HIGH);   //go forward
      delay(1000);

      digitalWrite(IN1, LOW);
      digitalWrite(IN2, LOW);
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, LOW);   //stop
      delay(1000);

      digitalWrite(IN1, HIGH);
      digitalWrite(IN2, LOW);
      delay(660);              //right wheel turning forward

      digitalWrite(IN1, LOW);
      digitalWrite(IN2, LOW);
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, LOW);   //stop
      delay(1000);
    }

    void obstacleavoidance(){

      myservo.write(90);  //setservo position according to scaled value
        delay(500);
        middleDistance = getDistance();
        //delay(100);
        if(middleDistance <= 20) {
          stop_r();
          delay(500);
          myservo.write(10);
          delay(1000);
          rightDistance = getDistance();

          delay(500);
          myservo.write(90);
          delay(1000);
          myservo.write(180);
          delay(1000);
          leftDistance = getDistance();

          delay(500);
          myservo.write(90);
          delay(1000);
          if(rightDistance > leftDistance) {
            right();
            delay(360);
          }
          else if(rightDistance < leftDistance) {
            left();
            delay(360);
          }
          else if((rightDistance <= 20) || (leftDistance <= 20)) {
            back();
            delay(180);
          }
          else {
            forward();
          }
        }
        else {
            forward();
        }
    }

title: Can someone help me solve a loop question and a couple others for my program?

Answers: 1

body:
Hannah, people that write software are inherently lazy, so because your code does the same thing over and over its quite alien to most people on here :)  As a rule of thumb if you copy and paste it more than once it should be a function.

You have functions at the top of the code to move the car, but you don't seem to use them.  Using them will make the code shorter, but also much more readable.

In your `setup()` function you are repeatedly setting the pinMode of pins.  Group all your `pinMode()` call and then use the pins.  Again this will make the code easier to read and less likely to break when you change it.

So back to your question, how to you make the bot run around in squares until you press a button?  Well it will be something like this:

    void square ()
    {
      while (condition)
      {
        for (int side = 0; side < 4 && condition; ++side)
        {
          forward ();
          delay (1000);
          stop ();
          right ();
          delay (660);
          stop();
        }
      }
    }

You need to work out a way to tie make `condition` be updated by your stop button, I don't want to do everything for you.

Hope that helps, if not shout out.


body: I have been using Lora Shield for communication between server and multiple sensor with arduino . But recently i must save data received to Cloud . So i choose Wemos D1 R2 that have similar board with arduino . But when i upload example code , LoraReceiver can'nt get data . Can Anyone Solve my problem ?

title: Using Library LoRa.h with Wemos D1 R2 for Lora Shield

Answers: 1

body: When you change boards you must also update your pin connections in software.  When you initialize the Lora Shield, you probably specify a few data pins.  Those pin numbers cannot be assumed to remain the same on the new ESP8266 based board.  Furthermore, the ESP8266 board is 3.3v logic while Arduinos are 5v logic so you must ensure that the shield and sensors will also work with 3.3v.


body:
I have 2 Arduino Nano's. One with RF transmitter and the other with an RF receiver of 433 MHz and both have two 3v vibration motors. I want one Arduino to send a string to the other Arduino to let him know which vibrator he needs to vibrate. The connection works, when the Arduino with the transmitter sends a message, the other Arduino gets the message and sets pin 2 (the pin for the vibrator via a tip120) HIGH. But the vibrator does not vibrate. When I change the vibrator with a led it works, the led goes on and off. So why does the led work but the vibrator motor not?

I use the VirtualWire library for the RF modules.

Here is the code and I also provided a summary:

Summary: This is the receiver Arduino code. `message_received` is the string variable where the message is stored and in the loop, that message is to check what it contains. And then the led goes off and on.

```
#include <VirtualWire.h>

byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = 255; // the size of the message

String message_received;

String message_go_on = "GO_ON";
String message_go_off = "GO_OF";

void setup() {
  Serial.begin(9600);
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  Serial.println("RECEIVER MONITOR");
}

void loop() {
  // put your main code here, to run repeatedly:
  if (vw_get_message(message, &messageLength)){ // Non-blocking
    Serial.print("Incoming message: ");
    for (int i = 0; i < messageLength; i++){
      Serial.write(message[i]);
      message_received += (char)message[i];
    }
    Serial.println();
  }
  if(message_received == message_go_on){
    digitalWrite(2, HIGH);
  }
  if(message_received == message_go_off){
    digitalWrite(2, LOW);
  }
  message_received = "";
}
```

----------

Summary: This is the code of the transmitter. I have 2 messages that I want to send every 200 milliseconds. The send method is for the transmitter and it needs a char array so I change the string to a char[] with a toCharArray() method.
```
#include <VirtualWire.h>

String message_go_on = "GO_ON";
String message_go_off = "GO_OF";

char buf1[VW_MAX_MESSAGE_LEN];
char buf2[VW_MAX_MESSAGE_LEN];

void setup() {
  Serial.begin(9600);
  vw_setup(2000); // Bits per sec

  message_go_on.toCharArray(buf1,VW_MAX_MESSAGE_LEN);
  message_go_off.toCharArray(buf2,VW_MAX_MESSAGE_LEN);
  Serial.println("TRNASMITTER MONITOR");
}

void loop() {
  send(buf1);
  delay(200);
  send(buf2);
  delay(200);
}

void send (char *message)
{
  vw_send((uint8_t *)message, strlen(message));
  vw_wait_tx(); // Wait until the whole message is gone
}
```

The circuit of the receiver Arduino:
[![The circuit of the receiver Arduino][1]][1]

I think the vibrator might be undersupplied but why would the led work?

Thanks for the help!

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

title: Circuit with a tip120 works with a Led but, don't with a vibrator motor

Answers: 1

body:
The TIP120 is possibly the worst transistor you could choose for this job. It is a Darlington Pair transistor, and those have a (relatively) massive forward drop of between 2 and 4 volts. It works with the LED because an LED needs a tiny amount of current to operate compared to the motor and has a fixed forward voltage of its own. The motor doesn't, and is being starved of power by that huge voltage drop (it's getting maybe half the voltage it should be getting).

Throw away that TIP120 and replace it with a decent N-channel MOSFET - one with a "threshold voltage" (VGS) of 2.5V or less ideally.


body:
I have an ESP8266 (ESP-12F), which I flashed with [ElegantOTA][1], a variation of [ArduinoOTA][2] with just a different interface. I never managed to flash anything else, so it's a bare OTA I flashed using a dedicated programmer. The device has not even pins for further flashing.

The ESP is already in a device that I would like to avoid opening, and I would like to avoid soldering pins and flashing locally the [ESPhome][3] firmware (which is also configured for future OTA).

I'm not sure the bootloader or whatever is used to self-flash the chip is compatible. How can I do it?

Or should I just open the ArduinoOTA webpage, upload a ESPhome firmware and go on?

  [1]: https://github.com/ayushsharma82/ElegantOTA
  [2]: https://github.com/jandrassy/ArduinoOTA
  [3]: https://esphome.io

title: How can I switch from ArduinoOTA to ESPhome safely?

Answers: 2

body: I've found that when a flash fails with a space error, I've usually specified the wrong flash size option in Arduino (under Tools->Flash Size).  Depending on the version of Arduino you're using, try picking the one with "No SPIFFS" or FS:none that matches the size of your flash memory.  Once you make that change, recompile and reupload.

body:
I compiled a minimal ESPhome firmware, with only OTA and wifi captive portal, and I tried to upload it (300 KB, more or less).

Initially I got the error "Space is not enough", but then after rebooting the ESP8266 and trying again, it worked.

So as said by dandavis, different firmwares are compatible in regard to OTA capabilities and it's possible to cross-flash.


body:
I have a working code that uses MCP2515 CAN module. Wanted to minimize the size of required modules, so I went with VP230 CAN transceiver and I'm having trouble relaying the same data through different libraries. All it has to do is log in with the first ''payload1'' and send voltage instruction with ''setdefaultvolt''. Any help is greatly appreciated.

**MCP2515** code:

```
#include <mcp_can.h>
#include <mcp_can_dfs.h>
#include <SPI.h>
#include <Wire.h>

//pins:
#define CAN_INT 17                                                                         // Set INT to pin 2
MCP_CAN CAN(5);                                                                         // Set CS to pin 4 (D2)

void setup()
{
  Serial.begin(115200);
  delay(100);
  pinMode(17, INPUT);                                                                       //Setting pin 2 for /INT input

START_INIT:
  if(CAN_OK == CAN.begin(MCP_ANY, CAN_125KBPS, MCP_8MHZ))
  {
  }
  else
  {
    delay(100);
    goto START_INIT;
  }
  CAN.setMode(MCP_NORMAL);                                                        //set operation mode to normal so the MCP2515 sends acks to received data.
  unsigned char payload1[8] = {0x16, 0x50, 0x71, 0x07, 0x97, 0x089, 0x00, 0x00};  //login data with serial number
  CAN.sendMsgBuf(0x05004804, 1, 8, payload1);                                     //send login data

  unsigned char setdefaultvolt[5] = {0x29, 0x15, 0x00, 0xFE, 0x10};              //this is the command for setting the default output voltage (Last two bytes, LSB first). 16 80 is the maximum voltage of 57.6 V
  CAN.sendMsgBuf(0x05019C00, 1, 5, setdefaultvolt);                              //send setup data
}

void loop()
{
}
```
**VP230** code:
```
#include <CAN_config.h>
#include <ESP32CAN.h>

CAN_device_t CAN_cfg;

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

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

  CAN_cfg.speed=CAN_SPEED_1000KBPS;
  CAN_cfg.tx_pin_id = GPIO_NUM_19;
  CAN_cfg.rx_pin_id = GPIO_NUM_23;

  CAN_frame_t my_frame;
  CAN_frame_t my_frame2;

  ESP32Can.CANInit();

  my_frame.FIR.B.FF = CAN_frame_ext;
  my_frame.MsgID = 0x05004804;
  my_frame.FIR.B.DLC = 8;

  my_frame.data = {0x16, 0x50, 0x71, 0x07, 0x97, 0x089, 0x00, 0x00};

  ESP32Can.CANWriteFrame(&my_frame);

  my_frame.FIR.B.FF = CAN_frame_ext;
  my_frame.MsgID = 0x05019C00;
  my_frame.FIR.B.DLC = 5;

  my_frame2.data = {0x29, 0x15, 0x00, 0xFE, 0x10};

  ESP32Can.CANWriteFrame(&my_frame2);

}

void loop()
{
}
```

title: Simple ESP32 MCP2515 CAN code to VP230

Answers: 2

body:
Just spotted this, but if any one else finds it: You have one CAN speed set to 125kb on MCP2515 the other to 100kb on the VP230.

That's why you won't get anything!

Mark

body:
from datasheet ...CAN controller at speeds up to 1 Mbps.

On the SN65HVD230 and SN65HVD231, pin 8 provides three different modes of operation: high-speed, slope
control, and low-power modes. The high-speed mode of operation is selected by connecting pin 8 to ground,
allowing the transmitter output transistors to switch on and off as fast as possible with no limitation on the rise
and fall slopes.


body:
I am using Arduino Yun to send data from serial to client, and it's partially working because I only get short data delivered, while long data (like more than 100Byte) get the most of them lost.

on the other hand when I use the softwareSerial example in the IDE to send from serial to serial it works with no data lost. I am trying to do like the example as possible with the serial to client code using client.write(mySerial.read()) but not working as expected!

 what am I missing? I guess client.write doesn't hold long data or is too slow to transmit. How can I solve this or even another way to achieve my point?

I am sending the data (as a file content on one time, not in sequence- it's a must) from pc using terminal Programm sscom32e. I am receiving the data as client using netcat on the same pc (Yun and PC connected with RS232-USB and are on the same network).

```
#include <SoftwareSerial.h>
#include <Bridge.h>
#include <BridgeClient.h>

#define PORT 9000
// Make the client connect to the desired server and port
IPAddress addr(192, 168, 0, 100);

//not all pins on the yun are assignable as rx/tx
SoftwareSerial mySerial(10, 11); // RX, TX

// Define our client object
BridgeClient client;

int led = 4;
bool Connected;
void setup() {
 pinMode(led, OUTPUT);

 // set the data rate for the SoftwareSerial port
 mySerial.begin(9600);
 mySerial.println("Hello, world?");
 mySerial.setTimeout(20000);

 // Start Bridge
 Bridge.begin();
 //delay(1000);

 // Start Console communications and wait for port to open:
 //Console.begin();
 //delay(1000);

 //Console.println("Client connecting on port 9000");
 Connected = false;

 //delay(1000);
 //connectToClient();
 connectToClient();
}

void loop() // run over and over
{
 while (mySerial.available()) {

 client.write(mySerial.read());

 //mySerial.read();
 }

}

void connectToClient() {

 // is a connection currently active?
 if (!Connected)
 {
 // not currently connected, try to establish a connection
 client.connect(addr, PORT);
 delay(1000);

 if (client.connected())
 {
 // send something to the client
 client.println("hello server!");
 digitalWrite(led, HIGH);
 }
 else
 {
 connectToClient();
 digitalWrite(led, LOW);

 }
 }
}

```

title: send data from serial to client

Answers: 1

body: I believe now that serial.read and client.write cann't work together at the same time efficiently. when client.write starts, serial.read stops and therefore data get lost. Now I am saving the serial.read in 3 arrays of each 255Byte, when they are full or I receive an end-marker I call client.write to send them and Serial stops anyway. This works but for max. 765 Byte data. I can't do more arrays to save the serial data due to the limited memory of the module, which means it's not the best solution right now. I will post the code for this later when I optimate it. the other Idea coming to my mind is to send orders to the serial to wait until client.write finishes and then continue receiving and so on. Is this possible? Is Serial that flexible? How could I communicate with Serial to wait and to continue?


body:
So I recently followed a tutorial on youtube and I've assembled the car and connected all the wires.

What I've done:
[Car][1]

Now in the video, when the guy connects all the wires, the wheels constantly turn while in mine they're completely still. Is this a problem? Is it an indicator of some connection issue or something else?

For context, here is the schematic:
[![Schematic][2]][2]

  [1]: https://i.stack.imgur.com/WPDvZ.jpg
  [2]: https://i.stack.imgur.com/SIvPR.png

title: Help me get my robotic car to work?

Answers: 3

body: The ENA/ENB (enable A/B) pins have to be at HIGH level (either hardwired or set by an mcu). There exist lots of different driver boards (mostly based on the same ICs) which sometimes don't provide this enable pin, but they are "enabled" by default. You didn't tell us which board you use, but you'll know.

body:
I don't know your motor-driver board but here are several things to check out, based on your schematic:

- The motor driver board has two enable pins. Neither of them is connected. It would make sense that these pins turn the two motors on and off.
- The pin marked 12v is connected to +5v.
- The linked photo of your car shows two 9v "Transistor" batteries. This kind of battery in particular is not capable of supplying much current and they most likely unable to turn the motors.

body:
Check These:

As you have used two power source you must **common ground them**.

**You must check L298N motor drivers enable pins.As you have only 4 wire to motor driver from arduino.So you must give EnA and EnB pin 5v/HIGH or  You can give it (0-255) pwm value from arduino to control the speed of your motor **

If wiring is ok then you must go throw you Sketch.


body:
While researching minimum-voltage requirements of Uno, I came across what appear to be two datasheets for the ATmega328P:

http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf

http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf

Specifically, the power requirements (and processor speed for each power level) differ. How could I know which datasheet applies to the chip I'm using? I'm actually using an Arduino clone:

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

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

title: Which Datasheet applies to the ATmega328p?

Answers: 2

body:
You have ATmega328P-AU. Classic Uno with DIP socket has ATmega328P-PU. Arduino Uno SMD has Atmega328P-MU.

The automotive versions ATmega328P-15AZ and ATmega328P-15MZ have separate datasheet starting in Revision History with

> Creation of the automotive version starting from industrial version
> based on the ATmega48P/88P/168P/328P datasheet 8025F-AVR-08/08.
> Temperature and voltage ranges reflecting automotive requirements.

body:
I think there is an error concerning the information about supply voltages. At least it's not consistent: microchip has separate websites for [ATmega328][1] and [ATmega328p][2]. On the site for the ATmega328p it says: "The device operates between 1.8-5.5 volts". But the [datasheet][3] they link on the exact same site says:
    "Operating voltage: 2.7V to 5.5V for ATmega328p".

This is not just confusing, but contradictory and so I think the only one who can say for sure is the manufacturer.

Actually, the specified supply voltages are determined by the manufacturer by testing at various levels, but the device **might** operate even below or above this range (of course, a developer has to comply with the specs). The 2.7V rating could be an old spec and in the meantime they might have found out that the device indeed runs fine even at 1.8V. Maybe, they have just missed to apply this change everywhere this rating is mentioned, but that's just a guess.

  [1]: https://www.microchip.com/wwwproducts/en/ATmega328
  [2]: https://www.microchip.com/wwwproducts/en/ATmega328p
  [3]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf


body:
I'm using an Arduino uno and a Nodemcu for making a game with the phone as a WiFi controller.
The Nodemcu is the server that receives inputs from the phone connected via WiFi and sends to the Arduino a signal via SoftwareSerial.
The Arduino reads the signal and then decides what to do and sends output to TV.
It works good but every time the nodemcu sends something, the TV signal gets distorted.

note: the code for the game is not completed

code for Nodemcu:
```c++
#include<SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid = "SpaceInvaders";
const char* password = "12345678";

IPAddress local_ip(192,168,1,1);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
SoftwareSerial SUART(4, 5); //SRX=Dpin-D2; STX-DPin-D1
ESP8266WebServer server(80);

void setup() {
  SUART.begin(115200);
  Serial.begin(115200);
  WiFi.softAP(ssid, password);
  WiFi.softAPConfig(local_ip, gateway, subnet);
  server.on("/", handle_OnConnect);
  server.on("/0", nope);
  server.on("/1", left);
  server.on("/2", right);
  server.on("/3", left_right);
  server.on("/4", shoot);
  server.on("/5", left_shoot);
  server.on("/6", right_shoot);
  server.on("/7", left_right_shoot);
  server.onNotFound(handle_NotFound);

  server.begin();
  Serial.println("HTTP server started");
}

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

void handle_OnConnect() {}

void nope()             {SUART.print(0); server.send(200, "text/html", " "); Serial.println(0);}
void left()             {SUART.print(1); server.send(200, "text/html", " "); Serial.println(1);}
void right()            {SUART.print(2); server.send(200, "text/html", " "); Serial.println(2);}
void left_right()       {SUART.print(3); server.send(200, "text/html", " "); Serial.println(3);}
void shoot()            {SUART.print(4); server.send(200, "text/html", " "); Serial.println(4);}
void left_shoot()       {SUART.print(5); server.send(200, "text/html", " "); Serial.println(5);}
void right_shoot()      {SUART.print(6); server.send(200, "text/html", " "); Serial.println(6);}
void left_right_shoot() {SUART.print(7); server.send(200, "text/html", " "); Serial.println(7);}

void handle_NotFound(){
  server.send(404, "text/plain", "Error: not found");
}
```

code for arduino (note: seems that stackexcange identifies this function as spam so i posted them [here](https://pastebin.com/0sZ0KbCG) ):
```c++
#include<SoftwareSerial.h>
#include <TVout.h>
#include <fontALL.h>
SoftwareSerial SUART(2, 3); //SRX=Dpin-2; STX-DPin-3
TVout TV;
//#define debug 1
#define numberOfEnemies 15
#define maxEnemyMovement 20
#define playerDefaultY 75

int points = 0;
unsigned long int millisLastEnemyMovement = 0;
int enemyMovementDelay = 850;
int enemyMovement = 0;
bool directionIsRight = true;

struct b {
  int x;
  int y;
  bool shootable;
} bullet;

struct p {
  int x;
} player;

typedef struct {
  int x;
  int y;
  bool alive;
} Enemy;

Enemy enemyList[numberOfEnemies];

void renderEnemy(int x, int y){ //draws sprite of enemy

}

void renderPlayer(int x, int y){  //draws player sprite

}

void shoot(){
  if(bullet.shootable){
    bullet.shootable = false;
    bullet.x = player.x;
    bullet.y = 100;
  }
}

void left(){
  if(player.x > 0){
    player.x--;
  }
}

void right(){
  if(player.x < 105){
    player.x++;
  }
}

void spriteUpdate(){
  if(!bullet.shootable){
    bullet.x--;
    if(bullet.x < 0){
      bullet.x = 0;
      bullet.y = 0;
      bullet.shootable = true;
    }
    for(int i = 0; i < numberOfEnemies; i++){
      if(bullet.x > enemyList[i].x && bullet.x < enemyList[i].x + 11 && bullet.y > enemyList[i].y && bullet.y < enemyList[i].y + 8){
        bullet.shootable = true;
        enemyList[i].alive = false;
        points++;
      }
    }
  }
  if(millis() - millisLastEnemyMovement > enemyMovementDelay){
    millisLastEnemyMovement = millis();
    if(directionIsRight){
      enemyMovement++;
      for(int i = 0; i < numberOfEnemies; i++){
        enemyList[i].x++;
      }
    }else{
      enemyMovement--;
      for(int i = 0; i < numberOfEnemies; i++){
        enemyList[i].x--;
      }
    }
    if(enemyMovement == 0 || enemyMovement == maxEnemyMovement){
      directionIsRight = !directionIsRight;
    }
  }
}

void render(){
  TV.delay_frame(1);
  TV.clear_screen();
  renderPlayer(player.x, playerDefaultY);
  for(int i = 0; i < numberOfEnemies; i++){
    if(enemyList[i].alive){
      renderEnemy(enemyList[i].x, enemyList[i].y);
    }
  }

}
void setup()
{
  char x;
  Serial.begin(115200); //enable Serial Monitor
  SUART.begin(115200); //enable SUART Port
  bullet.x = 0;
  bullet.y = 0;
  bullet.shootable = true;
  for(int i = 0; i < 5; i++){
    enemyList[i] = {4+i*20, 3, true};
    enemyList[i+5] = {4+i*20, 18, true};
    enemyList[i+10] = {4+i*20, 33, true};
  }
  player.x = 50;
  TV.begin(PAL, 120, 96);
  while(true){

  }
}

void loop(){
    if (SUART.available() != 0){
      x = SUART.read();  //read char
      switch(x){
        case 'a':
          left();
          break;
        case 'b':
          right();
          break;
        case 'c':
          //left and right same time?
          break;
        case 'd':
          shoot();
          break;
        case 'e':
          left();
          shoot();
          break;
        case 'f':
          right();
          shoot();
          break;
        case 'g':
          //left and right at same time?
          shoot();
          break;
      }
    }
    spriteUpdate();
    render();
}
```
This is the schematic:
[![this is the schematic][1]][1]

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

title: SoftwareSerial interfers with TVout

Answers: 2

body: Software Serial is a pretty crummy library.  It disables interrupts while receiving for long periods of time.  That causes any other library that uses interrupts to have issues with timing.  There are a plethora of other soft serial libraries out there.  Try one of those instead.  AltSoftSerial comes to mind.

body:
> It works good but every time the nodemcu sends something, the TV signal gets distorted.

That's correct. SoftwareSerial is terrible. Don't use it. When it's sending or receiving data nothing else at all can happen.

If you have to resort to SoftwareSerial then you are using the wrong hardware for your project. Maybe an ESP32 would be a better choice.

----

Basically you have two software hacks. Both require precise timing and neither is happy if that timing is messed with. To that end both will disable interrupts to stop things interfering. You can use one or the other, but not both.


body:
am using fingerprint sensor r307 on my project and when l use connection from datasheet(My circuit connection is:

(Green) TX => Pin 0 [PWM]

(White) RX => Pin 1 [PWM]

//It doesn't respond when connected to 5V, it only heats up

(Red) VCC => 3.3v

(Black) GND => GND) the finger print is not light up and it starts to over heat but when l connect from left as ground , tx,rx and last vcc respectively the sensor lights up but it does not shown in the serial monitor it says did not find fingerprint sensor:

my code from Adafruit

    #include <Adafruit_Fingerprint.h>

    // On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
    // uncomment this line:
     #define mySerial Serial1

    // For UNO and others without hardware serial, we must use software serial...
    // pin #2 is IN from sensor (GREEN wire)
    // pin #3 is OUT from arduino  (WHITE wire)
    // comment these two lines if using hardware serial
    //#include <SoftwareSerial.h>
    //SoftwareSerial mySerial(10, 11);

    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    uint8_t id;

    void setup()
    {
      Serial.begin(9600);
      while (!Serial);  // For Yun/Leo/Micro/Zero/...
      delay(100);
      Serial.println("\n\nAdafruit Fingerprint sensor enrollment");

      // set the data rate for the sensor serial port
      finger.begin(57600);

      if (finger.verifyPassword()) {
        Serial.println("Found fingerprint sensor!");
      } else {
        Serial.println("Did not find fingerprint sensor :(");
        while (1) { delay(1); }
      }
    }

    uint8_t readnumber(void) {
      uint8_t num = 0;

      while (num == 0) {
        while (! Serial.available());
        num = Serial.parseInt();
      }
      return num;
    }

    void loop()                     // run over and over again
    {
      Serial.println("Ready to enroll a fingerprint!");
      Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
      id = readnumber();
      if (id == 0) {// ID #0 not allowed, try again!
         return;
      }
      Serial.print("Enrolling ID #");
      Serial.println(id);

      while (!  getFingerprintEnroll() );
    }

    uint8_t getFingerprintEnroll() {

      int p = -1;
      Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
      while (p != FINGERPRINT_OK) {
        p = finger.getImage();
        switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.println(".");
          break;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          break;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          break;
        default:
          Serial.println("Unknown error");
          break;
        }
      }

      // OK success!

      p = finger.image2Tz(1);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      Serial.println("Remove finger");
      delay(2000);
      p = 0;
      while (p != FINGERPRINT_NOFINGER) {
        p = finger.getImage();
      }
      Serial.print("ID "); Serial.println(id);
      p = -1;
      Serial.println("Place same finger again");
      while (p != FINGERPRINT_OK) {
        p = finger.getImage();
        switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.print(".");
          break;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          break;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          break;
        default:
          Serial.println("Unknown error");
          break;
        }
      }

      // OK success!

      p = finger.image2Tz(2);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      Serial.print("Creating model for #");  Serial.println(id);

      p = finger.createModel();
      if (p == FINGERPRINT_OK) {
        Serial.println("Prints matched!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_ENROLLMISMATCH) {
        Serial.println("Fingerprints did not match");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }

      Serial.print("ID "); Serial.println(id);
      p = finger.storeModel(id);
      if (p == FINGERPRINT_OK) {
        Serial.println("Stored!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_BADLOCATION) {
        Serial.println("Could not store in that location");
        return p;
      } else if (p == FINGERPRINT_FLASHERR) {
        Serial.println("Error writing to flash");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }

title: fingerprint sensor r307

Answers: 0


body:
I use Waveshare's Sound Sensor module.

I use this simple code to test the module:

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

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

As you can see, the problem is that when I have a delay in the program, once the analogRead is bigger than 10 (by slightly knocking the mic with my finger), "sound" is printed, but sound sensor's output doesn't decrease back to normal values and "sound" keeps repeating.
If I don't use delay, everything works fine, but I need that delay.

*NOTE: on this test I use a STM32 nucleo development board, but I don't think that contributes to the problem.

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

title: Sound sensor's output stucks to high values when I include a delay in the loop function

Answers: 1

body:
The AOUT pin of that device is no more than an amplified audio signal. It is AC coupled, and that means that it is a small signal varying around 0v. It is not suitable for feeding directly into an ADC.

The AC coupling capacitor will be being charged up by the DC offset it is there to remove, and the lack of any drain on that capacitor while the ADC is not sampling means it never discharges as it should. By sampling faster you increase the load and thus it can discharge somewhat.

To properly read that AOUT pin you need to add your own DC offset to half the VCC voltage of your Arduino board, which can be done by adding two 10k resistors. One from VCC (5v) to the analogue input, and the other from the analogue input to ground.

The signal you read will then be "idle" at around 2.5v (512 ADC reading) and vary around that as sound is picked up.

Note that you can't just sample once per second and hope: there is no provision for "did sound happen in the past second". Instead you really need to be sampling all the time.

If all you care about is if some sound above a threshold has happened then you would be better using DOUT connected to a digital input or even an interrupt pin, and using the threshold setting trim pot on the board.


body:
I'm trying to develop one code in which I'm facing issue with while loop. Once I enter any newString it enter in while loop it count till 10 times, when (n>10)  then it is coming out from the while loop.
Facing issues in this part
```
while (n < 10)
  {
    while (!ret) {
      if ((time + 15) < millis()) {
        ret = dmd.stepMarquee(-1,0);
        time = millis();
      }
    }
     ret = false;
     n++;
    }
```

I just want when I enter any newString when loop is running it break while loop and start display newString.

Please help me out with this. Thanks for your help, greatly appreciated.

Here is my full code:
```
#include <SPI.h>
#include <DMD.h>
#include <TimerOne.h>
#include "SystemFont5x7.h"
#include "Arial_black_16.h"

//Fire up the DMD library as dmd
#define DISPLAYS_ACROSS 2
#define DISPLAYS_DOWN 1
DMD dmd(DISPLAYS_ACROSS, DISPLAYS_DOWN);

String inputString = "";
boolean stringComplete = false;
String commandString = "";

void ScanDMD()
{
  dmd.scanDisplayBySPI();
}

void setup()
{
   Serial.begin(9600);
   Serial.println("Arduino Start");
   Timer1.initialize( 5000 );
   Timer1.attachInterrupt( ScanDMD );
   dmd.clearScreen( true );
}

void loop() {

if(stringComplete)
{
  stringComplete = false;
  getCommand();

  if(commandString.equals("STAR"))
  {
   dmd.clearScreen( true );
  }

  else if(commandString.equals("PRSC"))
  {
    String text = getTextToPrint();
    printText(text);
  }
  inputString = "";
}

}

void getCommand()
{
  if(inputString.length()>0)
  {
     commandString = inputString.substring(1,5);
  }
}

String getTextToPrint()
{
  String value = inputString.substring(5,(inputString.length())-2);
  return value;
}

void printText(String text)
{
  char newString[256];
  int sLength = text.length();
  text.toCharArray( newString, sLength+1 );
  dmd.selectFont(System5x7);
  dmd.drawMarquee( newString , sLength , (32*DISPLAYS_ACROSS )-1 ,1);
  unsigned long time;
  boolean ret = false;
  time = millis();
  int n;
  n= 0;
  while (n < 10)
  {
    while (!ret) {
      if ((time + 15) < millis()) {
        ret = dmd.stepMarquee(-1,0);
        time = millis();
      }
    }
     ret = false;
     n++;
    }
}

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;
    }
  }
}
```

title: facing issue with while loop

Answers: 2

body:
Forget using `serialEvent()`. It is one of the more stupid things that Arduino implemented.  It is nothing more than a function that gets called (wrapped in a check to `Serial.available()`) once per iteration of the main `loop()` function.

It is not really an "event" function at all.

To have anything happen inside your `while` loop you have to *manually* implement that thing within your `while` loop.  Nothing outside of the `while` loop (with the exception of interrupts) can affect the operation of the `while` loop.

body:
**Now my code is working like** I'm sending the data to Arduino UNO via serial(Keyboard) when it receive any serial data it scroll till 10 time and when _(n>10)_ then will loop stop. In between this whenever I'm send any new data it is not accepting.

 **what exactly I want** whenever I send new data to Arduino UNO via serial(Keyboard) and then UNO is to turn expected to scroll the received text on P10 DMD display at the same time.  Whenever it receive new serial data it start displaying that data into display.


body:
So I have a java program that picks up the mouses x and y coords on the display and I would like to send those to my arduino and then move my two servos to those locations (I have two servos ontop of each other, one for x and one for y).

The java (processing) code i have is below

```
void draw(){  //same as loop in arduino
  background(52, 152, 219); // background color of window (r, g, b) or (0 to 255)
  //lets give title to our window
  fill(0, 255, 0);               //text color (r, g, b)
  textFont(font);
  text("Ripple Effect Maker", 80, 30);  // ("text", x coordinate, y coordinat)
  ellipse(mouseX, mouseY, 33, 33);
  int x = mouseX;
  int y = mouseY;
  port.write(x+":"+y);
  println(x+":"+y);
  //println("y="+y);
  delay(100);
}
```
I don't have much arduino code because I can't seem to find a way to split the data into two seperate variables and then move the servos to their corresponding variables.

Thanks for the help!

title: Receiving two values over serial port using servos

Answers: 1

body:
Your problem is that you aren't providing anything to split the data on. You just send the X and y coordinates with a : between X and y. There's nothing between the y and the next X.

By changing the line

    port.write(x+":"+y);

To

    port.write(x+":"+y+"\n");

You then get the linefeed character to split your data on.


body:
Sorry if there is information missing, im new to the topic.

I have an ESP32 connected to a Waveshare 7,5" RWB display, and i can display images by converting them to .xbm and including the hex code in the sketch.
So far, so good.

But heres my question: What exactly are the requirements? Because when looking at the .xbm image code, i see that its a pattern like this:

`0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00`

But when i used a python script

```
import binascii
filename = 'test.png'
with open(filename, 'rb') as f:
    content = f.read()
print(binascii.hexlify(content))
```
to convert an image to hex code, i got this:
`b'89504e470d0a1a0a0000000d4948445200000280000001800802000000b2...'`(continues for thousands of characters, didnt want to paste all of that here

However, when trying to run the sketch that successfully displayed the first hex code with the second image code, i got this error(cut out the big string clutter again):

```
...0000000049454e44ae426082};

^

C:\Users\Administrator\Desktop\SPI_test_example\SPI_test_example.ino: In function 'void loop()':

SPI_test_example:167:21: error: 'showBitmapExample' was not declared in this scope

   showBitmapExample();

                     ^

SPI_test_example:171:51: error: 'showFont' was not declared in this scope

   showFont("FreeMonoBold9pt7b", &FreeMonoBold9pt7b);

                                                   ^

exit status 1
'showBitmapExample' was not declared in this scope
```

So, i would like to know - does the image code have to have exactly the format i mentioned first? This is very important for me because i want to automate the process from inputting any image to using the resulting code to feed the display.

Thanks in advance!

EDIT: As far as my understanding goes, both formats are the same data, just that the first one is displaying a white pixel as 0xFF,0xFF,0xFF and the second one as FFFFFF.

title: What image formats are accepted for displays?

Answers: 1

body:
This is not a question of image format but of what format c accepts data in.

What you have is a python representation of binary data in hexadecimal encoding. That can only be used with python.

C represents hexadecimal values by prefixing them with `0x`.

You will have to change your python code to output each byte individually and prefix it with `0x` and separate each one with a comma. That can then be wrapped in an array structure.


body:
Is it safe to measure current like this as long as measured voltage drop don't exceed 5V? I'm asking this because in almost all current sense circuits they used an opamp in their design.

Do I need a resistor between shunt resistor and ADC? Is there any noticeable current flowing to Arduino ADC that can damage it?

<!-- 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/BPV4f.png)

<!-- End schematic -->

title: Measuring current directly with Arduino

Answers: 2

body:
Let's imagine that you expect to have 1A of current going through your circuit.
Resistor of 0.1 Ohm will give you a voltage drop of 0.1V.
This causes two problems.

Firstly Arduino has a cheap ADC builtin. It's supposed to be easy to use, but not really precise. It has nonlinearities towards lower and higher range. You will get more precise reading when measuring voltages around 2.5V.

Secondly The precision of your measurement is cut by factor of 50. Arduino contains ADC that has resolution of 10 bits. This means that there are only 20 steps between 0V and 0.1V That's not really precise.

Solution? Use an opamp as "[differential amplifier][1]". If you multiply the voltage difference by 25 you will get 2.5V on the amplifier output when the resistor has 0.1V of drop on it. This value is much more precise when reading it by analogRead of the Arduino, and even a tiny change in voltage on the resistor will give you 25 times larger change on the amplifier output. This way it's much more precise and accurate.

  [1]: https://www.electronics-tutorials.ws/opamp/opamp_5.html

body:
There's a bad current flowing into your Arduino, if ADC voltage exceeds Vcc (5V). This undesired current can be limited by a resistor. But if there's such a high voltage across a shunt resistor, something else is wrong. You rather suffer from a too small voltage for useful measurement.

My first doubt is rather, whether it's safe for the shunt resistor.


body:
Can I power my Pi 3 using the 3v3 pin (pin 1) and GND pin (pin 6)? Also, if I want to protect the board from power surges can I just put a fuse between my power supply and the 3v3 pin?

Thanks in advance,

title: Can I power Raspberry Pi 3 via 3V3 and GND pin?

Answers: 1

body:
This is not an Arduino question **BUT** definitely do **NOT** try this!

The Foundation [Hats Master](https://codeload.github.com/raspberrypi/hats/zip/master) has recommendations.

*"It is possible to power the Pi by supplying 5V through the GPIO (sic) header pins 2,4 and GND. The acceptable input voltage range is 5V ±5%. ⋯ Implement a duplicate power safety diode ⋯ supply 5V at a minimum of 1.3A ⋯ Under no circumstances should a power source be connected to the 3.3V pins."*


body:
I have a simple test sketch to run for my led aquarium:

    #include <IRremote.h>
    #include <IRremoteInt.h>

    IRsend irsend;
    void setup() {

    }

    void loop() {

    irsend.sendNEC(0xF7C03F, 32);
    delay (2000);
    }

I am using a 850nm Infrared LED and a 330Ohm resistor.
The connection:
Digital 3 to Resistor -> GND
  [1]: https://i.stack.imgur.com/vnKUN.jpg
[![enter image description here][1]][1]

On the Arduino nano it runs perfectly: the LED of my aquarium turns on and off like the sketch tells it to.
But on the Pro Mini nothing happens.

To be honest, it is my first time using the pro mini.
Maybe I forgot something???
I am using a FTDI232 (set to 5V) to flash it.

Hope someone can help me.
Kind regard
Daniel :)

title: Sketch works on Arduino nano but not Pro Mini

Answers: 0


body:
I am able to interface  gps and the ultrasonic sensor and obtain data successfully for individual interfacing with the Arduino UNO. When I combined the code for these two, I only get the data values from gps but no measurement values are obtained for the ultrasonic sensor.In the variable data, I have stored the gps data packet. I have read the solution for the same problem but none of them worked. I have attached the code below:

        #include <SoftwareSerial.h>
        #include "TinyGPS++.h"

        SoftwareSerial serial_connection(8, 9);

        TinyGPSPlus gps;
        TinyGPSCustom Trackingangle(gps, "GPRMC", 8);
        TinyGPSCustom Dir_NS (gps, "GPRMC", 4);
        TinyGPSCustom Dir_EW (gps, "GPRMC", 6);

        String data,tr,ew,ns,d1;
      int a=0;
        const int trigPin = 6;
        const int echoPin = 7;
        long duration;
        int distance;
        int buttonPin = 12;
        String s="",str_dist="",str_button="";
        int buttonPushCounter = 0;
        int buttonState = 0;
        int lastButtonState = 0;

        void setup()
        {
          pinMode(trigPin, OUTPUT);
        pinMode(echoPin, INPUT);
        pinMode(buttonPin, INPUT);
          Serial.begin(9600);
                serial_connection.begin(9600);
        }

        void loop()
        {
          data="";tr="";d1="";
        serial_connection.listen();
         dat_gps();
           if(data!="")
        {
        Serial.println("GPS DATA= "+data);
        ultra();
          }
       }
            void ultra()
        {
    distance=0;duration=0;
             digitalWrite(trigPin, LOW);
        delayMicroseconds(2);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);
        duration = pulseIn(echoPin, HIGH);
        //if(duration!=0)
        {
          distance= duration*0.034/2;
            Serial.print("Distance= ");
        Serial.println(String(distance));
        }
        }

        void dat_gps()
        {
         {
          while(serial_connection.available())
          {
            gps.encode(serial_connection.read());
          }

        if (Trackingangle.isUpdated())
        {
            tr=String(Trackingangle.value()); //    Serial.println(tr);
        }
        if (Dir_EW.isUpdated())
        {

         ew=String(Dir_EW.value());
        }
        if (Dir_NS.isUpdated())
        {

          ns=String(Dir_NS.value());
        }
        if(tr!="")
        { if(gps.location.isUpdated())
         {       delay(2000);
            data=String(gps.satellites.value());
           data+=",";
           if(data!="0,")
           {
            data+=String(gps.location.lat(), 6);
            data+=",";
            data+=String(gps.location.lng(), 6);
            data+=",";
               data+=String(gps.speed.mph());
                  String a=String(gps.altitude.feet());
             if(a!="")
           {   data+=",";
           data+=a;
             data+=",";
              data+=String(gps.hdop.value());
             data+=",";
             data+=tr;
             data+=",";
             data+=ns;
             data+=",";
             data+=ew;
             data+="";
                }
           }}
          }
         }
        }

title: Interface gps and ultrasonic sensor simultaneously

Answers: 0


body:
I am just sending the AT command to test if the serial communication works, the response I am getting is a flipped "?" or a square or rectangle symbol.

I have tested the communication using software provided by Waveshare connected through on board USB to UART.

https://www.waveshare.com/wiki/SIM7600E-H_4G_HAT

    int PowerKey = 2;
    char answer;

    void setup()
    {
     Serial3.begin(96u00);
     Serial.begin(9600);
     pinMode(PowerKey, OUTPUT);
     Serial.println("initializing");
     digitalWrite(PowerKey, HIGH);
     delay(1000);
     digitalWrite(PowerKey, LOW);
    }

    void loop()
    {
      answer = send_at_cmd("AT\r\n");
      Serial.println(answer);
    }

    uint8_t send_at_cmd(const char* ATcommand)
    {
      char response;
      // send test command AT
      Serial3.print(ATcommand);
      Serial.println(ATcommand);
      delay(1000);
      //Check for response from the sim7600E-H
      while(Serial3.available() != 0)
      {
        response = Serial3.read();
      }
      return response;
    }

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

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

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

title: Serial communication problem with sim7600 with Arduino Mega

Answers: 1

body:
You have change baud rate by at+iprex=9600 before upload your code, because sim7600 set 115200 by default then save your setting by at&w.

hope this help someone.


body:
I am trying to convert a char[12] array that contains a Mac Address into a byte[6] in order to use within the Ethernet.begin method. I have tried various methods from online, but had little success to date. The char array currently contains "A4BDC334688C" and i would like a byte array containing { A4, BD, C3, etc }.

The following is extremely close to working, with the output of the following
"File Opened.
A4BDC334688C
A4
9D
C3
34
68
6C" With BD incorecctly converting to 9D, and 8C becomming 68.

    #include <SPI.h>
    #include <SD.h>
    #include <ArduinoJson.h>

    byte ByteMacAddress[6]; // RESERVED MAC ADDRESS
    StaticJsonDocument<200> doc;

    int ShotCount = 0;
    byte buf[40];

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

      //Initialise SD Card for Config
      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
      }

      // open the file for reading:
      File ConfigFile = SD.open("Config.txt");
      if (ConfigFile) {
        Serial.println("File Opened.");
      } else {
        Serial.println("error opening Config.txt");
      }

      //Deserialize Json Config in File
      delay(5);
      DeserializationError error = deserializeJson(doc, ConfigFile);
      ConfigFile.close();
      // Test if parsing succeeds.
      if (error) {
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(error.c_str());
        return;
      }

      char* SDMacAddress = doc["MacAddress"];
      Serial.println(SDMacAddress);

      char arr[12];
      strcpy(arr, SDMacAddress);

      auto getNum = [](char c){ return c > '9' ? c - 'a' + 10 : c - '0'; };
      byte *ptr = ByteMacAddress;

      for(char *idx = arr ; *idx ; ++idx, ++ptr ){
        *ptr = (getNum( *idx++ ) << 4) + getNum( *idx );
      }

      //Check converted byte values.
      for( byte b : ByteMacAddress )
        Serial.println( b, HEX );
    }

    void loop(){
      //Maintain DHCP Lease
      //Ethernet.maintain();

      //GetShotCount();
      delay(500);
    }

title: How to convert char[12] to byte[6]

Answers: 2

body:
Please see the comments in the code:

    // SDMacAdress is zero terminated
    // (it should be because you use strcp not strncp)
    // char arr[12]; you need one extra byte for the zero
    char arr[13];
    strcpy(arr, SDMacAddress);

    auto getNum = [](char c)
    {
      // you forgot upercase HEX letters (A-F)
      // don't use sophisticated code
      // the best programmers produce understandable code IMHO at least ;-)
      // perhaps you copied it from the internet
      // return c > '9' ? c - 'a' + 10 : c - '0';

      if ( c >= '0' && c <= '9' ) return c - '0';
      if ( c >= 'a' && c <= 'f' ) return 10 + c - 'a';
      if ( c >= 'A' && c <= 'F' ) return 10 + c - 'A';

      return 0;
    };

    byte *ptr = ByteMacAddress;

    for(char *idx = arr ; *idx ; ++idx, ++ptr )
    {
      *ptr = (getNum( *idx++ ) << 4) + getNum( *idx );
    }

body:
It is not clear why you are trying to implement it from scratch. If your input is always properly formatted you can perform the conversion in one call to `sscanf`

    char arr[] = "A4BDC334688C";
    byte ByteMacAddress[6];

    sscanf(arr, "%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
      &ByteMacAddress[0],
      &ByteMacAddress[1],
      &ByteMacAddress[2],
      &ByteMacAddress[3],
      &ByteMacAddress[4],
      &ByteMacAddress[5]);

Of course, you can also implement it [more elegantly] through a cycle, i.e. `sscanf` it one byte at a time.


body:
I've created a small project using an Uno. I usually mess around with ESP8266 chips, because they have WiFi and are relatively easy to work with. However, this time I've decided to go right back to the Uno.

I've made a clock using a bunch of MAX7219 matrix displays (32x8 total). I want to be able to sync the time from the computer to the Arduino, no matter which PC is connected.

My thought was to create a small program, that detects the connected Uno, then sends the data over serial. However, there's probably a more clever way to do that, which requires very little programming on the PC side.

Any clues? The Arduino is connected via USB. Would love this to work on both Windows and MacOS.

title: Send information from computer to Arduino via USB (basic clock)

Answers: 0


body:
I have a project with many components.  I'd like to use 12v adapter from wall.
I have a simplified experiment to apply to the actual project.  I can't find any info on the internet after days of searching.
I want to control each of 6 leds independently with an arduino. They all have different forward voltages.  But I would like them to be powered by the same 12v external power supply.  I suspect I would use transistors, Could someone point me in the right direction to wire these up?
I can figure out the code myself.

title: How to control multiple leds independently with arduino but they share a 12v external power source

Answers: 1

body:
The basic schematic for one LED is:

<!-- 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/gvfg7.png)

<!-- End schematic -->

Make sure that:

* R1 is the right resistance for the supply voltage, forward voltage, and desired current
* M1 has a threshold low enough that the Arduino turns it fully on.

Just duplicate the circuit for each LED you want to control. The code is no different to having an LED directly attached to the Arduino.


body:
I would like to stream pots data to a web browser using websockets.  I'm using WebSocketsServer on a Huzzah but sendTXT isn't working, but does for Connected WStype.  Is there a way to do this?   Partial code:

      // New client has connected
    case WStype_CONNECTED:
    {
      IPAddress ip = webSocket.remoteIP(client_num);
      Serial.printf("[%u] Connection from client: ", client_num);
      Serial.println(ip.toString());
      webSocket.sendTXT(client_num, "Server says Client is connected \r\n");
    }

    void loop() {
    int potValue =analogRead(A4);
    //Serial.println(potValue);
    webSocket.loop();
    }

javascript:

    /*----  WEBSOCKET SERVER CONNECTION    ------- --*/
    connect();

    function connect()
    {

    var socket = new WebSocket("ws://10.0.0.1:1337");

    try
    {
     message('
Socket Status: '+socket.readyState);

     socket.onopen = function()
     {
     message('
Socket open Status: '+socket.readyState+' (open)');
        }
        socket.onmessage = function(msg)
     {
      message('
Received: '+msg.data);
        }
     socket.onclose = function()
     {
        message('
Socket close Status: '+socket.readyState+' (Closed)');
     }
    }
    catch(exception)
    {
     message('
Error'+exception);
    }

    /* ----SEND TO SERVER -----*/

    $('.fan').click(function()
    {
     var idClicked = $(this).attr('id');
     console.log(idClicked);

     sendTo(idClicked);

    });

    function sendTo(idClicked)
    {
     socket.send(idClicked);
     message('
Sent: '+idClicked)
    }

    function message(msg)
    {
     $('#pots').html(msg+'
');
    }

title: ESP32 WebSocketsServer - stream pots data to web browser

Answers: 0


body:
I'm trying to understand if I can use the AD7476 with Arduino and SPI:

[datasheet][1]

My rough idea is that I should put CS low, then read two bytes using SPI.transfer() twice, and then bring CS high again. Is that correct?

But looks like the AD7476 doesn't have any buffer, so I guess timing must be really precise in order to not miss any bit?
what if SPI.transfer() occurs too late after CS going low?

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

  [1]: https://www.analog.com/media/en/technical-documentation/data-sheets/AD7476_7477_7478.pdf
  [2]: https://i.stack.imgur.com/zTPP6.png

title: AD7476 adc and SPI

Answers: 1

body:
> My rough idea is that I should put CS low, then read two bytes using SPI.transfer() twice, and then bring CS high again. Is that correct?

Yes, that is correct.

>But looks like the AD7476 doesn't have any buffer, so I guess timing must be really precise in order to not miss any bit?

No. The conversion is controlled *by the SPI clock*.  The ADC is a *successive approximation* ADC.  That means for each "sample clock" a more accurate approximation of the voltage is created. In this instance that "sample clock" is the same as the "SPI clock".  Each time you send one clock pulse a new, more accurate, approximation is created.

> what if SPI.transfer() occurs too late after CS going low?

Within reason, nothing untoward.

The way an SAR ADC works is it uses a DAC which is controlled by a clock to create a voltage. That voltage is halfway between 0V and "the current estimated voltage" (starting at "vref" - 5V in this case).  The voltage is compared with the "sampled" voltage (stored in a tiny capacitor). That forms one bit of the resultant value. At the next clock the DAC voltage is halved (and maybe added to the previous voltage depending on the previous comparison result) and repeated. This is the next bit of the result. It repeats with the voltage getting smaller and smaller and smaller.

Each time you clock one bit through your SPI interface it generates and compares the next voltage generating the next bit of data for you to read.

The knock-on effect of this is that there is both a maximum and a minimum frequency that you can use the SPI interface at.  Too fast and it is unable to generate the comparison voltages and do the comparison in time. Too slow and the internal capacitor loses charge through self-discharge and leakage current.  Thgis is why on page 8 of the datasheet it specifies a minimum and a maximum frequency for the SPI interface (10kHz to 20MHz).


body:
I would like to control my dc motor using the Arduino Uno WiFi Rev2 using an html range slider. Now I can control the motors speed and direction using push buttons just fine. My code is posted below of what I've done so far.

    client.println("");
    client.println("<input type=\"range\" class=\"class-name\" orient=\"vertical\" id=\"range\" min=\"0\" max=\"255\" step=\"0\" onchange=\"motor1(this.value)\" value=\"0\">");

This code below is the current button code. I need the below code to be used by the slider code above:

    if (currentLine.endsWith("GET /MONFWD")) {
    digitalWrite(MOTOR_A_ONE, HIGH);  // Establishes forward direction of Channel A
    digitalWrite(MOTOR_A_TWO, HIGH);  // ENGAGE BRAKE
    delay(1000);                      // DELAY BEFORE RELEASING BRAKE
    digitalWrite(MOTOR_A_TWO, LOW);   // Disengage the Brake for Channel A
    analogWrite(MOTOR_A_ENGAGE, 255); // Spins the motor forward on Channel A at full speed

title: Control DC Motor with Arduino Uno WiFi Rev2 Html Slider Code

Answers: 1

body:
**Here's an example of slider that changes a Servo speed,**
**In html page code you have to add this:**

      <input type="range" min="0" max="1023" value="512" class="slider" id="myRange">

Value:

**In arduino you have to define handler like this:**

    void handle_pwm() {
     String  pwm_val = server.arg("PWMval"); // reading from slider on html pagae

     Serial.print("slider val: ");
     Serial.println(pwm_val);
    int pwm_value = map(pwm_val.toInt(), 0, 1023, 0, 180);
    Servo.write(pwm_value);

    server.send(200,"text/plane","0"); // handling the webpage update

    }

**And define servo and handler in Setup() section:**

    void setup(void){
    ....
    Servo.attach(MotorPin,1000,2000);
    server.on("/setPWM", handle_pwm);
    ....
     }


body:
I have this board:

[![Arduino Leonardo Beetle mini board][1]][1]

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

It has the `atmega32u4` chip.

I have updated its code several times, and used it without issues for several months. Today, while updating (using Arduino IDE) it started to throw some errors. At the end it said that the checksum didn't match, so I repeated again few more times with the same behavior until it reported "Uploaded" without errors. I used for few minutes and it was working as expected. Then, I had to do another update and the same happened (checksum didn't match). However this time I got to the point in which it was no longer detected by the OS (Ubuntu), and no LED is turning on.

Whenever I connect it to the USB port, I can only see in the logs:

`usb 1-9.4: new full-speed USB device number 9 using xhci_hcd`

However `/dev/ttyACM0` is not longer created.

I'm trying to use `avrdude` to reset it, but it is reporting:

`avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory`

which make sense as `/dev/ttyACM0` doesn't exists. So, what are my options? Is there anything I can do to make it work again?

**UPDATE**

I didn't realize that this board has a reset marked as "RES". Following `Juraj` recommendation I bridged `RES` and `GND`. The LED marked as "SDA" turns ON after I release the contact and I can read in the logs:

```
[1212051.679205] usb 1-9.4: USB disconnect, device number 22
[1212058.532030] usb 1-9.4: new full-speed USB device number 23 using xhci_hcd
[1212058.621972] usb 1-9.4: New USB device found, idVendor=2341, idProduct=0036
[1212058.621982] usb 1-9.4: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[1212058.621988] usb 1-9.4: Product: Arduino Leonardo
[1212058.621994] usb 1-9.4: Manufacturer: Arduino LLC
[1212058.622933] cdc_acm 1-9.4:1.0: ttyACM0: USB ACM device

```

Which I think its good news. However, it seems ttyACM0 becomes available for few seconds. I was able to upload the Blink example into the chip and I can confirm its working because its blinking. Still the ttyACM0 disappears after few seconds.

Output of `avrdude -c avr109 -p atmega32u4 -P /dev/ttyACM0` :

```
Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.00s
avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: safemode: Fuses OK (E:FB, H:D8, L:FF)
avrdude done.  Thank you.
```

title: It is possible to revive my Arduino Leonardo (mini beetle) board?

Answers: 1

body:
Probably you have overwritten your Bootloader.

Connect MOSI, MISO, SCK and RESET to an ISP-Programmer and flash the file
Caterina-LilyPadUSB.hex
to it.

There are lots of tutorials on the net how to use a spare arduino as an ISP-Programmer.


body:
I have a problem with stepper motor direction.

I want to change the direction of the stepper motor rotation, when the stepper motor shaft is stuck.

For example, when I hold the shaft of the stepper motor with my hand, the direction should change.

How can I do it?
Someone told me you should calculate the current, but I don't know how to do this?

My material components:

 - Arduino
 - stepper motor gearbox 12 V
 - ULN 2003A

title: Stepper Motor Direction via Flow Amps

Answers: 1

body:
When motors stuck their current draw increases, you can sense that increase in the current and then change the rotation of the motor. The simplest way to measure current is with using a shunt resistor, for sensing high currents, current sensors based on hall effect sensors is usually used. [ACS712][1] is one example.

How to sense current using a shunt?

Basically we're measuring the voltage drop over a resistor (RS), but the voltage drop is too small for Arduino to measure so we need an opamp to "amplify" the input:

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

The schematic above is the simplest way to measure the voltage drop at "LOW SIDE", there is differential mode and "HIGH SIDE" measurement methods.

The gain of opamp can be set with resistors and this formula:

VOUT = (1 + R2/R1) * V1

The output of opamp then can be calculated to get current using ohm's law:

I = V / R

A simple code to calculate current:

    int rawAnalog;
    float voltageDrop;
    int resistor = 0.1;
    float current;

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

    void loop() {
      rawAnalog = analogRead(A0); // Read A0 input
      voltageDrop = (rawAnalog * 5) / 1024; // Convert the raw value to voltage
      current = voltageDrop / resistor; // calculate the current
    }

Bonus: [INA219][2] is an easy to use high-side I2C module which can measure both current and voltage.

  [1]: https://www.sparkfun.com/datasheets/BreakoutBoards/0712.pdf
  [2]: https://www.adafruit.com/product/904