text:
Can anyone help be get readings off of my potentiometer with a push of a button?
Hi I'm trying to get my Arduino Uno code to work with a in a specific way where if I push a button, the Arduino will read the raw potentiometer value once and if I don't push it nothing happens.
https://i.sstatic.net/uCHkR.jpg
int switchState = 0
int switchPin = 2
int potPin = A0;

void setup() {
pinMode (potPin, OUTPUT);
pinMode (switchPin, INPUT);
Serial.begin (9600);

}

void loop() {
switchState = digitalRead(2);
if (switchState == High) {
Potval = analogRead(potPin);
Serial.print("potval:");
Serial.Println(Potval);
delay(200);
}

else {
(switchState == LOW);
while (Potval);
}
}

what is your question about the arduino? ... the question in your title is not really related to the arduino, and it has an answer of yes

What should that do: (switchState == LOW); while (Potval);? The first line is doing nothing, since this expression is not inside of any flow control command. The second line will loop forever (blocking the code indefinitely), when Potval is not zero. Doesn't seem fitting to me. Why are you even doing this?

Beware that the Arduino language (C++) is case sensitive: Println is not the same as println, High is not the same as HIGH.

I had a very similar issue an it is that you aren't setting up your button as an INPUT_PULLUP. When you press the button, you are sending 5V or ground through it depending on your circuit. But then it won't reset on release. That is why either you can put a physical resistor as the schematic shows here:

or you can simply change the button initialization to INPUT_PULLUP.

There were several issues with your code:

It would not compile due to some missing semi-colons (lines 1 & 2);
The 'else' clause in your loop() function didn't do anything useful;
If your code didn't get trapped in the loop within the 'else' clause (it probably would!), it would print repeatedly as long as you were NOT pressing the button, since you wired the button to read LOW when pressed (which is perfectly fine, buy your code has to take that into account).
Buttons appear to bounce (electrically) when you press or release them. They don't switch once and stay that way. They switch multiple times before they settle down, due to the rough contact surfaces sliding over one another. The code has to allow for this as well.
An analog pin has to not be set to OUTPUT if you want to read analog with it.

Here is a revised version of your code, compiled and tested. You'll find notations in the comments where I made changes:
int switchState = 0;            // (';' was missing)
int switchPin = 2;          // (';' was missing)
int potPin = A0;
int Potval = 0;             // (this declaration was missing)
bool didPrint = false;      // true if we printed on this button-push
// prevents multi-printing while button stays high

void getSwitch();               // declare the new function

void setup() {
  //  pinMode (potPin, OUTPUT);  // not OUTPUT for analog read
  pinMode (switchPin, INPUT_PULLUP);  // needs pullup or reads may be unreliable
  pinMode (13, OUTPUT); digitalWrite(13, LOW); //DEBUG
  Serial.begin (9600);

}

void loop() {
  getSwitch();
  if (switchState == LOW ) {        // pressed == LOW the way you've wired it

    if (!didPrint) {
      Potval = analogRead(potPin);
      Serial.print("potval:");
      Serial.println(Potval);

      didPrint = true;      // prevent printing again til button has been released
    }
  }
  else if  (switchState == HIGH) {
    didPrint = false;       // printing allowed on next button push
  }
}

void getSwitch() {
  switchState = digitalRead(switchPin);
  delay(30);                // waits for button to settle - may need to tweak this
}


text:
ESP32 with Lolin 2.4 inch TFT Shield Power control
I am running out of intelligence trying to control a Lolin 2.4 Inch TFT shield.
I connected the shield via the official TFT connector to a Lolin D32 Pro. I am using the ILI9341 libary from Adafruit. With the libary it is no porblem controlling the display.
Unfortunately, as soon as I put the esp32 into Deep Sleep, the display goes white but the background illumination stays on.
Does someone know, how I can trun off the background illumination?
As far as I understood, the background light is not controlled via the ILI9341. Instead I tried putting the GPIO32 on Low, since accoring to the schema of the Lolin TFT cable it is responsible for the TFT_Led
Unfortunately that does not work either

forget about sleep for now ... focus on IO32 ... set to HIGH, wait a second, set to LOW, wait a second ... see what happens ... also, try to find a datasheet for the Lolin 2.4 Inch TFT shield

i did a search https://duckduckgo.com/?q=Lolin+2.4+Inch+TFT+shield+schematic ... the first hit points to wemos ... hit comes back as "not found" ... examined URL and found a mis-selling ... corrected mis-selling in the URL and got a good webpage that contains a schematic

@jsotola Sorry for not answering earlier. Thanks a lot for your help!

The backlight of this shield is ON as long as there's power on the 3.3V pin, unless you make GPIO 32 an output and pull it low.
In deep sleep, however, GPIO 32 will stop acting as a pulled down output pin but the esp32 keeps its 3.3V output pin powered, so the backlight will switch ON.
You could power the display over a mosfet, controlled by a GPIO.

Thanks for your help! It works now.
If someone else with mediocre coding skills read this question in the future. All you need to do is to put in the setup: pinMode(32, OUTPUT);
and when you want to use the screen put:
digitalWrite(32, HIGH); in front of it and digitalWrite(32, LOW); after it to disable the screen

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
NodeMCU ESP8266 burnt. What have I done fundamentally wrong here?
So my setup is:
A 12v DR7-12 battery is providing the power for the board through a DC buck converter set to 3.3V connected to the 3.3V pin of the esp8266.
I then am using pins D5 and D6 to control an L298N motor driver, which has it's 12V connected to the battery (not through the board), it's ground to the battery and the IN1 and IN2 pins connected to the D5 and D6 pins.
I've ended up with three dead ESP8266 boards, they heat up and become unresponsive but as far as I know, I'm not putting any power through the board am I? What am I doing wrong?!

possibly because of no ground connection between ESP8266 and motor driver

So the ground pin of the board is connected to the buck converter and then the ground of the battery and the L298N is connected to the ground of the battery as well. Do I need to connect the ground of the L298N directly to the ground of the board as well or in place of?

it should be ok as long as the buck converter output ground is the same as the battery ground ... also, never disconnect the motor driver ground if the battery positive is still connected

Please set up a proper regulated 3.3V src before burning more (capacitors are always good and a vreg > buck).  The L298N can be pretty aggressive on its current needs so check that from the 3.3v src before using the esp in the middle.

When things get hot that is because current is flowing, in your case it appears to be to much. Voltage in itself will not do it in but if allowed to push current past the input protection diodes you can fry it very easily.  The input protection diodes are connected to VCC and Ground so the current is pushed into one of those rails, to much voltage pushes it into VCC and can mess up anything else connected to the VCC as well. You need to determine what part is getting hot, if it is the regulator you may be able to replace it. When in doubt insert resistors and measure voltages.

@Abel as the OP said, the L298N gets its power directly from the battery (12V), not from the buck converter. I aggree that the OP should check if there are regulated 3.3V at the output of the regulater before connecting anything!

So the ground pin of the board is connected to the buck converter and then the ground of the battery and the L298N is connected to the ground of the battery as well - just to make sure: is the buck converter's ground connected to the battery ground? In general, all grounds need to be connected!

@Gil from my understanding the OP is working with the bare esp8266 module rather than a nodeMCU. So the regulator is an external part anyway...

OOPS since he stated he is using pins D5 and D6 I assumed it was on a board. However my statement was on a chip level. I should have noted that some junctions can burn up and not warm the chip because they are small. In his case since it is getting warm typically it would be protection device on the chip or simply a breakdown of a junction which will still cause current to flow and get hot.

Thank you very much all for your detailed responses. You were right, I hadn't connected the ground on the output of the buck converter to the other grounds. So the esp8266 was only connected to the buck converter and the L298N was connected the ground of the battery. When I connected all the grounds together, I haven't had a problem. Why is this needed? Do you always tie all the grounds together?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
esp8266 sending to both webserver and myphpadmin
I have tried to send all the variables to both the webpage and to myphpadmin. I seperated
the code into two functions and put the functions inside the void loop() function under the
impression that it will loop both but it seems if I put both then the device will only send
data to phpmyadmin. However, if I delete void logs() which is the function that sends data to
phpmyadmin then the void page() which sends the data to the webpage starts working. I can't find a solution for these two functions to work together, I really don't understand what I'm doing wrong, your guidance would be much appreciated
this is my code:
String header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";

String html_1 = R"=====(
<!DOCTYPE html>

  <meta name='viewport' content='width=device-width, initial-scale=1.0'/>
  <meta charset='utf-8'>

  <title>Temperature & Humidy Monitor</title>

Temperature & Humidity Monitor

Time

Temperature

 -- ℃

Humidity

 -- %

Pressure

 -- hPs

Altitude

 -- m

)=====";

#ifdef ESP32
  #include <WiFi.h>
  #include <HTTPClient.h>
#else
  #include <ESP8266WiFi.h>
  #include <ESP8266HTTPClient.h>
  #include <WiFiClient.h>
