text:
Low Power, SD Card module and SCK
in order to minimise power consumption in a project using the Arduino Nano, I need to set pin D13 to HIGH after using it as SCK for transferring data to an SD card module (I use the SD.h module. I already read that there are issues, but trying SdFat.h somehow made the issue worse). The board is powered by 4*1.3 V batteries, which is within specifications of the chip. The onboard voltage regulator, the power LED and the built-in LED (connected to D13) are torn off the board.
So I power up the module via a MOSFET switch circuit, start the communication with SD.begin(SDChipSelect) and write something to the SD card. All of this works just fine. Afterwards, I call pinMode(SDCLK,OUTPUT); digitalWrite(SDCLK,HIGH); (where SDCLK == 13) before powering off the whole module by closing the MOSFET switch and going to deep sleep forever.
The switch setup (using an n-channel MOSFET) is such that the SD module's VCC is always HIGH, but no current can flow to ground, if the switch is off. Hence I need to turn D13 HIGH, not LOW, in order to turn off the module completely. Changing MISO, MOSI pins didn't affect anything, so I don't change them.
But... instead of drawing something like 0.1 mA without anything attached, the Arduino draws around 1 mA, which I can't afford. Apparently, the reason is that D13 doesn't care that I want it to go to HIGH. I can confirm this directly by measuring its voltage as well as by measuring the current drop if I pull off the connection between the SD module's SCK and the D13 pin on the Arduino. If I pull off the wires connecting MISO, MOSI or even the MOSFET itself, power consumption doesn't change.
That being said, power consumption is low, if I never write to the card (i.e. if I turn D13 high at in the setup, never power on anything, do not initialise the module via SD.begin(...), but go to deep sleep immediately).
What am I doing wrong? Do I somehow need to "end" the communication with the SD module, so I can turn D13 high or is there something special going on with this particular pin?
Here are the relevant parts of my code:
#include <LowPower.h>
#include <SD.h>

static const int GPSPower = 5;
static const int MP3Power = 2;
static const int SDPower  = 8;
static const int SDCLK    = 13;

void blink(int n) {
  for (int i=0; i<n; i++) {
    digitalWrite(9,HIGH);
    delay(50);
    digitalWrite(9,LOW);
    delay(200);
  }
  return;
}

void setup() {
  // this pin is used in 'blink' to power an LED for debugging
  pinMode(9,OUTPUT); digitalWrite(9,LOW);
  // Set all pins connected to MOSFET gates as low outputs.
  pinMode(MP3Power,OUTPUT); digitalWrite(MP3Power,LOW);
  pinMode(GPSPower,OUTPUT); digitalWrite(GPSPower,LOW);
  pinMode(SDPower,OUTPUT);  digitalWrite(SDPower,LOW);
  // this is D13
  pinMode(SDCLK,OUTPUT); digitalWrite(SDCLK,HIGH);

  // if false, power consumption stays at ~0.1 mA
  // if true, two strings are written and power consumption stays ~1.0 mA
  if (false) {
    String filename = "test.txt";
    write2sd("firststring",filename);
    write2sd("anotherstring",filename);
    blink(3); // feedback for debugging
  }

  // never go into loop
  while (true) {
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  }
}

void loop() {
}

int write2sd(String data, String filename) {
  // power SD module
  digitalWrite(SDPower,HIGH);

  // check availability
  if (!SD.begin(SDChipSelect)) {
    // return early but power off the module first
    pinMode(SDCLK,OUTPUT); digitalWrite(SDCLK,HIGH);
    digitalWrite(SDPower,LOW);
    blink(10); // indicates an error
    return 1;
  }
  // SD Card should be initialised now
  File file = SD.open(filename, FILE_WRITE);

  // write to file
  if (file) {
    file.println(data);
    file.close();
  }

  // CLK still runs at this point and causes power consumption of ~1mA
  // power it off
  pinMode(SDCLK,OUTPUT); digitalWrite(SDCLK,HIGH);

  // turn off module power
  digitalWrite(SDPower,LOW);
  return 0;
}

You can't change the SPI pins, as long as SPI is enabled. In other words; digitalWrite(SDCLK,HIGH);   doesn't do anything.

Well I guess that explains it. Is it possible to disable SPI every time after writing?

Check out this article: https://thecavepearlproject.org/2017/05/21/switching-off-sd-cards-for-low-power-data-logging/

@Gerben, do you want to write a proper answer, which I can accept? Calling SPI.end() at the end of the routine before setting CLK, MISO and MOSI to HIGH afterwards actually works and my power consumption is down to 0.1 mA again :)


text:
Why is my SPI clock voltage lower at higher frequencies?
I measured that the SPI-Clock of my Arduino Nano in my project didn't reach near 5V. So I quickly tested with a new one, nothing attached except a (mydaq) scope.
I measured the SPI clock:
2.5 V @ 8 Mhz;
3.6 V @ 4 Mhz;
5 V @ 1 Mhz.
I think the graph looks like that because the low max sample of the mydaq, so I dont worry to much about that. The MISO could reach about 5V but why is the clock voltage lower at higher frequencies? And how to reach 5V?

#include <SPI.h>

void setup() {
  SPI.begin();
  SPI.beginTransaction(SPISettings(8000000, MSBFIRST, SPI_MODE0));
}

void loop() {
  SPI.transfer(1);
}

I also tried SPI mode 2 or 3 @8Mhz, idle state was 4,7 V but Vp-p again only 1,9 V.

It's not a lower voltage. You're just trying to measure it with something that is not capable of measuring it. To read a signal of 4MHz you need minimum 8Msps. For 8MHz you need minimum 16Msps. You cannot get the voltage with just a fraction of the samples you need to recover the waveform. Plus there will be a certain amount of low pass filtering happening massively reducing the frequencies this "mydaq" thing can read.

@Majenko I wondered why I can reach 5V at MOSI then? but now I transfered binary 1010 1010 @ 8Mhz and the MOSI line reading also "dropped". Thank you, that made a lot of sense actually :) Time for upgrade

You can use a peak detector to get an idea of the maximum voltage, and another one for the minimum, if you don't have a high enough sampling rate.

This is the second time the Nyquist frequency has come up in the last couple of days.
In order to accurately measure a changing signal, like you are doing, you need to sample at, at least, twice the frequency of the signal. If you don't your samples may give incorrect results because you are sampling partway up or down the curve.
To measure an 8 MHz signal, you therefore need to sample at 16 MHz, which you don't appear to be doing.

According to the MyDAQ specifications the analogue input has a pass-band filter of "DC to 400kHz". That means that at 400kHz the signal will be reduced by -3dB, and anything above that will be reduced even further, and the higher the frequency the more it will be reduced.
Further to that the MyDAQ samples at up to 200ksps, which means it can only capture a maximum frequency component of 100kHz.
The MyDAQ is little more than an educational toy. It's just a glorified sound card and really not worth wasting your time with.

source: Stack Exchange

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

sort: votes


text:
an lcd with I2C is not recognized by esp32
I have a NodeMCU esp32-s board and I'm trying to connect My 16x2 lcd with PCF8574T I2C bus to the esp32 , the problem is that the lcd doesn't show anything and the WireScan sketch can't recognize the lcd too,but when I use arduion uno ,it's recognized and work perfectly ,I hope somebody can help me,the schematic for the connection is :

the schematic for the connection of the lcd with the bus is below with the bus module part number :

please add a clear, answerable question to your post

What things need to be cleared?

you need to make it clear how the LCD is connected and, most importantly, which LCD you are using ... right now, all we know which pins are connected at the ESP32 ... we know nothing else ... also, you have not asked a question about the problem

well,if you return back to my question you see I have mentioned the type and part number and this is exactly the problem, I can't provide more.

the PCF8574T is an IC that is part of the LCD ... it is an I2C bus expander ... which component is used in the display module has no bearing on the connector pinout of the LCD module

ok , thanks , I have just edited the question , please let me know if it is clear now or not.

Can you verify 5 VDC and ground are present at the I2C, LCD backpack? How are you powering the ESP32?

yes they exist and they are named as VDD and VSS , also the two parts are soldered together and the lcd is lighting when using esp32.

Do the ESP32 GIOPs operate at 3.3 VDC? You may need a logic level converter of some type on the I2C lines. For example: https://www.aliexpress.com/item/1005003157047080.html?spm=a2g0o.productlist.main.1.74f168cfuMUXE9&algo_pvid=581ce205-0f3f-42bc-8d30-a719047333f2&algo_exp_id=581ce205-0f3f-42bc-8d30-a719047333f2-0&pdp_ext_f=%7B%22sku_id%22%3A%2212000024404763535%22%7D&pdp_npi=3%40dis%21CAD%212.39%212.16%21%21%21%21%21%40211bc2a016760709924762576d06d7%2112000024404763535%21sea%21CA%21915735244&curPageLogUid=y2eJwfSkV6yg

I'm using the 5v pin to power the I2C module , but SDA and SCL pins are powered with GPIO pins which I think they are providing 3.3v.

You can run the PCF8574 on 5V and the EXP on 3V3 just be sure the I2C is pulled up to the 3V3 and NOT the 5V. I do this a lot and have never had a problem. The reason it works is the bus is driven by open collector/drain drivers which do not source any voltage.

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


text:
Triggering a picture with esp32-cam and GPIO13
I'm trying to trigger a picture using the GPIO13 of an esp32-cam, AI Thinker model.
I'm using that example as a base:
https://randomnerdtutorials.com/esp32-cam-pir-motion-detector-photo-capture/
but instead of the PIR/Transistor combination, I'm using a press button with a pull-up resistor that pulls the GPIO13 pin down when pressed, simulating the PIR signal.
I'm feeding the esp-32 cam with a 5V power supply and the button circuit with the 3.3v
pin of the esp32, all grounded.
All hardware, SD card and so on is tested ok, I got the right voltages and I can see the GPIO13 Pin going to ground on my scope, but I just doesn't work.
Any ideas?
Edit 1: I'm using the ESP32-CAM-MB USB Board

What is it printing on the serial output?

I cannot watch the serial port while running this, as the board doesn't have a USB port.

@brunobhr Then use your programmer board to see the serial output. The same that you're using for flashing the chip.

You cannot run the board in flashing configuration.

I don't seem to have any problem running an ESP32-CAM while looking at its serial connection. I don't understand why you are. However, you can at least make a function that blinks an LED call that from places where error messages are also printed. You can add to the question what you find out.

If you're using the ESP32-CAM-MB: The -MB has an usual requirement with respect to control signals. It will not show you sketch serial output in just any terminal software. If you use the latest IDE and select the correct board it will set the control signals as necessary will show sketch output, including your diagnostic messages.

@timemage Thank you. Unfortunately my -MB model makes it impossible to hook up external circuits when plugged in. I'll have to desolder it and re-solder longer pins, or find a way to read the serial monitor on an LCD

