body:
I'm using a capacitive touch sensor that as 12 touch points and stores it's state data as a binary number.

[![getting the touch state][1]][1]

I want to take that state, add a bit of data onto the front, and then send it up to a server via websockets. I'm using the [Arduino Websockets](https://github.com/gilmaimon/ArduinoWebsockets) library for my websocket client.

The library has a `sendBinary` method that allows you to provide a character pointer for the data.

[![sendBinary declaration][2]][2]

So, I wrote a function that makes a new 32 bit unsigned integer, adds my metadata, then the touch state, and then attempts to take the address of the payload integer and cast it to a character pointer:

```cpp
void sendTouchStateToServer()
{
    Serial.println("sending state to server");

    uint32_t payload = touchControllerMessageType << 12;
    Serial.println(payload);
    payload |= currentTouchState;

    Serial.print("Payload contents: ");
    Serial.println(payload);
    Serial.print("Payload contents cast as character pointer: ");
    Serial.println((char *)&payload);
    Serial.print("Payload size: ");
    Serial.println(sizeof(payload));

    client.sendBinary((char *)&payload, sizeof(payload));
}
```

The issue is that while the integer version of the payload looks fine, when I try to cast it into a character pointer the contents is wrong.

[![garbled output][3]][3]

I've also tried creating a `payloadPointer` and directly set the address of the integer as the pointer address, but this also fails.

[![direct pointer addressing (I think)][4]][4]