#endif
#include <Wire.h>
#include "HTTPSRedirect.h"
#include "DebugMacros.h"
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <ESP8266WebServer.h>
#include <DHT.h>

#define SEALEVELPRESSURE_HPA (1013.25)
#define DHTPIN 2     // what digital pin we're connected to
#define DHTTYPE DHT11   // DHT 11

Adafruit_BME280 bme;

const char* ssid = "fl";  // Enter SSID (WiFi Name) here
const char* password = "99110233";  //Enter Password here
const char* serverName = "http://192.168.101.17/sensordata/post-esp-data.php";
ESP8266WebServer server(80);

String apiKeyValue = "tPmAT5Ab3nnn9";
String sensorName = "BME280";
String sensorLocation = "Office";

float Temperature;
float Humidity;
float Pressure;
float Altitude;
String request = "";
int pin = 2;

void setup() {
  // initialize GPIO 2 as an output.
  pinMode(pin, OUTPUT);

  Serial.begin(115200);

  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }

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

  //connect to your local wi-fi network
  WiFi.begin(ssid, password);

  //check wi-fi is connected to wi-fi network
  while (WiFi.status() != WL_CONNECTED) {
  delay(10);
  Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected..!");
  Serial.print("Got IP: ");  Serial.println(WiFi.localIP());

  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);

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

}

void loop() {

  page();
  logs();

}

void page(){
  //sends data to webpage
  server.handleClient();

  WiFiClient client = server.client();     // Check if a client has connected
    if (!client)  {  return;  }

    request = client.readStringUntil('\r');     // Read the first line of the request

    Serial.println(request);
    Serial.println("");

    if ( request.indexOf("getTemp") > 0 )
     {
          Serial.println("getTemp received");

          // Reading temperature or humidity takes about 250 milliseconds!

         Temperature = bme.readTemperature();
         Pressure = bme.readPressure() / 100.0F;
         Altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);
         Humidity = bme.readHumidity();    // Read temperature as Fahrenheit (isFahrenheit = true)

          if ( !isnan(Temperature) && !isnan(Humidity) && !isnan(Pressure) && !isnan(Altitude) )
          {
              client.print( header );
              client.print( Temperature );   client.print( "|" );
              client.print( Humidity );   client.print( "|" );
              client.print( Pressure ); client.print( "|" );
              client.print( Altitude ); client.print( "|" );
              Serial.println("data sent");
          }
          else
          {
              Serial.println("Error reading the sensor");
          }
     }

     else
     {
        client.flush();
        client.print( header );
        client.print( html_1 );
        Serial.println("New page served");
     }

    delay(5);

    if (Temperature > 20.0){
    digitalWrite(pin, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(50);               // wait for a second
    digitalWrite(pin, LOW);    // turn the LED off by making the voltage LOW
    delay(1);
  }
}

void logs(){
  //sending to database
  //Check WiFi connection status
  if(WiFi.status()== WL_CONNECTED){
    HTTPClient http;

    // Takes Domain name with URL path or IP address with path
    http.begin(serverName);

    // Specifies content-type header
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");

    // Prepare HTTP POST request data
    String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName
                          + "&location=" + sensorLocation + "&value1=" + String(bme.readTemperature())
                          + "&value2=" + String(bme.readHumidity()) + "&value3=" + String(bme.readPressure()/100.0F) + "";
    Serial.print("httpRequestData: ");
    Serial.println(httpRequestData);

    //String httpRequestData = "api_key=tPmAT5Ab3nnn9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";

    // Send HTTP POST request
    int httpResponseCode = http.POST(httpRequestData);

    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }

    http.end();
  }
  else {
    Serial.println("WiFi Disconnected");
  }
  //Send an HTTP POST request every 30 seconds
  delay(30000);
}

void handle_OnConnect(){

  Temperature = bme.readTemperature();
  Pressure = bme.readPressure() / 100.0F;
  Altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);
  Humidity = bme.readHumidity();

}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

https://github.com/esp8266/Arduino/issues/7613#issuecomment-700869953


text:
Can't get Adafruit MusicMaker and Ethernet to work at the same time
Working on an IoT project.
Environment:

Adafruit Feather M4 Express
Adafruit MusicMaker FeatherWing (amplified, this is a VS1053 at heart)
Silicognition PoE FeatherWing (electrically compatible with the Adafruit Ethernet FeatherWing)
PlatformIO with Visual Studio Code on a Mac (all libraries are up-to-date)

The Problem:
I can get either the Ethernet to work or the MusicMaker to work, but not both at the same time.
There are no errors during initialization, they just don't work.
Specifically, the MusicMaker's sineTest() method doesn't generate any sound if Ethernet has been initialized. Likewise, the Ethernet client's connect() method is unable to connect if the MusicMaker is initialized. Both methods work fine if the other device hasn't been initialized.
Feather Pins:
Purpose                    Pin
-------------------------- ---
VS1053 Chip select           6
VS1053 Data/command select  10
VS1053 Data request          9
SD Card Chip select          5
Ethernet Chip select        14

Note that I'm not currently using the SD card and haven't called its begin() method.
Note also that the Ethernet chip select is on a non-standard pin because the default conflicts with the VS1053 data/command select.
Also, the PoE FeatherWing has an EEPROM on it with a unique MAC address and reading this works fine.
One other note: I thought that I had this combination working in an earlier prototype a few months ago, but that may have been with the Feather 32U4.
TIA.
The prototype code:
#include <Arduino.h>
#include <Adafruit_VS1053.h>
#include <Ethernet.h>
#include <IPAddress.h>
#include <SPI.h>
#include <Wire.h>

//
// Pins for the Ethernet and MusicMaker FeatherWings.
// NOTE: These definitions assume a Feather M4 Express with a PoE FeatherWing
//       modified to have its chip select on pin 14 because the default conflicts
//       with the MusicMaker's DCS pin.
//
#define VS1053_CS       6     // VS1053 chip select pin (output)
#define VS1053_DCS     10     // VS1053 Data/command select pin (output)
#define SD_CARD_CS      5     // Card chip select pin
#define VS1053_DREQ     9     // VS1053 Data request, ideally an Interrupt pin
#define ETHERNET_CS    14     // Ethernet chip select pin. Note that this is custom because the default conflicts with VS1053_DCS.

//
// PoE FeatherWing.
//
#define MAC_EEPROM_I2C_ADDRESS      0x50  // I2C address of the 24AA02E48 EEPROM chip that contains our MAC address (on the PoE FeatherWing).
#define MAC_EEPROM_REGISTER         0xFA  // Register within the 24AA02E48 that contains the first byte of our MAC address.

#define HANG      while( true ){ delay( 10 ); }
IPAddress         host = { 172, 24, 110, 1 };
uint16_t          port = 8000;
const char*       path = "/sounds/DingDong.mp3";
Adafruit_VS1053   player{ Adafruit_VS1053( -1, VS1053_CS, VS1053_DCS, VS1053_DREQ ) };
EthernetClient    client;
uint8_t           mp3Buf[VS1053_DATABUFFERLEN];
uint32_t          contentLength;
byte              macAddress[6]{};

uint32_t          beginRequest();
void              readMacAddress( byte* );

void setup()
{
  Serial.begin( 115200 );
  while( !Serial ){ delay( 10 ); }
  Serial.println( "MusicMaker/Ethernet Prototype" );

  Wire.begin();

  Ethernet.init( ETHERNET_CS );
  readMacAddress( macAddress );
  if( !Ethernet.begin( macAddress ))
  {
    Serial.printf( "Unable to initialize the network; hardware status is %d\n",
                   Ethernet.hardwareStatus());
    HANG;
  }

  Serial.print( "Mac address: " );
  for( int ii = 0; ii < 6; ii++ )
  {
    if( macAddress[ii] < 16 ) { Serial.print( '0' ); }
    Serial.print( macAddress[ii], HEX );
    if( ii < 5 ) { Serial.print( ':' ); }
  }
  Serial.println();
  Serial.print( "DNS IP:      " ); Serial.println( Ethernet.dnsServerIP());
  Serial.print( "Local IP:    " ); Serial.println( Ethernet.localIP());
  Serial.print( "Gateway IP:  " ); Serial.println( Ethernet.gatewayIP());
  Serial.print( "Subnet mask: " ); Serial.println( Ethernet.subnetMask());

  if( !player.begin())
  {
    Serial.println( "Unable to initialize the MusicMaker" );
    HANG;
  }
  Serial.println( "Initialized the MusicMaker" );
  player.setVolume( 40, 40 );
  player.sineTest( 0x44, 1000 ); // 1KHz tone for one second.

  contentLength = beginRequest();
  Serial.printf( "HTTP content length: %d\n", contentLength );
}

void loop()
{
  if( player.readyForData())
  {
    if( client.available() > 0 )
    {
      uint8_t bytesRead = client.read( mp3Buf, VS1053_DATABUFFERLEN );
      if( bytesRead > 0 )
      {
        player.playData( mp3Buf, bytesRead );
        contentLength -= bytesRead;
        if( contentLength <= 0 )
        {
          Serial.println( "That should be all of our sound" );
        }
      }
    }
  }
}