I don't understand, but then I can't see your wiring either. If more information shows up in the question, e..g if you post wiring and/or take the LED blinking suggestion, maybe there will be some way of helping.

Checking the specs of the cam board, I see that GPIO13 has the function HS2_DATA3, suggesting that the SD card is using that pin (which is also corroborated by this article.)
This may or may not be a problem, as the state of GPIO13 is only relevant for sleep/wakeup when the chip is sleeping, and only relevant for SD card access when the chip is running; but there is an external addon: your pullup resistor on the button is still there when the chip is running. The PIR module from the tutorial that you're trying to replace probably has an open collector output (floating when inactive, pulled LOW when active).
My best hunch is to get rid of the pullup resistor on your button, so that the pin is floating during SD card access.
There still is the possibility that you then interfere with the SD card data when you keep the button pressed. If that is the case, you may need to put a resistor in series with the button, so that the wake-up signal is weaker than the SD card data signal (start at 100KOhm and reduce until wake-up works).
If that isn't it, the question is lacking details. As you did not even post a description of what exactly "just does not work", first thing would be to produce a minimal sketch just to test sleep/wakeup via GPIO13 and post that here.

Thank you, but how does the code provided in the link deals with that? I'm just replacing a signal by another..

Also, getting rid of the pullup resistor and adding any value in series doesn't change anything.

And doesn't work means it's not acting as intended eg. no picture on the SD Card.

The code in the example link is doing wakeup through GPIO13

@brunobhr Yes, you're replacing one signal with another, but we don't know what type of signal you're replacing. The PIR from the tutorial probably provides a weak open collector output to ground, but your button originally is a strong push-pull output.

@brunobhr You'll need to tell what exactly is "not working". An image on the SD card is the desired end result, but there are a lot of steps to check beforehand: Can you flash the cam board successfully? Which output on the serial line comes up after flashing? Does the chip go to sleep successfully? Does it wake up successfully? If no, can you make it wake up by other means (e.g. taking a wire to pull GPIO13 to 3.3V or GND)? What is printed on the Serial output after waking up? Are there any status LEDs on the board, and if yes, when are they lit up?

Sorry but have you read the link I provided?

Yes, I have read the link, but those tutorials never go into the details you need if you're altering the setup in the slightest.

I'm just trying to get a pin to ground, this example works according to the comments. Now asking me if I can flash my board is not gonna get us somewhere I think. Thank you anyway


text:
Novice learning Serial.readString()
New to Arduino, getting into String variables and reading them from serial monitor.
Basically what I'm trying to do is have the user input either red, green, yellow. Whichever String they enter the LED comes on.
What is happening seems to be that the if statements are not true and are never entered thus not LEDs come on. I do have a serial.Println(myColor) at the end which displays myColor as the user has inputted into serial monitor. I just don't understand why the if statements are not firing. its really weird.
String msg="What LED do you want to turn on?";
String myColor;
int redPin = 12;
int greenPin = 13;
int yellowPin = 8;

void setup(){
Serial.begin(9600);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
}

void loop(){
    //LED ColorDEmo

    Serial.println(msg);                //print the question to serial monitor
    while(Serial.available() == 0){     //while we wait do nothing till data is available

    }
    myColor = Serial.readString();      // set myColor to serial value

    if (myColor == "red"){              // if the value is red
        Serial.println("In red");
        turnOffLEDS();                  // turn off all LEDS
        digitalWrite(redPin, HIGH);     // turn on red lED
    }

    if (myColor == "green"){            // if the value is green
        Serial.println("In green");
        turnOffLEDS();                  // turn off all LEDS
        digitalWrite(greenPin, HIGH);   // turn on green LED
    }

    if (myColor == "yellow"){           // if the value is yellow
        Serial.println("In yellow");
        turnOffLEDS();                  // turn off all LEDS
        digitalWrite(yellowPin, HIGH);  // turn on yellow LED
    }
    Serial.println(myColor);            // print myColor

}

// turns all LEDS off
void turnOffLEDS(){
    digitalWrite(yellowPin, LOW);
    digitalWrite(greenPin, LOW);
    digitalWrite(redPin, LOW);
}

debug your code by printing data to the serial console ... print the received message and print the length of the message

myColor = Serial.readString();
Serial.println(myColor.length());
Serial.println(myColor)
results
4
red
So it seems it is attaching an additional character tot he end of the String variable. SHould i be using readStringUntil() instead

Just a little side-point: It is a good to get used to using char arrays rather then strings. I know the current way arduino moves is to keep users on lover level, (buing more shields) but once you get to more advanced tasks and have to deal with memory footprint, then habit of using char array makes your life easier latter.

Thanks @Tomas, that's a really good point. String variables are memory hogs from what I've heard from others as well.

Also, what is the program to do if the user enters "RED" instead of "red", "RE" only, "R" only, etc.  That is why single character responses are generally better and less error-prone.

Avoiding String objects (back to the basics) often makes life easier.
Simply check if the answer contains one of the characters 'd' 'g' 'y'
Or (and) simplify your protocol to only send one character.
BTW:You might notice a delay in readString, waiting for a multi-character input to finish, because Serial.available() is true already after the first character of an input, and readString terminates only if it times out

thats a good idea, simplify into single characters.

thank you @jsotola
throught he debugging you mentioned i was able to learn that the '\n' was added to the end of the string. Instead of using
Serial.readString() I used Serial.readStringUntil('\n');
this would check for a delimiter character '\n' then stop. Thus, my myColor variable would be red instead of red'\n'


text:
Connect Arduino + ESP8266 to Azure IoT Hub Device via X509 certificate
I would like to connect ESP8266 with Azure IoT Hub Device via X509 certificate. Currently, I can connect using the symmetric key connection to my device, but I have devices that I want to authenticate with X509 certificate.
I found a solution, but is for Arduino Nano 33 IoT, which is probably using another chip and it has encryption slot.
I am trying to do this using the Azure IoT SDK C library, but without much success. Here is a code that is using Mqtt and WiFiClientSecure plus BearSSL in order to connect via certificate. Unfortunately, the only solution that I found was to generate ECCX09 certificate with a chip that have encryption and to just use the thumbprint. Here is my try to use the certificate:
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT

// C99 libraries
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include <cstdlib>

// Libraries for MQTT client, WiFi connection and SAS-token generation.
#include <ESP8266WiFi.h>
#include <ArduinoBearSSL.h>
#include <ArduinoMqttClient.h>

// Additional sample headers
#include "secrets.h"

// Utility macros and defines
#define LED_PIN 2

// Translate iot_configs.h defines into variables used by the sample
static const char* ssid = SECRET_WIFI_SSID;
static const char* password = SECRET_WIFI_PASS;
static const char* host = SECRET_BROKER;
static const String device_id = SECRET_DEVICE_ID;

// Memory allocated for the sample's variables and structures.
static WiFiClientSecure wifi_client;
static BearSSLClient ssl_client(wifi_client);
static MqttClient mqtt_client(ssl_client);

// Auxiliary functions
static void connectToWiFi()
{
  Serial.begin(115200);
  Serial.println();
  Serial.print("Connecting to WIFI SSID ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.print("WiFi connected, IP address: ");
  Serial.println(WiFi.localIP());
}

/*
 * Establishses connection with the MQTT Broker (IoT Hub)
 * Some errors you may receive:
 * -- (-.2) Either a connectivity error or an error in the url of the broker
 * -- (-.5) Check credentials - has the SAS Token expired? Do you have the right connection string copied into arduino_secrets?
 */
void connectToMQTT() {
  Serial.print("Attempting to MQTT broker: ");
  Serial.print(host);
  Serial.println(" ");

  while (!mqtt_client.connect(host, 8883)) {
  // failed, retry
    Serial.print(".");
    Serial.println(mqtt_client.connectError());
    delay(5000);
  }
  Serial.println();

  Serial.println("You're connected to the MQTT broker");
  Serial.println();

  // subscribe to a topic
  mqtt_client.subscribe("devices/" + device_id + "/messages/devicebound/#");
}

unsigned long getTime() {
  // get the current time from the WiFi module
  // return WiFi.getTime();
  return time(NULL);
}

static void establishConnection()
{
  // Set the username to "<broker>/<device id>/?api-version=2018-06-30"
  String username;

  // Set the client id used for MQTT as the device id
  mqtt_client.setId(device_id);

  username += host;
  username += "/";
  username += device_id;
  username += "/api-version=2018-06-30";
  mqtt_client.setUsernamePassword(username, "");

  if(WiFi.status() != WL_CONNECTED) {
    connectToWiFi();
  }

  if (!mqtt_client.connected()) {
    // MQTT client is disconnected, connect
    connectToMQTT();
  }
}

// Arduino setup and loop main functions.

void setup()
{
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);

  Serial.begin(9600);

  // Set the X.509 certificate
  // ssl_client.setEccCert(CLIENT_CERT);
  ssl_client.setEccSlot(0, CLIENT_CERT);

  // Set a callback to get the current time
  // used to validate the servers certificate
  ArduinoBearSSL.onGetTime(getTime);

  establishConnection();
}

void loop() {}

This fails on setting the Certificate and to use the ecc slot 0, because I am using ESP8266 that does not have cryptography in it (or at least I do not know). I saw in the library that there is another method in the BearSSL - void setEccCert(br_x509_certificate cert); , but I do not know how to initialize br_x509_certificate (here is the ref).
I decided to try something else, too, reading the certificate with SPIFFS, then adding to WiFiClientSecure. Unfortunately, I cannot load the private key to make client connection.
#include "FS.h"             // File system commands to access files stored on flash memory
#include <ESP8266WiFi.h>    // WiFi Client to connect to the internet
#include <PubSubClient.h>   // MQTT Client to connect to AWS IoT Core
#include <NTPClient.h>      // Network Time Protocol Client, used to validate certificates
#include <WiFiUdp.h>        // UDP to communicate with the NTP server
#include "secrets.h"

// Utility macros and defines
#define NTP_SERVERS "pool.ntp.org", "time.nist.gov"

// Translate secrets.h defines into variables used by the sample
static const char* ssid = SECRET_WIFI_SSID;
static const char* password = SECRET_WIFI_PASS;
static const char* iot_hub_broker = SECRET_BROKER;

// callback function that will be called when the device receive a message
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

// Memory allocated client variables
static WiFiUDP ntp_UDP;
static NTPClient time_client(ntp_UDP, "pool.ntp.org");
static WiFiClientSecure esp_client;
static PubSubClient mqtt_client(iot_hub_broker, 8883, callback, esp_client);

