body:
I am using ArduinoJson and ESP8266HTTPClient.

Say I have a DynamicJsonDocument that has an unknown number of entries with information on different persons:

```
[
    {
        "ID": "12345",
        "name": "John Smith",
        "Address": "Street 1"
    },

    .
    .
    .

    {
        "ID": "00345",
        "name": "Paul Anderson",
        "Address": "Street 2"
    }
]

```

I would like to somehow store the values associated with the key "name" for all the different persons. For example, have something like:

```
String name1 = "";
...
String nameN = "";

.
.
.

Serial.println(name1);
...
Serial.println(nameN);

```

To print a list of all the names:

```
John Smith
Paul Anderson
```

The only information of the JSON I have beforehand is the keys each entry will have. I do not know how many entries there will be.

How can I go about this?

EDIT: Why I want to do this:

I am using the ESP as a client to get information from a server in the form of a JSON similar to what I wrote above. At the same time, I am serving a simple HTML website by doing `server.send(200, "text/html", HTML_code);` using the ESP as an AP. I was able to just cram the whole JSON into the HTML as text, but I would like to just have specific information from the JSON, as explained above.

I am aware what I am doing is far from elegant or the "correct way to do it", but I am learning all of this, so any criticism and help is more than welcome :)

title: How to get a specific value from an unknown number of JSON representations?

Answers: 1