uint32_t beginRequest()
{
  if( !client.connect( host, port ))
  {
    Serial.print( "Unable to connect to " );
    Serial.print( host ); Serial.print( ':' ); Serial.println( port );
    HANG;
  }

  Serial.print( "GET " ); Serial.print( path ); Serial.print( " HTTP/1.1\r\n" );
  Serial.print( "Host: " ); Serial.print( host ); Serial.print( "\r\n" );
  Serial.print( "Connection: close\r\n\r\n" );

  client.print( "GET " ); client.print( path ); client.print( " HTTP/1.1\r\n" );
  client.print( "Host: " ); client.print( host ); client.print( "\r\n" );
  client.print( "Connection: close\r\n\r\n" );

  char http[] = "HTTP/";
  client.find( http );                  // Skip over the HTTP/ part of the header.
  client.parseFloat( SKIP_WHITESPACE ); // Skip over the HTTP version number.

  int httpStatus = client.parseInt( SKIP_WHITESPACE );
  if( httpStatus < 200 || httpStatus > 299 )
  {
    Serial.printf( "GET request failed; HTTP status is %d\n", httpStatus );
    client.stop();
    HANG;
  }

  char lengthHeader[] = "Content-Length:";
  client.find( lengthHeader );
  int contentLength = client.parseInt();

    char endOfHeaders[] = "\r\n\r\n";
  if( !client.find( endOfHeaders ))
  {
    Serial.println( "Invalid HTTP response (missing trailing line endings)" );
    client.stop();
    HANG;
  }
  return contentLength;
}

void readMacAddress( byte* addr )
{
  Wire.beginTransmission( MAC_EEPROM_I2C_ADDRESS );
  Wire.write( MAC_EEPROM_REGISTER );
  int failed = Wire.endTransmission();
  if( failed )
  {
    Serial.printf( "Unable to retrieve MAC address; endTransmission returned %d\n", failed );
    HANG;
  }

  byte* b = addr;
  int bytesRead = Wire.requestFrom( MAC_EEPROM_I2C_ADDRESS, 6 );
  if( bytesRead < 6 )
  {
    Serial.printf( "Unable to retrieve MAC address; fewer than six bytes\n" );
    HANG;
  }

  while( Wire.available())
  {
    *b++ = Wire.read();
  }
}

is a SD card inserted? if yes, then remove it or set the CS pin HIGH at the beginning of setup(). set the CS pin of the player HIGH before Ethernet.begin()

Set both the SD card CS and the player CS to outputs and set them high prior to Ethernet.init() and Ethernet.begin(). If both Ethernet and player are initialized, neither works. player's sineTest() method doesn't do anything and EthernetClient's connect() method returns zero. They both use SPI. Could there be some sort of conflict there?

Turned out to be a hardware problem.
The PoE FeatherWing's default CS pin conflicts with the MusicMaker's DCS pin. The PoE CS pin can be changed by cutting a trace on the back of the board and bodging a wire from a pad to whatever pin you want to use instead. I had done that.
Turns out though, that I hadn't cut it completely. This was causing the Ethernet library to pull the MusicMaker DCS low every time it pulled the Ethernet CS low.
I finally figured it out when I hooked up a logic analyzer to all of the CS pins and the SPI pins. It was very clear that MusicMaker DCS was going low with Ethernet CS.
Yay Logic Analyzer.


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

So I've recently started Arduino and I just had a question about the digitalRead() function.
Does the IO Pins read Voltage or Current?
The reason I'm asking is because of the attached circuit.
So IO pin 7 is HIGH when the button is not pressed because the resistor is connected to 5V through the resistor. When the button is pressed the button is shorted to ground and is LOW. Why does it read LOW? Surely it would still read 5v because it is still connected to 5V through the resistor?

you do not need a pullup resistor on the switch ... just enable the internal pullups

Surely it would still read 5v because it is still connected to 5V through the resistor? Equally you might argue it will read 0v because it is connected to Gnd via a direct short. The short will take precedence over the resistor.

They read voltage.  When you close the pushbutton switch the input should have a 0V or digital "0" on it.  When you open the pushbutton the resistor should pull the input to 5V or digital "1".
Yes, it is still connected to +5V via the resistor but the nearly 0 Ohm switch pulls the line all the way (or very close) to 0V.

For digital pins, it's more of a voltage comparison. They only measure if the voltage is above of below a certain threshold. So they only check whether it's HIGH of LOW. For the ATMega328p on the UNO, any voltage below 1.5V will return a LOW / 0, and anything above 3.5V will return a HIGH / 1. (Any voltage in between don't have a guaranteed outcome).

@Gerben If we're aiming to be absolutely accurate here, then the actual specification for Vil(max) is 0.3 * Vcc and Vih (min) is 0.5 * (0.6 * Vcc).  So if you are running at Vcc = 5.0V that comes out to be 1.5V and 3.5V.  If your Vcc is different from 5.0V, then these values also vary. See the Atmel/Microchip ATMega328P datasheet on page 258.  https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf


text:
share enum between python and arduino
I have created a gui in python that allows an arduino controlled mecanum wheel cart to move around.
The cart allows for 8 different move directions and can rotate left and right. Commands are sent over a serial connection between the laptop(w10, python) and the arduino.
I have an Enum class in python representing the different move directions.
I have a corresponding enum in the arduino to interprete the commands from the python task.
What is an easy way to share a single common enum definition for both coding environments?

You mean simple code-sharing between two pieces of source code in differing languages? You'll have to find some common ground between them.

You mean copy and past the text (the enum list) between the two?  I found a great thread that talks about Python enums specifically.  But even with the slightly different syntax of all the different options in Python, I still see slight differences that will likely prevent cutting and pasting w/o modification.  Ask and I'll post that as an answer if you want.

One approach that I have used for similar purposes is to generate the appropriate header files (or module or whatever) from a simple text file for all the required uses.
Since you already know python this should be pretty easy. Quick "proof of concept" follows. (Warning: I barely know any python.)
One downside to this is that you have to remember to regenerate the header/module each time you update the enum (keys or values) - don't forget to recompile for the C++ part. If you have a build system, it is best to integrate that code generation step into it.
A variation of this is to parse one of the language's source code to extract the definition and output it in a format suitable for the other. That is generally much harder to do though if you want to make it robust.

robot.enum
UP    1
DOWN  2
LEFT  3
RIGHT 4
JUMP  5

enum_generator.py
def python_enum(filename):
    with open(filename, 'w') as w:
        w.write('class Robot(Enum):\n')
        with open('robot.enum') as r:
            for line in r:
                parts = line.split()
                w.write(f'    {parts[0]} = {parts[1]}\n')

def cplusplus_enum(filename):
    with open(filename, 'w') as w:
        w.write('#pragma once\n')
        w.write('enum Robot: int {\n')
        with open('robot.enum') as f:
            for line in f:
                parts = line.split()
                w.write(f'  {parts[0]} = {parts[1]},\n')
        w.write('};');

python_enum('robot_enum.py')
cplusplus_enum('robot_enum.h')


text:
Sync issue with signals

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "digitalWriteFast.h"

#define BUTTONPIN 2
#define FDCSPIN 6
#define CIPIN 5
#define SPEAKERPIN 4

float RPM=1000.0;
int PWus=1.5*1000.0;
int FDCSoffset=(1000.0/RPM/60.0/4.0) - (PWus/1000.0);
int CiCnt;
int totalCnt;
int CIState=B01100000;
bool Buttonstate=0;
LiquidCrystal_I2C lcd(0x27, 20, 4);

void setup()
{
  Serial.begin(9600);
  lcd.begin();
  lcd.backlight();
  lcd.clear();
  lcd.print("READY TO TEST"); // Waiting for button press
  pinMode(BUTTONPIN, INPUT);// Setting button as Input
  pinMode(FDCSPIN, OUTPUT); // Fuel Delivery Control Signal
  pinMode(CIPIN, OUTPUT); // Cylinder Identification
  digitalWriteFast(FDCSPIN, LOW);
  digitalWriteFast(CIPIN, LOW);
}

void loop()
{
 Buttonstate=digitalReadFast(BUTTONPIN);
 if(Buttonstate==1)
 {
  delay(5);
  if(Buttonstate==1)
  {
    runInjectorTest();
  }
 }
}
void runInjectorTest()
{
  lcd.print("Test Run");
  playtesttone();

    for(totalCnt=0;totalCnt<8000;totalCnt++)
    {

      PORTD=CIState;
      delayMicroseconds(FDCSoffset);
      PORTD=PORTD^B01000000;
      delayMicroseconds(PWus);
      if(totalCnt%4==0)
      {
        CIState=CIState^B00100000;
      }
    }
  totalCnt=0;
  playfinishtone();
}
void playtesttone()
{
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
}
void playfinishtone()
{

  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);

}