// Auxiliary functions
static void configureX509CertificateConnection() {
  time_client.begin();
  while(!time_client.update()) {
    time_client.forceUpdate();
  }

  esp_client.setX509Time(time_client.getEpochTime());
  Serial.println("Time client and ESP client are set up.");

  // Attempt to mount the file system
  if (!SPIFFS.begin()) {
    Serial.println("Failed to mount file system");
    return;
  }

  // Load certificate file from file system
  File cert = SPIFFS.open("temperature-sensor-1-all.pem", "r");
  if (!cert) {
    Serial.println("Failed to open certificate from file system");
  } else {
    Serial.println("Successfully opened certificate file");
  }

  // Load private key file from file system
  File private_key = SPIFFS.open("/temperature-sensor-1-private.pem", "r");
  if (!private_key) {
    Serial.println("Failed to open private key from file system");
  }
  else {
    Serial.println("Successfully opened private key file");
  }

  delay(1000);

  // Load private key to client connection
  if (esp_client.loadPrivateKey(private_key)) {
    Serial.println("Private key loaded to client connection");
  }
  else {
    Serial.println("Private key not loaded to client connection");
  }
}

static void connectToWiFi() {
  Serial.begin(115200);
  Serial.println();
  Serial.print("Connecting to WiFi: ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.print("WiFi connected, IP address: ");
  Serial.println(WiFi.localIP());
}

/*
 * Establishses connection with the MQTT Broker (IoT Hub)
 * Some errors you may receive:
 * -- (-.2) Either a connectivity error or an error in the url of the broker
 * -- (-.5) Check credentials - has the SAS Token expired? Do you have the right connection string copied into arduino_secrets?
 */
void connectToMQTT() {
}

static void establishConnection() {
  if (WiFi.status() != WL_CONNECTED) {
    connectToWiFi();
  }

  configureX509CertificateConnection();
}

// Arduino setup and loop main functions.
void setup() {
  pinMode(2, OUTPUT);
  digitalWrite(2, HIGH);
  Serial.begin(115200);

  establishConnection();
}

void loop() {}

P.S. I have it up and running on Raspberry Pi, but I have to make some experiments using the Arduino and ESP8266.
P.S.2. I am using Arduino with Atmega328P with integrated ESP8266 chip, but working only with the ESP8266. Additionally, I am using Arduino IDE 1.8.19 and installed the Azure IoT SDK C library (and some other required ones).
P.S.3. Additionally, I could find X509 certificate sample, but it is using the Paho Mqtt Client and I am not able reproduce it on Arduino.


text:
IF statement to run even if the requirement isn't met anymore
I have built a flasher for the headlamps on my race car. Whilst it works when I hold the switch down, if I release the switch and the circuit is closed my IF statements requirements are no longer met and it stops flashing.
Is there a way to have it continue to run the IF statement (but only once) even after I've let go of the switch and the requirement is no longer met?
Thanks in advance.
CODE:
#define trig A3

const int flash = 3; //D3
const float mVc = 4.67; //reference voltage
float counts = 0;
float mV = 0;

void setup() {
  Serial.begin(115200);
  pinMode(flash, OUTPUT);
}

void loop() {
  counts = analogRead(trig);
  //counts = 255;
  Serial.println(String(counts));

  mV = (counts*mVc) / 1000;
  Serial.println("Input Voltage: " + String(mV) + "v");

  //delay(1000);

// voltage will need to be changed to matched output voltage when on car
  if (counts > 10) {
    analogWrite(flash, 100);
    delay(300);
    analogWrite(flash, 0);
    delay(80);
    analogWrite(flash, 100);
    delay(300);
    analogWrite(flash, 0);
    delay(80);
    analogWrite(flash, 100);
    delay(300);
    analogWrite(flash, 0);
    delay(80);
    analogWrite(flash, 100);
    delay(300);
    analogWrite(flash, 0);
    delay(80);
    analogWrite(flash, 100);
    delay(300);
    analogWrite(flash, 0);
    delay(1000);
  }
}

EDIT:
TL;DR Don't use voltage dividers to power the Nano.
When using a voltage divider to power the Nano (I know, I know) the below solution didn't fix the issue. I thought it may be due to the voltage dropping when the Nano supplies the 5vo to the mosfet but I'm not sure why holding the switch would stop that from happening. Regardless I swapped to a linear voltage regulator and then it started to flash, "Hurrah!" -- almost.
With the regulator in it was running the code constantly. I decided to print the runcount and I got a number over 35,000, meaning it would run the flash 5 times for >35,000 times. Although curious as to what would happen when it reached zero, I decided to go back to my original code and...now it works.
So I guess the lesson is: Even if you can calculate the drop off, don't run your Nano on a voltage divider.

I have checked the answer below as the solution, although it didn't fix my issue there is no reason it shouldn't have worked and it may be useful to someone else.

why are you using analog I/O?

You could define an int runcount = 0 variable at the top. Then change your loop logic to something like
if (counts > 10) {
  runcount = 2;
}

if (runcount-- > 0) {
  //flashy flashy
}

The effect is, that while button is pressed and counts > 10, runcount is set to two. Every time we check the runcount, it is decreased by 1. While the button is pressed, runcount is resat to 2. If you let go of the button, runcount will be 1 at the start of the if condition check. It will be compared to 0, condition will be true, and it will then be decreased to 0 and the if section will be executed one last time. Using another number than 2 will change the number of extra runs.

Thank you, I will give this a go tomorrow and then all that is left is the "easy" bit of fitting it to the car. :)


text:
Can someone help me figure out why my menu gets stuck?
When I try to run my code so far with the menu and select buttons, it seems that it works, except that the main menu will not move past "Main Garden" to "Currants". There's also a problem with the submenu where after the first watering warning, pressing the select button makes it simply return to the main menu without lighting the LED on the LEDPower pin or running that watering routing for the whole watering interval.
The one guess I still haven't tried is that maybe I should change void MainMenu() to a Switch Case structure instead of If-Else?
.
edit:
.

Problem One (Menu not moving past Main Garden to Currants):
MainOld is used to increment MenuState but MainOld never gets incremented, which means it will never have a value greater than 0. Accordingly MenuState can
never be greater than 0 + 1.
Problem Two (Sub Menu looping back to main):
'Checking' the state of LEDPower like in Water1() is not the best way to accomplish what you want to accomplish. It may work but is not technically correct as LEDPower is a pin state and you never actually read the state.
The other issue in Water1 is that previousWaterMillis doesn't get updated anywhere in your code, which means that anytime Water1 is called more than 10 seconds after boot your solenoid will activate and then immediately deactivate. I would recommend a while loop inside your Water1 function. ex.
void Water1(){
  digitalWrite(Relay1, HIGH);
  unsigned long currentMillis = millis();
  previousWaterMillis = millis();
  int LEDPowerState = digitalRead(LEDPower);

  while(currentMillis - previousWaterMillis <= WateringInterval){
    digitalWrite(LEDPower, HIGH);
    Serial.println("Watering Garden with LED Lit");
    currentMillis = millis();
  }

  digitalWrite(Relay1, LOW);
  digitalWrite(LEDPower, LOW);
  SubMenuState = 0;
  SubMenuOld = 0;
}

^^ This will illuminate your LED and activate the solenoid for the 10 secs you wish to water.

Thank you so much!! I added
 MainOld = MenuState;

to menubuttoncheck() to make MainOld increase with the presses, did void Water1 as you said, and it works!


text:
Which key is KEY_LEFT_GUI?
This might be a very simple question but I don't know which key represents KEY_LEFT_GUI on my keyboard. I thought it was the windows key but when I program Arduino Micro to execute it. Run does not open and it prints powershell on the "Search Programs and Files" section in Windows7 VM.
  Keyboard.press(KEY_LEFT_GUI);
  delay(1000);
  Keyboard.press('r');
  delay(1000);
  Keyboard.releaseAll();

  delay(500);

  Keyboard.print("powershell");
  typeKey(KEY_RETURN);

KEY_LEFT_GUI is the left Windows key. I think the problem may be that your code is only holding those keys down for microseconds. You need to give the computer a little bit of time to recognize the keypresses because it's expecting a human using a keyboard, not a microcontroller running at 16MHz. Try adding a delay before Keyboard.releaseAll();.

it's still just opening the start menu and typing it there instead of opening run I added a 1000 delay before releaseAll and a 1000 delay above press('r') but it is only detecting the windows press not the r

I guess I just didn't know how fast a millisecond really is. I changed the delay to 4000 and it's working now.

I know it's a late answer, but you can use to open the run window:
Keyboard.press(KEY_LEFT_GUI);
  Keyboard.press(114);
  Keyboard.releaseAll();
And yes, as per1234 says, KEY_LEFT_GUI is the left windows key

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


text:
How to move my robot in the right direction?
After all there is more question poping up then answers i decide to upload the pdf where is everything writen, like the wire, motor type and what we can and can't use. Here is the link pdf format of the assignment
So i am working on a project for the school, it is first time for me to work with Microcontrollers. I and i got stuck with the rest of my assignment, so i hope a good soul can help me out with this.
So my code for now is this
#include <stdio.h>
#include "dev/uart.h"
#include <util/delay.h>
#include <avr/io.h>
#include "dev/adc.h"

#define LED_RED     (1 << PE5)
#define LED_YELLOW  (1 << PE3)
#define BUTTON      (1 << PF2)
#define SENSOR      (1 << PF3)
#define PUSH        (PINF & (BUTTON))
#define TILT        (!(PINF & (SENSOR)))

#define JOYSTICK_X  (1 << PF0)
#define JOYSTICK_Y  (1 << PF1)

typedef struct
{
    uint16_t x;
    uint16_t y;
} inputVector;

typedef struct
{
    int16_t x;
    int16_t y;
} convertedVector;

void joystick_init()
{
    adc_init(0x03);
}

convertedVector joystick_status()
{
    inputVector newVector;
    convertedVector vector;
    newVector.x = adc_get(0);
    newVector.y = adc_get(1);

    inputVector max;
    max.x = 896;
    max.y = 902;

    inputVector min;
    min.x = 8;
    min.y = 9;

    vector.x = 0;
    vector.y = 0;

    if(newVector.x >= 498 && newVector.x <= 518)
    {
        vector.x = 0;
    }
    else if(newVector.x < 498)
    {
        vector.x = ((newVector.x * 100) / 901) - 100;
    }
    else
    {
        int16_t half = 896/2;
        vector.x = ((newVector.x * 50) / half);
    }

    if(newVector.y >= 492 && newVector.y <= 512)
    {
        vector.y = 0;
    }
    else if(newVector.y < 492)
    {
        vector.y = ((newVector.y * 100) / 901) - 100;
    }
    else
    {
        int16_t half = 901/2;
        vector.y = ((newVector.y * 50) / half);
    }

    printf("x: %d, y: %d\n", vector.x, vector.y);

    return vector;
}