(I should take this moment to say I'm still pretty green to arduino cpp concepts like this).

What's the right way of doing this? I'm reading up on pointers and trying to understand how to properly do it, but I can't quite figure it out. Could someone explain the correct way of doing it and why? I want this to work, but more than that I want to understand the "why and how" of the proper way.

Thanks! :bows:

  [1]: https://i.stack.imgur.com/nmsW1.png
  [2]: https://i.stack.imgur.com/xw8y1.png
  [3]: https://i.stack.imgur.com/TCDkv.png
  [4]: https://i.stack.imgur.com/OkfM0.png

title: Issues converting an uint32_t into a char*

Answers: 2

body:
Your code with `sendBinary` is probably fine, as long as on the other side you _also_ use a function that expects to receive exactly 32 bits of binary data (in little-endian format).

Trying to print `(char*)&some_32bit_int` on the other hand will not do anything useful.

The short version is this:

- if you want to send (or receive) binary data, use functions made for binary data - they will usually take a pointer to `char` (or `uint8_t` or something like that) _and a length_.
- if you want to send (or receive) strings, use functions meant for strings. They'll sometimes take `String`, or `std::string` or, unfortunately perhaps, `char *` for C strings.

Never mix both.

Functions that expect a (C) string expect it to actually _be_ a C string, i.e. a sequence of chars ending with a null byte (`0x00`). The chars are expected to be mostly ASCII printable characters. If you give them just plain raw data like the memory address of an `int`, you won't get what you want.

Trying to print raw data using a function that expects a C string will result in garbage (or nothing at all, or a lot more garbage than you expected!). (Details in the second part.)

If you want to format your data into a string for sending (using a string/text protocol), then use functions like `sprintf` to do the conversion. (Or use a library that does JSON if your receiver is a web thing - that's pretty handy.)

e.g.

    char buffer[32];
    sprintf(buffer, "{data:%d}", payload);

Then send `buffer` via a function that expects a C string.

---

Consider this:

    uint32_t payload = 0x00323130;

The first line initializes a 32 bit int to a specific value, `0x00323130` in hex. Now let's assume that `payload` was stored in memory at address `0x0100`. The memory after that assignment would look like this:

    Addr.  Val
    0x0100 0x30  // our same number 0x00323130 stored in little-endian format
    0x0101 0x31
    0x0102 0x32
    0x0103 0x00

When you do:

    client.sendBinary(&payload, 4);

Those four bytes get send over the wire (or the air) exactly as they are. Nothing more, nothing less. If that's what the receiver expects you're golden.

Now if you do:

    Serial.println((char *) &payload);

`Serial.println` is an overloaded function. When you give it a `char *`, it expects a C-string, which is a series of characters terminated by a "null byte", i.e. a byte value of zero. `Serial.println` will then look at the first byte pointed to by the argument. If it's zero, it stops. Otherwise it outputs that char to the serial line, and moves on to the next character. Repeat until a zero byte is found.

In the specially crafted case here with that specific value of `payload`, `Serial.println` would receive address `0x0100` and:
- Look at the value at `0x0100`, get `0x30`, check that it's not zero, and pass it on to the serial line. Serial monitor would receive `0x30` and display that. By lucky coincidence this is the ASCII character code for the digit "0".
- Look at the value at `0x0101`, get `0x31`, check that it's not zero, and pass it on to the serial line. Serial monitor would receive `0x31` and display that. By lucky coincidence this is the ASCII character code for the digit "1".
- Look at the value at `0x0102`, get `0x32`, ... serial monitor displays "2".
- Loot at the value at `0x0103`, get `0x00`. That is a null byte, so it stops there, and sends a newline sequence to the serial.

So in this fabricated scenario the output on the serial monitor would be "123".

Try it with `payload = 0x00616263;` - serial monitor will display "cba".

In short, `Serial.println` will output exactly the bytes it finds in memory to the serial, until it encounters a zero byte. The serial monitor will try to display those bytes. But, unless you've crafted those values very carefully, all you'll get out of it is garbage - relatively few 8bit values map to printable characters, and even when they do they won't "look" anything like the raw data you had.

If your number happens to start with a zero byte in its binary little-endian representation, `Serial.println` won't print anything - like if you had given it an empty string.

If your number _doesn't_ contain a zero byte, it will keep on reading memory past the storage allocated for `payload` until it finds one - possibly outputing much more "junk" than a 32bit variable could ever contain.

body:
The sending with `client.sendBinary((char *)&payload, sizeof(payload));` is OK.

Your attempts to print binary data are wrong.

A `print()` of the 4 bytes of uint32_t as char array will print 4 characters which ASCII codes are in those 4 bytes and then continue print characters from memory after the variable, until a byte with 0 is read. Some of the characters can be a not printable terminal control characters.

A `Serial.write((char *)&payload, sizeof(payload));` will print 4 characters which ASCII codes are in those 4 bytes.

The simplest way to visualize your binary payload is `Serial.println(payload, BIN);`. This will print the uint32_t value in binary.


body:
I am trying to program a 4DOF robotic arm (using 4 servo motors). I would like to move the servos using an Android app, by means of bluetooth (HC-05).

I developed the app, in whose interface there are 7 buttons (Up, Down, Left, Rght, Forward, Backward, Save) and a field in which you can type using the keyboard (I attached an app interface screenshot).

So far, I tried to manage only Up button (which senses 'U' via bluetooth to Arduino) and Down (which sens 'D'), which would move the servo intended for vertical arm movements. That code works quite well, although the app crashes sometimes, but I still can't figure the reason out. Using the println() function I can see that Arduino reads in the bluetooth input the character '⸮ ' , what does it mean? I use a baud rate of 9600.

Then, what I would like to do is: once I have moved the servo and reached a particular position, I'd like to save the position of the motor into an array. In order to allow multiple positions saving, after Save button is pressed, I want Arduino to wait for another input from the bluetooth (so that, it would wait for another button to be clicked from the app or for something typed into the dedicated bar from keyboard) that defines the position within the array, in which I save the servo position (eg: I type '2' into the dedicated app bar and Arduino, which is waiting for an input, receiving it, saves the last servo position into the array servo01pos[2]). I wrote the "case ('S')" code that is quite long and inefficient but, at least, it works.

Thanks in advance to anyone who will help me.

Giammarco
```c++

#include <SoftwareSerial.h>
SoftwareSerial bluetooth(10, 11); //BlueTooth RX ,TX
#include <Servo.h> // servo library

unsigned long timestampSend = 0; // BT Write wait period
String readString;
Servo servo01; // servo name
byte pos01 = 90;
#define ANGLE_STEP 10 // 10 degree steps
int servo01pos\[50\];
char data;
char button;
int x = 1;

void setup() {
  Serial.begin(9600);
  bluetooth.begin(9600);
  delay(1000);
  Serial.println("Ready ...");
  Serial.println ("\n");
  servo01.attach(12);
  servo01.write(pos01);
}

void loop() {
  do {
    if (bluetooth.available() > 0) {
      Serial.println(data);
      do {
        delay(500);
        data = bluetooth.read();
        Serial.println(data);
      } while (bluetooth.available() > 0);
      if (data == 'U' || data == 'D' || data == 'L' || data == 'R' || data == 'F' || data == 'B' || data == 'S' || data == 'X') {
        Serial.print("Received value: ");
        Serial.println(data);
        switch (data) {
          case ('S'): //SAVE
            Serial.println("Enter the button you desire to set...");
            do {
              data = 254;
              bluetooth.listen();
              button = bluetooth.read();
              if (button == '0' || button == '1' || button == '2') {
                data = 'S';
              }
            } while (data != 'S');
            Serial.println("SAVING POSITIONS ...");
            if (button == '0') {
              servo01pos\[0\] = pos01;
            } else if (button == '1') {
              servo01pos\[1\] = pos01;
            } else if (button == '2') {
              servo01pos\[2\] = pos01;
            }
            servo01.write(pos01);
            Serial.println(button);
            Serial.println(pos01);
            Serial.println(servo01pos\[1\]);
            Serial.println(servo01pos\[2\]);
            Serial.println(servo01pos\[0\]);
            //}
            break;

          case ('U'):
            Serial.println("UP");
            if (pos01 <= 180 - ANGLE_STEP) {
              pos01 = pos01 + ANGLE_STEP;
              servo01.write(pos01);
              Serial.println(pos01);
              delay(20);
              Serial.println(data);
            }
            break;

          case ('X'):
            Serial.println("EXIT");
            x = 0;
            break;
        }
      }
    }
  } while (x != 0) ;
}

```
[![App interface][1]][1]

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

title: Movement and storage of servo positions via bluetooth

Answers: 1

body: The character '⸮ ' was given everytime there was a power outage. So, it is enough to use an external power supply to power bluetooth and servos (Arduino cannot power all those modules simultaniously).


body: I want to make a next version of my current project. I’m hoping to use an Arduino compatible processor that also supports at least 2 processes simultaneously without using pro threading or any other software workaround. The more commonly used the processor is, the better the user support will be if something goes wrong.

title: What’s the most common (and low cost) microprocessor with at least two threads?

Answers: 2

body: ESP32.  Dual core 240MHz, plus an extra XLP state machine.  Cheap and easily available on eBay/Amazon/Ali Express etc.  And with full Arduino support.

body:
You *may* also be interested in the Teensy 4.0. It *is* single-threaded (one CPU core), but it executes two instructions at a time if possible and runs at 600 MHz.

Beyond that, I only know of the ESP32 as well, for genuinely having two threads. Beware, if you want to design a product using that there might be extra hurdles with the FCC/whatever your country has since it is a radio emitter. Using an ESP32 module might simplify things, but I have very little idea how the legalities work.

It also seems a little wasteful to use a processor with Bluetooth and WiFi capabilities just because you need two threads, but it may be the only option.


body:
I am am trying to make a code which automatically controls relay on basis of ultrasonic sensor measurements. I am using a nodeMCU as a microcontroller rather than an arduino. The relay and the ultrasonic sensor is being powered from a 5V source and nodemcu from a 3.3V Source. I don't think none of the sensors are interfering with each other as all the sensors are kept at a distance[![enter image description here][1]][1]. Due to the random values my relay is being latched without any reason.
Can someone please help me out with the problem. I don't want these values(above 3000) being shown in the serial monitor.

```
#define TRIGGER 5
#define ECHO    4
#define RELAY   0

void setup() {
  Serial.begin(9600);
  pinMode(TRIGGER, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);
  pinMode(RELAY, OUTPUT);
}
void loop() {
  long duration, distance;
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, LOW);
  duration = pulseIn(ECHO, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance < 30 ){
    digitalWrite(RELAY, HIGH);
  }else{
    digitalWrite(RELAY, LOW);
  }

  Serial.print("Centimeters: ");
  Serial.println(distance);

}
```

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

title: Ultrasonic Sensor(HC-SR04) recording random distance

Answers: 1

body:
These random values could be nothing but noise as your receiver may be sensing other source of ultra sound. In your case, the circuit is especially sensitive as the output powers a relay and any noise in the input side will cause the relay to "chatter". There are many approaches to filtering and smoothing out the signal. One method would be to implement a basic averaging algorithm where you take several readings and then average out the result. Compare this result with the threshold and the output should be smoother.

**EDIT**

Here is a rudimentry example, where I take multiple readings (```nb_measurements``` measurements) and then take the average over it:
```
long getDuration() {
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, LOW);
  return pulseIn(ECHO, HIGH);
}

void loop() {
  float duration = 0, distance = 0;
  int nb_measurements = 10;
  for (int i = 0; i < nb_measurements; i++) {
    duration += getDuration();
  }
  duration = duration/nb_measurements;
  distance = (duration / 2) / 29.1;

  if (distance < 30 ){
    digitalWrite(RELAY, HIGH);
  } else{
    digitalWrite(RELAY, LOW);
  }

  Serial.print("Centimeters: ");
  Serial.println(distance);

}
```
Due to the extra processing, this will be in theory slower than your previous code but in practice, you wouldn't perceive it as long as you keep ```nb_measurements``` at a reasonable value. There are more complex digital signal filtering algorithms, search around and you can find good documentation and libraries online.


body:
For a project I would like to be able to control my RA8875 display driver as quick as possible using an Arduino due.

I started from the [Adafruit library][1] and replaces all  "digitalWrites" with direct port manipulation.

Apart from that I wanted to also use that maximum possible SPIspeed.
In the adafruit [datasheet][2] I didn't find any specification of the maximum SPIspeed of the controller. In an older datasheet I only found the max speed in relation to the system clock. But I have no idea what that is. [![enter image description here][3]][3].

After googling, the max spi speed of the RA8875 seems to be 12Mhz ([source][4]).

So I decided to just try different SPIspeeds. Though I do found the library's [Adafruit_RA8875.cpp file][5] a bit confusing since it defines *uint32_t spi_speed* multiple times based on the architecture.
- Once starting at line 48
- Once starting at line 134
- Once starting at line 164

And the chosen speeds for each architecture are not consistent between those 3 assignments.

I decided to replace line 66:

> SPI.beginTransaction(SPISettings(spi_speed, MSBFIRST, SPI_MODE0));

with:

> SPI.beginTransaction(SPISettings(12000000, MSBFIRST, SPI_MODE0));

and tried other speeds. But it always resulted in a black screen on my display.

  [1]: https://github.com/adafruit/Adafruit_RA8875
  [2]: https://cdn-shop.adafruit.com/datasheets/RA8875_DS_V12_Eng.pdf
  [3]: https://i.stack.imgur.com/jEcCR.png
  [4]: https://github.com/sumotoy/RA8875/wiki/About-RA8875-SPI-Speed
  [5]: https://github.com/adafruit/Adafruit_RA8875/blob/master/Adafruit_RA8875.cpp

title: Maximizing SPI-speed between Arduino DUE and RA8875 display driver

Answers: 1

body: To speed up the RA8875, you should start with small clock frequency to initialize the RA8875 including the pll configuration and then you can make the clock frequency faster. It works with me.


body:
I got a beginner level problem.

I got two [esp2866 nodeMCU](https://www.amazon.com/ESP8266-NodeMcu-Internet-Development-Micropython/dp/B07L8W9SP3/ref=as_li_ss_tl?ie=UTF8&linkCode=sl1&tag=gswwl-20&linkId=9c1489c61f8470102c3754f8472241e6&language=en_US), they both work with the usb cable and I can get the blink program to run though it.
Running them with external power doesn't seem to work though. I expect the blink program to run when I plug them in but I get no led light signal at all. My power source looks identical to [this](https://www.banggood.com/sv/MB102-Breadboard-Power-Supply-Module-Adapter-Shield-3_3V5V-p-996801.html?utm_source=googleshopping&utm_medium=cpc_organic&gmcCountry=SE&utm_content=minha&utm_campaign=minha-se-sv-pc&currency=SEK&cur_warehouse=CN&createTmp=1&utm_source=googleshopping&utm_medium=cpc_union&utm_content=xibei&utm_campaign=xibei-ssc-se-all-0716&gclid=CjwKCAiA7939BRBMEiwA-hX5J9gVWi65P85-IPsxaOFKIKzzY0FjG7xe9pbvaF9Poin_yIG2jhBp_BoC4eUQAvD_BwE). I got jumpers set on 5V. I don't have a voltage meter but I've tested against my Arduino Uno and it runs as expected when connected to the same wires.

1. Shouldn't I get the blink signal or any other led signal if the nodeMCU got power?
2. Any clue to how I could fail to provide power?

thank you!

edit: picture and jack barrel power input: 5V 3A
[![no power to the nodeMCU][1]][1]

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

title: esp2866 powered externally not working

Answers: 2

body:
Linear Regulator Dropouts
-------------------------
The linear voltage regulators found on that board are going to expect more than 5V at the barrel jack, because they require a minimum "drop out" voltage.  The AMS1117 that is on that board, so far as I can tell, has a drop out voltage up to 1.3V.  So you would want at least 6.3V (perhaps better 7V) at the barrel jack in order to get 5V out of it.

So the NodeMCU board may be seeing 5 - 1.3 or 3.7V at the input to its 3.3V regulator, which also requires its own drop out.  The output of that 3.3V regulator may then be significantly below what the esp8266 specified operating voltage range.

UPDATE
------
So I did the tests mentioned in the comments, just to illustrate the problem.  And the results are about as expected.

I altered the stock blink sketch that comes with IDE version 1.8.13 to use LED_BUILTIN (as opposed to 9) in the pinMode and digitalWrite calls.

I changed the LOW period, which is LED ON for my board, to 10000ms so that my voltmeter would have time to settle on a voltage test across the LED.

And I uploaded to the board, a NodeMCU 1.0 clone by Hitletgo.

When powered on its USB micro b jack, 3.3V labeled pin of the broad measuring 3.30 V.  The LED color is blue, it is bright and it is dropping 2.66V.

Then I switched to powering the NodeMCU board by via of VIN pins from the YwRobot regulator board.  I provided 5.05V to the barrel jack.  To not great surprise, it does not blink.

The voltage out of regulator board was 3.26V.  To be clear, I have this jumper for 5V.  As a sanity check, I jumpered it for 3.3V and got about 2.5V out of it.  Again, this is unsurprising because it also needs a dropout voltage.

I then measured the "3.3V" header line on the NodeMCU itself to be 2.14 V.  Without sufficient voltage into the 3.3V regulator, it is not providing 3.3V out.  And what it is producing is below that LED forward voltage when lit.  So it is not surprising that it is not lit.

The ESP8266 technical specifications suggest that it can run down to 1.8V.  So just for the hell of it I connected the board back to USB and updated the blink sketch to "blink" D8 (or GPIO15) 4 seconds on, 4 seconds off.  I did not attach anything to this pin except the voltmeter.

I then reconnected the board to the test rig and found with a meter that it is "blinking" D8 just fine with a logic level consistent with the voltage the ESP8266 is actually receiving.

So in summary, the arrangement here is running the ESP8266 but there is not enough available voltage for it to light the LED.  And it is very likely the exact same thing is happening for you.

body: Think of Vin like a car, not enough gas and you will not get there. Over fill it and you could burn it up.


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

So I've recently started Arduino and I just had a question about the digitalRead() function.

Does the IO Pins read Voltage or Current?

The reason I'm asking is because of the attached circuit.

So IO pin 7 is HIGH when the button is not pressed because the resistor is connected to 5V through the resistor. When the button is pressed the button is shorted to ground and is LOW. Why does it read LOW? Surely it would still read 5v because it is still connected to 5V through the resistor?

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

title: Do the I/O pins on Arduino read current or voltage?

Answers: 1

body:
They read voltage.  When you close the pushbutton switch the input should have a 0V or digital "0" on it.  When you open the pushbutton the resistor should pull the input to 5V or digital "1".

Yes, it is still connected to +5V via the resistor but the nearly 0 Ohm switch pulls the line all the way (or very close) to 0V.


body:
My 3d printer, Creality Ender 4, has an ATmega 2560 chip based card, and I need to identify the number associated with a particular Pin.
I read, on the official Arduino website, a simple tutorial in which through a small led connected to two pins of the card, you wrote a code (sketch) that made it turn on, but you had to know the Pin number.
I would like to do this on my board, I unplug all cables (power supply, motors, etc.) and connect it to the PC via USB and from Arduino IDE, I execute the code, connecting the LED on the ground and on the signal (see image).[![enter image description here][1]][1]
To identify the Pin number I thought I would go to exclusion, because I know all the PIN numers of the chip, until the LED lights up.
So I ask, is that correct? is there a chance of damaging the card? or is there a better method?
Thanks in advance

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

title: How to identify pinout of ATmega 2560 derivative board?

Answers: 1

body:
Disconnect everything but the switch.<br>
Run this:

    for each pin,
      set the pin to INPUT_PULLUP mode;
      do,
        read and print the pin number and pin state;
      until operator touches a key;
      read and discard the serial input;
    end;

You do:
 - Each time a new pin number prints on the terminal,
  toggle the switch a few times to confirm whether you are seeing the result of your actions.
 - If not, touch the spacebar to try the next pin #
 - else, you found it.


body:
I would like to control a toy car from the server. I use RadioHead library for communication and it works fine.

The application running on the server side is as follows.

    #include <RHReliableDatagram.h>
    #include <RH_ASK.h>
    #include <SPI.h>

    #define SERVER_ADDRESS 1
    #define ROBOT_ADDRESS 2
    #define GO_RIGHT "Go right"
    #define GO_LEFT "Go left"
    #define GO_FORWARD "Go forward"
    #define GO_BACK "Go back"
    #define STOP "Stop"
    #define SERVER_DELAY 500

    unsigned int transmitterPin = 10;
    unsigned int receiverPin = 12;

    RH_ASK transmitterServer(2000, receiverPin, transmitterPin, 0);

    RHReliableDatagram radioCommunication(transmitterServer, SERVER_ADDRESS);

    void setup()
    {
        Serial.begin(9600);
        if (!radioCommunication.init())
            Serial.println("Radio communication failed");
    }

    uint8_t buffer[RH_ASK_MAX_MESSAGE_LEN];

    void sendData(uint8_t * data, uint8_t length)
    {
        Serial.println("I'm sending commands to the robot");

        // Send a command to the robot
        if (radioCommunication.sendtoWait(data, length, ROBOT_ADDRESS))
        {
            // Now wait for a response from robot
            uint8_t from;
            if (radioCommunication.recvfromAckTimeout(buffer, &length, 2000, &from))
            {
                Serial.print("I've got - ");
                Serial.print((char*) buffer);
                Serial.print(" - message from the robot whose addres is : ");
                Serial.print("0x");
                Serial.println(from, HEX);
            }
            else
            {
                Serial.println("No response. Does the robot works?");
            }
        }
        else
            Serial.println("Attempt to resend data failed.");
        delay(SERVER_DELAY);
    }

    void loop()
    {
        sendData(GO_RIGHT, sizeof(GO_RIGHT));
        sendData(GO_LEFT, sizeof(GO_LEFT));
        sendData(GO_FORWARD, sizeof(GO_FORWARD));
        sendData(STOP, sizeof(STOP));
        sendData(GO_BACK, sizeof(GO_BACK));
        sendData(STOP, sizeof(STOP));
    }

The application running on the robot is as follows.

    #include <RHReliableDatagram.h>
    #include <RH_ASK.h>
    #include <SPI.h>

    #define SERVER_ADDRESS 1
    #define ROBOT_ADDRESS 2
    #define GO_RIGHT "Go right"
    #define GO_LEFT "Go left"
    #define GO_FORWARD "Go forward"
    #define GO_BACK "Go back"
    #define STOP "Stop"
    #define RIGHT_LIGHT 4
    #define LEFT_LIGHT 7
    #define FORWARD_LIGHT 8

    unsigned int receiverPin = 2;
    unsigned int transmitterPin = 12;

    RH_ASK robotTransmitter(2000, receiverPin, transmitterPin, 0);
    RHReliableDatagram radioCommunication(robotTransmitter, ROBOT_ADDRESS);

    void setup()
    {
        Serial.begin(9600);
        pinMode(RIGHT_LIGHT, OUTPUT);
        pinMode(LEFT_LIGHT, OUTPUT);
        pinMode(FORWARD_LIGHT, OUTPUT);

        if (!radioCommunication.init())
            Serial.println("Radio communication failed");
    }

    uint8_t buffer[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t command[RH_ASK_MAX_MESSAGE_LEN];

    void moveRight()
    {
        Serial.println("------------");
        Serial.println("I'm going right");
        Serial.println("------------");

        /*
           // Time consuming task

        for (int i = 0; i < 3; ++i)
        {
            digitalWrite(RIGHT_LIGHT, HIGH);
            delay(1000);
            digitalWrite(RIGHT_LIGHT, LOW);
            delay(1000);
        }

        */
    }

    void moveLeft()
    {
        Serial.println("------------");
        Serial.println("I'm going left");
        Serial.println("------------");

        /*
           // Time consuming task

        for (int i = 0; i < 3; ++i)
        {
            digitalWrite(LEFT_LIGHT, HIGH);
            delay(1000);
            digitalWrite(LEFT_LIGHT, LOW);
            delay(1000);
        }

        */
    }

    void runCommand(char* command)
    {
        if (strcmp(command, GO_RIGHT) == 0)
        {
            moveRight();
        }
        else if (strcmp(command, GO_LEFT) == 0)
        {
            moveLeft();
        }
    }

    void loop()
    {
        uint8_t response[] = "OK";
        if (radioCommunication.available())
        {
            uint8_t length = sizeof(buffer);
            uint8_t from;
            if (radioCommunication.recvfromAck(buffer, &length, &from))
            {
                Serial.print("I got - ");
                Serial.print((char*) buffer);
                Serial.print(" - command from the server whose addres is ");
                Serial.print("0x");
                Serial.println(from, HEX);
            }
            // Send the message to the server (with retries) and wait for an ack.
            if (!radioCommunication.sendtoWait(response, sizeof(response), from))
                Serial.println("Repeated attemps to send data to server failed");
            strncpy(command, buffer, sizeof(command));
            runCommand(command);
        }
    }

As it stands, the serial output of robot is as follows:
[![radiohead serial][1]][1]

Let's increase the `SERVER_DELAY` variable to `2000`. This way the server will send a command every two seconds.

Besides this, let's run a command that will take some time on the robot. To do this we might uncomment time consuming task lines.

So that, when the robot receives `Go right` command, it will try to turn on and off lights three times.

After making these changes let's look at the serial output of robot.

[![Robot serial output][2]][2]

What happens is, after receiving the `Go left` command it tries to blink `LEFT_LIGHT` three times. But meanwhile it misses `Go forward` command. And again after receiving the `Go right` command it tries to blink `RIGHT_LIGHT` three times but misses `Go left` command.

What I would like to do is when robot receives a new command, it should stop whatever it was doing and execute the new command.

How should I do this? Any ideas. Thanks.

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

title: RadioHead library change the state when a new message is received

Answers: 1

body:
An easy-enough fix would be to replace your `delay` calls with something that regularly checks if data is available from the server.

Something like:

    /* returns true if the sleep was interrupted by incoming data */
    /* warning: does not wait at all if data is available */
    bool interruptible_delay(unsigned long ms)
    {
      unsigned long end = millis() + ms;
      while (millis() < end) {
        if (radioCommunication.available()) {
          return true;
        }
        delay(10); /* tune to taste */
      }
      return false;
    }

This should work as long as the innner delay is much shorter than your communication timeouts.

You will most likely need to handle the case where the sleep was interrupted in your "action" functions if they become more complexe than a led blink. I.e. if your action is a series of complex motor moves, and a message arrives in the middle, you need to design the function so that it is in a safe or neutral state before returning to the main loop.


body:
I searched for ov2640 with Arduino examples but only I could get the examples of Arducam. So I'm trying [**this**][1] example with [**OV2640**][2] camera. As ov7670 and ov2640 have similar pinouts. But I'm not getting the image(output)(But I got the output while using [**OV7670**][3] camera). I don't know why I'm not getting the output. Someone please let me know where do I go wrong(Reference image attached) and please let me know any other example you may know.

Thank you,
Roshan

[![OV2640 Camera][4]][4][![Connections][5]][5][![Circuit Board][6]][6][![Circuit Diagram][7]][7]

  [1]: https://circuitdigest.com/microcontroller-projects/how-to-use-ov7670-camera-module-with-arduino
  [2]: https://robokits.co.in/sensors/camera-module/ov2640-2-megapixel-camera-module-support-esp32-cam-development-board?gclid=Cj0KCQiAkuP9BRCkARIsAKGLE8XUbVp3GJtFd655gelnjPUf-wYwZ8LTPsn8y2tbXAyuAQXl0prg-r4aAkoYEALw_wcB
  [3]: https://robokits.co.in/sensors/ov7670-vga-sensor-camera-breakout-board
  [4]: https://i.stack.imgur.com/50BUS.jpg
  [5]: https://i.stack.imgur.com/c72yT.jpg
  [6]: https://i.stack.imgur.com/fpaom.jpg
  [7]: https://i.stack.imgur.com/IbRgm.jpg

title: OV2640 Camera example with Arduino

Answers: 0


body:
So, i need to send sound sensor data from an Arduino Uno to the ESP8266 (ESP-01), so it can output a push notification to my phone whenever there's a loud noise. I have the sensor just powered and hooked up to the Analog 0 pin, and the ESP powered and hooked up to the Arduino Serial pins in reverse (RX to TX, TX to RX)

This is the code i have on the Arduino:

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

    void loop() {
      Serial.write(analogRead(A0) + "\r\n");
      delay(100);
    }

And this is the code i have on the ESP:
(i'm omitting the notification part for clarity, it doesn't even use Serial, so i don't think it should interfere)

    void setup() {
      Serial.begin(115200);
    }
    void loop() {
      String val;
      val = Serial.readString();
      if( val.toInt() < 50 ){ sendNotification("Hello!"); delay(10000);}
    }

I have tested the Sensor output and it seems fine, whenever i snap or clap the readings show a peak (although reversed, it stays on 1023 constantly then peaks to around 0~50), and the ESP can also send notifications normally. But the trigger on the notification never seems to fire, so i guess the ESP is not receiving the data properly.

I'm new-ish to Arduino, so i don't know if i'm doing something wrong here,
Thanks in advance!

title: How to send Serial data from an Arduino Uno into the Serial of an ESP-01?

Answers: 1

body:
Writing Junk From Memory
========================
```cpp
Serial.write(analogRead(A0) + "\r\n");
```

This is advancing a pointer to "\r\n" by whatever number is being returned by analogRead.  In other words, you are not sending the measurement but junk from memory after (or sometimes at) `"\r\n"`'s memory location.

`Serial.println(analogRead(A0));` appears to be what you were going for here.  `println`'s line termination for the UNO serial connection is `"\r\n"`.

Logic Levels
============

When it comes to attaching the serial connections together, there should be some level conversion going on.  Because an UNO's pins are 5V logic levels and the ESP-01 expects 3.3v levels.


body:
I had a problem when installing the esp32 core. I couldn't do it through the board manager procedure because I can't find esp32 for installation in the board manager even though I put the link correctly in the preferences section so I had to download a zip file and unzip it in hardware/espressif/esp32 folder. Now whenever I try to upload the code(a simple LED blinking code) it says error compiling for board with the following error message
exec: "C:\\Users\\ABDUL\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/xtensa-esp32-elf/bin/xtensa-esp32-elf-g++: file does not exist
Please help me. I don't know what to do anymore

title: Error uploading to esp 32 board

Answers: 0


body:
I've been trying, for over a week now, to create a program that will store my keypad presses into variable, and with a press of an enter, it will switch to the next variable to store the presses. The program is made to load addresses (mainly IP addresses) to different devices over serial connections. Because there are different types of addresses, each time the user press enter in the keypad (made the # button to a '\r' char) the program needs to switch to the next type of address and get the key presses from the keypad and store them until the next '\r' press. My problem is that I don't know how to store those addresses in the Arduino, and switch to a different "char" (I used char because I didn't knew how to convert them to store key presses into string) every '\r' press. I've included the handler for this part of my code. This is my first post here so if anything is missing let me know. thanks ahead.

    bool handlerManualEntry( void )
    {
        static uint8_t stateManualEntry = statesFunc::ST_INIT;

        char keyval = ReadKey();
        switch( stateManualEntry )
        {
            case    statesFunc::ST_INIT:
                //do whatever inits you need here (screen, variables etc)

                stateManualEntry = statesFunc::ST_RUN;

            break;

            case    statesFunc::ST_RUN:
                //is there a keypress?
                if( keyval != NO_KEY )
                {
                    switch( keyval )
                    {

                        case    '\r':
                            //when we get a return, send it to the serial port
                            Serial.print( '\n' );
                            u8g2log.print('\f');
                            for(int i=0; i<6; i++)
                            {
                              if(i == 0)
                              {
                              Serial.print(ethernetIP);
                              }
                            else if(i == 1)
                              {
                              Serial.print(ethernetSubnet);
                              }
                            else if(i == 2)
                              {
                              Serial.print(ethernetGetway);
                              }
                            else if(i == 3)
                              {
                              Serial.print(vmeIP);
                              }
                            else if(i == 4)
                              {
                              Serial.print(vmeSubnet);
                              }
                            else if(i == 5)
                              {
                              Serial.print(eventPort);
                              }
                            else if(i == 6)
                              {
                              Serial.print(timeOut);
                              }
                            }
                            //and finish out by returning the state to INIT and returning true
                            //stateManualEntry = statesFunc::ST_INIT;
                            //return true;

                        break;
                        case 'D':
                              u8g2log.print('N');
                              Serial.print('N');
                        break;

                        case 'C':
                              u8g2log.print('Y');
                              Serial.print('Y');
                        break;

                        default:
                            //for any other key, print to the serial port and LCD
                            u8g2log.print(keyval);

                            enterAddresses();
                        break;

                    }

                }

            break;

        }

        return false;

    }

    void enterAddresses()
    {
      int x;
      if(keyval != '\r')
      {
        if(pointer == 1)
        {

          keyval = keypad.getKey();
          u8g2log.print(keyval);
          ethernetIP += keyval;
        }
        else if(pointer == 2)
        {
          keyval = keypad.getKey();
          u8g2log.print(keyval);
          ethernetSubnet += keyval;
          }
        }
        else if(pointer == 3)
        {

          keyval = keypad.getKey();
          u8g2log.print(keyval);
          ethernetGetway += keyval;

        }
        else if(pointer == 4)
        {
          keyval = keypad.getKey();
          u8g2log.print(keyval);
          vmeIP += keyval;
        }
        else if(pointer == 5)
        {
            keyval = keypad.getKey();
          u8g2log.print(keyval);
          vmeSubnet += keyval;
        }
        else if(pointer == 6)
        {
          keyval = keypad.getKey();
          u8g2log.print(keyval);
          eventPort += keyval;
        }
        else if(pointer == 7)
        {

          keyval = keypad.getKey();
          u8g2log.print(keyval);
          timeOut += keyval;

        }
        pointer++;
        u8g2log.print('\f');

    }

    char keys[ROWS][COLS] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'.','0','\r','D'}
    };

    byte rowPins[ROWS]={39,41,43,45};
    byte colPins[COLS]={31,33,35,37};

    //Create an object of keypad
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
    char keyval;

title: Arduino keypad variables to serial port

Answers: 1

body:
 - Consider constraining the user and simplifying your code.

Simplify your code by putting rules on how the IP address is entered. When entering the [IPv4 address in dot-decimal notation][1] require that all 3 digits are always used for each of the four quad-dotted notation values.  For example, the IPv4 address 192.168.10.20 would be entered as "192168010020".

 - Eliminate unnecessary keypad buttons.

The only keys required for the above scheme are 0, 1, 2, ..., 9.  No other keys need to be detected or supported by additional software.

 - Start simple, get that working then add complexity.

Essentially, a [state machine][2] is most often used as the underlying coding pattern when interfacing with a user.  Keeping track of what the user has done, the current state the user is in and where the user may go is the job of the state machine.  To implement the above, the state machine will need to be complex enough to track the 1s, 10s & 100s position of each quad-dotted notation values as well as which quad-dotted notation value is currently being entered.  This is complex enough for a first pass.  Later, in subsequent passes, consider adding an "abort" key for when the user feels a new attempt is in order.  Still later, consider adding a "back space" key.  Finally, consider adding an "enter" key and dripping the 3 digit per quad-dotted notation value requirement.

  [1]: https://en.wikipedia.org/wiki/Dot-decimal_notation#IPv4_address
  [2]: https://en.wikipedia.org/wiki/Finite-state_machine


body:
I'm sorry for the basic question, but I have a switch case where any code placed after a certain function call simply never gets called, and I've spent half a day looking at it, so thank you so much for your help.

Running on an Arduino UNO.

Here is the loop, and every option in the switch case after the call to moist_sensor.read() simply never gets in:

```

void loop() {

  while (Serial.available() > 0) {
    char val = (char)Serial.read(); // read data byte by byte and store it
    Serial.println(val);
    switch(val) {

      case 'O':
      digitalWrite(13, LOW);

      break;

      case 'I':
      digitalWrite(13, HIGH);

      break;

      case 'W':
            water(2000);
            break;

      case 'E':

            int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            break;

//it never enters any of these cases below

      case 'M':

        //String reading2 = moist_sensor.packaged_reading();
        //Serial.println(reading2); // send the received data back to raspberry pi
        break;

      case 'W':

        water(5000);
        break;

      default:

        delay(5000);

    }
  }

```

I've tried changing the name of the function with fears of special keywords, swapping it with other cases (such as putting case 'W' above, where it works, and vice versa), and I always get the same behaviour. If i comment the line, everything works as expected.

I know the method isn't actually called all the time, but for sanity's sake, moist_sensor.readd() right now is just:

```
int readd() {
return 0;
}
```

It also works fine if its the last case, but this buggs me, and I want to create other cases with function calls.

Thank you so much!

title: Switch case options get broken after a function call

Answers: 2

body:
As soon as I posted this, I looked at the variable declaration inside the case and thought I'd fix this ugly code, and turns out that is what breaks the entire thing, I had no idea...

```
case 'E':

            int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            break;

```
should just be

```
case 'E':

            reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            break;
```

with the "int reading;" declaration somewhere else above.

body:
You seemed to have solved it. For the reason, take a look at the compiler errors:

    sketch_nov22a:31: error: jump to case label [-fpermissive]
           case 'M':
                ^
    sketch_nov22a:25: error: crosses initialization of 'int reading'
                 int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                     ^
    sketch_nov22a:38: error: jump to case label [-fpermissive]
           case 'W':
                ^
    sketch_nov22a:25: error: crosses initialization of 'int reading'
                 int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                     ^
    sketch_nov22a:43: error: jump to case label [-fpermissive]
           default:
           ^
    sketch_nov22a:25: error: crosses initialization of 'int reading'
                 int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                     ^
    exit status 1

If you got it to compile your compiler must be configured a bit differently to mine. However you can see that by putting `int reading = ...` in the case block, the compiler tries to execute that first (to initialize `reading`) which causes it to jump case labels.

By moving `int reading` outside the case statement, the compiler no longer has to initialize the variable, and that line merely becomes a function call and assignment (not a variable initialization).

---

You can avoid that by putting the code into its own block, that is, instead of:

      case 'E':

            int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            break;

Use:

      case 'E':
            {
            int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            }
            break;


body:
I am making a self-contained stills camera and the ESP32-based modules seem well-suited to my project due to the easy incorporation of a TFT viewfinder screen and TF card slot in one package. I am not interested in saving video or web streaming.
I have worked with the TTGO ESP32 camera that uses the OV2640 2MP sensor and can save full 2MP UXGA (1600x1200) resolution stills (albeit with mandatory JPEG compression turned on - I have only managed to get 1.3 MP images without compression).

I see now there is a version of ESP32 camera that uses the OV3660 3MP sensor (called 'M5Stack Timer Camera'). However, the specs for that camera [https://docs.m5stack.com/#/en/unit/timercam][1] say it can save upto a maximum of UXGA - i.e. 2MP images.

So what is the advantage of having a 3MP sensor chip if you can only save 2 MP images? Or is there a way of saving the full 3MP sensor resolution (i.e. 2048 x 1536) stills from this camera?

Thanks

  [1]: https://docs.m5stack.com/#/en/unit/timercam

title: What is the advantage of a 3MP OV3660 sensor on the ESP32 M5Stack camera if it can only save upto 2MP images?

Answers: 3

body:
The limit isn't the camera - it's the memory.

At 3 megapixels you have 3145728 pixels. At 3 bytes per pixel (8 bits each of red green and blue) it requires 9437184 bytes to store the image. That's more than can fit into the 8MB PSRAM.

1600x1200 will probably be one of the standard resolutions that the specific camera in use can capture, and is probably the biggest size that is below 8MB in size for a single frame.

So, what advantage of having a 3 megapixel camera? Well, none to you, other than the cost. It's probably cheaper to use a newer 3 megapixel camera than an older 2 megapixel camera.

----

It is perfectly possible to run at the resolutions you desire though. This resolution is known as `QXGA` and is supported by the OV3660 driver in the [ESP32 Camera library](https://github.com/espressif/esp32-camera).  There are some caveats though:

1. You must use JPEG compression. Not only is this to make the image small enough to fit into PSRAM but also to make it possible to write the whole frame into PSRAM fast enough that you don't miss bits of the data.
2. You will not be able to "do" anything with the image other than send it to somewhere else (such as an SD card or a web server). There just isn't enough room to uncompress the image.

body:
I contacted the M5Stack people directly and they assured me that they made an error in their original web page specs and that the camera does indeed support full 3MP capture. So I bought one of these M5Stack Timer Cams and tested it. I can confirm that the device will save a 3 MP image at full QXGA resolution (2048 x 1536).
This option was not available on with the Win10 example app they provide but it was only possible with their official Arduino 'webcam' example. This is a web server WiFi example sketch and one of the options is QXGA and this does work.

So the definitive answer to my question (based on practical experience) is that the advantage of using the OV3660 is that it can provide 3MP pictures and the original specs provided by M5Stack were misleading hence the confusion expressed in my question.

It would also be interesting to hear if anyone has managed to get OV3660 working at full 3MP on other generic ESP32 boards. So far I have seen no other example published on the web.

body:
The m5stack timer camera X (OV3660) lacks support.
There is nothing on how to flash and use micropython in this device.
There is a cameratool you can download and take snapshots via serial port, there is the standard arduino software you can flash and that's it.
I miss some guides on how to flash micropython on it and make it work with mqtt and more complex setups. I'm not an arduino person, just want to code some python on it.

I bought 2 of those cameras and those are sitting in a shelf for 6 months with 0 use. One day when someone publish a full micropython firmware for that camera, i'll give it a try.

PS: I've tried to compile a micropython firmware with OV3660 support, but no luck on make it work.


body: I've compiled a solution and have received a ttf file from Intel Quartus which is designed for the Vidor 4000 Arduino board. The file represents a synthesized bitstream to be sent to the FPGA. How do I upload the file to the FPGA onboard the VIDOR board? I've got a JTAG programmer if necessary.

title: How does one upload a synthesized solution to the Arduino Vidor FPGA?

Answers: 0


body:
I am using Arduino Zero with Windows 10. I tried following the procedure listed in [Getting started with Arduino][1] to set up my Arduino/environment, however, when I connect the Zero's Programming Port to my laptop's USB 3.0 port, it detects it as **"Atmel Corp. EDBG USB Port"** instead of **"Arduino Zero Prog. Port"** (or something similar) as described under the section "Installing Drivers for the Zero" in the above link. Since it is recognized as an EDBG USB Port, I am unable to burn bootloader or upload sketches using the Programming port as it cannot detect CMSIS-DAP.

when I try to upload a sketch I get the following error:

    Arduino: 1.8.13 (Windows 10), Board: "Arduino Zero (Programming Port)"
    Sketch uses 23496 bytes (8%) of program storage space. Maximum is 262144 bytes.
    Global variables use 3536 bytes (10%) of dynamic memory, leaving 29232 bytes for local variables. Maximum is 32768 bytes.
    Open On-Chip Debugger 0.10.0+dev-gf0767a31 (2018-06-11-13:36)
    Licensed under GNU GPL v2
    For bug reports, read
     http://openocd.org/doc/doxygen/bugs.html
    debug_level: 0
    none separate
    adapter speed: 400 kHz
    cortex_m reset_config sysresetreq
    Error: unable to open CMSIS-DAP device 0x3eb:0x2111
    Error: No Valid JTAG Interface Configured.
    Error: No Valid JTAG Interface Configured.

When I try to burn bootloader I get the following error:
```
Open On-Chip Debugger 0.10.0+dev-gf0767a31 (2018-06-11-13:36)
Licensed under GNU GPL v2
For bug reports, read
 http://openocd.org/doc/doxygen/bugs.html
debug_level: 0
none separate
adapter speed: 400 kHz
cortex_m reset_config sysresetreq
Error: unable to open CMSIS-DAP device 0x3eb:0x2111

Error while burning bootloader.

```

**How can I fix this?**

So far, I tried

 1. re-installing the IDE several times, and also tried uninstalling the device- but it auto installs the driver when I connect again.
 2. Starting IDE as an admin did not help, although I think the issue is the EDBG CMSIS-DAP is not installed, and instead, the EDBG USB driver is installed

  [1]: https://www.arduino.cc/en/Guide/ArduinoZero

title: Arduino zero programming port recognized as EDBG USB port

Answers: 1

body:
I don't have one of these to test with, but in looking at the driver installation instructions, I would expect it to say "EDBG Virtual COM Port" before a driver is installed and "Atmel Corp. EDBG CMSIS-DAP" after the driver is installed.

The "Arduino Zero Programming Port" is something I expect only appears in the Tools/Port menu in the IDE, despite what it says in the article.  You can see this name given in the boards.txt file.  And this makes sense to me, given that the EDBG firmware is Atmel's not Arduino's and there appears to be no indication in the driver directory, the content of the INF files, to suggest that they they're providing their own customized driver for the programming port.  So I would trust what you see in the images, suggesting it *should* say CMSIS-DAP without mention of "Arduino Zero" at all.  So far as I can tell, you're not doing anything incorrect driver-wise, but I'm also not seeing everything.

In any case, it appears you should have the VID (**03eb**) and PID (**2157**) in the device properties that boards.txt instructs the IDE to look for:

```none
arduino_zero_edbg.name=Arduino/Genuino Zero (Programming Port)
  1 arduino_zero_edbg.vid.0=0x03eb
  2 arduino_zero_edbg.pid.0=0x2157
```

However, your error mentions PID=**2111**.  I looked this up in a USB VID/PID database, and it mentions the an ATMEL Xplained board, which is not a completely unrelated thing, but this VID:PID are not mentioned in the driver information or boards.txt for the Arduino Zero.

I did find [this one mention][1] that the Xplained USB PID was used on the [M0 Pro][2] which is a different beast from the [Zero][3].

In any case, I would not worry about not seeing something like "Arduino Zero Prog. Port" in device manager itself for the programming port.

Make sure you are using Zero and not M0 Pro.  **If you have the M0 pro**, in which case properties in Device Manager may show PID as ***2111**, I'm not sure what to suggest except that maybe you should install [Microchip Studio][4] since this seems to be the only way I can find to get the Xplained EDBG drivers.  Some work may still be required after that to get it to work in the IDE.

If you have a Zero and not M0 Pro installing Microchip Studio may also install the EDBG driver for it as well, although this really shouldn't be necessary.

  [1]: https://forum.arduino.cc/index.php?topic=360330.msg2485017#msg2485017
  [2]: https://store.arduino.cc/usa/arduino-m0-pro
  [3]: https://store.arduino.cc/usa/arduino-zero
  [4]: https://www.microchip.com/mplab/microchip-studio


body: I am using sim 800l with arduino. I am successfully sending AT command from arduino, not in serial monitor but I am unable to catch the response after each successful command execution if its ok or not. I want to do that because, if there is an error in a certain command the next command will not be executed unless its successful. Can you tell me is there any way to do so?

title: Is there any way to catch the response of SIM800L after sending the at command?

Answers: 1

body:
for a polling serial read I use this method :

    bool tSim8_sendCommand(uint8_t sim_cmd[])
    {
     uint8_t simOK[2] = {0}, i=20;
     tSoftSerial1_write(sim_cmd);
     tSoftSerial1_write("\r\n");
     while (i--)
     {
      simOK[0] = simOK[1];
      simOK[1] = tSoftSerial1_readChar();
      if(simOK[0] == 'O' || simOK[1] =='K')
      {
       return true;
      }
     }
     return false;
    }

the variable `i` i the while loop, is used just for retries, so the program doesn't get trapped in an infinite loop. the code is self-explanatory. the incoming characters are "pushed" into an array till the array reads "OK".

for a non-blocking one, it's a bit complicated as you have to define state-machines and concurret loops. here is a method I use for finding out if the last transmission was OK:

    void tsim_phase_ok_routine(uint8_t inChar)
    {
     if(tsim_aux_buff[0] == 'O' && tsim_aux_buff[1] =='K' && tsim_aux_buff[2] =='\r')
     {
      tsim_status_flag |= (1<<PHASE_OK);
      tsim_status_flag &=~(1<<PHASE_CON_ERR);
      return;
     }
     else
     {
      tsim_aux_buff[0] = tsim_aux_buff[1];
      tsim_aux_buff[1] = tsim_aux_buff[2];
      tsim_aux_buff[2] = inChar;
      err_timeout--;
     }
     if(!(tsim_status_flag & (1<<PHASE_OK)) && !err_timeout)
     {
      tsim_status_flag &=~(1<<PHASE_OK);
      tsim_status_flag |= (1<<PHASE_CON_ERR);
     }

    }

I define "PHASES" to find out which phase is sim800 in. the whole function would be written in RX interrupt service routine and the input character would be fed to it.


body:
I'm confused with register wrting method by compound assignment and/or pointer because I don't know where are some of the values come from.

**Example 1**
```
REG_PMC_PCER1 |= PMC_PCER1_PID36;  // Enable PWM - Peripheral Identifiers 36
```
- This works the same as ``REG_PMC_PCER1 = (1<<4)``
- ``REG_PMC_PCER1`` is not readable, so ``|=`` operator shouldn't work.
- What is ``PMC_PCER1_PID36`` ? Is the some sort of bit mask defined in the IDE ?

**Example 2**
```
PMC->PMC_PCER0 |= PMC_PCER0_PID13;   // PWM controller power ON
```
- This works the same as ``REG_PMC_PCER0 = (1<<13)``
- This is similar to Example 1 but there is pointer ``PMC``. Why it's needed ? If ``PMC_PCER0_PID13`` is a bit mask then ``REG_PMC_PCER0`` need not indexing.

**So my questions are:**
1. Why compound assignment works on write-only registers ?
2. Where are those constants (``PMC_PCER1_PID36``,``PMC``,etc.) defined ?

Thanks in advance !

title: Register writing by compound assignment and pointer in Arduino due

Answers: 1

body:
> Why compound assignment works on write-only registers ?

Probably out of force of habit more than anything.  People are used to having to set bits in registers where the other bits can be read and they want them to stay the same, in which case `|=` makes sense.

I'd considered that `|=` might be generating a more efficient instruction, but at least with your `REG_PMC_PCER1 |= PMC_PCER1_PID36` example objdump indicates that this is not the case.

> Where are those constants (PMC_PCER1_PID36,PMC,etc.) defined ?

Code-wise, they're defined in the ATMEL's (now Microchip's) CMSIS files.  These are header files whose existence is somewhat standardized by ARM for these ARM Cortex processors.  Much of their content isn't however.  E.g., you may see a few things related Cortex M3 that are the same between this ATMEL device in an STM32 counterpart, but GPIO registers may be completely different.

My broadly, they're defined by ATMEL in their datasheets.


body:
I'm working on a remote control project and have come across many different RF receiver/transmitter modules. Many have a pairing/mode button on the receiver that serves to pair the receiver and transmitter and to choose which mode the transmitter is in, momentary, latching, toggle, etc.
[![enter image description here][1]][1]

How can I replicate this feature using Arduino and those cheap RF transmitter/receiver combos on Ebay? Specific code would be nice, but just a general idea as to how it would be done in theory will work too. I've watched several tutorials that explain the use of the Radiohead library with the cheap RF combos, but none demonstrate how to set up a feature such as this. Thanks.
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/17ZeP.jpg
  [2]: https://i.stack.imgur.com/FBNyh.jpg

title: How to make a pairing and mode button on a remote control receiver

Answers: 1

body:
Remote sends a number before the command bits. The receiver checks if this number is the same with the number that corresponds with the position of the switches.

You can do the same in software. Have the first few bits be some number. The receiver can then check if the first few bits of the received "message" matches that number. If it doesn't it will just throw it out.

This is the same method used with IR-remote controls. The signal from your VCR remote will also be received by your TV. But the TV sees that the code doesn't match the one it's expecting. So it will ignore those.


body:
I have two sets of 4 LEDs.

Set A (Led1 Led2, Led3, Led4)
Set B (Led5 Led6, Led7, Led8)

Both sets have its own tactile button:

Tactile A,
Tactile B,

Tactile A, turning on the LEDs set A and tactile B turning on the LEDs on set B.

So each time I press the tactile A, Led1 from Set A will turn on. The next press will turn on Led2 and LED1 off, then Led3 on, Led2 off, and Led4 on and led3 off.

Same for Tactile B and set B.

Tactile A will not change the set be and same tactile B.

So I came up with the below code. It works fine for Tactile A, for set A. But I am not able to turn on the set B with Tactile B. Tactile B is keep switching itself one after another the tactile B is no functioning. Each set should work with its own tactile button.

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

    //Start -- Power supply on/off code

    #include <Bounce2.h>

    #define POWER_PIN 13
    #define power 12

    //End -- Power supply on/off code

    //Start -- Switching Leds
    // Leds set A
    #define button 2
    #define led1 8
    #define led2 7
    #define led3 6
    #define led4 5
    //Leds set B
    #define tactile 3
    #define led5 11
    #define led6 4
    #define led7 9
    #define led8 10
    int state = 0;      //integer to hold the current state Set A
    int old = 0;        //integer to hold the last state Set A
    int tactitleState = 0;      //integer to hold the current state Set B
    int oldState = 0;        //integer to hold the last state Set B
    int buttonPoll = 0; //integer to hold the button state for set A
    int tactilePoll = 0; //integer to hold the button state for set B
    //End -- Switching power

    //Start -- Power supply on/off code

    int powerState = LOW;
    Bounce b = Bounce(); // Instantiate a Bounce object

    //End -- Power supply on/off code

    void setup() {
      //Start -- Power supply on/off code

      b.attach(POWER_PIN, INPUT_PULLUP); // Attach the debouncer to a pin with INPUT_PULLUP mode
      b.interval(25); // Use a debounce interval of 25 milliseconds
      pinMode(power, OUTPUT); // Setup the LED
      digitalWrite(power, powerState); // Turn off the LED

      //End -- Power supply on/off code

      //Start -- Switching power

      pinMode(button, INPUT); //button set as input
      pinMode(led1, OUTPUT); //Output set Led1
      pinMode(led2, OUTPUT); //Output set Led2
      pinMode(led3, OUTPUT); //Output set Led3
      pinMode(led4, OUTPUT); //Output set Led4

      digitalWrite (led1, HIGH); //set state Led1
      digitalWrite (led2, HIGH); //set state Led2
      digitalWrite (led3, HIGH); //set state Led3
      digitalWrite (led4, HIGH); //set state Led4

      digitalWrite (power, HIGH); //state of the input power

      //Second relay
      pinMode(tactile, INPUT); //button set as input
      pinMode(led5, OUTPUT); //Output set Led5
      pinMode(led6, OUTPUT); //Output set Led6
      pinMode(led7, OUTPUT); //Output set Led7
      pinMode(led8, OUTPUT); //Output set Led8

      digitalWrite (led5, HIGH); //set state Led5
      digitalWrite (led6, HIGH); //set state Led6
      digitalWrite (led7, HIGH); //set state Led7
      digitalWrite (led8, HIGH); //set state Led8

      //End -- Switching power

    }

    void loop() {
      //Start -- Power supply on/off code
      b.update(); // Update the Bounce instance
      if ( b.fell() ) {  // Call code if button transitions from HIGH to LOW
        powerState = !powerState; // Toggle LED state
        digitalWrite(power, powerState); // Apply new LED state
      }
      //End -- Power supply on/off code

      //Start -- Switching power Set A.

      buttonPoll = digitalRead(button); //Detect the state of the button
      if (buttonPoll == 1) {              //Check if the button pressed
        delay (50);                       //Delay 50ms
        buttonPoll = digitalRead (button); //Poll button again
        if (buttonPoll == 0) {           //if it is 0 considered one press
          state = old + 1;               //increas state by 1
        }
      }
      else {
        delay (100);                    //Delay 100ms
      }
      switch (state) {     //react tot button press & state
        case 1:
          digitalWrite (led1, LOW); //led1 is on
          digitalWrite (led2, HIGH); //led2 is off
          digitalWrite (led3, HIGH); //led3 is off
          digitalWrite (led4, HIGH); //led4 is off
          old = state;
          break;
        case 2:
          digitalWrite (led1, HIGH); //led1 is off
          digitalWrite (led2, LOW); //led2 is on
          digitalWrite (led3, HIGH); //led3 is off
          digitalWrite (led4, HIGH); //led4 is off
          old = state;
          break;
        case 3:
          digitalWrite (led1, HIGH); //led1 is off
          digitalWrite (led2, HIGH); //led2 is off
          digitalWrite (led3, LOW); //led3 is on
          digitalWrite (led4, HIGH); //led4 is off
          old = state;
          break;
        case 4:
          digitalWrite (led1, HIGH); //led1 is of
          digitalWrite (led2, HIGH); //led2 is off
          digitalWrite (led3, HIGH); //led3 is off
          digitalWrite (led4, LOW); //led4 is on
          old = state;
          break;
        default:                   //if the there is no state, then all leds are off
          digitalWrite (led1, HIGH); //led1 is of
          digitalWrite (led2, HIGH); //led2 is off
          digitalWrite (led3, HIGH); //led3 is off
          digitalWrite (led4, HIGH); //led4 is off
          old = 0;   // All states are reset to 0 off
          break;
      }
      //End -- Switching  led set A
      //Start -- Switching led set B

      tactilePoll = digitalRead(tactile); //Detect the state of the button
      if (tactilePoll == 1) {              //Check if the button pressed
        delay (50);                       //Delay 50ms
        tactilePoll = digitalRead (tactile); //Poll button again
        if (tactilePoll == 0) {           //if it is 0 considered one press
          tactitleState = oldState + 1;               //increas state by 1
        }
      }
      else {
        delay (100);                    //Delay 100ms
      }
      switch (tactitleState) {     //react tot button press & state
          case 1:
          digitalWrite (led5, LOW); //led5 is on
          digitalWrite (led6, HIGH); //led6 is off
          digitalWrite (led7, HIGH); //led7 is off
          digitalWrite (led8, HIGH); //led8 is off
          oldState = tactitleState;
          break;
        case 2:
          digitalWrite (led5, HIGH); //led5 is off
          digitalWrite (led6, LOW); //led6 is on
          digitalWrite (led7, HIGH); //led7 is off
          digitalWrite (led8, HIGH); //led8 is off
          oldState = tactitleState;
          break;
        case 3:
          digitalWrite (led5, HIGH); //led5 is off
          digitalWrite (led6, HIGH); //led6 is off
          digitalWrite (led7, LOW); //led7 is on
          digitalWrite (led8, HIGH); //led8 is off
          oldState = tactitleState;
          break;
        case 4:
          digitalWrite (led5, HIGH); //led5 is off
          digitalWrite (led6, HIGH); //led6 is off
          digitalWrite (led7, HIGH); //led7 is off
          digitalWrite (led8, LOW); //led8 is on
          oldState = tactitleState;
          break;
        default:                   //if the there is no state, then all leds are off
          digitalWrite (led5, HIGH); //led5 is off
          digitalWrite (led6, HIGH); //led6 is off
          digitalWrite (led7, HIGH); //led7 is off
          digitalWrite (led8, HIGH); //led8 is off
          oldState = 0;   // All states are reset to 0 off
          break;
      }
      //End -- Switching Leds set B
    }

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

title: Turning on and off two set of LEDs with two tactile buttons

Answers: 1

body:
Your code is rather hard to follow.

Your code to read a button press doesn't make much sense:

```
  buttonPoll = digitalRead(button); //Detect the state of the button
  if (buttonPoll == 1) {              //Check if the button pressed
    delay (50);                       //Delay 50ms
    buttonPoll = digitalRead (button); //Poll button again
    if (buttonPoll == 0) {           //if it is 0 considered one press
      state = old + 1;               //increas state by 1
    }
  }
  else {
    delay (100);                    //Delay 100ms
  }
```

That code will, I *think*, only detect a button press if you press the button for exactly 50 mS. Given that you already use the Bounce library, why don't you create Bounce instances for your LED controller buttons and use those to read those buttons as well?

Next issue: you are setting your `button` and `tactile` pins to `INPUT` rather than `INPUT_PULLUP`. Do you have pulldown resistors on those? (when your input is set to `INPUT` mode you need pulldown resistors, and need to connect the switches to +5V. If you use INPUT_PULLUP mode you don't need any resistors, but you connect your switches to ground. They then read HIGH until you press a switch, at which point the switch connects the pin to ground and pulls it LOW.)

Next issue: You are treating a value of `1` as pressed and `0` as not pressed. You should use the constants `HIGH` and `LOW` instead. (And note that if you use `INPUT_PULLUP` mode for your pins, you should wire your buttons to VCC, and treat HIGH as not pressed and LOW as button pressed.)

I would suggest renaming your variables and using arrays of LED pin numbers:

```
int set1Button 2;
int set1LEDs[] = {8, 7, 6, 5};
int set1State = 0; //No LEDs lit

int set2Button 3;
int set2LEDs[] = {11, 4, 9, 10};
int set2State = 0; //No LEDs lit
```

Pressing `setButton1` should advance `set1State`, and pushing `set2Button` should advance `set2State`.

For value 0, set all LEDs to off. any other value, set the LED at index `setXState - 1` on and all others off.

This code would work for the first set of LEDs:

```
for (int index = 1; index <= 4; index++) {
     int value = set1State == index ? HIGH : LOW;
     digitalWrite (set1LEDs[index-1], value);
}
```


body:
I want to call them “words”, but I’m uncertain if this is how they are referred to in documentation for the use of a header board that might plug into an ardino board.

So if you have a sequence of ONs and OFFs being read or sent from a microcontroller board are those called words?  What are they called?

title: What are patterns of bits sent to or read from GPIO pins called?

Answers: 2

body:
Here is a simplistic diagram.

Larger than 8 bits is usually referred to as WORD.

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

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

body:
Consider backing away from Arduino hardware for just a moment

> I want to call them “words”, but I’m uncertain ...

For most computers and processors a word is comprised of bytes and bytes are comprised of bits.  A bit is an individual 0 or 1.  That's always true.  A byte is almost always made up of 8 bits.  Why? Because it is always convenient to do things on a computer or processor in powers of 2.  That is, 2 or 4 or 8 or 16 or 32 or ... (keeps going).  And 8 is a convenient sized number of bits!  A word is usually 2 bytes or 16 bits.  But that's not always true.  For some computers it is more.

Keep in mind, so far, we are just talking about data.  Not physical [GPIO pins][1].  When we do interface through the GPIO pins this data can be sent out in [parallel][2] or in [serial][3] form.  It really depends on how we want to interface with the world!  For instance, many Arduino projects uses a serial interface called an [I2C bus][4] to [talk with peripherals such as a temperature sensor][5].

> So if you have a sequence of ONs and OFFs being read or sent from a
> microcontroller board are those called words?

This sounds like you are talking about serial data (as apposed to parallel data).

 * Talking about the hardware: The GPIO lines on most embedded processors are designed to interface with the world using parallel data.  You can use software and "emulate" a serial stream of data on one of the GPIO lines.  But you might not be able to send out data fast.  Instead, most embedded processors have special serial port pins which are connected to fast hardware usually called [UARTs][6]. When sending or receiving serial data, it is almost always better to use a pin connected to a UART.

 * Talking about the data: Again, word can mean different amounts of data on different processors. And to further complicate things, some serial protocols mix things up and end up sending out or reading data using an odd number of bits.  Which makes talking about the combined bits as a word confusing.  At this point I would just stop using the word "word" to describe the data and just call it "data".

Besides, most Arduino boards (like the Arduino Uno) use embedded processors which interface directly to peripherals such as temperature sensors over serial ports.  As such, the data format is usually spelled out by the peripheral and is (very) specific for the purpose of the peripheral (temperature sensing in this case). It is recommended to read the specifications for the peripheral and use the terminology presented there when communicating with others regarding that particular peripheral.

  [1]: https://en.wikipedia.org/wiki/General-purpose_input/output
  [2]: https://en.wikipedia.org/wiki/Parallel_communication
  [3]: https://en.wikipedia.org/wiki/Serial_communication
  [4]: https://en.wikipedia.org/wiki/I²C
  [5]: https://learn.adafruit.com/adafruit-mcp9808-precision-i2c-temperature-sensor-guide/arduino-code
  [6]: https://en.wikipedia.org/wiki/Universal_asynchronous_receiver-transmitter


body:
I’m using a 5v 20a power supply run through a barrel connector into an Arduino Uno to control an LED strip. When only the barrel is connected, the green light on the Uno comes on but the yellow light lights dimly for a few milliseconds then goes dark. The light strip doesn’t light at all. When a USB is also connected, the board lights up fully (green and yellow LED) and the LED strip runs through its routine.

I’m making this as Christmas lights on a tree outside so I want it to run on the stand alone power supply. Why doesn’t the barrel work on 5v?

[![measuring voltage from barrel, board with just barrel, board with barrel and USB][1]][1]

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

title: Uno doesn’t get enough power from 5v barrel connector. Why?

Answers: 1

body:
Voltage Drop
------------
Well, if you put 5V into your barrel jack, your UNO's onboard 5V regulator is going to drop that down to 3.5V or so.  You must have more than 5V into the regulator to get 5V out of it.  This is referred to as the regulator's "[drop out][1]" voltage.
The [specs for an UNO][2] say to power it from at least 7V for that reason.

As an experiment you can power it this way without your lights attached and measure the "5V" header to GND to see this happening.

Power Dissipation
-----------------
Linear regulators like that found on the UNO are not efficient. They waste energy as heat in proportion to the current through it and voltage dropped by it.

If you provide it with 7V at the regulator and your project draws 0.5 amps from the regulator, you will try to generate 0.5A * (7V - 5V), that is 1 Watt of heat.  Your regulator can probably dissipate half that with how it's mounted on the UNO and normal ambient air temperature.

Note this situation gets worse if you put 12V (for example) into the barrel jack, as you'd be dropping 7V across the regulator.

Many linear regulators have thermal overload protection built into them.  They'll stop producing as much voltage at the output as they heat up to try to survive the event.  And that's likely what you're seeing if you're trying to power your christmas lights from the regulator.

If you want to see this yourself might try **very** briefly tapping the regulator with your finger; it may be **blazing hot**.  You might just dampen your finger and hold it *near* the regulator's surface to feel the heat coming off of it.

You will more than likely need to route power around the Arduino board to your lights to prevent this.

  [1]: https://en.wikipedia.org/wiki/Voltage_regulator#Dropout_voltage
  [2]: https://store.arduino.cc/usa/arduino-uno-rev3


body:
I wrote a code that worked perfectly on an Uno. I switched everything out to a Nano Every, and now I'm getting the following errors:
```
In file included from C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal\src\LiquidCrystal.cpp:1:0:

C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal\src\LiquidCrystal.h:45:36: error: expected class-name before '{' token
 class LiquidCrystal : public Print {
                                    ^
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal\src\LiquidCrystal.h:86:9: error: 'Print' has not been declared
   using Print::write;
         ^~~~~

exit status 1

Error compiling for board Arduino Nano Every.
```
I'm new to programming (this is the first thing I've done that wasn't from a tutorial), so I don't understand what any of the above means.

In the Tools dropdown, I have

Board: Arduino Nano Every

Registers Emulation: None (ATMEGA4809)

Programmer: Onboard Atmel mEDBG (Uno Wifi Rev2)

Here's the code:
```
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  lcd.begin(16, 2);
  lcd.print("Charging");
  delay(750);
  lcd.print(".");
  delay(750);
  lcd.print(".");
  delay(750);
  lcd.print(".");
  delay(750);
  lcd.clear();
  lcd.print("Charged");
}

void loop() {
  const int buzzerPin = 6;
  const int switchPin = 13;
  const int buttonPin = 7;
  const int ledPin = 9;
  pinMode(switchPin, INPUT);
  pinMode(buzzerPin, OUTPUT);
  int switchState = digitalRead(switchPin);
  int buttonState = digitalRead(buttonPin);
  lcd.setCursor(0, 1);
  lcd.print("Mode: ");
  if (switchState == LOW) {
    lcd.print("Stun");
  } else {
    lcd.print("Kill");
  }
  if (buttonState == HIGH) {
    const int buzzerMax = 2000;
    const int time = 3;
    int buzzerTone;
    int totalReps = 50;
    int reps = 10;
    while (reps < totalReps) {
      buzzerTone = ((totalReps - reps) * 2 * (buzzerMax / totalReps));
      tone(buzzerPin, buzzerTone);
      analogWrite(ledPin, (255 / reps));
      delay(time);
      reps++;
      delay(time);
      if (reps == totalReps) {
        noTone(buzzerPin);
        analogWrite(ledPin, 0);
      }
    }
    lcd.clear();
    lcd.print("Charging");
    delay(333);
    lcd.print(".");
    delay(333);
    lcd.print(".");
    delay(333);
    lcd.print(".");
    delay(333);
    lcd.clear();
    lcd.print("Charged");
  }
}
```

title: Errors occured when switching from Uno to Nano Every

Answers: 0


body:
**Problem:**
- I'm using Due's QDEC function to decode a 32bit quadrature encoder.
- I need to pipe out the counter value as fast as possible to another instrument's DIO.
- The rear strip is selected as digital output because it's easy to slap an IDC connector on it.

```
#define QA 2
#define QB 13
const unsigned int mask_QA = digitalPinToBitMask(QA);
const unsigned int mask_QB = digitalPinToBitMask(QB);

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

    // QDEC block
    REG_PIOB_PDR = mask_QA;     // activate peripheral function
    REG_PIOB_ABSR |= mask_QA;   // choose peripheral option B
    REG_PIOB_PDR = mask_QB;
    REG_PIOB_ABSR |= mask_QB;

    REG_PMC_PCER0 = (1<<27);                                // activate clock for TC0 (PID27)
    REG_TC0_CMR0 = (1 << 0) | (1 << 2) | (1<<8) | (1<<10);  // config clock
    REG_TC0_BMR = (1<<9)|(1<<8)|(1<<12);                    // activate QDEC
    REG_TC0_CCR0 = 5;                                       // enable the clock and reset counter

    //PIO BLOCK
    // mask write, the rear strip of Arduino Due
    REG_PIOA_OWER = 0x0018c808; // A 7 14 15 19 20
    REG_PIOB_OWER = 0x04204000; // B 14 21 26
    REG_PIOC_OWER = 0x000FF3FE; // C 1-9 12-19
    REG_PIOD_OWER = 0x0000064F; // D 0 1 2 3 6 9 10
}
void loop() {

  // data write
  REG_PIOA_ODSR = REG_TC0_CV0;
  REG_PIOB_ODSR = REG_TC0_CV0;
  REG_PIOC_ODSR = REG_TC0_CV0;
  REG_PIOD_ODSR = REG_TC0_CV0;
}
```

- This code is untested as I don't have access to the hardware right now.
- Basically 4 bit masks (for PIO ABCD) are created to map the 32bit ```REG_TC0_CV0``` onto the rear strip.

**Requirement:**
- [Priority] As little **delay** as possible, every clock cycle matters.
- [Secondary] Output bandwidth should match the update rate of ```REG_TC0_CV0```, which I didn't manage to find in the manual. The output should also provide a latch for the receiving equipment to sync sampling.

**Question:**
- Would disabling peripheral functions for all 32 pins on the rear strip interfere with the core functionality that this program depends on (timer/counter etc) ?
- Are there other ways that can accomplish this faster ?
- I would like to use the main CPU tread for serial interface. It is possible to attach the four ODSR writing instructions to a timer ISR so it does not interfere with ```void loop()```?

Thanks in advance !

title: Writing a 32-bit register to 32 pins as fast as possible in Arduino Due

Answers: 0


body:
I am trying to run a small 3v motor with a Keyestudio MEGA 2560(which is the same as the Arduino MEGA 2560). I am getting a consistent 5 volts everywhere I check with a multimeter. The voltage drops to 0.01-0.05 once I connect the motor. The motor runs once it is connected directly to the Arduino's 5v output pin. The motor draws about 600mA consistently when we connect it directly to 5v.

My code is rather basic, which just sends voltage out pin 5.  I am not using any shield. controlling the speed is not my main concern here, though later on in my project I would like the motor to be able to reverse as well.

I found this circuit diagram in "Arduino for dummies," and found this same diagram on many other websites too.

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

    void loop() {
      digitalWrite(5,HIGH);
    }

<!-- Begin schematic: 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/su8X6.png)

<!-- End schematic -->

title: Why won't my motor run?

Answers: 1

body:
An [NPN bipolar transistor][1] requires a current to flow from base to the emitter which is then multiplied by the beta of the transistor controlling the maximum current which flows from the collector to the emitter.  A [2n2222][2] beta is about 100.  Let us calculate the amount of current which will be allowed to flow from the collector to the emitter of the 2n2222 transistor.  First calculate the current from the base to the emitter:

    I(be) = (5.0 volts- 0.7 volts) / 1,000 ohms
    I(be) = .0043 Amps

Use this current to find the maximum current flowing from the emitter to the collector:

    I(ce) = 100 x I(be) = 0.430 Amp or 430mA

We see that the transistor does not provide enough current to drive a 600mA motor.

We need to reduce the value of R1 such that I(ce) is at least 600mA which means that I(be) needs to be at least 6mA.  Rearranging the earlier equation to find R1:

    I(be) = (5.0 volts- 0.7 volts) / 1,000 ohms
    I(be) = (5.0 volts- 0.7 volts) / R1
    R1 = (5.0 volts- 0.7 volts) / I(be)
    R1 = (5.0 volts- 0.7 volts) / 0.006 Amps
    R1 = 716.67 ohms

However, because of the large amount of I(ce) current necessary to drive the load, we find the transistor reaching it's limits and the beta of the transistors drop apprecably:

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

This diagram is a little hard to understand.  And there is no curve for 600mA.  But we can get an idea of what to expect if we look at the 500mA curve.  We see that in order to get less than a volt drop across the transistor (V(ce)) we need to pump in more than 10mA (I(be)).  To get similar results for 600mA we would likely approach 20mA and now we are dangerously close to the processor pin current driving capabilities.

A common alternative is to use a [Darlington Transistor][4] configuration:

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

The resulting beta is essentially the product of the individual transistor's betas.

Let's do some rough calculations.  If the 2n2222 that switches the load current has a lower beta of about 10, we would need about 60mA to switch a 600mA current.  To generate 60mA through the transistor connected to the processor, we would need about 0.6mA from the processor.  That's really small and we can afford to triple it to ensure reliable operation.  So let's pick 3mA:

    R1 = (5.0 volts- (2 * 0.7 volts)) / 0.003
    R1 = 1200 ohm

So a 1K ohm resistor should likely work.

  [1]: https://en.wikipedia.org/wiki/Bipolar_junction_transistor
  [2]: https://en.wikipedia.org/wiki/2N2222
  [3]: https://i.stack.imgur.com/ETCUD.jpg
  [4]: https://en.wikipedia.org/wiki/Darlington_transistor
  [5]: https://i.stack.imgur.com/pAUpa.png


body: I've been trying to install esp32 on Arduino IDE for days now but I keep getting 'error downloading package' message. I checked the over and over again, it's correct. I even tried installing it manually using GitGUI but it's not working. Please help me.

title: Error downloading package_esp32

Answers: 0