I am using this code to generate 2 signals, called CI and FDCS. CI stays on until the 5th FDCS pulse. I checked the output which is connected to a driver using the scope and I got this.
The rising edge and falling edge of the longer signal (CI, dark green) are supposed to sync with the rising edge of the FDCS signal (Lime green),but they are inline with the falling edge. Note that the output is inverted (when compared to the code) hence the signal generated by the Arduino pins is according to the code.

so, what is your question?

@jsotola Why is the signal not turning on at the exact same time? according to the code, I am writing the PORTD register at the same time for both pin 6 and 5, so they should sync up right?

which code line writes both bits to PORTD?

@jsotola PORTD=CIState, under runInjectortest(), in the for loop. CIState=B01100000

If the output is inverted, and you turn the higher frequent signal on it is displayed on the scope as a falling edge. (because it is inverted: rising edge becomes a falling edge.) You got what you programmed. ;-)

@PeterPaulKiefer Oh god thanks, now are there any way to change the code to work on the falling edge?

You change both signals separately with a delay between. I added an answer to show you my idea.

I did not tried it out. But something like this might help to synchronize the inverted signals to the rising edge of the high frequent signal.
I removed the FDCSoffset delay, because it is negative according to the variables at the top.
// initialize CIState with 00
int CIState=B00000000;

// lines not shown .....

for( totalCnt=0; totalCnt<8000; totalCnt++ )
{
  CIState=CIState^B01000000;
  if(totalCnt%4==0)
  {
    CIState=CIState^B00100000;
  }
  // both signals are set at the same time
  PORTD=CIState;
  delayMicroseconds(PWus);
}


text:
Bit Bang signal generation

  #include <Wire.h>
  #include <LiquidCrystal_I2C.h>
  #include "digitalWriteFast.h"

  #define BUTTONPIN 2
  #define FDCSPIN 6
  #define CIPIN 5
  #define SPEAKERPIN 4

  float RPM=1000.0;
  int PWus=1.5*1000.0;
  int FDCSoffset=(1000.0/RPM/60.0/4.0) - (PWus/1000.0);
  int totalCnt;
  int CIState=B00000000;
  bool Buttonstate=0;
  LiquidCrystal_I2C lcd(0x27, 20, 4);

  void setup()
  {
    Serial.begin(9600);
    lcd.begin();
    lcd.backlight();
    lcd.clear();
    lcd.print("READY TO TEST"); // Waiting for button press
    pinMode(BUTTONPIN, INPUT);// Setting button as Input
    pinMode(FDCSPIN, OUTPUT); // Fuel Delivery Control Signal
    pinMode(CIPIN, OUTPUT); // Cylinder Identification
    digitalWriteFast(FDCSPIN, LOW);
    digitalWriteFast(CIPIN, LOW);
  }

  void loop()
  {
   Buttonstate=digitalReadFast(BUTTONPIN);
   if(Buttonstate==1)
   {
    delay(5);
    if(Buttonstate==1)
    {
      runInjectorTest();
    }
   }
  }
  void runInjectorTest()
  {
    lcd.print("Test Run");
    playtesttone();

      for(totalCnt=0;totalCnt<8000;totalCnt++)
      {

        PORTD=CIState;
        delayMicroseconds(PWus);
        PORTD=PORTD^B01000000;
        delayMicroseconds(FDCSoffset);
        if(totalCnt%4==0)
        {
          CIState=CIState^B00100000;
        }
      }
    totalCnt=0;
    playfinishtone();
  }
  void playtesttone()
  {
    tone(SPEAKERPIN, 500, 500);
    delay(700);
    tone(SPEAKERPIN, 500, 500);
    delay(700);
    tone(SPEAKERPIN, 500, 500);
    delay(700);
    tone(SPEAKERPIN, 2000, 500);
  }
  void playfinishtone()
  {

    tone(SPEAKERPIN, 2000, 500);
    delay(700);
    tone(SPEAKERPIN, 2000, 500);
    delay(700);
    tone(SPEAKERPIN, 2000, 500);
    delay(700);
    tone(SPEAKERPIN, 500, 500);

  }

I am trying to generate 2 signals using the code above and this output is
From the image, the lime green signal is called FDCS and the other is called CI. Note that the scope shows the inverted form of the signal. I want the falling edge of CI to match with the Falling edge of the 5th FDCS signal (right now rising edge is matching with the falling edge of the CI signal). But the Rising edge of the CI signal should match with the Rising edge of the first FDCS signal (which it's already doing). How do I change my code to do this?

What should the behaviour of "CI" be when it is "low", after the falling edge of the fifth "FDCS" pulse? For how many "FDCS" pulses should it remain low? The code is easy to adapt but you've not yet specified the complete "CI" cycle.

@StarCat To summarise, CI should go HIGH when FDCS goes HIGH, then stay HIGH for 4 complete cycles of FDCS, then go LOW on the FALLING edge of the 5th Cycle. Now the CI pin should stay LOW until the RISING edge of the 10th cycle of FDCS after which the pattern repeats. The pattern should repeat 2000 times.

Alread asked and answered here: Sync issue with signals

If I understand correctly, you signal has a period of 8 FDCS pulses:
4 with CI high and 4 with CI low. Since the rising and falling edges of
CI do not happen at the same place relative to the FDCS pulses, you
should handle these separately.
I suggest something like the following. Note that, as I do not know what
signal(s) your setup inverted, I just try to reproduce what you show on
the scope, with non inversion:
uint8_t portState = 0;
for (int totalCnt = 0; totalCnt < 16000; totalCnt++)
{
    // On pulse 0, CI rises with FDCS.
    portState |= _BV(FDCSPIN);
    if (totalCnt % 8 == 0)
        portState |= _BV(CIPIN);
    PORTD = portState;

    delayMicroseconds(FDCSoffset);  // pulse width

    // On pulse 4, CI falls with FDCS.
    portState &= ~_BV(FDCSPIN);
    if (totalCnt % 8 == 4)
        portState &= ~_BV(CIPIN);
    PORTD = portState;

    delayMicroseconds(PWus);  // inter-pulse delay
}

Could you let me know what the postState variable is?

@Redlion11: It's a typo. ;-) Fixed!

Thanks for the clarificationn!!


text:
Arduino websockets send id in connection
I am creating home automation using esp's and little home server. Idea is to connect arduinos to server, add each of them id and let them talk via websockets with server and server will forward (by some logic inside) messages to different arduinos. Pretty simple.
What I found, is that I cannot tell, what websocket client I am talking to. I use simple example from lib: https://github.com/gilmaimon/ArduinoWebsockets
client.onMessage(onMessageCallback);
client.onEvent(onEventsCallback);
client.connect(websockets_server_host, websockets_server_port, "/");
client.ping();

My idea is to send id of arduino with connection handshake. Is it even possible?

This is a websocket client code. The client is not talking to other clients, but the server. He doesn't need to differentiate clients.

Exactly. Server will forward messages from one client to antoher. Problem is, that on server side I have multiple clients, that I cannot distinguish so I need each client to identify itself when it connect

You can even add your device id with every message you send to the server.

I like to pass a an identifying GET param in the websocket URL (eg. system_get_chip_id()), then the PC-based server socket lib has a (sometimes roundabout) way of getting the request URL to id who's asking.


text:
Sending 4 analog values from one arduino to another with I2C
I have modded a cheap drone controller to output its joystick values to an Arduino Nano.
I made it to output its 4 pot values using I2C to another Arduino don't ask why. So my problem is that I need to send 4 values but I can send only 1. Help me please.
I don't have a time limit or something so I don't need this quick or now!
I am also using a 16x2 LCD without I2C to show the live values and sometime I want to make a menu there or stuff like that.
I would like if you wrote the code for me but its ok if you cant. Also I'm kind of a noob at arduino programming.
Master(a.k.a the nano in the controller):
int pot1 = A0;
int pot2 = A1;
int pot3 = A2;
int pot4 = A3;

int potValue1 = 0;
int potValue2 = 0;
int potValue3 = 0;
int potValue4 = 0;

int led = 10;
int button = 8;

int lastButtonState;    // the previous state of button
int currentButtonState; // the current state of button

int output1 = A4;
int output2 = A5;
int output3 = A6;
int output4 = A7;

#include <Wire.h>
#include <LiquidCrystal.h> // includes the LiquidCrystal Library

LiquidCrystal lcd(2, 3, 4, 5, 6, 7); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7)

#define SLAVE_ADDR 9

void setup() {
  pinMode(led, OUTPUT);
  pinMode(button, INPUT_PULLUP);

  // Open serial communications and wait for port to open:
  Wire.begin();

  lcd.begin(16, 2);
  lcd.print("   ArduinoTX");
  digitalWrite(led, HIGH);
  delay(600);
  digitalWrite(led, LOW);
  delay(600);
  digitalWrite(led, HIGH);
  delay(600);
  digitalWrite(led, LOW);
  delay(600);
  digitalWrite(led, HIGH);
  delay(600);
  delay(3000);
  lcd.clear();
}