int main(void) {
    uart_init(9600);
    //uint8_t counter = 0;

    DDRE |= (LED_RED); /* OUTPUT */
    DDRE |= (LED_YELLOW);

    DDRF &= ~(BUTTON);  /* INPUT */
    DDRF &= ~(SENSOR);

    /*      JOYSTICK       */
    DDRF &= ~(JOYSTICK_X);  /* INPUT */
    DDRF &= ~(JOYSTICK_Y);
    joystick_init();

    while (1){

        if(!PUSH && !TILT)
        {
            PORTE |= (LED_RED);
            PORTE |= (LED_YELLOW);
            _delay_ms(50);
            PORTE = 0;
            _delay_ms(50);
        }

        if(PUSH && !TILT)
        {
            PORTE |= (LED_RED);
            _delay_ms(50);
            PORTE = 0;
            _delay_ms(50);
        }

        if(!PUSH && TILT)
        {
            PORTE |= (LED_YELLOW);
            _delay_ms(50);
            PORTE = 0;
            _delay_ms(50);
        }

        if(PUSH && TILT)
        {
            PORTE |= (LED_RED);
            _delay_ms(500);
            PORTE = 0;

            PORTE |= (LED_YELLOW);
            _delay_ms(500);
            PORTE = 0;
        }

        joystick_status();
        //_delay_ms(100);
    }
    return 0;
}

What it does now it reads the input values from joystick and it can be (x or y) min: 8 and max: 900, but we need to map it to [-100,100] this works but not perfect, so if someone can help to do the mapping better i would be grateful, but that is not the main point of my question.
But my real question is how i can  programm the MCU to generate PWM signals ?
I need to implant those 3 functions :

servo_init(), to initialize the timer/counter2;
servo_left(int v), to set the angular velocity of the left wheel;
servo_right(int v), to set the angular velocity of the right wheel;

There are four registers to be set during the initialization: TCCR2A, TCCR2B,
OCR2A, OCR2B.So what they mean ?
The two functions servo_le f t(intv) and servo_right(intv) set the corresponding
Output Compare Register to control the pulse duration of the output
control signal. The input parameter v of each function is an integer in
the range [−100, 100] whose absolute value is proportional to the angular
velocity of the corresponding servomotor and whose sign defines the direction
of rotation. As overall, these functions map the input range [−100, 100]
to the output range [1.0, 2.0] ms which corresponds to the pulse duration
of the control signal, thus the angular velocity and rotation direction of
the servomotor. Notice that, as the two servomotors are symmetrically
mounted, one of the two functions has to invert the direction of rotation.
Right wheel : PortB, pin 4, Output Compare Register : OC2A, TinkerKit Conn:  O1
Left wheel : PortH, pin 6, Output Compare Register : OC2B, TinkerKit Conn:  O2
I spend all day on the internet finding anything that would help out, but i didn't have any luck.

It's not wrong, but I just want to confirm something. You are using Arduino right? because your code does not seems like one

You may ask your teacher if it's okay to use the Arduino platform or servo libraries. Possibly it is, possibly he wants you to implement it in a low level fashion.

Don't cross post on multiple SE sites. Your other question was already put on hold for being off topic, but you asked here before that.

Because i din't know that we have this page.

||-----PWM Register Explanation-----||
It will be easier to explain with an example.
Here is a sample of Timer setup on ATMega2560 (assuming that is the one you use due to the tag "Arduino-mega") based on  datasheet section 20 : 8-bit Timer/Counter2 with PWM and Asynchronous :Operation:
TCCR2A= 0b10110001; //set COM2A1, COM2B1, COM2B0 and WGM20
TCCR2B= 0b00000001; //set CS20

WGM22,WGM21, and WGM20 --> 001 ==> Using Phase correct PWM mode
COM2A1, COM2A0 --> 10 ==> Clear OC2A on Compare Match when up-counting, and
Set OC2A on Compare Match when down-counting
COM2B1, COM2B0 --> 11 ==> Set OC2B on Compare Match when up-counting, and
Clear OC2B on Compare Match when down-counting
CS22, CS21 and CS 20 --> 001 ==> No clock prescaling

COM2A1, COM2A0 set the Timer2A on non-inverting mode, and COM2B1, COM2B0 set the Timer2B on inverting mode.
OCR2A and OCR2B is the duty cycle value of PWM. Because timer2 is 8 bit, so the value is ranging from 0-255. Its also the answer to your question

How i can program the MCU to generate PWM signals ?

PWM Signal frequency is defined by its duty cycle :

Duty cycle of Timer2x = (OCR2x/255)*100%

for example :
OCR2A = 100;
OCR2B = 155;

Timer2A will work on 39.2% duty cycle and OCR2B will also work on 39.2% duty cycle. What? Because Timer2B works on inverted mode (100%-60.8%) ==> 39.2%
||-----PWM topic closed here-------||
I've seen several people losing several hair while trying to control analog servo without manually  (well, some even move to Arduino only because of its servo libs).
You can check this Servo Library which is (maybe) the most common library used to control servo using Arduino (which also mentioned in @st2000 answer).
But, it will be better if you also post a detail about your "motorservo". At first I though it was a motor DC (by its PWM - Dir configuration).
||-----Additional-----------------------||
In your while(1), there are several if that can be optimalized by using simple if-else if-.. statement. So this one would be better (also minimalized "bug" chance) :
while(1)
{
  if(!PUSH && !TILT)
       {...} else
  if(PUSH && !TILT)
       {...} else
  if(PUSH && TILT)
       {...} else
...
...
}

--EDIT--
After reading several page of the PDF, I assume you have to make your own library (not Arduino). Perhaps this will give you something :
void servo_init(void)
{
 TCCR2A= 0b10110001;
 TCCR2B= 0b00000001;
 /*phase correct PWM mode,
  *no clock prescaler,
  *Timer2A -> non inverted,
  *Timer2B -> inverted
  */
}

void servo_left(int v)
{
 int convertedvalue =//map angular velocity of left servo into 0-255
 OCR2A = convertedvalue;
}

void servo_right(int v)
{
 int convertedvalue = //map angular velocity of right servo into 0-255
 OCR2B = convertedvalue;

}

we are using two servomotor's to control the movements of the robot. He goes forward and backwards when the 2 motors have the same velocity and right or left if on has high velocity then other one.

If so, further information about the servomotor is needed. i.e : what is the motor series? do you use driver motor?  what about the wiring? You can edit your question with those information so that other user can quickly notice

so i edit the question and post a link to the pdf, because it would be just annoying to type it all

Let us continue this discussion in chat.

Your question is confusing.  It appears you are creating code for an Atmel processor which directly interfaces with hardware.  Atmel does make some of the processors used in Arduinos.  However, all Arduinos abstract the hardware using libraries with very simple APIs.  For example, to control a servo motor an application written in the Arduino paradigm only needs to include the servo header file, instantiate an instance of the servo class, call a servo class method to indicate which pin the servo is connected to then call a servo class method with a value equal to the angle the servo motor is to move to:
#include <Servo.h>

Servo myservo;

void setup()
{
  myservo.attach(9);
  myservo.write(90);  // set servo to mid-point
}

void loop() {}

If you decide to switch to the arduino paradigm, the above code should be all you need to control your normal servo motors.
On the other hand, you may be using continuous servo motors.  Again, this is confusing because you did not say what type of servos you are using.  But it may be that the angle in the above example will actually be interpreted as a speed when dealing with continuous servo motors.

please see my.comment about the motor above.

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


text:
Cannot move TM1637 from Uno to Pro Mini
I have a very simple setup which works fine with an Uno.

#include <SevenSegmentTM1637.h>
#include <SevenSegmentExtended.h>

const byte PIN_CLK = 2;
const byte PIN_DIO = 3;
SevenSegmentExtended display(PIN_CLK, PIN_DIO);

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

  display.begin();
  display.print(F("TEST"));
}

void loop() {}

When I use the very same setup with a Pro Mini (XCSOURCE ATMEGA 328P, 5V 16Mhz), the display doesn't light up. I get monitor outputs and can blink the onboard LED, but no reaction from the TM1637 display.
I get this output in the console:
�E%MA1e� 10001111
Acknowledged: 0
ADDR :  11000000
DATA0:  0
write byte: 84
ADDR :  11000000
DATA0:  1111000
write byte: 69
ADDR :  11000000
DATA0:  1111000
write byte: 83
ADDR :  11000000
DATA0:  1111000
write byte: 84
ADDR :  11000000
DATA0:  1111000

Does anyone have an idea how to debug or fix this?

Could you please post a schematic?

I just added it to my original question.

You haven't created the display object. Shouldn't you have a line somewhere that creates the object:
SevenSegmentTM1637    display(PIN_CLK, PIN_DIO);

Yes, sorry. I forgot to copy that in. I edited the question now.

What would be the output of the console on an UNO?

Include library link please

It doesn't appear that the code segment you posted corresponds to the actual code that creates the listed serial monitor output. Can you show the actual code?

Since you're using a Grove Display, I believe it will be using I2C.
For better debugging, try using the actual I2C pins on your Pro mini, which are A4 and A5.

I2C: A4 (SDA) and A5 (SCL). Support I2C (TWI) communication using the
  Wire library.
  https://www.arduino.cc/en/Main/ArduinoBoardProMini

I2C may need pull-up resistors on your data lines.
(https://en.wikipedia.org/wiki/I%C2%B2C)
It can also be nice to use "verified to be working" code, like example code from the manufacturer.
/*
 * TM1637.cpp
 * A library for the 4 digit display
 */
#include "TM1637.h"
#define CLK 39 //pins definitions for TM1637 and can be changed to other ports
#define DIO 38
TM1637 tm1637(CLK,DIO);
void setup()
{
    tm1637.init();
    tm1637.set(BRIGHT_TYPICAL);//BRIGHT_TYPICAL = 2,BRIGHT_DARKEST = 0,BRIGHTEST = 7;
}
void loop()
{
    int8_t NumTab[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};//0~9,A,b,C,d,E,F
    int8_t ListDisp[4];
    unsigned char i = 0;
    unsigned char count = 0;
    delay(150);
    while(1)
    {
        i = count;
        count ++;
        if(count == sizeof(NumTab)) count = 0;
        for(unsigned char BitSelect = 0;BitSelect < 4;BitSelect ++)
        {
            ListDisp[BitSelect] = NumTab[i];
            i ++;
            if(i == sizeof(NumTab)) i = 0;
        }
        tm1637.display(0,ListDisp[0]);
        tm1637.display(1,ListDisp[1]);
        tm1637.display(2,ListDisp[2]);
        tm1637.display(3,ListDisp[3]);
        delay(300);
    }
}

You will need to adapt the pin numbers.
But after these steps it should work just fine.
Source: http://wiki.seeed.cc/Grove-4-Digit_Display/

You will need pullups resistors 4.7K are normally a good value.

Your answer is false, the TM1637 uses CLK and DIO not I2C. http://playground.arduino.cc/Main/TM1637

http://olimex.cl/website_MCI/static/documents/Datasheet_TM1637.pdf
The wiring does show the pull-ups. And a note on the datasheet includes: "Microprocessor data realize the communication with TM1637 by means of two–wire bus interface (Note: The
communication method is not equal to 12C bus protocol totally because there is no slave address)". So I believe that, in hardware it's I2C but not completely in software. But it indeed appears that you can put it on any of the pins.