body:
Directly from the [ArduinoJson Assistant](https://arduinojson.org/v6/assistant/):

```c++
// Stream& input;

StaticJsonDocument<384> doc;
deserializeJson(doc, input);

for (JsonObject elem : doc.as<JsonArray>()) {
  const char* ID = elem["ID"]; // "12345", "13244", "00345"
  const char* name = elem["name"]; // "John Smith", "Jason Statham", "Paul Anderson"
  const char* Address = elem["Address"]; // "Street 1", "Street 2", "Street 3"
}
```

See also:

* [How to use ArduinoJson with HTTPClient?](https://arduinojson.org/v6/how-to/use-arduinojson-with-httpclient/)
* [How to deserialize a very large document?](https://arduinojson.org/v6/how-to/deserialize-a-very-large-document/)


body:
I have tried everything on this url

https://stackoverflow.com/questions/10165761/java-cant-connect-to-x11-window-server-using-localhost10-0-as-the-value-of-t

session output:

    root@whale:/home/kermit# echo $DISPLAY
    localhost:1.0
    root@whale:/home/kermit# cd dev/sht30/
    root@whale:/home/kermit/dev/sht30# arduino --upload sht30v1.ino --port /dev/ttyUSB0
    Exception in thread "main" java.awt.AWTError: Can't connect to X11 window server using 'localhost:1.0' as the value of the DISPLAY variable.
            at java.desktop/sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
            at java.desktop/sun.awt.X11GraphicsEnvironment$1.run(X11GraphicsEnvironment.java:102)
            at java.base/java.security.AccessController.doPrivileged(Native Method)
            at java.desktop/sun.awt.X11GraphicsEnvironment.<clinit>(X11GraphicsEnvironment.java:61)
            at java.base/java.lang.Class.forName0(Native Method)
            at java.base/java.lang.Class.forName(Class.java:315)
            at java.desktop/java.awt.GraphicsEnvironment$LocalGE.createGE(GraphicsEnvironment.java:101)
            at java.desktop/java.awt.GraphicsEnvironment$LocalGE.<clinit>(GraphicsEnvironment.java:83)
            at java.desktop/java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:129)
            at java.desktop/sun.awt.X11.XToolkit.<clinit>(XToolkit.java:231)
            at java.base/java.lang.Class.forName0(Native Method)
            at java.base/java.lang.Class.forName(Class.java:315)
            at java.desktop/java.awt.Toolkit$2.run(Toolkit.java:588)
            at java.desktop/java.awt.Toolkit$2.run(Toolkit.java:583)
            at java.base/java.security.AccessController.doPrivileged(Native Method)
            at java.desktop/java.awt.Toolkit.getDefaultToolkit(Toolkit.java:582)
            at processing.core.PApplet.<clinit>(Unknown Source)
            at processing.app.Preferences.save(Preferences.java:735)
            at processing.app.Preferences.init(Preferences.java:249)
            at processing.app.Base.main(Base.java:117)

How do you run arduino in headless mode on a raspberry pi?

Answers: 1

body:
It is probably a non-existant or stale auth cookie in your .Xauthority file.  This sort of thing happens when you're running your X session with one user but trying to run your X application as different user.  Doing sudo or su root (or really any other user) is a common way to get in that situation.  Running the IDE as root usually mean something else has already gone sideways.  The typical reason for that is you're running as root instead of fixing your permissions to the Arduino serial device file.

---

That said, if you want to run headless builds and uploads of Arduino projects, what you're looking for is [arduino-cli][1].

```bash
cd /path/to/directory/containing/sht30v1.ino
arduino-cli -b arduino:avr:nano compile
arduino-cli -b arduino:avr:nano upload --port /dev/ttyUSB0
```

  [1]: https://arduino.github.io/arduino-cli/latest/


body:
Updated question.  The original question was based on using 'Upload' from the Arduino IDE, instead of 'Upload Using Programmer' under 'Sketch'.  The problem in getting the Atmel-ICE to work with Arduino IDE appears now to be one of incorrect ICE drivers loaded when I installed Atmel Studio. [![Device Manager conflict][1]][1]

Arduino requires libusb-win drivers, which can be checked with Zadig.   Available here: [https://zadig.akeo.ie/][2]

This problem was 99% solved (with help) by selecting [![Install WCID driver][3]][3] and the libusb-win32 driver using Zadig.   I say 99% solved, because _my program now loads and runs!_ , but I do get the red 'X' there as the WCID status.

Apologies if this amendment to the original question is not in the correct context, this is new to me.   Thank You.
Jaco

  [1]: https://i.stack.imgur.com/4CAWp.jpg
  [2]: https://zadig.akeo.ie/
  [3]: https://i.stack.imgur.com/SCZCk.jpg

title: Programming 328PB from Arduino IDE using Atmel-ICE to ICSP port

Answers: 1

body:
Hello The 328 "PB" has major issues with running external clocks...(yes I have first hand experience with this PB model)... Try switching to the internal oscillator as I can testify first hand the the external clocks on the PB don't work correctly. They tend to sell the PB a few bucks cheaper because you will only buy them once and only once when you find out how bad the external crystal clock driver is. If you look at the latest datasheet for the PB they try and talk their way out of the bad driver by explaining how you need to match capacitors with the following snippet. I call BS as the 328p never needed such precision on it Xtal1 & 2 pins to run but to be fair they PB is meant to be low power.

This Crystal Oscillator is a low power oscillator, with reduced voltage swing on the XTAL2 output. It gives
the lowest power consumption, but is not capable of driving other clock inputs, and may be **more
susceptible to noise in noisy environments.**
The crystal should be connected as described in Clock Source Connections. When selecting crystals,
load capacitance must be taken into consideration. The capacitance (Ce+Ci) needed at each TOSC pin
can be calculated by using:
�� + �� = 2�� − ��
where:
• Ce - is optional external capacitors. (= C1, C2 as shown in Figure 11-2)
• Ci - is the pin capacitance in Table 11-3.
• CL - is the load capacitance specified by the crystal vendor.
• CS - is the total stray capacitance for one XTAL pin.
Table 11-


body:
I have created an arduino shield and i want to measure the voltage between the GND pin and 5V pins, to see if i see a voltage difference between the two points, in order to test if my pcb is fine.

My concern is since these are right next to each other and my multimeter probes are thick.

If the multimeter probe that 5V pin touches the GND pin, in other words, if i short circuit the 5V and GND pins, then will my arduino be safe?

I am afraid of damaging the arduino.

title: Short circuiting GND and power pins

Answers: 3

body:
It all depends on how you are powering the board.

If you're running it from USB then the computer should shut off the power to the USB port. If it doesn't then the Arduino has a small self-resetting fuse on the USB power which should shut the power off for you.

However if you're powering through the barrel jack there's no protection. Worst case scenario: it will blow the voltage regulator, which then "fails short", meaning it passes the whole of the input voltage through to the microcontroller, which then kills it.

So yes, it's possible to damage the Arduino with a short circuit.

Most multimeters have a better way of testing the board though: either the "beepy" continuity test, or the resistance mode.  You can use that to test the continuity or resistance between your 5V and GND pins without having to connect the shield to the Arduino at all. 100% safe.

body:
No, shorting +5 to Gnd is not safe, although a brief short might not cause damage. If it persists, you could burn a trace, overheat the voltage regulator, or damage the computer USB if that is what powers your Arduino. Most computers will sense that short and disconnect power to that USB until the short goes away, but you don't want to count on it!

If your meter has probes with clip-ends, use those to clip two bread-board wires, and probe the Arduino pins by plugging the wires into your shield. If the shield has no pin sockets installed, at least the bread-board wires are small enough not to short adjacent pins.

body: mostly yes , mostly no . my old arduino got a little too much dusty and when i cleaned it with mild amount of water (nervously) and dried it partially . nothing happened to it . it was operating normally . but some beginner manuals tell not to short circuit it . dunno what's going on ...


body:
I have a Arduino uno board, ESP-01 board and a logic level shifter (bidirectional) and to program the esp module i wired my Arduino and esp like this

>__Arduino uno(atmega328p removed)__  --> __level shifter__ --> __ESP-01__\
>5v --> highvolt\
3v3 --> lowvolt\
TX --> ch1 --> TX\
RX --> ch2 --> RX\
proper ground connections

but when i click upload the RX pin lights up indicating its receiving data but esp doesn't respond to that when i reset the module while its uploading the compiler throws this
```esptool.py v2.8
Serial port COM3
Connecting........_____....._____....._____....._____....._____....._____.....____Traceback (most recent call last):
  File "C:\Users\TRAJU\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4/tools/upload.py", line 65, in <module>
    esptool.main(cmdline)
  File "C:/Users/TRAJU/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.4/tools/esptool\esptool.py", line 2890, in main
    esp.connect(args.before)
  File "C:/Users/TRAJU/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.4/tools/esptool\esptool.py", line 483, in connect
    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header
_
the selected serial port _
 does not exist or your board is not connected
```

It as working fine yesterday and it stopped today :(

Please help and thanks in advance.

title: ESP-01 not responding to serial data while programming with esptool.py

Answers: 1

body:
I found my problem.

esptool.py uploads the firmware at 115200 baud rate, which my logic level converter couldn't handle.  I found this out after writing this question. I thought of connecting RX and RX directly to the ESP module's RX and TX and it uploaded the program. Maybe I am wrong.  Please, if any one know why this happened I am curios to know.  Thanks in advance. ;)


body:
I need some help :)
 1. Is it even doable?
 2. Is there anyone who wants to help me program it?

My wish:
I want to receive a iphone notification when 1 arduino analog input drop from 5 to 0 volt.

Then (later) when the voltage goes back to 5V i want another message.

It needs to be over Wifi (not BT).

Is there anyone that can help me with this?

Thanks in advance

title: Arduino analog input to iphone notification

Answers: 1

body:
It is totally doable, but we cannot give detailed tutorials here, since this is a simple Q&A site. So I will point you to a direction, that can lead you to the solution.

When building IOT devices with Arduino (and thats exactly, what you are doing) there are 2 internet services, that are commonly used for getting information from the device to other devices (like your phone):

- Blynk
- IFTTT (means If This Then That)

Both have apps and can be used to push notifications, when your IOT device does a webrequest to the service. There are also libraries for Arduino available (at least for Blynk). There are many tutorials out there, so I suggest, that you search for yourself and try some of them.

For the hardware of your IOT device, I would suggest an ESP board, because they already have Wifi build in, for example the ESP32 gives you great IO capabilities.


body:
I'm not that good at this. Calculates RPM through Peripheral Speed and Interrupt.

Everything works fine when I show this in the IDE with `Serial.print` without OLED. When I connect an SSD1306 OLED I2C, the interrupt stops working. No `serial.print`.

If I uncomment the `display.display()`, Same problem with `display.setRotation(90)`: everything is fine and `serial.print` starts working, but of course not the OLED.

In the code I have a `void` addressing, `visadisplay()`. If I put this addressing in `void loop ()` then everything works but then there is a risk of unsynchronization, wrong values. I have also removed `visadisplay();` without change.

Help...

```c++
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// Function for serial display.
// Connections for Nano.
// Hall sensor connection: (Signal out) --- (D2).
// Display connection: (SDA) --- (4A) / (SCL) --- (A5)

volatile unsigned long PulsTid = 0UL;
volatile unsigned long StartTid = 0;
volatile unsigned long SlutTid = 0;
volatile unsigned long CalcTid = 0;
volatile float omkrets = 7.5;
volatile float HastighetPerferi = 0;
volatile unsigned long Rpm = 0;
volatile float Vinkel = 0UL;

void isr() { // interrupt service routine
  Vinkel = 0;
  StartTid = millis();
  CalcTid = SlutTid;

  detachInterrupt(0);             //detaches the interrupt while calculating

  PulsTid = (StartTid - SlutTid);
  HastighetPerferi = (omkrets / PulsTid);
  SlutTid = StartTid;
  Rpm = ((HastighetPerferi / (omkrets / 1000) * 60) / 2); // Calculate speed

  visadisplay();
  attachInterrupt(0, isr, FALLING);  //attaching the interrupt again
}

void visadisplay(void) {
  Serial.print("Varvtal: ");
  Serial.println(Rpm);

  display.setRotation(90);
  display.clearDisplay();
  display.setTextSize(1);              // Text size.
  display.setTextColor(SSD1306_WHITE); // White text.
  display.setCursor(0, 0);             // Start position
  display.println("RPM: ");
  display.setCursor(40, 10);
  display.setTextSize(2);
  display.print(Rpm);
  display.display();
}

void setup() {
  Serial.begin(115200);
  attachInterrupt(0, isr, FALLING);  //attaching the interrupt

  //SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }
}

void loop(){
}
```

title: Arduino, problem with interrupt and SSD1306 OLED

Answers: 2

body:
Your problem is (most likely) that you are doing *everything* from an interrupt. That is not only bad practice, but on Arduinos it is generally impossible.

On small microcontrollers you typically only have one interrupt priority (occasionally two). That means that only one interrupt can run at a time, and if an interrupt is running then no other interrupt can interrupt it.

So anything that relies on interrupts to operate can never be used inside an interrupt service routine, or it will never function.

That includes things like `delay()` and, depending on the implementation, such things as `Wire` (I2C) and `SPI`.

Instead your ISR really should be as short as possible. It should at most do any short calculations and store results, and then indicate (through the use of a *semaphore*) to the main thread that it should do some work.

The simplest "fix" to your problem would be to move `visadisplay()` into `loop()` and in `isr()` simply set a `bool` flag when there is data to display. Your `loop()` then checks that flag and, if set, resets it and calls `visadisplay()`.

Also, you don't need to detach and re-attach the interrupt all the time - if the ISR is running then interrupts can't happen anyway.

```c++
// ... snip ...
volatile bool doDisplay = false;

void isr()          //interrupt service routine
{
  Vinkel = 0;
  StartTid = millis();
  CalcTid = SlutTid;

  PulsTid = (StartTid - SlutTid);
  HastighetPerferi = (omkrets/PulsTid);
  SlutTid = StartTid;
  Rpm = ((HastighetPerferi/(omkrets/1000)* 60)/2);  //Calculate speed

  doDisplay = true; // Signal to the main thread there's data to display
}

// ... snip ...

void loop() {
    if (doDisplay) {       // If there is something to display
        doDisplay = false; // then clear the flag for next time
        visadisplay();     // and display the data.
    }
}
```

body:
About rotating text on OLED, rotation codes are 0, 1, 2, 3
(see [Adafruit web site](https://learn.adafruit.com/adafruit-gfx-graphics-library/rotating-the-display)).

So your code should look like:
```c++
  Serial.print("Varvtal: ");
  Serial.println(Rpm);

  display.setRotation(1);
  display.clearDisplay();
 ```


body:
I want to give missed call to GSM module; how to do that? Whenever I call to GSM module, after 3 RINGs, it should be disconnected. How to do this?

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

String string = "";
int ring=0;
int i;
//Create software serial object to communicate with SIM800L
 SoftwareSerial mySerial(3, 2); //SIM800L Tx & Rx is connected to Arduino #3 & #2

void setup() {
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM800L
  mySerial.begin(9600);

  Serial.println("Initializing...");
}

void loop() {
  serialEvent();
  if (ring >= 1) {
    Serial.write("ATH");
  }
}

void serialEvent() {
  while (mySerial.available()) {
    char read_char = Serial.read();
    string += read_char;
    i++;

    if (string[i - 4] == 'R' && string[i - 3] == 'I' && string[i - 2] == 'N' && string[i - 1] == 'G') {
      ring = 1;
    }
  }
}
```

title: Missed call to GSM

Answers: 0


body:
I am a beginner on Arduino. I have a project that I will only be using: a heart rate sensor whose values I am displaying on an LCD display. The code compiles and uploads once I set my project up, but the value doesn't appear on my LCD screen.

```c++
#include<LiquidCrystal.h>
#include <TimerOne.h>

LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
int HBSensor = 4;
int HBCount = 0;
int HBCheck = 0;
int TimeinSec = 0;
int HBperMin = 0;
int HBStart = 2;
int HBStartCheck = 0;

void setup() {
  lcd.begin(20, 4);
  pinMode(HBSensor, INPUT);//heartbeat sensor
  pinMode(HBStart, INPUT_PULLUP);
  Timer1.initialize(800000);
  Timer1.attachInterrupt(timerIsr);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Current HB: ");
  lcd.setCursor(0, 1);
  lcd.print("Time in Sec :");
  lcd.setCursor(0, 2);
  lcd.print("HB per Min :0.0");
}

void loop() {
  if (digitalRead(HBStart) == LOW) {
    lcd.setCursor(0, 3);
    lcd.print("HB Counting ..");
    HBStartCheck = 1;
  }
  if (HBStartCheck == 1) {
    if ((digitalRead(HBSensor) == HIGH) && (HBCheck == 0)) {
      HBCount = HBCount + 1;
      HBCheck=1;
      lcd.setCursor(14, 0);
      lcd.print(HBCount);
      lcd.print(" ");
    }
    if ((digitalRead(HBSensor) == LOW) && (HBCheck == 1)) {
      HBCheck=0;
    }
    if (TimeinSec == 10) {
      HBperMin=HBCount * 6;
      HBStartCheck=0;
      lcd.setCursor(14, 2);
      lcd.print(HBperMin);
      lcd.print(" ");
      lcd.setCursor(0, 3);
      lcd.print("Press Button again.");
      HBCount = 0;
      TimeinSec = 0;
    }
  }
}

void timerIsr() {
  if (HBStartCheck == 1) {
    TimeinSec = TimeinSec + 1;
    lcd.setCursor(14, 1);
    lcd.print(TimeinSec);
    lcd.print("");
  }
}
```

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

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

title: LCD display interfaced with Arduino Uno not displaying values

Answers: 0


body:
I would like to know if someone has experience with measuring high voltages using an Arduino.

I know you can use resistors to lower the voltage, however.

I want to be able to measure the pulses of an electric fence used to prevent farm animals from escaping. These pulses are high-voltage and will not always be a similar voltage. I want to read these voltages, to scan for differences.

So, I wondered if someone has done something like that, and if the Arduino gets weird when it gets a voltage above 5 V at a low amperage on its analog port.

--here some possible solutions for those wanting to know the answer--
-mostly based on comments and answers below-

 - Using resistors as a voltage divider while keeping an eye on the maximum spark gap distance and capacitive coupling.
 - using a transformer/coils to reduce the voltage.
 - using a high voltage probe to measure it.
 - using neon bulbs or other light sources to measure it.
 - charging a capacitor and measuring discharge time with high resistance(only works for the total power)

-this list is meant as a summary of what is discussed further ideas and solutions are still welcome-

title: Arduino measuring high-voltage electric fence

Answers: 2

body:
You are talking about measuring 2 to 10 kV pulses, with about 1 to 5 J of energy per pulse.

The maximum current may be very low, but the voltages you want to measure are very high, and will very probably damage your Arduino without proper measures.

You will at least need a voltage divider to reduce the voltage the Arduino sees to 5 V (or 3.3 V for some Arduinos) to be able to make a measurement with the Arduino's ADC.

The voltages are high enough to bridge a fair distance with a spark; they could well bridge a physically small resistor or the distance between two connections on your breadboard or PCB.

To be honest, I think you shouldn't go anywhere near such voltages with an Arduino, unless you know exactly what you are doing when preparing the signal for an Arduino's ADC pin.

body:
When you say 'scan for differences', do you mean differences along the fence, or something else?  Do you plan to use the Arduino as a portable voltmeter?  If so, buying a HV probe for a standard voltmeter sounds a lot more practical.

However, if you plan to install multiple sensor points along the fence so that you can continually monitor pulse amplitudes along the fence, then that is a different kettle of fish, especially if you are thinking about outdoor use over a long fence length.

Can you elaborate a bit, please?


body:
compared to the microchip's PICs:

pic16f's does not have an onboard CAN peripheral. so you need an SPI - CAN controller (like MCP2515).

some PIC18f's have an onboard CAN controller, and only need a CAN transceiver. In these cases there are exclusive TX and RX pins to be used.

Are there specific pins to be used as a CAN bus on esp32?
peripherals like adc, i2c and others need to use specific pins. Does this happen with CAN too?

I'm using the following configuration:
2 ESP32 devboard boards - arduino on PlatformIO
Pin 5 as TX and pin 4 as RX (already in the CAN library),
2 Sn65hvd230 transceiver modules

I looked for information about it in the documentation, but I couldn't find it.

I appreciate any help.

title: What are the correct pins for TWAI (CAN) on ESP32?

Answers: 2

body:
> I looked for information about it in the documentation, but I couldn't
> find it.

Well, some of [their documentation][1] says:

> The TWAI controller’s interface consists of 4 signal lines known as
> TX, RX, BUS-OFF, and CLKOUT. These four signal lines can be routed
> through the GPIO Matrix to the ESP32’s GPIO pads.

And that sort of seems to be backed up by their examples that make use of [TWAI_GENERAL_CONFIG_DEFAULT][2] to generate a structure with the arguments [filling fields that use `gpoi_num_t`.][3]

There is documentation to the GPIO Matrix generally in the [ESP32 technical reference][4].  It is described there as follows:

> The ESP32 chip features 34 physical GPIO pads. Each pad can be used as
> a general-purpose I/O, or be connected to an internal peripheral
> signal. The IO_MUX, RTC IO_MUX and the GPIO matrix are responsible for
> routing signals from the peripherals to GPIO pads. Together these
> systems provide **highly configurable I/O.**

(My emphasis in the above).

And also there is a table (Table 25) in Appendix 2 of the [ESP32 datasheet][5] for the GPIO matrix.

Many of the small chips, like the PIC16F series ones, have no internal routing for peripherals, except for deciding which of one or two special functions to use rather than GPIO and ADC channels.  Most of the of the ATTiny and ATMega series AVR chips that are not in the 0- and 1- series don't.  The 1- and 0- series an a few of the older series parts (e.g. ATTiny841) give you a fixed number (usually two) pre-determined destinations to chose from for some peripherals.

This sort of thing gets more flexible as you get into larger chips, but the having that "matrix" feature that lets choose more freely is *comparatively* rare.  Some of the Cypress "PSoC" labeled chips have this sort of feature.

  [1]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/twai.html
  [2]: https://github.com/espressif/esp-idf/blob/v4.2/components/driver/include/driver/twai.h#L43
  [3]: https://github.com/espressif/esp-idf/blob/v4.2/components/driver/include/driver/twai.h#L98
  [4]: https://www.espressif.com/sites/default/files/documentation/esp32_technical_reference_manual_en.pdf#iomuxgpio
  [5]: https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf

body:
When using arduino and the esp32 core, **any pin** can be assigned to the builtin TWAI controller.

If you use the esp32_can library [https://github.com/collin80/esp32_can][1]
you may change the pin assignment in the following file:

C:\Users\USER\Documents\Arduino\libraries\esp32_can-master\src\esp32_can.cpp

> //Set these to the proper pin numbers for you board. Set by default to correct for EVTV ESP32-Due

             //rxpin       txpin

ESP32CAN __attribute__((weak)) CAN0(**GPIO_NUM_16**, **GPIO_NUM_17**) ;

>//Select and uncomment the proper module you've got connected via SPI

//CS, INT

MCP2517FD __attribute__((weak)) CAN1(5, 27) ;

//MCP2515 __attribute__((weak)) CAN1(5, 27) ;

  [1]: https://github.com/collin80/esp32_can


body:
I have a sht30 that will output correct temperature readings for about 5 min and then will drift off.

So I'm trying to hit the reset every few seconds to keep the readings accurate.

I am on a nano connecting d4 to the sht30 reset pin, but I don't appear to be resetting. My temp still drifts.

How do you correctly hit the reset on a sht30?

code:

    #include <Wire.h>

    // SHT31 I2C address is 0x44(68)
    #define Addr 0x45

    int reset_pin = 3; // reset pin is set to d4 on board.
    int counter = 0; //reset counter

    void setup()
    {
      // Initialise I2C communication as MASTER
      Wire.begin();
      // Initialise serial communication, set baud rate = 9600
      Serial.begin(115200);
      delay(300);
    }

    void loop()
    {
      unsigned int data[6];

      // Start I2C Transmission
      Wire.beginTransmission(Addr);
      // Send 16-bit command byte
      Wire.write(0x2C);
      Wire.write(0x06);
      // Stop I2C transmission
      Wire.endTransmission();
      delay(300);

      // Start I2C Transmission
      Wire.beginTransmission(Addr);
      // Stop I2C Transmission
      Wire.endTransmission();

      // Request 6 bytes of data
      Wire.requestFrom(Addr, 6);

      // Read 6 bytes of data
      // temp msb, temp lsb, temp crc, hum msb, hum lsb, hum crc
      if (Wire.available() == 6)
      {
        data[0] = Wire.read();
        data[1] = Wire.read();
        data[2] = Wire.read();
        data[3] = Wire.read();
        data[4] = Wire.read();
        data[5] = Wire.read();
      }
      // Convert the data
      int temp = (data[0] * 256) + data[1];
      float cTemp = -45.0 + (175.0 * temp / 65535.0);
      float fTemp = (cTemp * 1.8) + 32.0;
      float humidity = (100.0 * ((data[3] * 256.0) + data[4])) / 65535.0;

      // Output data to serial monitor
      Serial.print("Temperature in Celsius :");
      Serial.print(cTemp);
      Serial.println(" C");
      Serial.print("Temperature in Fahrenheit :");
      Serial.print(fTemp);
      Serial.println(" F");
      Serial.print("Relative Humidity :");
      Serial.print(humidity);
      Serial.println(" %RH");
      delay(500);
      if(counter == 25){
        digitalWrite(reset_pin, HIGH); // sets the digital pin 13 on
        delay(1000);            // waits for a second
        digitalWrite(reset_pin, LOW);  // sets the digital pin 13 off
        delay(1000);
        counter  = 0;

      }
      counter++;
      Serial.println(counter);
    }

title: How to you initialize a reset on a sht30 digital thermometer?

Answers: 1

body:
You need to give a brief LOW pulse, not a long HIGH pulse:

In setup:
```c++
pinMode(reset_pin, OUTPUT);
digitalWrite(reset_pin, HIGH);
```

When you want to reset:

```c++
digitalWrite(pin_reset, LOW);
delay(1);
digitalWrite(pin_reset, HIGH);
```


body: For my work, I need to acquire data at a high sample rate (>100kSa/sec) using Arduino Portenta H7, which has 3 X 16-bit ADCs. Portenta H7 has STM32H747XI microcontroller. I don't want to use Serial.print command as I came to know that this command takes much time to execute, which makes achieving the targeted sample rate impossible.  What are the other possible ways to store the data from Arduino while maintaining this high sample rate? For example, saving the data and then printing them all at once at the end of testing( 3-5 second testing period). e.g. using an SD card or through saving in Arduino internal memory? Can you suggest techniques employed for high-sample rate data acquisition from Arduino?

title: Storing data from Arduino without Serial print- High Sample rate

Answers: 1

body:
The [Portenta][1] has a beast of an  STM32H7 Cortex M7 and a minimum of 8M bytes of external SDRAM in addition to the 1M on-chip.

You need to capture 2channels x 2 bytes x 100K/s x 5s = 2M bytes of data, so storing it on the on-board RAM and spitting it out later seems like a viable and low-risk approach.

A slow serial link might take a few minutes to transmit 2M bytes of data, but you have various other options if that is objectionable.

  [1]: https://www.arduino.cc/pro/hardware/product/portenta-h7


body:
I have an ESP32 cam, and I attached an i2c light sensor to it. I need to read the light level at startup, then I don't need the i2c connection again.
The problem is, the board uses 2 i2c connections I think (for the camera and such). So I use my custom pins for the sensor (15 and 16). It works well, I can read the light just fine, but then the camera fails because (I believe) the Wire.begin(15,16) changes the default pins and the camera gets confused.

So I would like to do something like Wire.end() to forget that I started the Wire.begin(). Any idea on how I can do that?

Here is the relevant code:

    #define I2C_SDA 16
    #define I2C_SCL 15
    BH1750 lightMeter (0x23);
    TwoWire I2Clightmeter= TwoWire(1);

    void setup()
    {
      I2Clightmeter.begin(I2C_SDA, I2C_SCL);
      lightMeter.begin(BH1750::ONE_TIME_HIGH_RES_MODE,0x23,&I2Clightmeter);

      delay(1000);
      uint16_t lux = lightMeter.readLightLevel();

    //rest of the code

title: How to close/end a Wire.begin()?

Answers: 1

body:
There is a way of doing it that's ESP32 specific. However it means changing how you define your I2C object.

The ESP32 system is set up so that if the TwoWire instance is destructed the I2C bus is released. But you can't do that with the way you normally define the object. So instead you have to use dynamic allocation to control it:

```c++
TwoWire *I2Clightmeter;

void setup() {
    I2Clightmeter = new TwoWire(1);
    I2Clightmeter->begin(I2C_SDA, I2C_SCL);
    lightMeter.begin(BH1750::ONE_TIME_HIGH_RES_MODE,0x23,I2Clightmeter);
    delay(1000);
    uint16_t lux = lightMeter.readLightLevel();
    delete I2Clightmeter;
    // rest of code
}
```

Another alternative is to keep the TwoWire object in a local scope so that it gets destroyed when you leave that scope - maybe with a special function for it:

```c++

uint16_t getLux() {
    TwoWire I2Clightmeter(1);
    I2Clightmeter.begin(I2C_SDA, I2C_SCL);
    lightMeter.begin(BH1750::ONE_TIME_HIGH_RES_MODE,0x23,&I2Clightmeter);
    delay(1000);
    return lightMeter.readLightLevel();
}

void setup() {
    uint16_t lux = getLux();
    // rest of code
}
```


body:
i'm making a device that's kind of based on Russian roulette.

I have 5 LED's  that are normally  white, and when you press the button one of the LED's is marked red.

After some tinkering I figured out how to do this with  the help of adafruit neopixel, but i also want to have a RGB strip with a rainbow effect running on the same arduino at the same time (or only just before the button is pressed).

The problem is that it interferes with the activation and running of my  Russian roulette.
I know you can't run two loops at a time, but is there some kind of way to solve this?

I will put my code below, thanks in advance!

```
#include <Adafruit_NeoPixel.h>

const int buttonPin = 2;

int buttonState = 0;

#define LED_PIN  6

#define LED_COUNT 5

#define LED_PIN2  7

#define LED_COUNT2 60

Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip2(LED_COUNT2, LED_PIN2, NEO_RGBW + NEO_KHZ800);

uint32_t wit = strip.Color(255, 255, 255);
uint32_t wit2 = strip2.Color(255, 255, 255);

void setup() {

  randomSeed(analogRead(0));
  strip.begin();
  strip.show();
  strip.setBrightness(255);
  strip2.begin();
  strip2.show();
  strip2.setBrightness(255);
  pinMode(buttonPin, INPUT);

}

void loop() {
    rainbow(10);
    shotknop();
}

void shotknop (){
  buttonState = digitalRead(buttonPin);
    strip.fill(wit, 0, LED_COUNT);
    strip.show();
    if (buttonState == HIGH) {
    theaterChase(strip.Color(255, 255, 255), 150);
    shot(strip.Color(0, 255, 0), 100, 5000, 0);
    }
    else{
      }
}

void shot (uint32_t color, int wait1, int wait2, int rng) {
    strip.clear();
    rng = random(LED_COUNT);
    for(int a=0; a<15; a++) {
      strip.setPixelColor(rng, color);
      strip.show();
      delay(wait1);
      strip.setPixelColor(rng, (0, 0, 0));
      strip.show();
      delay(wait1);
  }
    strip.setPixelColor(rng, color);
    strip.show();
    delay(wait2);
}
void colorWipe(uint32_t color, int wait) {
  for(int i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, color);
    strip.show();
    delay(wait);
  }
}
void theaterChase(uint32_t color, int wait) {
  for(int a=0; a<10; a++) {
    for(int b=0; b<3; b++) {
      strip.clear();

      for(int c=b; c<strip.numPixels(); c += 3) {
        strip.setPixelColor(c, color);
      }
      strip.show();
      delay(wait);
    }
  }
}
void rainbow(int wait) {
  for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
    for(int i=0; i<strip2.numPixels(); i++) {
      int pixelHue = firstPixelHue + (i * 65536L / strip2.numPixels());
      strip2.setPixelColor(i, strip2.gamma32(strip2.ColorHSV(pixelHue)));
    }
    strip2.show();
    delay(wait);
  }
}
```

title: two adafruit neopixel loops

Answers: 0


body:
How can I use **RN42** sketch by silverball

    /*
      RN42_HIDRaw_Arduino.cpp - Roving Netowrks RN42 Bluetooth HID raw library
      Developed by Chris Leitner - 2012

      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
      License as published by the Free Software Foundation; either
      version 2.1 of the License, or (at your option) any later version.

      This library is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      Lesser General Public License for more details.

      You should have received a copy of the GNU Lesser General Public
      License along with this library; if not, write to the Free Software
      Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

      RN42 HID raw report format:
      |start(1 byte)|length(1 byte)|descriptor(1 byte)|data(length - 1 [for the descriptor])
      Keyboard:
      |0xFD|9|1|modifier|0x00|code 1|code 2|code 3|code 4|code 5|code 6
      Keyboard modifier bits (sent as one byte)
      bit 7  |bit 6   |bit 5  |bit 4 |bit 3 |bit 2 |bit 1  |bit 0
      rt GUI |rt alt  |rt shift |rt ctrl|lt GUI |lt alt |lt shift |lt ctrl

      You must initialize the Serial library in your code before you call any of these functions.
      The default speed for the RN42 is 115200 - add this in the setup function Serial.begin(115200);
      */

    #include <stdlib.h>
    #include <string.h>
    #include <inttypes.h>

    #include "RN42_HIDRaw_Arduino.h"

    RN42_HIDRaw_Arduino::RN42_HIDRaw_Arduino(){
    }

    //Sends a raw report for a keyboard HID
    void RN42_HIDRaw_Arduino::SendKeyboardRaw(char raw_data[], uint8_t mod_bit){

     //write the RN42 Keyboard raw header
     Serial.write((uint8_t)0xFD); //start byte indicator for RN42
        Serial.write((uint8_t)0x09); //length of the raw report (how many bytes)
        Serial.write((uint8_t)0x01); //descritptor byte see the RN42 HID manual for details 0x01 is keyboard
        Serial.write((uint8_t)mod_bit); //modifier bit (indicates shift, control, and other keys (see comments above)
        Serial.write((uint8_t)0x00); //unused always send 0x00
     //write the key press data
     //each of these should be an ASCII keycode indicating a keypressed
     //example 0x04 is an 'a' see the RN42 HID manual for a list of codes
     Serial.write((uint8_t)raw_data[0]);
        Serial.write((uint8_t)raw_data[1]);
        Serial.write((uint8_t)raw_data[2]);
        Serial.write((uint8_t)raw_data[3]);
        Serial.write((uint8_t)raw_data[4]);
        Serial.write((uint8_t)raw_data[5]);
    }

    //This function just send a raw report with no keys or modifiers pressed
    void RN42_HIDRaw_Arduino::SendKeyboardRawBlank(void){

     //write the RN42 Keyboard raw header
     Serial.write((uint8_t)0xFD);
        Serial.write((uint8_t)0x09);
        Serial.write((uint8_t)0x01);
        Serial.write((uint8_t)0x00);
        Serial.write((uint8_t)0x00);
     //write the key press data
     Serial.write((uint8_t)0x00);
        Serial.write((uint8_t)0x00);
        Serial.write((uint8_t)0x00);
        Serial.write((uint8_t)0x00);
        Serial.write((uint8_t)0x00);
        Serial.write((uint8_t)0x00);
    }

    //Sends a raw report for a gamepad
    void RN42_HIDRaw_Arduino::SendGamepadRaw(char x_left, char y_left, char z_pos, char rot_pos, uint8_t buttons1, uint8_t buttons2)
    {
     //write the header part for RN42
     Serial.write((uint8_t)0xFD); //start byte
     Serial.write((uint8_t)0x06); //length of the descriptor
     //gampad positions and buttons
     //on a gamepad there typically is two analog joysticks one is typically used to
     //indicate x/y position and one is for z/rotation.
     Serial.write((uint8_t)x_left); //value between -127 to 127 indicating the x postition
     Serial.write((uint8_t)y_left); //value between -127 to 127 indicating the y postition
     Serial.write((uint8_t)z_pos); //value between -127 to 127 indicating the z postition
     Serial.write((uint8_t)rot_pos); //value between -127 to 127 indicating the rotation postition
     //one bit for each button pressed there can be a total of 16 buttons one byte in each
     //set the bit to show a button pressed and clear the bit to indicate not pressed
     Serial.write((uint8_t)buttons1);
     Serial.write((uint8_t)buttons2);
    }

    void RN42_HIDRaw_Arduino::SendMouseRaw(uint8_t buttons, uint8_t x_stop, uint8_t y_stop, uint8_t wheel){
     //write the header part for RN42
     Serial.write((uint8_t)0xFD);
     Serial.write((uint8_t)0x05);
     Serial.write((uint8_t)0x02);
     //gampad positions and buttons
     Serial.write((uint8_t)buttons);
     Serial.write((uint8_t)x_stop);
     Serial.write((uint8_t)y_stop);
     Serial.write((uint8_t)wheel);
    }

And act Like Keyboard.h do ? just simply putting `keyboard.press;`

JUst noob question.

title: RN42 Bluetooth HID KEYBOARD sketch by silverball

Answers: 1

body:
if you are using an Arduino, I recommend you to use the BPlib, it's a free arduino library that contains functions that are similar to the Keyboard.h.

The following link is from the Arduino website: https://www.arduino.cc/reference/en/libraries/bplib/

When you download the Lib, take a look at the examples given by the creator of the Library, all the example code have the explanation of each funcition used, and you can also check for some documentation online. I hope that this help you!


body:
I need a short beep for every minute of change. I wrote a separate function. The signal duration should be 50 ms, the rest of the time the emitter connected to the A1 contact should be silent.

A really working sketch is shown below:

    uint32_t mysound; // Variable for storing time (duration of the sound signal)
    uint32_t myTimer1;
    uint32_t t; //Time that always increases
    byte seconds; // Seconds
    byte minutes; // Minutes
    int k = 1;
    void setup()
    {
      DDRC = B00000010; // Set pin A1 as output
      //      76543210
      Serial.begin(9600);
      myTimer1 = millis();
    }

    void loop()
    {
      t = (millis() - myTimer1) / 1000; // Time in seconds
      seconds = t % 60; // when 60 seconds are reached, it is reset to zero
      minutes = t / 60 % 60; // Counts the minutes and drops to zero when 60 minutes are reached
      Serial.println(seconds);
      if (seconds == 0 && k)
      {
        sound();
      }
      if (seconds > 0) k = 1;
    }

    void sound()
    {
      mysound = millis();
      while (millis() - mysound < 50)
      {
        PORTC = B00000010; // We set high voltage on pin A1 for a time of 50 ms
      }
      k = 0;
      PORTC = B00000000;
    }

title: Switch on the piezo emitter for a short time

Answers: 2

body: Your `myTimer1` in `t = (millis() - myTimer1) / 1000;` is not set

body:
In addition to Qareke's answer, you also have a problem with the `mysound` variable. You only set this timestamp to `millis()` inside your `millis()` if statement. `mysound` is global and thus will be implicitly initialized with zero. So, by the time, that the code reaches the if statement, the difference between `millis()` and `mysound` is most likely already too big, thus the timestamp gets never set.

**Solution:** You need to move 2 lines around in your code:

- Move the `mysound = millis();` statement up into the `if (seconds == 0)` statement.
- Move the `sound();` statement outside of the if statement directly into the `void loop()` function (for example directly after the `if (seconds == 0)` statement).

Now the `sound()` function will always be executed, but it will only do a sound, if the timestamp was set to `millis()` previously, and then only for 50ms. Now we only need to make sure, that the timestamp variable `mysound` will only be set once, when the seconds get zero. You could either introduce a new flag variable for that, or you could just use the timestamp itself and check, if more than 1s passed since the last time the timestamp was set. So you need to change

    if (seconds == 0)

to

    if (seconds == 0 && millis() - mysound > 1100)

I used `1100` (1.1s) here, to make sure, that there is no bad edge case happening. Since `seconds` will only get zero every minute, that shouldn't be a problem.


body:
I'm new here and to the aurdino.

I'm building a 3D printed robotic arm controlled by a EMG sensor. I purchased a V3 EMG board and leads on Aliexpress. Here's a list of the things I've purchase for this project

 - Arduino Uno

 - EMG sensor
 - 2 MG996R servos 7.2 max voltage I know not to power these through the
   board.
 - X4 AA battery pack with male barrel input lead to power the arduino.
   Wiring, header pins and cables.

I don't have any breadboards BTW.

The functionality is basic, servos on pulleys and strings, I'm looking for one servo to control the open close hand function, and the other is to open and close the index and thumb for a pinch function to pick up smaller objects.

I need to know the following,

Option to power servo, EMG sensor and arduino from single power source or two batteries and how to wire these a simple picture or schematic would be great.

What code can I quickly copy and paste to perform the functions I mentioned.

I do have some very basic DC electronic experience.

I just don't want to damage my components by just experimenting as it takes weeks to replace them otherwise.  Thanks.

title: Aurdino EMG sensors and servos?

Answers: 0


body:
Following the suggestion of Fiendish to post here:
Hello

Nick, thank you very much for this I2C-anything library that works a treat with two arduinos (one sender, one receiver).

Is there any suggested method or at least an example sketch of having two different sender arduinos send their floats to the receiver  e.g. by alternating slave adresses in the receiver loop? With a simple re-insertion of the section (but with a different address) into the receiver sketch restarting with Wire.begin() and then Wire.begin(new address) things are botched up.

In addition: if I define -float f in sender A- and -float e in sender B- the receiver keeps on printing the float e value in the serial.Print ("float value e"); serial.println(e); -postion, no matter if I swap from Sender A to sender B -by changing the SCL/SDA connections,  and the serial.Print ("float value f");serial.println(f); prints fancy numbers.

If at least the swapping would cause the floats to be printed in the correct position I could maybe switch the respecive senders I2C down in turns....

Of course hotplugging /hotswitching SDA and SCL from senders causes the senders sketch to be blocked at times.

The idea of sending data from Sender B to Sender A, and from Sender A to to receiver left me frustrated the last few hours, due to the fact that Im a total noob and/or that its simply not possible to have two masters send to one slavereciver without running into i2C conflicts. Unless some unknown acrobatics is performed.

The ultimate idea is to have two separate megas (with i2c sensors attached to them) execute feedbackloops and still be able to transfer these values and other values to a display via I2C. the alternate way could be that a dac is used to translate the I2C values into voltages that hardware....)

Any help greatly appreciated
Best
Daniel

title: I2C_anything from Nick Gammon. Value of two senders to be received and printed by receiverslave

Answers: 1

body:
Dear Chrisl and Sim Son

Please accept my apologies for not replying earlier, am still recovering form a timbering accident and have limited painless access to my laptop.

thinking in boxes: BOX 1 = Arduino Mega number one regulates the pressure of proportional valves (via I2C conected quaddac MCP4728 to 0-10V) based on the flowvalues of 4 I2C-connected FLowsensors.

BOX 2= Arduino Mega number two does the same with a second set of 4 flowsensors and 4 analog proportional valves.

Splitting this to two arduinos was originally because a) i was unable figure out how to get 2 DACS on the same I2C line and handle the LDAC address fiddling which turned out to be a good approach because the total number of required GPIO pins exceeds the available number of pins of one Mega (many rotary encoders attached, TTL signal delayer for 8 channels, pots to set values, status LEDS.

Both arduinos are supposed to send the values for the flow-setpoints, actual pressure values, actual flow values, other sensor data to a third arduino MEGA =BOX 3 that displays all kind of things on a large TFT. (for what its worth, this third Mega has some inputs from a different set of other I2C sensors that basically provide TTL signal outputs, if event-criteria have been met. the latter TTL are fed back to the first two arduinos to provide decision criteria in if loops)

So, i learn from you that the multimaster approach unlikely to be fun at all, especially given my limited knowledge and loathing /ignorance to handle and send strings. You will at least laugh at me now but i saved quite some time the on day i wrote to you by simply translating all the flow etc values of BOX 1, Box 2-Ardinos (pressures, flowsetpoints and actual flow values into voltages with the help of additional multiplexed DACs, then I pick up the the voltages with I2C-ADCs hooked to the Arduino with the SPI-display (BOX 3) that in turns translates into the true values and prints to the TFT. Any delay and inprecision at the displays side is acceptable so far, analog value fluctuation has been smoothed, the additional hardware is no issue at this stage of the project.

I am sorry that his original issue regarding I2C led me astray to oldfashioned analog data processing

BUT: if you have any hints or pointers to libraries as how two arduinos that act already as I2C Masters can send their data (a bundle of floats) via UART/RXTX, or any other bus to a receiver that handles these as printable variables: more than welcome, i will try to keep abreast of what you suggest.

Best
Daniel


body:
I have a Python program that acts as a `Firmata` client. This program connects to the Arduino at a user-specified COM-port (with `Firmata` onboard, the sketch can be seen below), sends the user-requested string message to the Arduino, and awaits Arduino's reply. If the reply is present, the program prints it out as a list of ASCII symbol codes.

I expect the program and the sketch to work this way (block scheme is below), but the strings coming from the Arduino are damaged. They don't contain all symbols which were sent, but they contain only the first symbols in some random order, with a `\0` symbol present after each character in the string. For example,

| String sent to the Arduino |  Received as ASCII symbol codes | Received as a string |
| -------- | -------------- | -- |
| `A`    | `(65, 0)` | `A\0`
| `AB` | `(65, 0)` *where is the `B`?* | `A\0`
| `ABC` | `(65, 0, 67, 0)` *the `B` lacks presence* | `A\0C\0`
| `ABCD` | `(65, 0, 67, 0)` *the received data length remains the same, but `B` and `D` aren't present* | `A\0C\0`
| `ABCD(10)` | `(65, 0, 67, 0, 40, 1, 48, 1)` *WHAT IS THIS?* | `A\0C\0(\10\1`
| `DHTt(4)` | `(68, 0, 84, 0, 40, 0, 41, 1)` | `D\0T\0(\0)\1`

Program's screenshot:

[![Screenshot][1]][1]

Awaited work algorithm block scheme:
[![Block scheme][2]][2]

Python program code:

```python
import pyfirmata, time

class CustomArduino(pyfirmata.Arduino):
    def __init__(self, port: str):
        pyfirmata.Arduino.__init__(self, port)
        self.iterator = pyfirmata.util.Iterator(self)
        self.iterator.start()

        self.add_cmd_handler(0x71, self.receiveString)

    def receiveString(self, *args, **kwargs):
        print(f'Received: {args}')

    def sendString(self, data):
        self.send_sysex(0x71, bytearray(data, 'utf-8'))

    def send_sysex(self, sysex_cmd, data=[]):
        """
        Sends a SysEx msg.
        :arg sysex_cmd: A sysex command byte
        : arg data: a bytearray of 7-bit bytes of arbitrary data
        """
        msg = bytearray([pyfirmata.pyfirmata.START_SYSEX, sysex_cmd])
        msg.extend(data)
        msg.append(pyfirmata.pyfirmata.END_SYSEX)
        self.sp.write(msg)

print('STRING TESTER\nPlease input your COM port: ', end = '')
myCom = str(input())
device = CustomArduino(myCom)

while True:
    device.sendString(input('Send: '))
    time.sleep(1)
```

Arduino sketch:
```c++
#include <Firmata.h>

void stringCallback(char *myString)
{
  //The function accepts one charset.
  Firmata.sendString(myString); //send the *same* charset  back
}

void sysexCallback(byte command, byte argc, byte *argv)
{
  Firmata.sendSysex(command, argc, argv);
}

void setup()
{
  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
  Firmata.attach(STRING_DATA, stringCallback); //when there is a STRING incoming to the Arduino, call 'stringCallback'
  Firmata.attach(START_SYSEX, sysexCallback);
  Firmata.begin(57600);
  pinMode(13, OUTPUT);
}

void loop()
{
  while (Firmata.available()) {
    Firmata.processInput();
  }
}
```
How I can deal with this?

  [1]: https://i.stack.imgur.com/14QwH.jpg
  [2]: https://i.stack.imgur.com/d0xcb.png

title: Firmata: strings sent from the computer become damaged after Arduino

Answers: 3

body:
You have to understand the Firmata protocol to write your own client library. The spec is here: https://github.com/firmata/protocol.

In this particular case, you need to know that data that is sent (the string in this case) can never use bit 7 of the data, since these values have special meanings. Therefore, Firmata sends every byte as two bytes, first bits 0-6 and second bit 7 as bit 0 of the next byte. Therefore, the conversion to UTF-8 is not sufficient. You need to do a two-byte-per-8-bits encoding. The same applies for the reply.

body: Alternatively, if you want a system without Firmata's baggage of ancient MIDI constraints, like its bizarre 7-bit limit, you might consider DaqPort <https://www.daqarta.com/dw_rraa.htm>

body:
Instead of using the `UTF-8` encoding,
```python
def receiveString(self, *args, **kwargs):
    print(f'Received: {args}')

def sendString(self, data):
    self.send_sysex(0x71, bytearray(data, 'utf-8'))
```
it is necessary to use the `pyfirmata` special bytearray manipulation methods: `two_byte_iter_to_str` and ` str_to_two_byte_iter`:
```python
def receiveString(self, *args, **kwargs):
    print(f'Received: {pyfirmata.util.two_byte_iter_to_str(args)}')

def sendString(self, data):
    self.send_sysex(0x71, pyfirmata.util.str_to_two_byte_iter(data))
```


body:
Using a Mac (Big Sur 11.1)

When trying to set up the IDE I was able to install the package that contained the Due board, but the serial port for my Arduino Due isn't appearing in Tools -> Port -> Serial Ports. I did some searching and it seems that other Mac users had this problem as well.

If anyone has any tips on how to get my computer to recognize and show the serial port I'd appreciate it. I'm just getting started with these.

title: Arduino Due Serial Port Not Showing - Mac

Answers: 0


body:
I am an arduino noob. I have been searching for some interesting arduino projects recently and making a game controller using Arduino UNO seemed interesting. So I hooked up two dual-axis joystick modules to the arduino board and wrote a program to print something corresponding to the joystic movements. I collected the serial data through USB and passed it on to a python program. The code works fine, mostly. But the problem is, when I hook up the circuit and start using the joysticks, after few minutes my system  is freezing.

Why is my system freezing?

What can I do to avoid the freezing?

My system info:

1.Windows 10 64-bit

2.4GB RAM and 512GB HDD

Here is the code
```
int SW = 9;    // mouse joystick
int xpin = A0;
int ypin = A1;
int SW1 = 6;  //movement joystick
int xpin1 = A2;
int ypin1 = A3;
void setup()
{
  Serial.begin(9600);
  pinMode(SW, INPUT);
  digitalWrite(SW, HIGH);
  pinMode(SW1, INPUT);
  digitalWrite(SW1,HIGH);

}
int prev_state = 0; // previous state of switch
void loop() {
  int z = 0, xpos = 0, ypos = 0;
  int z1 = 0;char xpos1='0', ypos1='0';
  int x = analogRead(xpin);
  int x1 = analogRead(xpin1);
  int y = analogRead(ypin);
  int y1 = analogRead(ypin1);
  int sensitivity = 15; //mouse sensitivity

  if (x >= 550)                  // when moved up
    xpos = map(x, 550, 1023, 0, sensitivity);
  if (x <= 450)                // when moved down
    xpos = map(x, 450, 0, 0, -sensitivity);
  if (y >= 550)                 // when moved right
    ypos = map(y, 550, 1023, 0, sensitivity);
  if (y <= 450)               // when moved left
    ypos = map(y, 450, 0, 0, -sensitivity);
  int curr_state = digitalRead(SW);
  if (curr_state == 1 && prev_state == 0) // when SW is pressed
    z = 1;
  else
    z = 0;
  int prev_state1 = 0;
  if (x1 >= 550)                  // when pressed d
    xpos1 ='d';
  if (x1 <= 450)                // when pressed a
    xpos1 ='a';
  if (y1 >= 550)                 // when pressed w
    ypos1 ='w';
  if (y1 <= 450)               // when pressed s
    ypos1 ='s';
  int curr_state1 = digitalRead(SW1);
  if (curr_state1 == 1 && prev_state1 == 0) // when SW1 is pressed
    z1 = 1;
  else
    z1 = 0;
  if (xpos != 0 or ypos != 0 or z == 1 or xpos1=='d' or xpos1=='a' or ypos1=='w' or ypos1=='s' or z1 == 1) // prints when the joysticks are moved
  {
    Serial.print(xpos);
    Serial.print(":");
    Serial.print(ypos);
    Serial.print(":");
    Serial.print(z);
    Serial.print(":");
    Serial.print(xpos1);    // prints the data and separating by ":"
    Serial.print(":");
    Serial.print(ypos1);
    Serial.print(":");
    Serial.println(z1);
  }

  prev_state = curr_state;
  prev_state1 = curr_state1;
   delay(10);
}
```

I am using a python program, in visual studio code, to read the arduino serial data and perform the required operation.

The python code
```
import mouse, sys
import time
import serial
import keyboard as kb

mouse.FAILSAFE=False
ArduinoSerial=serial.Serial('com3',9600)  #assigning com port
time.sleep(1)

while 1:
      data=str(ArduinoSerial.readline().decode('ascii'))   #read the data
      (x,y,z,x1,y1,z1)=data.split(":")           # assigns to x,y,z,x1,y1,z1
      (X,Y)=mouse.get_position()        #read the current position of mouse cursor
      (x,y)=(int(x),int(y))
      mouse.move(X+x,Y-y)           # move camera/mouse
      # press the desired keys corresponding to joystick movement
      if y1=='w':
         kb.press('w')
         kb.release('w')
      if y1=='s':
         kb.press('s')
         kb.release('s')
      if x1=='a':
         kb.press('a')
         kb.release('a')
      if x1=='d':
         kb.press('d')
         kb.release('d')
      if '1' in z:                        # read the Status of SW
         mouse.click(button="left")    # clicks left button
      if '1' in z1:                    #read SW1
         kb.press('space')             # press space
```

title: Computer freezes while collecting serial data from Arduino Uno

Answers: 0


body:
I need to read the registers of a message gotten from `onReceive()`. I read [here][1] that

> There's nothing "magic" about the register pointer:  it's simply the first data byte in the packet.  So just write your I2C slave code so it examines the first received byte and treats it as an "opcode" for deciding how to interpret the rest of the packet.

So I thought that since hosts set registers by calling `write()` twice, I could just make my `onReceive()` handler function twice, like this
```
byte CURRENT_REGISTER = 0x00;

void onMessage(int numBytes){
  if(CURRENT_REGISTER == 0x00 && numBytes == 1){
    CURRENT_REGISTER = Wire.read();
    return;
  }

  char msg[numBytes];
  for(int i = 0; i < numBytes; i++){
    msg[i] = Wire.read();
  }

  //logic function goes here

  CURRENT_REGISTER = 0x00;
}
```
But then i noticed [here][2] that

> This first byte written here 'r' moves the register pointer to the register with address 'r'. You can think of the pointer as a read/write head.
>Now that the pointer is 'pointing' at the specific register you wanted, this command will **replace the byte stored in that register** with the value 'v'.

which made me think after `endTransmission()`, it only sent one message, which would ruin this idea.
Is this the case, and if so how can I obtain the registers as a slave?

  [1]: https://forum.arduino.cc/index.php?topic=13451.0
  [2]: https://forum.arduino.cc/index.php?topic=211587.0

title: Reading I2C registers as slave device

Answers: 1

body:
I just realized, what your actual question might be, so I'm prepending this to my answer:

With I2C and the typical register communication protocol, you have 3 communication patters:

- Master wants to write:
   - Master does transmission with first byte being the address of the register and following bytes being the data, that should be written to the addressed register (and following registers)
- Master wants to read:
   - Master does a 1 byte transmission with the address of the register, that is wants to read
   - Master starts a request for 1 or more bytes and the slave will send the previously requested register (and following registers, until no more bytes are available or requested)
- Some devices have sequential reads. For these devices the register address is not reset, when an operation is done. Thus the master could do more requests and read more data from the registers. Here the current register address is incremented on each read.

This means, that a master write cycle has only 1 transmission (only 1 `endTransmission()` in the master code), since every first byte in a master send transmission is handled as a register address. Your code snippet does not allow that. To solve that, just remove the check of `numBytes` and the return statement.

---

As mentioned in the comments, your question is really unclear. It seems you are asking things, that doesn't really make sense in the context of general I2C communication. So I will go over the basics and then point you in a good direction to solve your problem interfacing the Wiimote as peripheral.

**The I2C protocol:** This is the general communication protocol, that the Wiimote uses for its peripherals. It uses 2 lines and a master-slave structure. That means, that any communication is controlled by the master (the Wiimote in this case) and the slave (the peripheral, like a Motion+, a Nunchuk or your Arduino) cannot do anything by itself. The I2C protocol has markers for the start and end of a message and can address each slave on the bus with its specific address (which is send before the data). The protocol does **NOT** include any rules about the content of each message. So when writing code with the `Wire` library (the Arduinos library for interfacing the I2C hardware), you only get a buffer full of data bytes. It is up to you to interpret these bytes as needed for your application.

**Data structure protocol:** This protocol is imposed onto the data, that is end via I2C, so this is a higher level of abstraction and does not really have much to do with the I2C interface (you could use this data structure protocol with any binary communication interface, that has the concept of separated data packages). The data structure protocol defines the logic of the communication.

Here the registers come in. I2C is often used to interface simple sensor chips. These chips work by reading and writing to their internal memory. So the I2C interface exposes this internal memory to the master, who can now configure the sensor by writing data to the internal memory of the sensor, or read data from it.

An example: Lets imagine a simple distance sensor. It has 2 bytes/registers of internal memory. The first byte/register is for configuration of the sensor; the second byte/register represents the measured distance. The common communication protocol for such a chip can be:

    Master sends the address of the register, that it wants to access
    if Master wants to write to the register
        Master sends bytes to the slave
        Slave saves bytes into previously chosen register (and following registers)
    if masters wants to read form the register
        Master requests X bytes from the slave
        Slave sends X bytes with the content of the previously chosen register (and following registers)

The I2C master now wants to configure the sensor (for example setting the measurement frequency), thus writing a corresponding byte to the first byte/register. It will first send the address of the configuration register to the slave, which is 0 (first byte/register). Then it will send another byte, which is the new value of the configuration register.

Then our I2C master wants to read the distance measurement the sensor. For this it first sends the address of the register, that holds the distance measurement (1 aka second byte/register). Then it will request 1 byte from the slave. The slave will then send the content of the previously chosen register (register 1 aka distance measurement register).

So for the slave, the first byte of a Master send transmission is to be handled as a register address. More complex slave classes might have a 16bit (2byte) register address or even more.

---

Now to your problem mimicking a Wii Motion+. The description on the [site, that you linked to][1] is rather difficult. Unfortunately I cannot help much with that. But you can try to use an already existing library, that mimics a Wiimote peripheral: [Arduino-Wiimote][2]

I cannot guarantee, that is will work, but it is definitely a good start. If you don't want to use a library, but implement this yourself, you can still learn from how the library does it.

With more searching (for term combinations like "github wiimote arduino") you might find more libraries for this. I have only invested a limited amount of time.

  [1]: http://wiibrew.org/wiki/Wiimote/Extension_Controllers#Wii_Motion_Plus
  [2]: https://github.com/denizkoekden/arduino-wiimote


body:
I wish to blink only one led (number two in the strip) bit it does not do so, any idea why and how can I do it?

Code:

    #include "FastLED.h"

    //Number of LEDs
    #define NUM_LEDS 9

    //Define our clock and data lines
    #define DATA_PIN 11
    #define CLOCK_PIN 13

    //Create the LED array
    CRGB leds[NUM_LEDS];

    void setup() {
          FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, BGR>(leds, NUM_LEDS);
          FastLED.setBrightness(5);
    }

    void loop() {
      leds[0] = CRGB::Blue;
      leds[1] = CRGB::Green;

      //Blink this one only
      leds[2] = CRGB::Red;
      leds[2] = CRGB::Black;
      delay(500);
      leds[2] = CRGB::Red;

      leds[3] = CRGB::White;
      leds[4] = CRGB::Purple;
      leds[5] = CRGB::Green;
      leds[6] = CRGB::Blue;
      leds[7] = CRGB::Yellow;
      leds[8] = CRGB::Red;
      FastLED.show();
    }

title: Blink only one led in a led strip

Answers: 1

body:
Everytime, that you want the LEDs to change, you need to call the `FastLED.show()` function. You are doing that only once after you set the values multiple times. Also you need 2 delays in total (1 for the LED being on, 1 for it being off).

The workflow for blinking an LED would be:

    Set LED to on
    Call show function
    Delay
    Set LED to off
    Call show function
    Delay

You need to translate that to code.


body:
Photos and Screenshots: https://i.stack.imgur.com/NazA6.jpg

By the way, I used a screenshot that was originally from this post: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board

Hey guys,

I was trying to wire two TEC1-12706 Peltier plates to my breadboard, and I saw that using the USB connection for power was not enough for both plates. So, I found a 19v--3.9A DC/AC adapter/computer charger and plugged it in to my Uno via the Power Jack port. The Peltier plates were not wired to the board when I plugged it in and everything looked fine, all the normal LEDs on the UNO lit up, etc. Then, I wired a peltier plate to my breadboard. As soon as I did, a part exploded, and grey smoke come out of the "L" light area. I unplugged it immediately. The next day, I plugged the adapter back into the Power Jack port and a screenshot is attached of some observations I made by touching the board. Photos of my Uno are also attached. As you can see, the "Slightly less hot but still burning part" is pretty much destroyed. The "L" light will not light up and as of right now I can't upload any code to it. Might be an unrelated issue so I will continue troubleshooting that, but it is still another observation. The test LED I wired is lit up, so I guess the board can still kinda function? I'm high school student and obviously a complete beginner. Will continue to do research on this. I really want to know what happened. Please help?  Thanks everyone.

title: Part of Board exploded when Peltier Plate was wired t(o Board

Answers: 1

body:
You did a pretty good job of nuking your board. Gratz.

Basically what has happened: you connected 19V to the input of the 5V regulator (rated at 800mA max) and connected a 12V 50W device to the output.

I have no idea what a peltier will do when under powered, but at 12V it's going to want about 4A. That's 20x more than the 5V regulator can provide (also exacerbated by the massive amount of heat needed to be dissipated to drop 14V) - so it went *pop*.

In going pop it short circuited. That meant that 19V (or just short of) ended up going into the rest of your Arduino. The 3.3V regulator didn't like that (the bit that looks toasted), and neither will any of the rest of the components on the board.

In short: probably almost every component on the board has been nuked.

The moral of this story: don't connect high powered 12V devices direct to the Arduino. Things like peltier devices need their own dedicated power supply which can be controlled (as you would a motor or relay) through a power MOSFET.


body:
Note - I plan to use the Arduino Starter kit to make this project.

Hey everyone,

I've had an idea for a project recently and I would like to get some insight on its plausibility. Is it possible to heat and cool a bottle of water using 4 pelteir plates? I'd like to heat up or cool a bottle of water using 2 pelteirs for heating and 2 for cooling. Could the amount of power for the peltiers to function be supplied from a laptop, computer, or battery pack? The role of the Arduino is to program in some safety features or some things to help the circuit function better if necessary. For example, a feature I want to add in is if the cold pelteirs are on, the hot peltiers are off if nessecary. I might add an LCD to display which setting is on/off if I can (example: Cold: ON, Hot: OFF)

Thanks guys.

title: 4 Pelteir Plate Water Bottle wired to Arduino Uno

Answers: 2

body:
When it comes for amount of power from laptop, then this is not realy reasonable to expect even USB3, maybe some older laptops PCMCIA, or hardware docks. When it comes to Desk, They would have to be adjusted to get the ATX from PSU (it would have to be upgraded for purpose) We are still talking about a small Can or Yacult botle...

Even then insulate, insulate (and same again)

Then its a question of speed and how hot or cold) Battery pack that charges even when not used, used as buffer might work (for a short time).
Controlling it from Arduino is easy part using function that switches one on other off whenever you want and then calling the function itself to make sure both steps happen, rather then manualy editing or using one output for controlling power on/off and another on two way relay switching between sets (relay would increase consumption here).

body:
In a word, no. Laptop or desktop computer usually have USB ports, which put out like 10 watts of power for a "high current" USB port. That is not enough to do much heating or cooling. You want a high power supply. The pelteir plates I've seen run on 12V DC. Get a 5A 12V supply, or even higher.

You might be able to draw larger amounts of current from a USB-C port or a USB-C power supply, but why? Get a dedicated high current power supply that puts out the maximum voltage your peltier plates can handle.

Note that there is no reason to have 2 plates for heating and 2 plates for cooling. Run the current one way and they heat. Reverse the current and they cool.

Also I'm not sure of the value of using 2 plates to cool. A single plate able to handle more power would likely be more efficient, and easier to insulate. (With 2 plates you'd need 2 heatsinks, which will allow twice as much heat to leak through when the power is off. Doubling the current you feed into a single plate should give double he heating/cooling, without increasing the heat leakage when it's off. Just make sure you don't exceed the maximum rated current of your plate, and that you have a large enough heatsink to handle the heat transfer.)

You could use an H-bridge meant for controlling motors to provide either +12V or -12V under software control. Those generally handle high current.

You could also use a digital thermometer and make a thermostatically controlled system. You'd measure the temp in the bottle, and when it got to your desired temp range, turn off the power. When the temp moved outside the desired range, you'd turn the power back on.


body:
So I got 2x PSRAM chips from PJRC with my Teensy4.1 and soldered them on (it's a hideous job as I lost my tips) but it's all tested with a multimeter and the connections are solid.

I ran the [memtest sketch][1] from here compiled in both Teensyduino and PlatformIO:
https://www.pjrc.com/store/psram.html

Aaaaand external_psram_size is reading 0 for both cases. Setting the memory size manually in the program also fails (even with 8MB).

However... EXTMEM vars work as expected. I'm not sure how the mem addressing actually works with the provided memtest program, either - it certainly doesn't seem to use EXTMEM anywhere.

Here's my memory tester (run to crash):

    EXTMEM char bigBuf[10000000];
    //char bigBuf[10000];
    int c = 0;
    void setup() {
      c = 0;
    }

    void loop() {
      bigBuf[c] = 'a';
      Serial.println(bigBuf[c]);
      Serial.println(String(c));
      c = c + 1000;
      delay(1);
    }

Output with EXTMEM char[]: (as expected overflowed until 16MB)

    a
    0
    a
    100
    ...
    a
    16777100
    a
    16777200
Output with internal mem char[]: (as somewhat expected overflowed at 512K - max of RAM1)

    a
    0
    a
    100
    ...
    a
    488081
    a
    489081

Anyway, I'm glad EXTMEM works.. But can someone explain what's going on with the provided memtest? I admit I didn't read it over very well, but I thought that PSRAM could only be accessed via EXTMEM; how is it addressing otherwise?

  [1]: https://raw.githubusercontent.com/PaulStoffregen/teensy41_psram_memtest/master/teensy41_psram_memtest.ino

title: Teensy4.1 with 2x 8MB PSRAM Chips: external_psram_size=0 but EXTMEM char[] works as expected?

Answers: 2

body:
I'm afraid your test program doesn't work as you intended. I tested it with a T4.1 without RAM soldered on and it gives the same result as in your question.

 1. You didn't declare your array volatile. Thus, the compiler can (and probably will) simply optimize the reading back away.
 2. Even if you declare the variable volatile the processor reads back the value from the cache line, i.e. you always get the correct value back, even without any external RAM.

Here a simple test program showing the effect. It always switches the LED on, even without external RAM soldered on the board.

```c++
EXTMEM volatile int test;

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

    test = 42;
    if(test == 42)
    {
        digitalWriteFast(13, HIGH);
    }
}

void loop(){
}
```

Here the disassembly of the setup function. It clearly shows that the processor tries to store 42 in the (non existing) external RAM and reads it back from there. Obviously the read back value comes from the cache line.
(comments added by me)
```
void setup()
{
      7c: push {r3, lr}                         // pinMode code
    pinMode(13, OUTPUT);                             //
      7e: movs r1, #1                           //
      80: movs r0, #13                          //
      82: bl 160c <pinMode>                       //-------------

    test = 42;
      86: ldr r3, [pc, #20] ; (9c <setup+0x20>)  // load r3 with address of 'test' (0x70000000, stored at 0x9C)
      88: movs r2, #42 ; 0x2a                   // load r2 with #42
      8a: str r2, [r3, #0]                         // store content of r2 at address stored in r3. i.e., store #42 0x7000'0000 (EXTRAM)

    if(test == 42)
      8c: ldr r3, [r3, #0]                         // volatile forces the compiler to read back 'test' (store it in r3)
      8e: cmp r3, r2                               // check if equals r2 (contains #42)
      90: bne.n 9a <setup+0x1e>                  // goto 0x9A if not equal

CORE_PIN13_PORTSET = CORE_PIN13_BITMASK;             // digitalwritefast code (next 3 lines)
      92: ldr r3, [pc, #12] ; (a0 <setup+0x24>)  // ...
      94: movs r2, #8                           // ...
      96: str.w r2, [r3, #132] ; 0x84           // -------

      9a: pop {r3, pc}                             // return from setup()

      9c: .word 0x70000000                       // Address of 'test'; EXTRAM starts at 0x7000'000
      a0: .word 0x42004000                       // Address of GPIO register for LED
```

body:
Paul here.  I'm the author of that memtest program, and also the creator of Teensy.  While luni64 already answered very well about your test program, hopefully I can add some clarity about the official memtest program.

Regarding "I thought that PSRAM could only be accessed via EXTMEM", indeed use of EXTMEM arrays or variables is the normal way.  But it is not the only way.  The memtest program uses pointers with the known address range of those memory chips.  Because the wires physically connect to the "FlexSPI2" peripheral inside the chip, the memory will always start at address 0x70000000.  You can find this detail on page 35 of the chip's reference manual.

https://www.pjrc.com/teensy/IMXRT1060RM_rev2.pdf

Unfortunately the manual is tough to read and confusing in so many ways.  Even on page 35, it describes the memory as "ciphertext", which might be the case if the Bus Encryption Engine (mentioned on page 184) were used in a certain way.  No encryption is used, and if you read page 184 you'll see that engine only does decryption, so it really only could be used for read-only memory which is pre-loaded with encrypted data.

The point is we know the RAM always starts at 0x70000000 because of the way the hardware is designed.  If you look at the memtest code, you'll see it creates 2 variables called "memory_begin" and "memory_end", which are pointers used to directly access the memory within that known address range.

The idea behind the memory test is the entire memory is filled with a known data pattern.  This sort of testing is meant to catch any (very unlikely) internal problems inside the memory chips, where writing to one place inside the chip might corrupt data somewhere else in the same chip.

The pointer used is declared with "volatile" which prevents the compiler from trying to optimize away actual memory access.

After the memory is completely filled, you'll see a function called arm_dcache_flush_delete() is used.  Even if you use volatile to keep the compiler from optimizing away memory access, the Cortex-M7 hardware has 32K level 1 cache.  This function causes the ARM Cortex-M7 processor to completely write any cached data to the actual memory chip, and then delete the data from its cache.  Normally these special cache functions are only used by low-level driver code using Direct Memory Access (DMA), where you need to be sure data you've written is actually in memory before instructing a peripheral to use DMA to directly grab it from the memory (generally DMA-based peripherals can't access the cache), or before you read data a peripheral put into memory using DMA.  Normally you don't need to mess with the cache, but this sort of hardware testing and special benchmarking are the other sort of application where special attention to the processor's cache is important.

Then the entire memory is read back, using the volatile pointer so the compiler doesn't try to do anything too smart.  As the data is read, every 32 bit word is compared to the original pattern written.  Again, the idea is to check for the pretty unlikely case where the memory appears to work, but could theoretically have an internal problem where writing to one place causes corruption somewhere else inside the chip.

The entire test is repeated many times.  A variety of fixed 32 bit patterns are used.  Many of the tests fill the entire memory with a pseudo-random sequence, of course doing the same verification where any change to even just 1 bit within the entire memory range will be detected and reported as a failure.  Maybe that's overkill, but I tried to design the memtest program according to best practices described for testing PC memory, and those are the ways experts recommend to test memory (actually they recommend even more sophisticated & complex patterns... maybe someday I'll add those).

Hopefully this helps answer "can someone explain what's going on with the provided memtest?"

Regarding the soldering, a problem other people have seen involves the solder adhering only to the memory chip pin.  Even though it looks ok when viewed from above, it's possible for the solder to be a blob resting just slightly above the pad surface on the circuit board.  I would recommend re-heating the solder.  Allow time for it to fully heat and flow onto the pad.  While extra time heating isn't wonderful for the PSRAM chip, those chips are pretty hearty heat-size and if the memory isn't working you really don't have much to lose.  Counting to 10 while reheating the solder usually works.  If you have any liquid flux chemical, applying that before reheating might also help.

Focus your repair effort first on the chip mounted to the smaller set of pads next to the edge of the PCB.  The startup code looks for the first 8MB chip in that location.  If won't even look for the other chip if no memory is detected in the first location.


body:
I connected a wave generator to the analog pins to read the frequencies of the waves generated. I used different frequencies of sine waves with a minimum of 0V and maximum of 5V.

Whenever the voltage is greater than 2.5V, I made one of the digital pins HIGH, and LOW when less than 2.5V. Now by measuring the square wave from the digital pin, it always has the same frequency as the sine waves until 500Hz.

After 500Hz, the square wave's frequency doesn't agree with the sine wave, which made me think that the problem is in the `analogRead()`. Is there a way to have higher frequency?

Code:

```c++
const int sensorPin1 = A0;
const int sensorPin2 = A1;
const float maximumPower = 2.5;
int calibration = 1;

void setup() {
  Serial.begin(57600);
  pinMode(6, OUTPUT);
  digitalWrite(6, LOW);
}

void loop() {
  int voltage2 = 3;
  int voltage1 = 3;
  int sensorVal = abs(analogRead(sensorPin1) - analogRead(sensorPin2));
  float ratio = abs(analogRead(sensorPin2) / analogRead(sensorPin1));
  float voltageDifference = (sensorVal / 1024.0) * 5.0;
  float power = calibration * voltageDifference;
  if (power >= maximumPower || voltage1 <= 1 || voltage2 <= 1) {
    digitalWrite(6, LOW);
  }
  else {
    digitalWrite(6, HIGH);
  }
}
```

title: analogRead() doesn't read more than 500Hz

Answers: 1

body:
You have 4 calls to `analogRead()` in your loop. At about 112 µs per
call, that's already taking 448 µs. Add to that the time taken by the
floating point calculations, and you are likely to end up with something
in the order of 500 µs per loop iteration. This should give you a
sampling rate close to 2 kHz, which should allow you to detect the highs
and lows of an input signal up to 1 kHz, provided the duty cycle is
close to 50%.

There are a couple of easy optimizations that could be done here. Two of
the calls to `analogRead()` serve no purpose, as the results are never
used. And the floating point calculations are also pointless. The whole
loop can be simplified to this:

```c++
void loop() {
    if (abs(analogRead(A0) - analogRead(A1)) >= 512) {
        digitalWrite(6, LOW);
    } else {
        digitalWrite(6, HIGH);
    }
}
```

This should take about 224 µs per iteration. If you need to go faster,
you will have to increase the working frequency of the ADC. This can
cost some accuracy, but if accuracy is not critical to your application,
it can be a good trade-off. See [Nick Gammon's page on the Arduino
ADC][adc] for details. If that's not enough, you will have to use
external components, e.g. an analog subtractor made from an op-amp, and
a couple of comparators.

[adc]: http://gammon.com.au/adc


body:
So to wile away the long lockdown and curfew hours I decided to get out a stack of Wemos D1 mini ESP8266 boards and build simple indoor temperature and humidity sensors ( using an SHT30 and feeding the data into Graphite or Influx ). I'm using the WifiClientSecure library but its connect() function returns 0 ( false/fail ) every time I try this except when I connect to www.google.com. I've tried connecting to various other servers, both port 80 and 443 but they all fail. I can connect to all of these server absolutely fine from my network so it's not a firewalling issue. The D1 does get an IP and has DNS ( in fact, in my full sketch I'm using NTP with pool.ntp.org and that works fine ).

I've created a simple test ( https://gist.github.com/mkraats/1d1b11691c179793c799fcbb21e5debe ) with just the connect to WiFi and connect() but I still get the same results.

This code:

```void loop() {

    char servername[]="www.google.com";

    int connectval;
    connectval = client.connect(servername, 443 );
    Serial.println("...");
    Serial.println(connectval);
    Serial.println("...");
    delay(12000);

}
```
Works fine while this:

```
void loop() {

    char servername[]="graphite-us-central1.grafana.net";

    int connectval;
    connectval = client.connect(servername, 443 );
    Serial.println("...");
    Serial.println(connectval);
    Serial.println("...");
    delay(12000);

}
```
Does not. What stupid mistake am I making that I am not seeing? :-)

title: WifiClientSecure connect returns 0 ( fail ) except for www.google.com which connects

Answers: 0


body:
I want to power 3 hc-sr501 PIR motion sensors with a voltage regulator that can output 5v-1A.
If I make such a system, will there be a noise?

title: Can I run 3 motion sensors with a voltage regulator?

Answers: 1

body:
Many internet sources [like this one][1] claim the HC-SR501 requires less than 50uA (or 0.00005 Amps).  Likely this is only in a quiet or quiescent state and current demand may increase initially when power is applied and when motion is detected.  Regardless, this is an insignificant fraction of a 2 Amp power supply.

Likely the Atmel 328p will require several times the total current of the 3 PIR sensors added together.  Still, the over all current of the described project (1 processor and 3 PIRs) is expected to be far less than half the capacity of a 2 Amp power supply.

It is suggested to keep the PIR to Arduino wires as short as possible to avoid noise.  It would be preferable they only be several inches (10s of centimeters).  And certainly not as long as several feet (a meter).

  [1]: https://www.espruino.com/Pyroelectric


body:
I would like to display 65k color animated gifs on my oled. I'm using the adafruit library for https://learn.adafruit.com/096-mini-color-oled
Now I need to convert a significant number of images to hex arrays. I found a couple of tools that can deal with monochrome images and I found this: https://www.digole.com/tools/PicturetoC_Hex_converter.php which might work for individual images, but is impractical for batch processing. I also found this, but it appears to also be intended for individual images and doesn't simply work in wine. So isn't there some linux commandline magic to do that?

title: Efficient workflow/tools for converting color images to hex arrays

Answers: 1

body:
I found this plugin to be satisfactory: https://khalim19.github.io/gimp-plugin-export-layers/
It's not a single elegant command, but is quite fast and maybe can be optimized with some scripting.


body:
I am working on storing data from Portenta H7's ADC through a high sample rate (>100kSa/sec) per channel. I am using 2 ADC channel for my work.  Through the forum, I learned that the serial. print command reduces the sampling rate. Therefore one of the suggestions was to use the onboard available Portenta H7's 8MB SDRAM to store the sample values and then retrieving them after the sampling period. My sampling time is between 3-5 seconds so it is well within the storage limit of this SDRAM.

 However, since I have no previous experience with microcontrollers, I am struggling to find a starting point for accessing this SDRAM for saving my data?  Any suggestions from your side are most welcomed.

Please do recommend If you have any other ideas about managing the data for faster sampling.

You can find the Portenta H7 information here. https://store.arduino.cc/usa/portenta-h7. Portenta has STM32H747 dual-core processor.

Thank you all.

title: Storing data in Arduino Portenta H7's SDRAM

Answers: 1

body:
    #include <SDRAM.h>

    SDRAMClass ram;
    uint8_t *b;
    void setup() {
      ram.begin();
      b = (uint8_t *)ram.malloc(320 * 240 * sizeof(uint8_t));
    }

The way to do it is to use the SDRAM library for the portenta. Above you see an example for a uint8 array.


body:
I'm using `ESP8266WiFiMulti`, `ESP8266WebServer` and `ArduinoOTA` to communicate with my device and perform over-the-air-updates. Everything was working perfectly until I moved the ESP8266 further from the WiFi router. The OTA upload slowed down, which caused upload timeouts after 5 seconds. It fails at a different point each time, usually between 30% and 60%.

How do I increase the OTA timeout to 30 seconds?

Here is the setup code, let me know if you need more:

```c++
void startWiFi() {
    ESP8266WiFiMulti wifiMulti;
    wifiMulti.addAP(ssid, password);
    wifiMulti.run();
}

void startOTA() {
    ArduinoOTA.setHostname(_hostname);
    ArduinoOTA.setPassword(_password);

    ArduinoOTA.onStart([]() {
        Serial.println("Start OTA");
    });
    ArduinoOTA.onEnd([]() {
        Serial.println("\nEnd OTA");
    });
    ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
        Serial.printf("OTA Progress: %u%%\r", (progress / (total / 100)));
    });
    ArduinoOTA.onError([](ota_error_t error) {
        Serial.printf("Error[%u]: ", error);
        if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
        else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
        else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
        else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
        else if (error == OTA_END_ERROR) Serial.println("End Failed");
    });
    ArduinoOTA.begin();
}
```

title: How to change ArduinoOTA upload timeout?

Answers: 1

body:
The only timeout I can find is in the `espota.py` script itself. That is riddled with such lines as:

```
sock.settimeout(10)
```

You would need to scour that program and change them all.

<s>**However**

ArduinoOTA uses UDP for communication. Because of that it is *unreliable* (yes, that's a technical term). It doesn't have any form of retransmit / retry, so if a packet is lost it's lost for good. No amount of increasing of timeouts will make that packet reappear.

So increasing your timeouts most likely will just make it wait longer before failing.

You should consider switching to a more reliable update system which uses TCP instead of UDP - such as downloading an update from a website using `ESP8266httpUpdate`. </s>

**Update:**

ArduinoOTA uses a combination of both UDP (to initialise and authenticate the connection) and TCP (to make a "back channel" connection back to your computer) to download the actual binary.

The same still applies: you will need to alter the `espota.py` program to change its timeouts (`sock2` is the back-channel object), but there is also one line in `ArduinoOTA.cpp` that will need to be altered to increase timeouts.  [Line 294](https://github.com/esp8266/Arduino/blob/master/libraries/ArduinoOTA/ArduinoOTA.cpp#L294):

```
int waited = 1000;
```

This is not strictly the number of milliseconds to wait for incoming data, but it's not far off - it's a 1 millisecond delay in a loop while looking for incoming data.  Increasing that will allow more time for the ESP8266 to wait for data to arrive.

But of course, with an unstable WiFi connection YMMV...


body:
I have been trying to use find a Quadratic problem solver library which is compatible with Eigen library for my NodeMCU board (In my code I have to deal with a lot of matrix operations, that's why I chose Eigen)
I found the following one by jarredbarber : [https://github.com/jarredbarber/eigen-QP][1]

For some reason, I'm not being able to use the QP library in my nodemcu. Here is one very simple demonstration I've been trying to establish. But it throws away some errors, I can't figure why :

In my sketch for the NodeMCU:

    #include <Arduino.h>
    #include <EEPROM.h>
    #include <Wire.h>

    #include <iostream>
    //#include<ctime>        //srand()
    #include<cstdlib>

    #define _USE_MATH_DEFINES
    #include <cmath>        // for using M_PI, Trig. functions (sin/cos/tan)
    using namespace std;

    //#include <ArduinoSTL.h>
    #include "Eigen313.h"
    using namespace Eigen;

    #include "eigen-qp.hpp"
    using namespace EigenQP;

    //#define PI 3.1416

    void setup() {
      // put your setup code here, to run once:
      Serial.println("Lets start!!");
    int N=4;
    float gamma =10000;
    float safety_radius=0.1200;
      Eigen::Matrix<float,Dynamic,Dynamic> Q(2*N,2*N); Q.setIdentity();
      cout<<Q<<endl;
      Eigen::Matrix<float,Dynamic,1> c(2*N,1);
          c<<0,
             0,
        0.0086,
        0.0847,
       -0.1499,
        0.0687,
        0.0083,
       -0.0867;

        Eigen::Matrix<float,Dynamic,Dynamic> A(6,2*N);
      A<<0.0655,0.6483,-0.0655,-0.6483,0,0,0,0,
        -0.5839,0.6251,0,0,0.5839,-0.6251,0,0,
        -0.5587,-0.0275,0,0,0,0,0.5587,0.0275,
         0,0,-0.6494,-0.0232,0.6494,0.0232,0,0,
         0,0,-0.6242,-0.6758,0,0,0.6242,0.6758,
         0,0,0,0,0.0252,-0.6526,-0.0252,0.6526;
    std::cout<<"A:\n"<<A<<endl;
        Eigen::Matrix<float,Dynamic,1> b(6,1);
    b <<7.7197,
       47.8600,
        2.6007,
        7.5770,
       76.6646,
        7.8461;

        A=-A;
        b=-b;
    Eigen::Matrix<float,Dynamic,1> x(2*N,1);
    yield();
    delay(2000);
            //boost::timer::auto_cpu_timer t;
            //for (int ii=0; ii < 8; ii++)
            //QPIneqSolver::solve(&H,&f,&A,&b,&x);
    EigenQP::quadprog<float,Dynamic,Dynamic>(Q,c,A,b,x);
    std::cout<<x<<endl;

    }

    void loop() {
      // put your main code here, to run repeatedly:
    yield();

    }

It compiles fine, but in the serial monitor, these show up :

     ets Jan  8 2013,rst cause:2, boot mode:(3,6)

    load 0x4010f000, len 3584, room 16
    tail 0
    chksum 0xb0
    csum 0xb0
    v2843a5ac
    ~ld

I tried to run the same code in codeblocks software in my computer, it works fine though.

PS: This is the first time I've ever posted any topic in this forum, please inform me if I've violated any guideline for the post..
Thanks in advance.
  [1]: https://github.com/jarredbarber/eigen-QP

title: Can't make Quadratic Programming Library (EigenQP) library work in NodeMCU

Answers: 0


body:
Ive been trying to get POST working on my ESP8266. I followed this tutorial https://techtutorialsx.com/2016/07/21/esp8266-post-requests/ which works, but once i change the request URL to anything else i get -1 response from http.POST() which the library returns when "no info".

I have no clue what the "no info" means and what im doing wrong. Does anyone have any suggestions? Below is the code im using.

```
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

    HTTPClient http;    //Declare object of class HTTPClient

    //http.begin("http://192.168.1.88:8085/hello"); //Works fine
    //http.begin("https://httpbin.org:8080/post"); //Causes -1 as httpCode
    //http.begin("https://httpbin.org/post"); //Causes -1 as httpCode
    http.begin("https://XXXXX.execute-api.eu-west-2.amazonaws.com/XXXXX/XXXXX");
    http.addHeader("Content-Type", "application/json");  //Specify content-type header

    int httpCode = http.POST("{\"key\":\"1\",\"id\": \"ESPXXX2\",\"action\": \"rbg\",\"value\": \"255255000\"}");   //Send the request
    String payload = http.getString(); //Get the response payload

    Serial.println(httpCode);   //Print HTTP return code
    Serial.println(payload);    //Print request response payload

    http.end();  //Close connection

  } else {

    Serial.println("Error in WiFi connection");

  }

  delay(10000);  //Send a request every 10 seconds
```
Only serial output im getting is "-1" for httpCode and empty line for payload.

title: Whats wrong with my POST request?

Answers: 1

body:
I ended up ditching HTTPS since it doesnt seem to be implemented all that well (Requires hardcoding of fingerprint).
Changed the architecture of my system so that HTTPS is handled by Python which doesnt require jumping through hoops.