void loop() {
  currentButtonState = digitalRead(button);
  potValue1 = analogRead(pot1);
  potValue2 = analogRead(pot2);
  potValue3 = analogRead(pot3);
  potValue4 = analogRead(pot4);

  int sendValue = map(potValue4, 1, 1023, 1, 255);  //converting to values 255 max
  int sendValue2 = map(potValue3, 1, 1023, 1, 255);
  int sendValue3 = map(potValue2, 1, 1023, 1, 255);
  int sendValue4 = map(potValue1, 1, 1023, 1, 255);

  Wire.beginTransmission(SLAVE_ADDR); //sending only one pot value
  Wire.write(sendValue);
  Wire.endTransmission();

  lastButtonState  = currentButtonState;      // save the last state
  currentButtonState = digitalRead(button); // read new state

  if (lastButtonState == LOW && currentButtonState == LOW) { //dont worry about this
    lcd.print(potValue4);
    lcd.print("        ");
    lcd.print(potValue2);
    delay(delayTime);
    lcd.clear();
    lcd.setCursor(0, 2);
    lcd.print(potValue3);
    lcd.print("        ");
    lcd.print(potValue1);
    delay(delayTime);
    lcd.clear();
  }
}

Slave(or an uno who receives the values):
int rd;
int br;

#include <Wire.h>

#define SLAVE_ADDR 9

void setup() {
  // put your setup code here, to run once:
  Wire.begin(SLAVE_ADDR);

  // Function to run when data received from master
  Wire.onReceive(receiveEvent);

  // Setup Serial Monitor
  Serial.begin(9600);
}

void receiveEvent() {
  // read one character from the I2C
  rd = Wire.read();
  Serial.println(rd);
}

void loop() {
  delay(50);
}

Thanks!

"I would like if you wrote the code for me but its ok if you can't." That's very considerate of you.

"I need to send 4 values but I can send only 1" why can you only send 1?