I'm actually unsure if the pull-ups are on the board already. And it seems to work with regular pins aswel, but then again, there also is a software I2C library. But if it doesn't work, I would use the hardware-wise method.

Holy s***. The pins A4 and A5 really are the solution.

@Railsana, so it works by only changing the pins? (With the same code as you used previously, and without the pull-up resistors?) Can you verify that pin 2 and 3 work with normal execution (checking the status of a button and/or controlling an LED), it may be worthwhile to check that out :)

How does it work on the UNO then???

Maybe s/he used A4 and A5 on the Uno. ;)

Well, pins 2&3 and VERY far from A4&A5 or even SDA&SDL. Very weird...

I believe it will be using I2C. spi can use just two wires. the datasheet is clearly written for spi.

4.7k resistors on 2 and 3 pins does not help.
Works great if the tm1637 directly connected to 12 and 13 pins.


text:
It seems like the math of arduino is off
[SOLVED] By changing the offset for the incoming data into int16_t type there won't be any rounding errors and the values I'm getting are all back to zero in the sensor its base position
This is my first project where I use Arduino.
Until today everything went good with the Arduino Pro Mini (3.3v).
But as of today I got a bit of a weird problem.
I am using a MPU gy-521 (doesn't really matter) and I'm working on calculating the actual movement.
The problem which occured is that I'm using a deadzone to negate the smallest numbers (I know, this isn't the right way to use data). The way I negate the numbers is with the following code
// Check deadzone values
  if (ax+axo < adz && ax+axo > -adz) ax = -axo;
  if (ay+ayo < adz && ay+ayo > -adz) ay = -ayo;
  if (az+azo < adz && az+azo > -adz) az = -azo;

  if (gx+gxo < gdz && gx+gxo > -gdz) gx = -gxo;
  if (gy+gyo < gdz && gy+gyo > -gdz) gy = -gyo;
  if (gz+gzo < gdz && gz+gzo > -gdz) gz = -gzo;

ax is accelerometer data over the x-axis, axo is the offset, adz is the accelerometer deadzone.
gx is gyroscope data over the x-axis, gxo is the offset, gdz is the gyroscope deadzone.
All of the other letters are the same, for different axis.
After getting the values within the offset basically set to 0 with the offset I'm doing the following.
// Calculate acceleration
  axa = (ax+axo) / aFactor * g;
  aya = (ay+ayo) / aFactor * g;
  aza = (az+azo) / aFactor * g;

  gxa = (gx+gxo) / gFactor;
  gya = (gy+gyo) / gFactor;
  gza = (gz+gzo) / gFactor;

The a- and gFactor are mentioned in the datasheet, but these values should all be 0 if the value of axis plus the offset is within the deadzone.
The problem is that I'm not just getting 0.00 values.
I'm also getting -0.00 and 0.01.
0.00    0.00    -0.00   0.00    0.01    0.01

Could someone enlighten me about what's wrong in my situation or if this is just a Arduino issue.
[EDIT]
The data originally from the sensor is from type int16_t (ax, ay, az, gx, gy, gz) and the other variables are doubles.
The values which are off are always the same ones: Accelerometer Z, Gyroscope Y and Z.