Why are you limited to sending one value? You can have multiple Wire.write() calls in one transmission.
The slave side just needs to know to expect multiple values in order to accommodate. The best way to do this would be to read in values as long as the master is sending them (check out https://www.arduino.cc/en/Reference/WireRead).
Then your master changes from
Wire.beginTransmission(SLAVE_ADDR);
Wire.write(sendValue);
Wire.endTransmission();

to
Wire.beginTransmission(SLAVE_ADDR);
Wire.write(sendValue);
Wire.write(sendValue2);
Wire.write(sendValue3);
Wire.write(sendValue4);
Wire.endTransmission();

And the slave receiveEvent() becomes
int receiveValue;
int receiveValue2;
int receiveValue3;
int receiveValue4;
int index = 0;
while(Wire.available()){
    if(index == 0){ receiveValue = Wire.read(); }
    else if(index == 1) {receiveValue2 = Wire.read(); }
    else if(index == 2) {receiveValue3 = Wire.read(); }
    else if(index == 3) {receiveValue4 = Wire.read(); }
    index++;
}

I would also consider using arrays as a way to clean up some of your variables, but making the above changes should accomplish what you want if not as cleanly.

Happy New Year! But it still does not work :(  And also how do I Serial print these values maybe that's my problem because I put Serial.print(receiveValue); in void loop because i thought that's how it's meant to be. Say if I need to post updated code

If you want to print receiveValue, doing it in void receiveEvent() is the way to go. Unless you made receiveValue a global variable printing it in your loop will not work and could provide misleading results anyway. I'm not sure exactly what issue you are seeing at this point. Can you provide more info please? If it's just that its not printing 4 values, see my previous answer and add Serial.println() for all receiveValues.


text:
using a digital pin on node mcu as an analog
i want to use volte and current sensors (ZMPT101B and ACS712) on node MCU these sensors are analog but node mcu has on analog pin can i use digital D0 pin for voltage sensor?

yes, but the resolution is one bit.

@dandavis I was about to respond with NO but yours is better.

@dandavis lol ... your comment stirred a few memory cells ... more than one bit resolution is possible ... google 1-bit ADC

@mohamedmansour you can use one digital input if you use some external circuitry ... monitor the output of a comparator ... the two comparator inputs would be, the voltage input and an programmable reference voltage ... for example, suppose full scale is 6 V and you have an input of 4 V ... first you compare the input to 3 V and record  1 ... next compare to 3 + 1.5 V and record a 0 ... next you roll back the 1.5 V and compare to 3 + 0.75 V and record a 1  ... next compare 3 + 0.75 + 0.375 V and record a 0  ....... so far the digital data is 1010 .... you can keep going for more bits

use an I2C ADC module. they have usualy at least 4 ADC pins.


text:
SoftwareSerial read until available is empty only works with delay
I originally was only going to make my program work on an ESP until I needed it on an Arduino UNO (because  I suspect my ESP is broken).
I had to add SoftwareSerial support but because I didn't originally intend to, the strings I send from my app have no terminators on them. I thought this would be fine because I could do something like:
void loop()
{
    while (ble.available() > 0)
    {
        data += (char)ble.read();
    }

    if (ble.available() <= 0 && data.length() > 0)
    {
        ble.println(data);
        //do stuff
        data = "";
    }
}

All that is doing is creating a string out of the recieved characters. It then checks if there is nothing left to read, and stuff has already been read (ie data has a length), then print the data.
What I expect the output to be is (if the input string in 03:255,255,255):
03:255,255,255

What I actually get is:
0
3
:
2
5
5
,
//and so on

That is becuase, for some reason, even though ble.available() should return a number not 0 at the if statement, it returns 0 and therefore the statement will always become true.
The only way I've fixed this is by adding in a little delay at the end of the loop. Whether that be:
delay(10)

or even this, in the while loop:
Serial.println(ble.available()) //This introduces enough delay somehow

Without having to modify my app, can I pull this off without using a delay? With delays it seems hacky especially because for all I know, for older or newer devices this delay could be too high or too low.

Serial does not transmit data as one bunch, but byte by byte. There can easily be some little delays introduced, especially, when transmitted via a packaged protocol like bluetooth, long enough, for the Arduino to not see any new data in its buffer. Also the transmission needs some time, depending on the baudrate. When you read faster from the buffer, than you receive, you will encounter an empty buffer after every byte.
Now with that information look at your code:
void loop()
{
    while (ble.available() > 0)
    {
        data += (char)ble.read();
    }

    if (ble.available() <= 0 && data.length() > 0)
    {
        ble.println(data);
        //do stuff
        data = "";
    }
}

Let's assume, the Arduino receives one byte, then a little pause happens, then the next data is received. The code will go into the while loop and read the received byte from the serial buffer. To stay in the while loop, the next byte has to be received in the execution time of the code inside of the while loop. That is incredible short. So after one byte there is nothing more inside the buffer, thus the while loop exits, because ble.available() returns zero. Then the if statement is executed, also rather fast. Most likely, ble.available() will still return zero. But you already put a character into the buffer, so the if statement is executed.
The delay solves your problem because then you read way slower than you receive. The data is mainly received while the delay runs. Then the rest of your code can read, what was already received and put into the buffer.
**What to do instead of delay(): You need to make sure, that you always read a full message. There are different ways, depending on your requirements. If your messages always have the same length, you could wait, until the specified number of characters was received, and only then read them. But that will fail, if you for some reason (for example a reset of the Arduino) receive a partial message, which would cause a misalignment. You could clear the receive buffer, when you read a full message, that might help, if your data transmissions don't happen to often.
You could try to parse the incoming data according to the message format (which needs to stay constant for this purpose), like:
Read a number.
If it has a colon following it, it is a new message.
Then read number
    read comma
    read number
    read comma
    read number
Repeat.

For this purpose it would be fitting to read every byte, that gets received, and write then into your own circular buffer. You can then continuously add newly received characters at the end, while removing the already parsed messages from the start of the buffer.

You see, these ways have caveats and might be convoluted. The easiest way would be to add a delimiter/terminator to your messages, though from your question it sounds, as if this is not possible for you currently.
Note:

None of the above is specific to SoftwareSerial. It's the same for hardware Serial.
I suspect the code worked your ESP, because you had some other code there, which introduced a big enough delay (just like your delay() call)

Ah right ok that makes sense!  I do like the idea of a circular buffer where I can just remove what I've already parsed but unfortunately the format is inconsistent and so is the length. I think the easiest way is to just makes the strings have terminator characters. Thanks for the answer though!

@DreamingInsanity If you think, that my answer is correct, you can accept it as correct and thus mark the question as answered.

Yeah my bad! I forgot to last night.


text:
What module should I use for high precision localization?
I have a toy car and I want to measure the coordinates/location of that car in my house.
It need to bee high precision equipment so GPS won't work here.
My precision requriments is 5+- cm and the distance is like 10-20 meters as maximum raduis.
What module should I use then?

you could mount cameras to the walls and track the object optically

@jsotola that won't work for me. It need to be very like GPS, but local.

While there certainly are systems, that work like a local GPS, they will be very expensive and most likely not easy to use. Honestly I wouldn't know, where I would be able to source such a system. Please explain more about the requirements. Why won't cameras work for you?

@chrisl because cameras can't see through walls.

@DanielMårtensson So much I already thought. Please add a description of your general goal and setup to your question. I don't think, that a "local GPS" is really a viable option here. But maybe - when we know your setup and requirements - we can suggest different sensors (or maybe a combination of sensors)

there is no "module" you can use. Heck, there's not really anything you can use with an Arduino. There's a few systems that do things like this, though not to that level of precision, and those are lab-based proof of concepts more than working systems. Ultrasonic triangulation might be your best bet fi you can lower the precision requirements a notch or two, but even that's complex AF.

@dandavis Thank you. I think I have to quit my idea then if it's not possible to have a high precision Local Position System inside my house.

@chrisl I don't know my setup or requriments, except it need be small, have 4 wheels and have a precision about 5+- cm. That's all I need.


text:
Updating SPI transfer16 to create Transfer24
It might be a bit out there, but for a project that I am working on, my word size default is 24bits (3x8-bit), of which the first 8-bits are data and the next 16-bits are data. I would like to transfer it out of the system as fast as possible with minimal calls to the sub-routines. For this I am trying to reduce the number of calls, I have managed to reduce it from 3 to 2, Can I possibly make it 1 call.

My first attempt was to use 3x SPI.transfer() Second was to use 1x

SPI.transfer() and 1x SPI.transfer16()

I would like to know what would be the ideal way to write a SPI.transfer24 function.

What teensy are you using?

teensy 4.0 is the one i am using

And how much difference do you think making 1 function call as opposed to 2 will make at 600MHz? Will you even be able to tell?

@Majenko that is a fair point, but if you try to look at a digital logic level analyzer each word seems to to have a small impact, but when you write ~4M words a second it adds up unfortunately.

You can't.  The teensy 4.0 has hardware support for 8-bit, 16-bit and 32-bit transfers. Not 24-bit transfers.
But at 600MHz the overhead of making a function call is negligible anyway - certainly compared to the speed of SPI which is at best about 30x slower than the CPU operates at.
If you want high throughput you won't be wanting to use the SPI library anyway, instead you'd be using DMA to transfer your data with minimal CPU intervention.


text:
When I start running the Brushless motors with MPU6050 in my quadrocopter, there is a sudden spike in the data of Gyro X-axis and Gyro Y-axis
I am using the MPU6050_light library for getting the data for my quad-copter. When I am obtaining the gyro values from the MPU6050 without running the motors, its giving correct values but on running the motors and getting the values, I am getting a huge spike on both axes. I am a newbie and a tenth-grader so i don't know so much about electronics. I tried using a Kalman filter but could not find any code which can help me and the Kalman Library was too complex. I think if I apply some kind of filter the problem will be solved. If any one knows any other filter and its code, if you can share it, it would be of great help.
The code is as follows:
#include <SoftwareSerial.h>
#include <Servo.h>
#include <MPU6050_light.h>
#include <Wire.h>

double x = 0.0, y = 0.0, z = 0.0;
int c=0;

SoftwareSerial Slave(5,6);
Servo m1, m2, m3, m4, l;
MPU6050 mpu(Wire);

int throttle = 0;
int t1 = 0, t2 = 0, t3 = 0, t4 = 0;
unsigned long timer;
int of = 0;

void setup()
{
  Slave.begin(9600);
  Serial.begin(9600);
  Wire.begin();
  byte stat = mpu.begin();
  del(1000);
  mpu.calcOffsets();
  del(2000);
  m1.attach(3, 800, 2000);
  m2.attach(9, 800, 2000);
  m3.attach(10, 800, 2000);
  m4.attach(11, 800, 2000);
  l.attach(12, 800, 2000);
  throttle = 0;
  normal();
  del(10000);
  l.detach();
  while (of == 0)
  {debug();}
}

void loop()
{
  normal();
  debug();

  if (of == 0)
  {
    safe_land();
  }

  getxyz();

  if (x < -5.0)
  {
    t1 = t1 + 1;
    t3 = t3 + 1;
    debug();
    normal();
    getxyz();
  }

  if (x > 5.0)
  {
    t2 = t2 + 1;
    t4 = t4 + 1;
    debug();
    normal();
    getxyz();
  }
  if (y < -5.0)
  {
    t4 = t4 + 1;
    t3 = t3 + 1;
    debug();
    normal();
    getxyz();
  }

  if (y > 5.0)
  {
    t2 = t2 + 1;
    t1 = t1 + 1;
    debug();
    normal();
    getxyz();
  }

}
void normal()
{
  m1.write(throttle + t1);
  m2.write(throttle + t2);
  m3.write(throttle + t3);
  m4.write(throttle + t4);

}
void safe_land()
{
  throttle = 0;
  t1 = 0;
  t2 = 0;
  t3 = 0;
  t4 = 0;
  normal();
  off();
}
void off()
{
  m1.detach();
  m2.detach();
  m3.detach();
  m4.detach();
  while (true);
}
void del(int tii)
{
  unsigned long tim = (unsigned long)(tii);
  unsigned long t = millis();
  while (millis() - t <= tim);
}
void getxyz()
{
  mpu.update();
  x = (double)(mpu.getAngleX());
  Serial.print("X:");
  Serial.println(x);
  y = (double)(mpu.getAngleY());
  Serial.print("Y:");
  Serial.println(y);
  //z = (double)(mpu.getAngleZ());
}

void debug()
{

  if (Slave.available())
  {
   c=(int)(Slave.read());
  }
   if(c<=180)
   {
    throttle=c;
   }
   if(c==200 || c==201)
   {
    of=c-200;
   }
}

I am also using two Arduino UNOs, hence the software serial...

what is your question? ... have you tried ignoring gyro data when the motors start up?

@jsotola I can't make the drone balance itself because the mpu6050 values are coming wrong when i am starting the motors... the gyro data at start should be 0.0 both x and y because they are on the ground but they are coming x:10 and y:-12 and not 0.0

that's why I said to ignore the the gyro when you are starting the motors .... try reading the gyro data after the motors started

@jsotola thnx will try and say


text:
I'm making a trim wheel using a rotary encoder for flight simulation. Should I have the Joystick library use button presses or make it an axis?
Title says the majority of it. I'm looking to make a trim wheel for flight sim using a rotary encoder, the Joystick library and an Arduino Leonardo. I wasn't sure if it would be better to make it a button press or have it be an axis, possibly the Rx, Ry, or Rz axis.
Thanks in advance!

are you not the one that knows what you want?

As you build that project, it is up to you to decide, wether you want to control trim via a joystick or button presses.

@jsotola I had an idea of what I thought would be best, but I wasn't sure if anyone thought differently. Thanks though!

@chrisl I had an idea of what I though would be best, but I wasn't sure if anyone thought differently. Thanks though!

what I thought would be best ... yes, it is your job to define what best means ... nobody else can tell you what is good for you ... and nobody else's opinion is relevant unless you ask a technical question


text:
Use HC05 and FTDI as Slave to Connect to control PC using HC05
Hi i just wanna ask if its possible to do this on HC05. So i can send some keyboard function?

and if yes can you tell me how. Thanks

"send some keyboard function?" - I guess you mean, that it should act as a keyboard on your PC. Thats not possible with an FTDI. It will only give you a Serial interface. But you could exchange the FTDI with an Arduino, that has a native USB interface, like the Micro (it can act as a HID device). Then you can program the micro to read data over Serial from the HC-05 and translate that to keyboard presses on the PC.

ok so i can do this with pro micro connecting to slave HC05?

Sure, if you program it to do this

Thanks. Now i have idea on what to do. Im noob sorry.


text:
RN42 Bluetooth HID KEYBOARD sketch by silverball
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.

I think you're going to have to be more specific.

You see when you  put on your code this sample keyboard.press(KEY_LEFT_ARROW) it actually does that key on keyboard. But you cant do that if you're using Bluetooth module (unless your using ESP32). Im using RN42 and i want to do the same function as keyboard.h does. Ive been searching for 2 weeks and i stumbled upon that sketch above saying that it is keyboard sketch for RN42. But i dont know how it actually put on my sketch like keyboard.h does.

are you saying that you want to use the RN42 as a USB keyboard?

no, what i'm saying is, I want it to act as keyboard. I know its RN42 cant act as USB Keyboard thats why im searching for BLE Keyboard sketch. And silverball says that this code can act as keyboard
https://stackoverflow.com/questions/16243602/arduino-rn-42-bluetooth-module-hid
He says in this question. But didnt say how to use it. Im begginer at arduino and Im connecting RN42 to my Arduino Pro Mini. I want the RN42 to send a data that read in computer like you press a keyboard.

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!


text:
Incorrect DateTime value constructed
I'm working on alarm clock project using Arduino Nano (v 3.0, clone) and RTC module ZS-042 (containing DS3231 and EEPROM AT24C32).
The intention is to load the hours and minutes from EEPROM on start-up, use current date (to avoid zero-date problems) and compose DateTime object in order to utilize the TimeSpan object, making time calculations easier than using plain integer math. The issue is, the value in DateTime object seems not constructed correctly, although all the components used for its construction seem OK.
With the following code
/* Hardware definitions */
//RTC using I2C, pins 4,5
#include <Wire.h>
#include <RTClib.h>
RTC_DS3231 rtc;

#include <extEEPROM.h>
extEEPROM e2p(kbits_32, 1, 32, 0x57);

DateTime  alarm1Time;

void setup(){
  Wire.begin();
  rtc.begin();
  Serial.begin(115200);
  uint8_t e2pStatus = e2p.begin(extEEPROM::twiClock400kHz);      //go fast!
  DateTime t = rtc.now(); //get current time from RTC
  Serial.print("t.year: ");  Serial.print(t.year());
  Serial.print(" t.month: ");  Serial.print(t.month());
  Serial.print(" t.day: ");  Serial.println(t.day());
  alarm1Time = (t.year(),t.month(),t.day(),e2p.read(1),e2p.read(2),0);
  Serial.print("E2P : ");
  Serial.print(e2p.read(1));
  Serial.print(":");
  Serial.println(e2p.read(2));
  char buf1[] = "YYMMDD-hh:mm:ss";
  Serial.println(alarm1Time.toString(buf1));
}

I get on the serial monitor the following:
t.year: 2021 t.month: 1 t.day: 31
E2P : 7:15
060206-06:28:16

The date components (year, month, date) correspond to current date. As the bytes on address 1 and 2 in EEPROM read 7 and 15, I'd expect the Alarm1Time be 2021-01-31, 07:15, which isn't.
The output is constant, whatever the current date and the EEPROM stored time. Later in my code the alarm1Time parses into 6 hours and 28 minutes, in accordance with last line of the serial monitor output.
What could be (or better - where I'm) wrong? Thanks.
Libraries used:
RTClib (https://github.com/adafruit/RTClib)
extEEPROM (https://github.com/JChristensen/extEEPROM/blob/master/extEEPROM.h)

Here:
alarm1Time = (t.year(),t.month(),t.day(),e2p.read(1),e2p.read(2),0);

you are repeatedly using the comma operator, which essentially means
“discard all the values but the last one”. If you want to invoke the
DateTime constructor that takes these arguments, you should call it
explicitly:
alarm1Time = DateTime(t.year(),t.month(),t.day(),e2p.read(1),e2p.read(2),0);

or, better yet, you can declare and initialize alarm1Time at the same
time:
DateTime alarm1Time(t.year(),t.month(),t.day(),e2p.read(1),e2p.read(2),0);

You are absolutely right I'm incorrectly using the constructor. Am I so stupid or so tired? Hmmm. Probably it's because I'm neebie to C++, after years of using other languages.
Regarding the declaration and initialization at once - I need to declare it global, not withing setup(), otherwise I'd do it as you suggest. Thanks.


text:
I2C_anything from Nick Gammon. Value of two senders to be received and printed by receiverslave
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

Please draw a schematic for us. It is not really clear to me, how the setup is and why. Also please show your code. Without these two, your description is really difficult to understand. Generally I would discourage the use of multi-master mode in I2C. I'm myself working on multi-master for ATtinys, and I have to say, that it can be a real mess. If you describe the context, maybe we can point you to a better alternative.

Please describe why you think you need multiple masters for one slave. As chrisl wrote, I2C multimaster typucally is not much fun and there might be simpler solutions (one master/ 2slaves, I2C combined with UART, etc.)

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


text:
Teensy4.1 with 2x 8MB PSRAM Chips: external_psram_size=0 but EXTMEM char[] works as expected?
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 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?

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.

You didn't declare your array volatile. Thus, the compiler can (and probably will) simply optimize the reading back away.
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.
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

Thanks for the input; it's odd EXTMEM only decides to crash at 16MB but that seems to be what's happening. You were right - I tried to actually read from a value assigned near the beginning of a 14MB EXTMEM array and got nothing. I read some stuff on the Teensy4.1 beta testing thread (Arduino forum I think) about a couple digital pins being used to detect the PSRAM chips... I'll have to look into that somehow, or hope someone has other ideas (I guess I may have fried one soldering - I'll desolder one and see if that helps). Thx again, never use C so didn't even consider volatile.

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.

It's amusing that ASE had me reviewing your "late answer". You know, to make sure that it was up to standards. Gee, I dunno... I guess it's alright. =)


text:
Whats wrong with my POST request?
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.

Have you noticed the one thing that differs between all the URLs that fail and the one that works?

so try again http.begin("https://httpbin.org/post"); with http.POST

@Majenko, ESP8266HTTPClient library supports https

@Juraj Yes. if you set it up right...

@Majenko its the https thats causing the problem? I tried following another guide (https://circuits4you.com/2019/02/08/esp8266-nodemcu-https-secured-post-request/) but still no luck, cant seem get past connect. Had no trouble doing this in postman, js and python.

I never used it, but now I see begin(url) is deprecated. Client object should be supplied. @Slurba, see the examples

@Juraj Thanks for the tip, using the nondeprecated functions i got error 400 from begin(WiFiClient &client, const String& url) and -1 again from begin(WiFiClient &client, const String& host, uint16_t port, const String& uri = "/", bool https = false). I dont see a function that helps me set the port or fingerprint (if thats needed) so im not sure which function is correct

see BasicHttpsClient example

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.


text:
Input from serial monitor to control stepper direction coding problem
I am attempting to create a simple code that will home the motor then wait for input for direction.  I have the homing function working, however the loop that reads the data from the serial monitor and returns it to the program is acting really buggy.  If I enter a 1 the stepper will rotate one turn in the CCW direction, hit the home mark then reverse and go CW.  If I enter a 0 the stepper will make one turn in the CW direction then repeat that move.  I added a bit of feedback so I could see what my direction variable is doing, it will hold a "1", make the move, rehome and show a "0".  I know the problem is in the loop, but for the life of me I can't seem to figure it out.  I am new to coding, so for the love of god, go easy on me!  I have added my full code so someone a little higher up in the coding world will see what I am doing.  This is just some code so I can try and learn a little something and make some strange stuff in the future.  Gotta start somewhere.  If this question is better asked on a different thread, please direct me to it.
    // Connections
#define HALL_SENSOR      3
#define DIR      10
#define STEP      11

void homefunction() {

  while (digitalRead(HALL_SENSOR) == 1) {

    digitalWrite(DIR, LOW);
    digitalWrite(STEP, HIGH);
    delayMicroseconds(4000);
    digitalWrite(STEP, LOW);
    delayMicroseconds(4000);
  }

}

void setup() {

  // Setup the stepper controller pins as Outputs
  pinMode(DIR, OUTPUT);
  pinMode(STEP, OUTPUT);

  // Setup the Hall Effect switch as an Input
  pinMode(HALL_SENSOR, INPUT_PULLUP);

  // Home the motor
  homefunction();

  // Sets up serial monitor
  Serial.begin(9600);

}

void loop()

  {int Direction; //Use to get the direction from the serial monitor
    Serial.println("What Direction would you like the motor to spin?"); //Input data
    while (Serial.available() == 0) //Wait for data
    Serial.read();
       Direction = Serial.parseInt();

 {
  // Read motor direction
  digitalWrite(DIR, Direction);
  Serial.println(Direction);

  // Spin motor
  for(int x = 0; x < 200; x++)
  {
    // while (Direction==0) //Added to hold value
    digitalWrite(STEP, HIGH);
    delayMicroseconds(4000);
    digitalWrite(STEP, LOW);
    delayMicroseconds(4000);
    //Serial.println(x);
  }}}

debug your code ... sprinkle Serial.println() statements throughout your code so that you can see what is executing when ... i think that you will discover quickly the source of your problem


text:
Arduino pull-up resistor not working
I made a circuit where when I press a button, a LED lights up using a pull-down resistor. But when I tried the same with a pull-up resistor instead, the LED remains off (whereas I expected it to be on by default and go off when I push the button). What is the problem?
Here is the circuit:

And here the code:
int BUTTON = 7;
int LED = 8;

void setup()
{
  pinMode(BUTTON, INPUT);
  pinMode(LED, OUTPUT);
}

void loop()
{
  digitalWrite(LED, digitalRead(BUTTON));
}

Is that LED the right way around? The cathode side or the more negative side is the one with the cut-off edge, and while it's really hard to see from those kinds of drawings, if looks like anode is drawn towards the ground there, so the wrong way around.

Try connecting the button to 5V, you have no signal transition. With a pull up the switch has to ground it. With a pull down the switch needs to drive it high.

@ilkkachu yes, I just displayed it incorrectly in the picture.

@Gil but the button is connected to 5V via the 10K resistor. As is shown in circuit diagrams online.

It is important where the other end of the resistor is connected.  If you want pull up connect it to Positive the switch to negative, if you want pulldown connect it to ground and the switch to positive.  Try this link it will help you understand: https://www.electronics-tutorials.ws/

@Gil but isn't that exactly what I did in the schematic? Resistor is connected to positive and the switch to negative. And the MCU between the resistor and the switch like in the circuit diagrams here.
Btw thanks for the link! Looks like a great resource.

The drawing looks good, except for the LED. The code looks also good. So, show us the picture of your real circuit on breadboard. There may be a chance that your breadboard's broken.


text:
Can I make an Arduino Uno Rev3 pretend to be a joystick?
I want to create a joystick for my flight simulator and I need to make an Arduino Uno Rev3 pretend to be a joystick when I plug it to my computer.

The Uno doesn't have native USB capabilities. It uses an additional microcontroller (the Atmega16u2) as an USB to Serial adapter. In the default configuration this microcontroller is only programmed for providing a serial interface over USB, not a joystick interface. You can hack your Uno and reprogram the Atmega16u2 for providing a joystick interface (and there are tutorials for how to reprogram the Atmega16u2 online). (Note, that you need a genuine Arduino for this to work, since the cheap clones often only have CH430 chips as USB to Serial adapter)
But I would suggest going the easier way and buying an Arduino board, which itself has USB capabilities without the need of hacking the board, like the Arduino Micro. Then you can simply use one of the joystick libraries on it. This way will be a lot easier for a beginner than doing it with an Uno.


text:
Select pin to connect RF receiver
I use the RCSwitch library receive signals with a RF receiver. I really need to change the pin the receiver is connected to on my Arduino Uno.
What should I change in my sketch?
What pins can I connect the receiver to?
This is my code:
#include <RCSwitch.h>

RCSwitch receiver = RCSwitch();

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

  receiver.enableReceive(0);
  pinMode(1, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

  Serial.println("READY");
}

void loop() {
  if (receiver.available()) {

    int value = receiver.getReceivedValue();

    Serial.println(value);

    switch(value) {
      case 1:
        digitalWrite(1, HIGH);
        digitalWrite(9, HIGH);
        digitalWrite(10, HIGH);
        break;
      case 2:
        digitalWrite(1, LOW);
        digitalWrite(9, HIGH);
        digitalWrite(10, HIGH);
        break;
      case 3:
        digitalWrite(1, HIGH);
        digitalWrite(9, LOW);
        digitalWrite(10, HIGH);
        break;
      case 4:
        digitalWrite(1, HIGH);
        digitalWrite(9, HIGH);
        digitalWrite(10, LOW);
        break;
    }
  }
}

IIRC it needs an interrupt-capable pin, so 2 & 3 on an Uno. Why do you need to switch pins?

You can change
receiver.enableReceive(0);

which uses pin 2, to
receiver.enableReceive(1);

which is pin 3 on the Uno. These are the numbers of the external interrupt. The Uno only has two of them, which are tied to those two pins. So as long as you are using the Arduino Uno, you need to use one of these. The Arduino Mega for example has more external interrupts.
For reference also look at the github page of the RCSwitch library and it's wiki, especially the site about receiving, where this is described.

Besides that: As you are using Serial, you might want to change
pinMode(1, OUTPUT);

to a different pin, since pins 0 and 1 are used for the Hardware Serial interface (Serial, which is connected to USB). So the usage of that pin collides with the serial communication.

Isn't there another way to use a pin like 9?

@manarinian It needs an interrupt-capable pin: https://github.com/sui77/rc-switch/blob/7925dfb753c78bf22f6b8164995cac76fdaa97e1/RCSwitch.cpp#L561


text:
Can I use the microchip of Arduino Uno as a standalone microcontroller
I want use the ATmega328P chip of the Arduino Uno board as a standalone device.

Is that possible?
Which pins are which on the Arduino board and the ATmega328P?
Do I need any external components?

Does this answer your question? How do I convert Arduino to an ATmega328P-based project?

Yes it's possible. To use the ATmega328P to "emulate" an Arduino Uno board (without the USB part) you just need 3 ou 4 additional components: the oscillator, two capacitors and a resistor. Please take a look at: https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoToBreadboard for a schematic/breadboard.
The Atmega328P features itself the memory, cpu and flash so those components are already inside the chip. You can find the relation of the pins in this image:

you might also consider running it at 8Mhz w/o an xtal if you want simplicity, but a nano or pro micro would be easier.

You can check the UNO's schematic. You can use this as a starting position. You can leave out the things you don't need. You might for example have no need for a voltage regulator on your board.
You may also have a look at the schematic of the Pro Mini, which are a lot more bare-bones.


text:
Multiple IR Sensors with Arduino
I am fairly new to working with sensors and Arduino. I am working on a project using Max MPS to control the volume of three audio files. There will be three framed photos, each having its own IR sensor and audio file. So when someone gets closer to the sensor, the volume of the corresponding file gets louder. Is this doable? The samples I have seen with the board I have and an IR sensor only use one. I'm assuming I'll be able to use the breadboard I have to add more sensors like I've done in the past with photocell sensors but I have yet to test it since it's in the mail. Just hoping to get ahead of any issues I may face and see if I should order any other equipment.
I ordered 3 of these IR sensors and this is the Arduino kit I am working with.
Sorry if I may not be describing it in enough detail, but thanks in advance!

Yes, doable. Though the range will depend on the sensors. Do you have any other question, that is not just a yes-no question?

technically yes, there is no reason you can't do that project but the issues will come in how complex you wish to make system. For example, it shouldn't be too hard to hook up the three sensors to three analogue Pins on the Arduino and then have the Arduino constantly loop to check the voltage of the sensors, from which, you would tell it to 'do something' when one of the IR sensors voltage is above or below a certain value. What you then choose to do is up to you, if it's just to turn on a light then it can be done fairly quickly once you have all the components. For controlling the Audio in the file, I personally have no experience with this.
What might be better is first checking to see if you can Adjust the audio in one of your files using an Arduino (you may need to use bluetooth or have something on your PC communicate with your Arduino via UART through the USB).
Generally, with new projects, it's a good idea to figure out a solid plan for exactly what you want to do, so I would write down in detail what you want the system to do and then go through each part to see if it's possible


text:
Auto Fish Feeder
Good day, I am new to Arduino, but have made some nice projects work.
I have a n issue with a Auto fish feeder. I have used a servo that I modified to run 360. I am having a issue when the Nano board starts. It runs the time I have set between feeds, and then it stops. If I set it to feed every 10 sec, it starts up and run for 10sec and then the LED flashes and it stops. From there it works perfect. But if I lose power and it comes back, its going to feed for 10sec and that will kill the fish.
Here is my sketch I am using now, please can someone look at it and tell me where I am going wrong. I just want it not to run when it starts up, or just for the to that it feeds, not continues like now for 10sec, or 12 hours !!!
//--Setting Vars

   //Fish Feeder Vars.
int pinOutMotor = 3;
int pinOutLed = 5;
int pinInButton = 2;
int MotorRunDuration = 1000;
float AutoWaitDurationHours = 0.;
//--Program Vars
unsigned long currentMsSinceStart = 0;
unsigned long msValueAtLastRun = 0;
float HoursSinceLastRun = 0;
int buttonValue = 0;

void setup() {
  Serial.begin(9600);             //Turns on serial monitor.
  pinMode(pinOutMotor, OUTPUT);   //Is controlled by a 3906 npn transistor to switch the motor off and on.  When program started I need to add a line to turn off motor when program was started.
  pinMode(pinInButton, INPUT);    //Manual feed.
  pinMode(pinOutLed, OUTPUT);     //Shows motor is on when lite.
}

void loop() {
  //HoursSinceLastRun = AutoWaitDurationHours - 0.05; //this will make it run 3 minutes after turned on.

//Fish Feeder
  //get miliseconds since program start and calc.
  currentMsSinceStart = millis();
  HoursSinceLastRun = (currentMsSinceStart - msValueAtLastRun) / 10000; //10000 millis= 10 seconds.  To change the time to vary feeding times set for 12hrs type in 43200000 or 6hrs tyoe in 21600000.
  //check for button press
  buttonValue = digitalRead(pinInButton);
  if(buttonValue == HIGH){  //had to change state because of button from LOW to HIGH.
    //run motor for button press.
    RunMotor();
    Serial.println("Feed Fish Manually");  //serial print funtion completed by button

  } else if(HoursSinceLastRun > AutoWaitDurationHours){
    RunMotor();
    msValueAtLastRun = currentMsSinceStart;
    Serial.println("Feed Fish Auto");      //serial print funtion completed by auto wait duration hours
  }
  //slow the loop down so it isn't running at full CPU Utilization for nothing.
  delay(50); //delay 1/20th of a second.
}

void RunMotor(){
    analogWrite(pinOutMotor, 0);   // turn on motor
    analogWrite(pinOutLed, 80);        // turn on green led to show motor is on.
    delay(MotorRunDuration);   // wait for motor run duration to expire
    analogWrite(pinOutMotor, 255);    // turn off motor
    analogWrite(pinOutLed, 0);        // turn off green led to show motor is off.
}

I do not know what's wrong, as I copy and past from my sketch and mine is compiling 100%

I am using Arduino 1.8.5, if that helps

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/