Are all your variables declared as float ('axa, axo, aFactor, g, ...`) ?

The variables are all declared as double except for the ax, ay, az values which are int16_t by default

What are changes between "Until today everything went" and "today I got a bit of a weird problem" (source code, sensors, wiring, other) ?

Change axo etc... to also be int16_t rather than floats. That way when you set ax = -axo; and then do (ax+axo) there is no risk of rounding errors converting from double to int and back, you should always get exactly 0.

If axo is not an integer, then the statement ax = -axo; will perform rounding, and the expression ax+axo will be non-zero.

Iirc before today I was just getting zero's which was fine for me. Since then I removed the wiring and place them back (same setup) mostly the same code, atleast it shouldnt have changed the output.
When I change all of my variables into into16_t I just get zero's as output, no decimals. Since I'm working with dt precision I can't have this.
I fixed it by just setting the axo variable to int16_t, Thanks guys!

If your program is basically working but gives you rounding errors, it can be that you are facing some problems related to conversion from floating-point to binary or reverse. It is a very common problem in computer science. For example, the decimal number 0.1 has no exact binary  representation, it is infinite. For more information, you can read these pages:
http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/
https://www3.ntu.edu.sg/home/ehchua/programming/java/datarepresentation.html
In order to solve your problem, you can try to apply appropriate rounding to your results and if possible avoid mixing different data types and use double only if absolutely needed (which I guess is the case in your application).


text:
AccelStepper library - motor ticks when turning
When I'm using the AccelStepper library to control this closed loop stepper motor, the motor ticks when turning, maybe ~5 ticks/sec. Depending on the speed of the motor the ticks become more (at higher speed) or less (at lower speed) powerful.
At a low speed (<500 steps/sec) the ticks can only be detected by holding the motor and feeling the ticks. However, at greater speeds (>1000) you can also hear them and see the motor "house" move a little bit with each tick.
I'm not 100% certain but it seems like the ticking frequency is the same independent of speed. So if I tell the motor to make 3 revolutions, a slower speed will result in more ticks total because more time is needed to complete the revolutions.
Neither using the stepper library that comes with the Arduino IDE nor manually setting the pulse pin HIGH and LOW in a loop results in any ticking. Therefore I don't think it is the motor that is faulty.
This is the code I'm using:
#include <AccelStepper.h>

AccelStepper stepper(1, 7, 6);

long receivedPosition = 0;
long receivedSpeed = 0;
char receivedCommand;
bool newData, runAllowed = false;

void setup()
{
    Serial.begin(9600); //define baud rate
}

void loop()
{
    checkSerial();

    moveStepper();
}

void moveStepper()
{
    if (runAllowed == true)
    {
        if (stepper.currentPosition() != receivedPosition)
        {
            stepper.runSpeedToPosition();
        }
        else
        {
            runAllowed = false;
        }
    }
}

void checkSerial()
{
    if (Serial.available() > 0)
    {
        receivedCommand = Serial.read();
        newData = true;
    }

    if (newData == true)
    {
        // RUN
        if (receivedCommand == 'r')
        {
            runAllowed = true;

            receivedPosition = Serial.parseFloat(); //value for the steps
            receivedSpeed = Serial.parseFloat(); //value for the speed

            stepper.moveTo(receivedPosition);
            stepper.setMaxSpeed(receivedSpeed);
            stepper.setSpeed(receivedSpeed);

        }
    }
    newData = false;
}

Everything seems to work fine except for the ticking issue. Does anyone have any idea why this happens?

Does this also happen when you use one of the example sketches of the AccelStepper library?


text:
Define a string with single quotation marks?
This is kind of a short question. All I want to know is, if I can define a string using single quotation marks ('), instead of the regular ones("). I want to use it in a function like this:
print('Hello world');
I unfortunately do not have an Arduino nearby so I cannot test it myself.

single quotes identify a single character, while double quotes create a string literal

Could you please explain what you want to achieve rather than your likely misguided idea about how to achieve it (i.e. removing quotes)?

I am making an extensions for a program that requires Arduino code inside the program, but if I write the quotation marks, the debugger reports an error, because there are quotation marks inside quotation marks.

Then you need to update your extension to properly escape the arduino code so that reserved/special characters in the code are not interpreted by the non-arduino debugger. How to do that depends greatly on the program you are extending, which you have not named.

It's a bit unclear to me what you're trying to do, but perhaps just escaping the "s will achieve what you want.  In C, the way to escape something is with a , so for example char myString[] ="\"\""; would give you a string containing two "s.

You are still not being clear about what you are trying to achieve. What program? Language? Platform? You may want to check out these questions on stack overflow: “#include” a text file in a C program as a char[], and Embed data in a C++ program.

No, you can't.  'x' defines a single character or integer (note: 'ab' is a two-byte single value [integer] made up from the ASCII values of both characters).
To include " within a string you have two options:

Escape the " with \, as in: char foo[] = "He said \"Hello there\".";
Use "raw strings" if the compiler is configured to support it: char foo[] = R"(He said "Hello there".)";

Option 1 is the most portable since it doesn't require compiler support for modern C++ standards. However it's the hardest to read, especially when you get lots of escapes in the same string.
You can make it more readable by defining QUOTE:
#define QUOTE "\""

char foo[] = "He said " QUOTE "Hello there" QUOTE ".";

No, you cannot. This rules comes from the basic C++ syntax on which the Arduino platform is built.

Is there a way to define it without the qoutation marks?

Only very convoluted ways.

Actually, C++ raw string literals are easy to use (ref 1, 2); the only convoluted bit is adding a  -std=c++11 or -std=c++0x switch to IDE compiler options.


text:
Motor shield for Arduino Nano ATmega328
I am looking for a cheap and not so space consuming motor shield for my Arduino Nano ATmega328. I would like to charge the whole thing with a 9V battery. The shield must have at least 2.1A of output current so I can run 3 brushed DC motors on it. There will also have to be some pins left for a Bluetooth card and 3 analog pins for sensors.
Do you know any shields that meet my requirements?

In short:
Nano + Shield = no possible

[...] 9V battery. The shield must have at least 2.1A of output [...]

You can't invent power out of nowhere.

Options for the shield
Option 1:
Use an other Arduino. It will simplify everything.
Option 2:
Use a Nano to Uno adapter.
Option 3:
By an Uno shield and connect it pin by pin to the Nano.
Option 4:
Use MOSFETs. They'll work fine for what you are trying to do.

Options for powering
Option 1:
Use a 2s lipo. Voltage is above 5V so you have to reduce it with a down converter, but you should have enough juice for the motors.
Option 2:
Use a lot of AA, some in series to augment the voltage and then in parallel to augment the current.
Option 3: (just the the crazy minded)
Use a lead-acid battery (aka car battery).

Is  there a way, when using MOSFETs to switch the direction of the motor's rotation?

H-bridge. https://www.youtube.com/watch?v=iYafyPZ15g8

But why can't I use the regular 9V battery?

9V doesn't have enough current.

What is its current?

Depends, but they are mostly below 500mAh

Doesn't that mean I can run all of them for just 0,2 hours?

If it doesn blow up because you draw too much current.

Ok, I will try the AA battery tehnique. Thank you btw


text:
Using strings inside mBlock extensions code
The following question is about a 3rd party Arduino programming enviroment mBlock and creating extensions for it. I hope that there are some of you out there, who are fammiliar with it.
I was recently making an extensions for mBlock that can be used to write code for Arduino, when I came over this obstacle. I tried to write a function inside the "work":"" statement.
It looked like this:
"work":"Serial.print("Hello world");"
The extensions could not be imported, due to the quotation marks around the Hello world string. I tried removing the quotation marks, the extension was sucessfully added, but the program did not work, beacause quotation marks are needed inside C++ code to define a string.
Is there a way to add them in the extensions, without screwing up the code?

If that is a JSON format you could try using single quotes instead of double quotes:
"work":'Serial.print("Hello world");'

Alternatively you could escape the internal quotes:
"work":"Serial.print(\"Hello world\");"

None of the mentioned solutions seem to work. The extensions still do not get uploaded. The extension I am writing has a .s2e extension, if that helps (I am not really familliar with these kinds of files).

Looking at existing libraries the escaping should work. This is from serial.s2e: "work":"Serial.print({0});Serial.print(\"=\");Serial.println({1});\n"

For some reason it worked this time. I do not not why, but let's just go with it. Thanks.


text:
micros() resolution for Portenta H7
Is there any way to know the resolution of micros() for the Arduino Portenta H7. I have checked for other boards e.g. Nano which is mentioned as 4 uS. However, I couldn't find one for Portenta H7.
Is there any way to measure or look for that

Maybe grab the value in a tight loop and compute the shortest difference you find?

@PMF: That would only give an upper boundary: the resolution could conceivably be smaller than the time taken by a loop iteration.

I agree, but it would be a first hint.

A Protenta is completely different from a standard AVR Arduino. It is built with a M7/M4 dual core ARM mcu running on 480/240 MHz. There is also an OS installed on the board (mbed OS). The sketches run on top of this OS. I don't know the actuall status but ~2015 (?)  I followed a discussion about using a 'millis()' resolution of 50µs Arduino_mbed core. Unbelievable I know, but the reason was: The OS runs tasks and a timer irq with a call frequency  of a MHz would slow down the scheduler and the tasks.

So the discussion was seriously about a 50µs resolution that leads to 20kHz Timer IRQs. I'm not sure if this is still the truth. But if they still use a 50µs resolution you could follow the idea of @PMF and see if the difference between two micros() calls is dividable by 50 or 30 or whatever.

I did some measurements today. I used digital pins of the board to ON and OFF during each analogRead call for ADC.  These digital pins are then connected to the Oscilloscope.
Also, I used the micro() before and after the analogRead in my sketch to measure the time from the board. I obtained approximately 4uS time which it takes to execute one analogRead(), using an Oscilloscope.  However, the micros() function of the board couldn't give me that value. So it was showing the same time before and after the analogRead call.

Then, I called analogRead multiple times to increase the execution time and found that the maximum resolution I could obtain using micros() was around 32uS. This is inferior to the ordinary Arduino board even.

The question was cross posted to Arduino forum where user sbhklr asserted that the resolution was 1uS without providing any reasoning or references. https://forum.arduino.cc/t/micros-resolution-for-arduino-portenta-h7/697386

The question was cross posted to Arduino for STM32 forum, with some success. https://www.stm32duino.com/viewtopic.php?t=934  User edogaldo quoted Arduino doco in support of the 1uS answer. https://www.arduino.cc/reference/en/language/functions/time/micros/

The micros() language reference states that, "[The micros() function] returns the number of microseconds since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 70 minutes. On the boards from the Arduino Portenta family this function has a resolution of one microsecond on all cores. On 16 MHz Arduino boards (e.g. Duemilanove and Nano), this function has a resolution of four microseconds (i.e. the value returned is always a multiple of four). On 8 MHz Arduino boards (e.g. the LilyPad), this function has a resolution of eight microseconds.
It seems likely that the doco was updated some time after the OP posted the question.


text:
Storing data in Arduino Portenta H7's SDRAM
I am working on storing data from Portenta H7's ADC through a high sample rate (>100kSa/sec) per channel. I am using 2 ADC channel for my work.  Through the forum, I learned that the serial. print command reduces the sampling rate. Therefore one of the suggestions was to use the onboard available Portenta H7's 8MB SDRAM to store the sample values and then retrieving them after the sampling period. My sampling time is between 3-5 seconds so it is well within the storage limit of this SDRAM.
However, since I have no previous experience with microcontrollers, I am struggling to find a starting point for accessing this SDRAM for saving my data?  Any suggestions from your side are most welcomed.
Please do recommend If you have any other ideas about managing the data for faster sampling.
You can find the Portenta H7 information here. https://store.arduino.cc/usa/portenta-h7. Portenta has STM32H747 dual-core processor.
Thank you all.

The Portenta has 8 MB (megabytes, not gigabytes) of SDRAM. 2. You shouldn't have to do anything special for accessing the RAM. Just create a couple of arrays (one per channel) large enough to hold your data burst. The compiler should allocate RAM space for them.

#include <SDRAM.h>

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

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


text:
PIR sensor is already high, even though it is not detecting any person
I made codes like this through tinkercad.
const int temperature = A0;

int pir = 7;

void setup()
{
  pinMode(pir, INPUT);

  Serial.begin(115200);
}

void loop()
{
  int pir_state = digitalRead(pir);

  int value_temp = analogRead(temperature);
  float volt = (value_temp * 5.0) / 1024.0;
  float tempC = (volt - 0.5)*100;

  if (tempC >= 22 && pir_state == 1)
  {
    Serial.print(tempC);
    Serial.println("C");
  }

  delay(1000);
}

And following picture is the picture of a circuit I made.

I simulated this circuit. Originally pir_state is gonna be zero when PIR sensor is not detecting any person or object, but pir_state is always high irrespective of detecting. I thought the value of pir went wrong, so I read pir out. Then, I found it out that pir's value is always 7 regardless of detecting.
I know this isn't a big deal to you guys, but actually I'm noob so I can't figure it out what's wrong. Please, could you help finding what's happening to this and tell me what is the problem?
Here, this is a link of the circuit I make.
https://www.tinkercad.com/things/luV81NLkWKo-engineering-designcapstone-design/editel?sharecode=qsYWcgpijodDbgIpsfluJ3yUJwuN-70doPT62QNTv1Q

The value of "pir" is 7 because that is the (pin) number that you assigned to it. You should be interested in the value of "pir_state", which should be the output of the PIR sensor. Your Tinkercad link requires an account, so most people would not bother to see what's there.

You can confirm the code by connecting pin 7 to ground insted of the PIR sensor. If pir_state is zero then the code works correctly. I don't know tinkercad in detail. How is the PIR sensor triggered while simulating? By clicking on it?

Not having (nor likely going to have) a TinkerCad account, I'm unable to sufficiently convince myself that the connection you've made to the output pin of the PIR sensor to the black lead terminating at digital pin 7 is valid according to the simulator. You could eliminate that concern by showing that you still have the problem when doing nothing different except using a more conventional way of inserting it into the board which is also shown to work (without an account).

@user299980 I looked at your TinkerCAD model ... the PIR sensor is not connected to the arduino

Update:
@jsotola commented that Tinkercad does have some capability simulate to the PIR's behavior. So my next step would be to temporarily replace the if(){ ... }' block in your loop() function with a few statements that print your inputs and calculated values once per second and run that while I tweaked the simulated PIR device and the thermo-sensor (if the simulation lets you do that).
The terminal output values should lead you to what ever isn't working the way you expected it to.
You are running your program in simulation, but the PIR sensor is an active device that responds to external physical inputs (changes in infrared illumination on it) modified by sensitivity settings on the device. It's hard to simulate a device's active environment. Unless the simulation offers you a way to simulate that, too, there really isn't a way to simulate the its inputs to your program, so a constant output (as seen by your simulated code) makes sense.
Without the simulator letting you pre-program the PIR's physical environment, the only way to see a its active behavior is to use a real PIR, and monitor it's real output while you change its actual environment - such as waving your hand in front of it - and watch response with an Arduino, an LED (and resistor) to ground, or a DVM.

TnkerCAD does show a PIR field of view when the simulation is running ... clicking a mouse pointer within the field generates a movement event

Thanks for clarifying that!


text:
Odd characters in serial monitor
I have been recently working on a website that takes input from the arduino ie- temperature and humidity. But there is a fatal problem that I've encountered, the serial monitor spews out some garbage with some actual readings. Is there a way to eliminate this?
 ╰─λ cat /dev/ttyACM0
T0°C
Humidity: 39.00%
00%
Temperature: 32.70°C
Humidity: 39.00%
Temperature: 32.70°C
Humidity: 39.00%
Temperature: 32.70°C
Humidity: 39.00%
00%
Temperature: 32.70°C
Humidity: 39.00%
Temperature: 32.70°C
Humidity: 39.00%
Temperature: 32.70°C
Humidity: 39.00%
idit9.00Tempure:70°Humi: 39
emperatu32.7
Huty: 0%
idit9.00Tempure:70°umidity.00%Tratu32.7
idit9.00Tempture.70�Humi: 39
empere: 0°Cmidi39.0
atur°C
Hum9.00

code-
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>

#define DHTPIN 4

#define DHTTYPE    DHT11
DHT_Unified dht(DHTPIN, DHTTYPE);

uint32_t delayMS;

void setup() {
  Serial.begin(9600);
  sensor_t sensor;
  dht.begin();
  delayMS = sensor.min_delay / 1000;
}

void loop() {
  delay(delayMS);
  sensors_event_t event;
  dht.temperature().getEvent(&event);
  if (isnan(event.temperature)) {
    Serial.println(F("Error reading temperature!"));
  }
  else {
    Serial.print(F("Temperature: "));
    Serial.print(event.temperature);
    Serial.println(F("°C"));
  }
  dht.humidity().getEvent(&event);
  if (isnan(event.relative_humidity)) {
    Serial.println(F("Error reading humidity!"));
  }
  else {
    Serial.print(F("Humidity: "));
    Serial.print(event.relative_humidity);
    Serial.println(F("%"));
  }
}

board - Arduino Uno (R3)

Welcome to Arduino:SE.  Without seeing your code and hardware setup, we have no way to answer your question.

@sempaiscuba thanks for correcting me. I have edited it now, let me know if there are some further corrections.

I would print something unique in setup() that makes it evident in the output listing that it is only running once.

What is the actual value of delayMS? The calculation looks fishy, since sensor is not initialized. The value should be around 2500ms.

@PMF It says its 2000ms

Do you have ModemManager installed on your system? Could you check that nobody else is messing with the serial port? Like this: sudo fuser -v /dev/ttyACM0.

Evidently DHT11 sensors need at least 2 seconds to make a new reading.  Consider waiting slightly more than 2 seconds in your loop. Personally I couldn't get a DHTxx to work reliably and switched to, I believe, an si7021.

As has been noted in the comments, you are trying to read the sensor at a rate that is too fast.
Try changing this line:
delayMS = sensor.min_delay / 1000;

to:
delayMS = sensor.min_delay = 1000;

or:
delayMS = sensor.min_delay = 3000;

This will read the sensor at a slower rate and should give you clean output.


text:
Lag in sensor reading when Arduino Powered with 12V adaptor
So I am trying to power an arduino to measure water flow. It works all fine and dandy when I am powering it with laptop, but when I directly power it with 12V 1.5A adaptor the readings take a second to come to the LCD even though the pump starts running. Also when they come, I can see that sometimes it hangs. Why is that?
Before taking the readings I am switching on a motor which is also directly powered by the adaptor just like the arduino.
Below is a block diagram.

Would adding a voltage regulator that steps down 12V to 9v between arduino and adaptor help?

Please show your code and your actual wiring, not only a course scheme.

@chrisl does code matter if it works fine on power from laptop? Its just a command to switch on the relay (which switches on the pump) switch and next command starts printing the sensor values on LCD...

Can you check the voltage of your power supply with a voltmeter? Does it drop when the motor is turned on?

@EdgarBonet yup, true, just checked, the voltage to vin drops by nearly one volt even though I am powering it through LM7812 regulator module. The main power source voltage falls by almost two volts.

@EdgarBonet I am using this regulator (https://www.electronicscomp.com/lm7812-12v-dc-ac-three-terminal-voltage-regulator-power-module?gclid=CjwKCAjwtKmaBhBMEiwAyINuwPN5G4qe8VA7Ph4SIXA2q-S0DIiZIf6m9JAuTOHBV2SMhl5Y-iIcbhoCQlQQAvD_BwE), even then voltage is not constant

Thanks for adding a schematic.  I gave you an up vote for that.  Because the relay is not actually in the schematic (just the relay socket) I can not tell if it is a only a bare relay (then it too likely needs a reversed bias diode) or if it a module which already contains a diode or a diode and a driver circuit.

Your power supply is actually advertised at 1.2 Amps.  It's assumed you are powering the Arduino, the Relay, the Water Valve Solenoid and the Water-Pump-Motor all w/the same 1.2A power supply.  It is within reason that the sum of all those loads exceeds your power supply's capabilities.

It works all fine and dandy when I am powering it with laptop ...

It is assumed you were only powering the Arduino with the laptop.  Providing the Arudino with an independent power source is a common solution to this type of problem.  Obtaining a larger power supply (more Amps) is another possible solution.
Why does it eventually work?
Motors require more Amps when under a physical load.  If the water is stationary, the motor will have to "get it moving" requiring more current. The term "locked motor current" is used here in this article.
Also, inductor loads require more Amps when ever the voltage potential is suddenly changed.  The motor and relay are likely both seen as inductive loads.  This is referred to as inrush current.
Both of these can be assumed transitory.  Once the motor is moving and after the potential across the inductive loads are closer to zero, the initial current demand will subside and the power supply may then be capable of sustaining the constant voltage needed by the Arduino's processor.
Alternate solution:
Obtaining a larger power supply is likely the better solution.  Another option involves filtering the power only for the Arduino.  This option is discussed in this thread on forum.arduino.cc where a diode and capacitor are used to somewhat isolate the power for the motor, relay and solenoid from the Arduino.

Ok, Ok. My adaptor is 1.5A, so I guess I should go for 2A? And also replace my LM7812 with a more amps module? Can you recommend something? I must use only a single power source, I can't use two power sources, so will have to look for a solution around this...

and your answer also explains the voltage drop which I mentioned in my comment on my question? I'm an amateur enthusiast, so might not understand too technical english...

Relay is powered by arduino, but yeah, there's a solenoid valve in there also on the power adaptor sucking a lot of current probably

If you're constrained to only one power supply then likely you need, as you said, a power supply rated for more amps.  I usually add up the maximum required currents and find a power supply with double the capacity.  There are ways around this.  But they require more knowledge and testing.  They are usually reserved for situations that are cost sensitive.  Like isolating the power path to the Arduino with a diode and a capacitor. Or somehow attenuating the inrush current to the motor.  Something along the lines of a soft start motor device.

Wait, you have a solenoid valve as well?  If the water is under pressure, why use a pump at all?  And if not under pressure, why use the solenoid valve?

Water is not under pressure. I thought maybe the pump could lead to leakage of flow, so to stop flow absolutely when I wanted I added a valve.

I would test it once without the valve, see if the valve is actually serving a purpose.

And about that solution, situations always like to be cost sensitive. So I can try putting a diode between the Vin pin and the +ve terminal? And what value capacitor can I use? Since LM7812 regulator module already has two capacitors, would adding another in the path help?

If this is a 1 time project, I would try a dependable solution by obtaining a higher capacity power supply and be done with it. Only if this is a product to be made many times over would I consider alternate solutions. Such as a forward biased diode between the positive 12 volt power supply line and the Arduino w/ a suitable capacitor (perhaps 100uF to 1000uF depending on the Arduino's current demand and the duration the capacitor needs to maintain a voltage (the duration of the high current demand event)).  It doesn't sound like you have an oscilloscope to help pick a suitable value.

Ok, its right I don't have a oscilloscope, would it do if I just try with a big 1000uF capacitor?

Is it possible I've fried up my arduino by now? Its giving even more lag even when connected to laptop now

One clarity needed, that voltage drop which comes, its because of Rush Current?

You need to make either your word descriptions more precise or you need to draw better diagrams for us to help.  Some people post pictures showing all connections clearly.  Did you remove the Arduino's positive connection to the 12 volt power supply when you connected only the Arduino to the laptop USB port?  And did you keep the Arduino ground connected to both the laptop and the 12 volt power supply?  I don't mean to put you off, but I think the safest option is to buy a bigger power supply and see if your situation improves.

BTW, many relays have build in diodes, but I'm not sure about solenoids.  Read this stack exchange question / answer to understand the purpose of this diode.

I have added my schematic, can you please take a look and let me know all is fine? I don't want to ruin another Arduino. The only difference to my current wiring is that the solenoid switch is on the -ve side while in the schematic its on the +ve side. Also there is only one tactile switch. The diodes are IN4007. I'm using a relay module so I have just added pinouts for it.

The diodes have been added now based on ur suggestions, they weren't there before

I added a link to a diode/capacitor option/discussion if the larger power supply does not work.

Ok thanks...had added the sockets for the relay as I am using a module https://www.electronicscomp.com/1-channel-5v-relay-module-without-optocoupler?gclid=Cj0KCQjwnbmaBhD-ARIsAGTPcfVcln-o_BiNm7Jp_9r5nsP2b0nzm48GdKvnlaBkGC-nYU4-5W0d5OcaAh6wEALw_wcB . Will test it out on the system once I get my replacements for the ruined stuff. If the problem still persists then will try the other way and let u know.

Welcome. Your pump is turning on as soon as the power is turned on because the relay is connected to 5V. Your processor needs to initialize itself and then the display, the pump is up and running. On your laptop the pump was powered from the power supply and the Arduino by the laptop. The arduino was on and up and running when the pump was started. Hope this helps. I will take a SWAG and say this is powered up when the pump is needed and powered down when it is not needed.

So how do I get it out of bed in time?


text:
ML8511 Sensor, unable to achieve meaningful results. Output voltages are atypical
Problem: ML8511 Sensor, unable to achieve meaningful results.  A mapping to the voltage output yields values that are unrealistically high. Variance is greater than expected [by me], and sensitivity, if any is questionable. In essence, the sensor reports high levels of UV whether is a dimly lit room, or exposed to daylight.
Background:
The interface is simple enough, and Google Search renders numerous hits, e.g., https://learn.sparkfun.com/tutorials/ml8511-uv-sensor-hookup-guide
All coding examples I have seen are akin to the one shown by Sparkfun.
Prior experience: I have a number of other Arduino devices running my sketches that record, collect, analyse, distribute, transmit and display findings.  All of these work as intended.
Observations:  I have spent a lot of time trying to make sense of the behaviour i observe with the sensor output, but have been unsuccessful. I have used two different sensors [same model], and switched UNO boards.  I've removed all other connections to the board, reverted to using the example code, then to code measuring only pinout values.  I have also measured pin voltage via voltmeter for both the output signal and the 3.3 volt reference pin..  According to specs, the sensor outputs voltage correlate with UV levels, and calibration is achieved via a known voltage reference level.
Based on a 3.3 volt reference, the sensor should output 1 to 3 volts, which can be mapped to a UV Intensity (mW/sq cm) range of 0 to 15.  My output voltages range from 2.8 to 3.2 v, the last of which is seemingly out of specs.
I have also used different sample sizes that comprise a data point, but that has little effect, but since the underlying values are out of range, it really would not matter.
Although cheap sensors such as this are not known for great accuracy. I find that they generally work rather well.
My supposition is that:
a) I am working with defective [abeit new] sensors.
b) This particular model of sensor functions in an atypical manner.
c) Being unexperienced in such, I an overlooking something glaringly obvious to others.
d) Somehow my perception of reality is defective.
e) I have truly entered into the Twilight Zone.
Seeking: Information that supports or refutes my observations.  Ideas that I might use to further isolate/ identify the problem.  A solution to the problem.
Image of item used

ML8511 UV Intensity Graph from specs
[
Typical ML8511 Wiring Diagram, the GYML8511 also has an additional connector for 5V, which I have tried both connected and disconnected, not understanding the board behaviour.

I found another, third sensor identical to mine and functioning properly.  By measuring pin output, then cross swapping with one of my two "supposedly abberant" sensors, I have identified my two as being defective, i.e., the other sketch then failed to function properly with one of those so identified sensors, whilst mine now worked as it should.
I typically buy at least two of everything in an effort to isolate such problems, but if from the same batch, two may not be sufficient in some situations.


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

How big is a "sample"? How many samples before "end of testing"?

So about 2 megabytes. What kind of Arduino? "Arduino" is a brand name, not a product. Why does it have to be an Arduino?

@JanDorniak Thanks, my brain completely skipped over that.

Serial.print() is slow when it involves an actual UART, but it should be fairly fast when run via a direct USB connection.  Your board clearly has direct USB access to the main MCU which would be the sensible way to do this (even if you buffer in RAM first), what's not entirely clear is if that is the USB channel on the USB-C connector and supported by the Arduino Serial class, or a different one only available on a header.  Ultimately you might do better with some more traditional streaming solution, eg based on a Cypress FX2 USB-FIFO or the like.

The Portenta has a beast of an  STM32H7 Cortex M7 and a minimum of 8M bytes of external SDRAM in addition to the 1M on-chip.
You need to capture 2channels x 2 bytes x 100K/s x 5s = 2M bytes of data, so storing it on the on-board RAM and spitting it out later seems like a viable and low-risk approach.
A slow serial link might take a few minutes to transmit 2M bytes of data, but you have various other options if that is objectionable.

I don't know what Arduino ecosystem code is available. There are H7 ADC examples available in the STM32Cube IDE. The ADC will be what you want examples for.


text:
Portenta pinouts for ADC
I wanted to have your comments about one of my questions.
I am currently working on the sketch for the Arduino Portenta H7. However, due to my poor electrical background, I would like to ask your opinion about the pinouts.   Below you can find the pinout diagram from the document page 1 available at the below link.
https://content.arduino.cc/assets/Pinout-PortentaH7_latest.pdf
I am a bit confused about the analog pins. As the diagram and color-coding show ADC A0 ( available on the high-density connector)  and analog pin A0 both separately.   What can be the difference between them ? or maybe I am interpreting wrong.
Because, on an ordinary Arduino board ( as far as I found), we have the Analog pins which are used for the ADC too. However, here in the Portenta pinout diagram, we have ADC A0 and analog A0 separate?
I thank you for your time and opinion.

it is the same pin of the MCU

Hello Juraj. Could you please elaborate a bit more, please

MCU stands for MicroController Unit. here it is the STM32H747XIH chip

The "high density" connectors expose every pin of the MCU. The pins around the edge of the board duplicate just the immediately useful ones.
Every pin that is on the edge of the board is also on the high density connectors somewhere.
Why have the pin on both connectors? Simple: if you want to use it in a breadboard or with jumper wires then you want the useful pins on the edge. If you want to use a plug-in board then you don't want to have to connect to both the high density connectors and the breadboard connectors, that would just be really awkward (since both have completely different height profiles). So everything is on the high density connectors for plug-in boards, and the useful ones are also on the breadboard headers.
A0 is the Arduino name for the pin. ADC is the function of the pin. The A of ADC stands for Analog. It's a pin that Converts Analog to Digital. It's an Analog to Digital Conversion pin - ADC.

It is just the one pin that they marked two times as A0. I think they just wanted to make clear it's the same pin, maybe that people don't get confused, but in my opinion it's just more confusing.

Hello. I have added a new figure in my question. The pin marked ADC A0 is a separate pin A marked as high-density connector pin 73 of J2. So I guess probably both A0 and ADC A0 are different pins?

@BasitAli I think in the lower picture ADC A0 is used to describe that the pin is both of it as I can't see any other A0 description.


text:
Does Arduino Zero need to be switched between USB EDBG and JTAG port debug use?
I wanted to compare the debug output of the Arduino Zero when connecting via two different debug paths.

Via the embedded debugger (EDBG) connected to Arduino IDE via USB
Via the JTAG hardware connector J100 to a Black Magic Probe and GDB

The two paths being compared are shown on the Zero Schematic:

Using the Blink.ino compiled for debug, the EDBG works as expected into the Arduino IDE 2.0.4 debugger via USB.
However using the same sketch with the JTAG hardware port to a black magic probe fails to connect, reporting "Target voltage: 1.0V".
rowan@rowan-ThinkPad-X1-Carbon-4th:/tmp/arduino/sketches/1EBCACBEAD6C08902D692E87F523B56E$ arm-none-eabi-gdb Blink.ino.elf
GNU gdb (GNU Arm Embedded Toolchain 10.3-2021.10) 10.2.90.20210621-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "--host=x86_64-linux-gnu --target=arm-none-eabi".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from Blink.ino.elf...
(gdb) target extended-remote /dev/ttyACM1
Remote debugging using /dev/ttyACM1
(gdb) monitor jtag_scan
Target voltage: 1.0V
JTAG device scan failed!
Failed
(gdb)

The same probe and setup successfully debugs an Arduino Due. Acknowledging different processors on the two boards.
The JTAG connector is correctly oriented.
Is a switching action needed to enable one debug path or the other, or is something else wrong?
Update 2023-04-01: I bought an SWD breakout board so I could get some test leads on without risking bent pins (it took a couple of weeks to arrive). The VREF pin on the Zero is 0V when running the debug version of Blink.ino. In comparison the same test rig connected to Due running debug Blink.ino VREF is 3.3V as expected.
Tracing back the Zero JTAG VREF pin connection on the PCB, the connection is as expected compared to the published PCB Layout. It connects to a pin on the Atmel EDBG chip (IC3).

At J100 the schematic (snippet above) labels this connection VCC_P3V3. However it seems to connect to VCC_EDBG_P3V3.
I'm going to spend some time with the Atmel EDBG User Guide
Update 2023-04-01 #2: During successful debugging using the USB EDBG to Arduino IDE method, the JTAG (J100) VREF pin remains at 0V.
Update 2023-04-01 #3: Refering to the EDBG datasheet section 5. The pin on the EDBG chip (IC3) to which the JTAG Vref pin is connected is (K9) EDBG_TCK. Noting the orientation is inverted compared to the PCB image.

EDBG_TCK is described as "JTAG Test Clock pin for EDBG device", and is in the EDBG manufacturing programming group of pins.
OK, it's clear to me now, that this isn't the JTAG I was looking for, I'll write it up as an answer.

I’ve been trying out Chat GPT-4. Here’s what it has to say about the error message:
…There could be several reasons why the JTAG device scan failed. Some possible reasons include a faulty connection between the test probe and the target device, incorrect configuration settings in the test probe, or an issue with the JTAG interface of the target device.
… you could try checking the connections between the test probe and the target device, verifying that the test probe is configured correctly, and ensuring that the JTAG interface of the target device is functioning properly…

I believe the problem occured because I assumed that J100 on the schematic is the populated JTAG interface. Tracing through the schematics and PCB layout indicate that J100 on the schematic is CN2 on the PCB layout (the JTAG interface with no headers populated). J301 on the schematic is the JTAG interface with headers installed, called CN1 on the PCB layout

J301 (CN1) is for programming the EDBG chip.

J100 (CN2) breaks out JTAG target interface pins, but does not have header installed.

Contrary to the schematic, looking at J100 (CN2) on the PCB laypout and also by visual inspection of the physical PCB VREF pin 1 does not seem to have any connection to +3V3.
Top View:

Bottom View:

Counter to the microscope photo evidence, I do read 3.3V (using multimeter) on the square solder pad of the VREF pin, which matches the schematic. I'm having trouble explaining it though. This is a two layer PCB right?
Updated 2/4/2023: My conclusion is that the EDBG JTAG port is not useful with the Black Magic Probe as an alternative to EDBG. The J100 (CN2) port seems like it would be usable if it had headers.

https://content.arduino.cc/assets/Pinout-ZERO_latest.pdf

Thanks Juraj. That newer pin out is more clearly labeled. I’m still not convinced by the reported +3v3 at J100. I’ll add some microscope photos so you can see what I mean.

Re: This is a two layer PCB? No it's not as it turns out. Note the green traces in the photo above. Assumption is that J100 (CN2) VREF is making its connection to +3V3 on the middle layer and it's been missed out of the PCB layout diagram.


text:
Duinotech ATTINY85 Pinout
I'm sure this is a super nooby question but,
what is the pinout of the Digispark ATTINY85 Development Board
The board looks like this:

Now the reason why I'm asking this question, when I do digitalWrite(1, HIGH);, the test light will come on. My question is then, what is the virtual number for PB1 (P1 in photo).
Also, does that arduino output + or -?
Any help is appreciated. Thank You!

This seems to show an obvious pinout with an LED connected to p1 (digital pin 1).
With "virtual number" I guess you mean the Arduino pin nr. As your code shows you, it's Arduino pin 1.

when I do digitalWrite(1, HIGH);, the test light will come on.

nvm, got what you mean now.


text:
How to allow cross-domain requests with ESP8266WebServer.h ? - CORS policy: Access-Control-Allow-Origin
With an nodeMCUv2 I want:

to start a wifi server with ESP8266WebServer.h
serve a root html page which will interact with the ESP and fetch external data

Issue:
CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.'
Tried to make CORS happy, by either one of the followings, but didn't help:
.sendHeader("Access-Control-Allow-Origin", "*");
.enableCORS(true);
#include <ESP8266WebServer.h>
ESP8266WebServer srvAmb(80);
void handleRoot(){
// srvAmb.sendHeader("Access-Control-Allow-Origin", "*");
   srvAmb.enableCORS(true);
   srvAmb.send(200,"text/html; charset=utf-8", myRootWebPagWithJSExternalFetch);
}
void setup(){
...
    srvAmb.on("/", handleRoot);
...

Part of the served root html page:
try{
  const Qresponse = await fetch( "https://zenquotes.io/api/random" );
  const Qdata = await Qresponse.json();
  console.log(Qdata);
  ...
} catch (error) {
  console.error(error);
}

Console log in Chromium:

Access to fetch at 'https://zenquotes.io/api/random' from origin '192....' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

So, how does one fetch external data from the browser running on PC, smartphone, etc?
Thanks
P.S. One could ask the server to fetch the data, prior to supplying the html page, but that's not esp server's job.
P.P.S. I hadn't the credit to create tag keywords such as:
fetch, CORS, Allow-Origin, policy
REM: under How to allow cross-domain requests on ESP8266WebServer
it is suggested that .sendHeader("Access-Control-Allow-Origin", "*") could be deprecated, very well but ArduinoIDE does not raise any warning; anyway suggested solution fails.
Looking at the source code https://github.com/esp8266/ESPWebServer/blob/master/src/ESP8266WebServer.cpp,
the method sendHeader() on line 238, has a 3rd parameter(a boolean) that if set to true, puts before the passed name & value before the already passed header, otherwise puts it after, aka the declarative order is important.
Viz, what's the valid header the esp server needs to send??
Especially, has Chromium details, states:

Request URL: zenquotes.io/api/random

Request Method: GET

Status Code: 200

Referrer Policy: strict-origin-when-cross-origin

See also: https://javascript.info/fetch-crossorigin

One thing, because I struggled with CORS in a different context lately: Are you sure, that your browsers cache doesn't interfere here? I had the issue that setting allow origin to * wouldn't help, but as soon as I used a different browser (or in my case a fresh profile of firefox), it was working.

@chrisl. NO. But I wonder if it has nothething to do with the fact that the fetch is https while the connection with ESP is http.
GET https://zenquotes.io/api/random net::ERR_FAILED 200
https://stackoverflow.com/questions/22665232/what-can-cause-chrome-to-give-an-neterr-failed-on-cached-content-against-a-ser

Details in Chromium: states that the header is missing:
A cross-origin resource sharing (CORS) request was blocked because of invalid or missing response headers of the request or the associated preflight request .
...
Request Status Preflight Request (if problematic) Header Problem Invalid Value (if available)
random blocked  Access-Control-Allow-Origin Missing Header
So it does not do job as Chromium 107 expects.
https://web.dev/cross-origin-resource-sharing/?utm_source=devtools  and
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

The issue is URL specific.
Indeed, if I change API, namely
const Qresponse = await fetch( "https://zenquotes.io/api/random" );

by for example:
const Qresponse = await fetch( "https://api.open-meteo.com/v1/meteofrance?latitude=49.71&longitude=4.16&daily=sunset&timezone=Europe%2FBerlin" );

then it works.
I presume that I comes from network developper tools info in Chromium:

Referrer Policy: strict-origin-when-cross-origin

claiming a strict origin for zenquotes.io's API.
My esp server code being:
void handleRoot(){
    srvAmb.sendHeader("Access-Control-Allow-Origin", "*", 1);
    srvAmb.send(200,"text/html; charset=utf-8", myRootWebPagWithJSExternalFetch);
}

Remark, with or without the additional 3rd param of sendHeader() it works.