text:
pin going high not allowing analog read to change
I have the following problem:
My arduino takes analogRead(A0) from a potentiometer whose position I can't adjust directly.
When analogRead(AO) goes to a value X,  I want pin 8 to go HIGH, this causes the circuit to open. and stop A0 getting higher . so I do an if statement:
if(analogRead(AO)> X) {

digitalWrite(pin, HIGH)  \\opens the circuit}

else {
digitalWrite(pin, LOW)  \close the circuit
 }

The issue I have here, is when then circuit is open,  I would like to change the value of the potentiometer (A0) which is controlled by a motor which is also in the circuit: but doesnt depend on the arduino board.  Given I can't control A(0) then the circuit will remain on A(0) >X forever.
The system going to LOW pin or close circuit, after it reaches HIGH pin for 2 seconds would be great, but then the program goes to the beginning and realizes that still A(0)> X , and goes back to a open circuit state, therefore not allowing me to have the close circuit anymore in order to make A(0) < X  and leave the circuit closed . Maybe something that cyclically turns pin on an off for t mseconds? but this is not ideal as it would cause high wear on the system
Edited the post to be more precise. I hope now its clearer
thanks

thank you for your answers, but after playing for a while with your codes, and the ideas behind it, still cannot get it to work.
for instance, Chrisl with your first:
when potentiometer is at > X, It cuts the circuit which is good, but still doesn't go off until both potentiometer goes to < X and 3 seconds lapse , but this is not going to be possible to achieve anyways    because the value of the potentiometer is fixed on X
THis is what Id need-
if (PinState == HIGH)
after 3 seconds go low,
and not turn HIGH until at least these two conditions are met; analogRead has gone to < X and then analogRead > X ,and in that moment we are back at
PinState HIGH
is  even possible to achieve something like this?
the circuit is something like this:

simulate this circuit – Schematic created using CircuitLab
UPDATE:
I have using this code, which does almost what I want:
         if(analogRead(A0) > X) {
      unsigned long currentMillis = millis();
if ((unsigned long)(currentMillis - previousMillis) >= interval) {

   pinState = !pinState;
   digitalWrite(pin, pinState)
   // save the "current" time
   previousMillis = millis();
}}

When it gets to analogRead(A0)> X the problem of this code is that it switches the pin On and OFF continuosly,
but instead of switching it off/on after the interval time , I want it to be LOW always. Of course as long as time  is more than interval,and not get to a HIGH, until It has gone back to  analogRead(A0)> X and time is less than interval. And repeat the process... When time is more than interval it will go from where it was digitalWrite(pin, HIGH) to the new state digitalWrite(pin, LOW)
I made this table to be more clear
Table: analogRead(A0) > X?
1-yes -->now check if time in this state is less than interval = 3000:
1.1-YES, ---> digitalWrite(pin, HIGH)
   1.2- if no ( time is more than interval ) --->  digitalWrite(pin, LOW)
2-  No, analogRead(A0) < X . So -->  keep  digitalWrite(pin, LOW)
NEW UPDATE:
The state diagram for the new ranges should be something like this. I hope it is clear. I also removed the delays and replaced  (V < X ) for (V < Y )  , it works great. Thank you Edgar.
Z in the diagram being the variable for the new range, Z << X

LAST UPDATE:
Question Solved by Edgar Bonet

Its difficult to understand, what exactly the code should do. Please try to explain it more clear. Timed things can be best done using millis() like in the BlinkWithoutDelay example, that comes with the Arduino IDE

thanks, i tried to use it, but didnt work on what was trying to achieve, i edited the post hoping its more clear now.

So you want to physically turn the potentiometer with the motor to adjust the value to be lower than X? Then the motor must be controlled from the Arduino

maybe this way could work, everytime the system goes to a HIGH, it will remain there for 3 seconds , then it  makes circuit close or pinLOW. on the background however the variable A0 will keep reading but not affecting pin8 or the close circuit situation , and when the system goes more than X , it does the IF..else statement again, HIGH(3 seconds) stop the IF..ELSE,  reads A0 on the background and if more than X all repeats

it's a problem to control the motor directly because it depends on another parts of the circuit.

It is unclear, what you mean by "pinstate High". Please mske a clear table with everything that should happen. We need a clear and detailed description of the desired behavior

@chrisl I updated the original post, thank you very much for your time

The description you give for the desired behavior is very unclear and
hard to follow. I am going to rephrase what I think I understood in
terms of a finite state machine, which is the correct way of
describing this kind of systems. Please, review the description below,
as chances are I did not completely understand what you really want.
Let's say the system can be in any of these three states:

In the V_LOW state, the input voltage is below the threshold X and
the output is LOW. If the input raises above X, we set the output
to HIGH and transition to the V_HIGH state.
In the V_HIGH state, the input is above the threshold X and the
output is HIGH. If the input falls below X we go back to the
V_LOW state. If we remain in V_HIGH for three seconds, we switch
the output to LOW and go to the TIMEOUT state.
In the TIMEOUT state, the input is above the threshold, yet the
output is LOW. When the input falls below X we go to the V_LOW
state.

Below is a state graph for this machine. The states with a gray
background have the output LOW, whereas the state with a white
background has the output HIGH. Each possible transition is drawn as
an arrow, labeled by the condition that triggers the transition:

Is this the behavior you have in mind? If no, try to describe the
behavior you want in terms of a finite state machine, as I have done
here. If yes, then I suggest you follow chrisl's advice and implement
some hysteresis, by having different thresholds for going into and out
of V_LOW.
Anyhow, below is a translation of the FSM above in C++. It may not be
the most efficient way to write it, but I believe it is straightforward
enough to not require any additional explanation:
void update_output()
{
    static enum { V_LOW, V_HIGH, TIMEOUT } state;
    static uint32_t time_entered_v_high;
    int V = analogRead(A0);

    switch (state) {
    case V_LOW:
        if (V >= X) {
            digitalWrite(pin, HIGH);
            state = V_HIGH;
            time_entered_v_high = millis();
        }
        break;
    case V_HIGH:
        if (V < X) {
            digitalWrite(pin, LOW);
            state = V_LOW;
        } else if (millis() - time_entered_v_high >= 3000) {
            digitalWrite(pin, LOW);
            state = TIMEOUT;
        }
        break;
    case TIMEOUT:
        if (V < X) {
            state = V_LOW;
        }
        break;
    }
}

Edit 1: Here is how to implement the hysteresis: you need to choose a
second, lower threshold, for going back to the state V_LOW. Let's call
it Y, which is smaller than X. Then, both on the diagram and the
code, replace every instance of “V < X” by “V < Y”. That's it. There is
absolutely nothing more to change.

Edit 2: Addressing the updated question. Now the output should go
HIGH when the input is out of a defined range. I'll add hysteresis
right away by using four thresholds
V0 < V1 < V2 < V3:

the input is in range if it is within
[V1, V2)
the input is out of range if it is not within
[V0, V3)
the ranges [V0, V1)
and [V2, V3) provide hysteresis.

Note that for consistency I like to have all the intervals closed on the
same side. I will also rename the states V_LOW and V_HIGH to
IN_RANGE and OUT_OF_RANGE respectively. Here is the updated code:
void update_output()
{
    static enum { IN_RANGE, OUT_OF_RANGE, TIMEOUT } state;
    static uint32_t time_exited_range;
    int V = analogRead(A0);

    switch (state) {
    case IN_RANGE:
        if (V < V0 || V >= V3) {
            digitalWrite(pin, HIGH);
            state = OUT_OF_RANGE;
            time_exited_range = millis();
        }
        break;
    case OUT_OF_RANGE:
        if (V >= V1 && V < V2) {
            digitalWrite(pin, LOW);
            state = IN_RANGE;
        } else if (millis() - time_exited_range >= 3000) {
            digitalWrite(pin, LOW);
            state = TIMEOUT;
        }
        break;
    case TIMEOUT:
        if (V >= V1 && V < V2) {
            state = IN_RANGE;
        }
        break;
    }
}

Dear Edgar, I cannot thank you enough. That is exactly what I wanted, so thankful to you.  This problem has driven me crazy.   I just added a few delays at the end of each case and now it works perfectly without any flickering when switching states. As per your suggestion about the hysteresis .

Just a question, In case I wish to add a range, for example ( case V_LOW , case V_HIGH , case TIMEOUT ) going from ( ( (V >= X) , (V < X) , V < X)) to (( V >= X && V <= X ), ( V < X && V > Y ), ( V < X && V > Y ))  with Y being a minimum value, How that could work? . I tried adding the ranges, more if's , more cases, but neither would work. I also tried creating a function: e.g. bool inRange(int V, int minimum, int maximum) and replacing the range ( V >= X && V <= X ), ( V < X && V > Y ), ( V < X && V > Y ) ) with inRange(V, X, Y) functions but didn't work either .

@Fraunhofer: 1. Flickering is expected with this FSM whenever the input is noisy and close to the threshold. Hysteresis is the usual way to fix it. Delays are a stop gap solution that should better be avoided. 2. I couldn't understand your ranges thing. Could you draw your idea as a state diagram similar to the one I drew? You can then add it to the question.

I added the state diagram . Thank you very much

Thank you so much for all your help and explanations.  Now it's perfect.

Using different threshold values to switch states - a higher threshold to go HIGH and a lower value to go LOW - is called hysteresis. It makes a dead-zone between the two switching values that prevents jitter, or flickering the LED in this case, that would happen with a single switch-point and the analog value was very close to it.
To do that, you just need the second clause of your if block, now an else, to become an else if. So it would look like this (in pseudo-code):
if analog > 5,
   open the circuit;
else if analog < 4
   close the circuit;
// else must be >4 but <5, so do nothing.

for 3 seconds I make circuit close ... when the system goes more than X again, it does the IF..else
  statement again

Update:
So instead of hysteresis, you want close the circuit for a fixed amount of time? Then try something more like this:
if millis() - stop_time > 0 && analog > 5,
   save stop_time = (millis()+3000);
   open the circuit;
end

i did that but still not what I want.  what if, I keep the if statement, and for 3 seconds I make circuit close goes to LOW,  on the background however the variable A0 will keep reading but not affecting pin8 or the close circuit situation  , and when the system goes more than X again, it does the IF..else statement again

As I wrote in my comment, you can use millis() to solve your problem. First you should ditch the else statement, since you don't want the analog signal to turn the output of.
unsigned long timestamp=0;
unsigned long interval = 3000;

void loop(){
    if(millis() - timestamp > interval){
        digitalWrite(pin, LOW);
        if(analogRead(A0) > X){
            timestamp = millis();
            digitalWrite(pin, HIGH);
        }
    }
}

This code will check, if the time difference between now and the last activation is over 3s. If yes, it will first set the output to LOW. Then it checks, if the analog input is above X. If yes, the output will be set to HIGH and the timestamp will be set to the current time. On the next loop iteration the time difference will be lower than 3s (since we just set the timestamp to now). Thus nothing will change, keeping the output to HIGH for 3s. After that the output will be set to LOW and the code will be sensible to A0 again.
If you the output to just trigger once ever, you can use a simple flag.
unsigned long timestamp=0;
unsigned long interval = 3000;
byte flag=1;

void loop(){
    if(millis() - timestamp > interval){
        digitalWrite(pin, LOW);
        if(flag && analogRead(A0) > X){
            timestamp = millis();
            flag = 0;
            digitalWrite(pin, HIGH);
        }
    }
}

The flag is initially set to 1, which actives the analogRead() part. Then it is set to zero, which deactivates it.
Note that this code is relatively simply and comes with some caveats, that might or might not matter to you:

The code will not react to changes in the first 3 seconds after startup, since the timestamp is set to zero initially.
After about 50 days runtime, the millis() counter will overflow. So, if the inner if statement doesn't get triggered for this long, the code will again not be able to react for 3s (until the time has run 3s after the timestamp).


text:
expected primary-expression before ',' token
EDIT: have solved the problem. It was missing the quotation marks around each letter. Thanks for your help, st2000!

I am very new to Arduino and C++ (coding in general!). Have copied an example code, only modifying the notes to make my own tune. But when I click 'verify', I am getting the error above, and I can't for the life of me, work out what is wrong! I've searched and read several forums and FAQs, but am just coming up blank. This is the code I have, where the error is occuring:
  int melody[]={
    a,C,D,
    a,a,C,D,D,C,
    C,C,D,D,C,
    C,D,E,F,E,D,C};

Any help would be greatly appreciated!

Can you provide the source from where you copied the code? Can you provide the wole code? It is hard to tell what is wrong if we don't see the definition of those variables a C D E F.

High likely those notes (a to g, A to G) are either frequency values or mapped frequency values.

I think the same but I question that they have been defined anywhere in the code. Thus leading to the compiler error message.

Guessing, I think the OP has based their project on this example.

So, what is a,C,D, a,a,C,D,D,C? What are these identifiers referring to?

Have you noticed your #define … does not define anything? (well it defines letters but with no meaning except that they are defined)

Close it. It is a question about an error caused by a mere typo

To answer your question we will assume your project is based on the Melody example at www.arduino.cc.
Likely you wanted to enter the ASCII values of these letters into an array of type char (type int would work as well.  But, in some cases, char would be more efficient).  To do this you need to place single quotes around each letter.  Specifically, you need to change your code:
int melody[]={ a,C,D, a,a,C,D,D,C, C,C,D,D,C, C,D,E,F,E,D,C};

...so that your line of code look like this:
int melody[]={'a','C','D','a','a','C','D','D','C','C','C','D','D','C','C','D','E','F','E','D','C'};

This is an assumption that doesn't seem right to me. Storing char-s in an array of int-s is a waste of space.

@Kwasmich, you may be correct.  I think I have see some processor / C compiler combinations which handled 8 bit values as if they were 16 bits.  Wasting memory space in favor of speed.

@st2000: In C, for example. In C language character constants are int value. There's nothing unusual in seeing a C platform with 16-bit int to handle character constants as 16-bit values. That's how C language requires them to be handled.

I have no idea what the above means (yet!), but this solution has worked for me. Thank you :)

@user60325, What a compiler does "behind the curtain" when optimizing code is sometimes confusing.  And is not necessarily the domain of the beginner programmer.  But, if you want to know more this Stack Overflow Q/A (read the answer which starts w/"Let's look at your output...") can get you started.

source: Stack Exchange

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

sort: votes


text:
Trouble with basic communication between two NRF24L01 modules
Introduction
I am trying to setup a radio communication using the NRF24L01 module because I want to use it to control a tank. The first thing I did when I got the modules was watching some basic tutorials on youtube, for reference I watched HowToMecharonics' video: https://www.youtube.com/watch?v=7rcVeFFHcFM
"Arduino Tutorial: Arduino NRF24L01 Wireless Tutorial with Arduino Uno"
At first I tried to rewrite the code myself to see if I got the concept, but all of my attempts failed, so I tried to copy-paste his exact code and use the arduino IDE, but it didn't work.
Later I noticed that the setup only worked if I plugged both arduinos to the PC, they don't work when plugged in a power supply.
The receiver is an arduino MEGA and the transmitter an UNO.
When I unplug the UNO the IDE says "avrdude: ser_drain(): read error: The device does not recognize the command."
Question
If I unplug the receiver it just doesn't work until I plug it back in, but no error pops up.
It seems strange to me that both arduinos have to be plugged yo the computer at al times, am I doing something wrong?
I also noticed that my modules are slightly different from the ones shown in the viedo, mine doesn't have a label below it
Code
TX
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";

void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop() {
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));
  delay(1000);
}

RX
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";

void setup() {
  pinMode(2, OUTPUT);
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
  Serial.println("working");
}

void loop() {
  if (radio.available()) {
    char text[32] = "";
    radio.read(&text, sizeof(text));
    digitalWrite(2, HIGH);
    delay(100);
    digitalWrite(2, LOW);
  }
}

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


text:
availableForWrite() function return error when compiling for Arduino nano 33 BLE
I used availableForWrite() function as below in my code. When I compile it for nano 33 IoT, everything is OK and compiles perfectly. However, when I change the board to nano 33 BLE, I end up with two scenarios:
1. using Arduino IDE as compiler > gives no error but the board doesn't after programming.
2. using the web-based compiler in Arduino website > give the following error:
error: 'class Arduino::USBSerial' has no member named 'availableForWrite'; did you mean 'available'?"

my code:
NoreplyTime=millis();
TimePassed= millis()-NoreplyTime;

         while(!Serial.availableForWrite()){
         TimePassed= millis()-NoreplyTime;
         if (TimePassed>1000){
         return false;
         }
        }

even simply having:
while (!Serial.availableForWrite());

generates error ONLY for nano 33 BLE board!
Thoughts?

"but the board doesn't after programming" What doesn't it? You need to describe further. "web-based compiler in Arduino website" which compiler site with which settings? Maybe the used core in that site does not implement that method

Sorry! I needed to clarify further. After programming nano 33 BLE it seems the CPU can't perform that command line and can't establish a serial connection. Surprisingly there is no problem when I program nano 33 IOT with the same code and it runs it perfectly. It sounds to me that the serial library does not include "Serial.availableForWrite()" command for BLE boards.

The new Arduino cores use a common API maintained in a separate repository. This was copied from AVR core long time ago and doesn't contain some function added later to other cores. The function Stream.availableForWrite was added to Arduino API repository 5 months ago.
For the Arduino Mbed core they created a branch in the Arduino API repository to move the Arduino core in C++ namespace 'arduino'. But this was before availableForWrite was added. So the API version used in Mbed core doesn't have the function.
I reported it as issue. Even if they add the function to API I doubt they add an implementation of it to Serial.

Thanks for the explanation. I am new to programming and have no idea how to help to fix this but in the meantime, I just removed it from my code,and trying to make sure always I have space to receive the data! I have a question, may sound silly, the link you provided for the repository provides installation instructions, should I install it or Arduino IDE did it itself?

@Afshin, the Arduino API is part of the boards package you installed for the Nano 33 BLE


text:
How can I add two different programs of bldc motor and servo motor in one so that they work in parallel?
This is for the servo motor:
#include <Servo.h> //Servo library

Servo servo_test;
//initialize a servo object for the connected servo
int angle = 0;

void setup() {
  servo_test.attach(9);
}

void loop() {
  for(angle = 0; angle < 180; angle += 1) {
    servo_test.write(angle);
    delay(15);
  }
  delay(1000);
  for(angle = 180; angle>=1; angle-=5) {
    servo_test.write(angle);
    delay(5);
  }
  delay(1000);
}

This is for the bldc motor with esc:
#include <Servo.h>

Servo esc_signal;

void setup() {
  esc_signal.attach(12);
  esc_signal.write(30);
  delay(3000);
}

void loop() {
  esc_signal.write(55);
  delay(15);
}

First thing, read the Blink without delay Arduino tutorial, then remove all calls to delay() from your programs.

Actually, this kind of task is not inconsistent with use of blocking delays, but they need to be used with more coordination and care.

Depending on how the code is driven. The simplest would be to simply run loop1 and loop2 in the new loop.

But that would make the code execute serially not in parallel as the OP requested.  You can't do parallel on an Arduino.

Try out this code. It may be helpful.
#include <Servo.h> //Servo library

Servo servo_test;  //initialize a servo object for the connected servo
int angle = 0;

Servo esc_signal;

void setup()
{
  servo_test.attach(9);

  esc_signal.attach(12);
  esc_signal.write(30);
  delay(3000);
}

void loop()
{
  servoFun();
  bldcFun();
}

void servoFun()
{
  for(angle = 0; angle < 180; angle += 1)
  {
      servo_test.write(angle);
      delay(15);
  }
  delay(1000);

  for(angle = 180; angle>=1; angle-=5)
  {
      servo_test.write(angle);
      delay(5);
  }
  delay(1000);
}

void bldcFun()
{
  esc_signal.write(55);
  delay(15);
}

No.  That won't do what is desired at all.

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


text:
RePaper 2.7" eInk Display with Arduino Due
I got a RePaper 2.7' eInk display that unfortunately doesn't support Arduino Mega because of its limited SRAM capacity (8k bytes). I am porting the library to Arduino Due because of its sufficient RAM capacity (96 KB in two banks: 64KB and 32KB).
I am using the thread rePaper - 2.7" Graphic eInk Dev Board Headers  and I've done all the modifications.
Has anyone successfully ported the library to Arduino Due? Also, does anyone have a library for Dynamic Printing for this display?

Can you please provide a link to the source code for Due library? (And also the data sheet for the display would be handy.)

I've got a dynamic image loading project on the Uno (very limited RAM), you can check it out on github https://github.com/Paul-Ver/Arduino_PhotoFrame

You're trying to port the library from the Due to the Mega? If the library is large a "port" just isn't going to happen because relatively minor modifications to the code are very unlikely to shrink the size significantly; you'll need a complete rewrite.
My suggestion is to start by studying the data sheet for the device and the code for the existing Due driver to get an idea of how it works. Then sit down and write some sketches for your Mega that make something happen on the display (perhaps just clearing it, turning on and off a few specific pixels, the like) to verify your understanding. Once you've done that, you can start to consider the design of your driver.
Because of the vastly different memory limitations it's likely that your driver will look and work very differently from the Due driver. For example, a 264 x 176 x 1 bit frame buffer would use almost 6K of RAM (most of the RAM in a Mega 2560 and far more than in an Uno), so you're not going to want to have one. I don't know if the Due driver has a frame buffer (I'm just using this as an example of a typical difference you might encounter), but if it does, and that's used for doing certain kinds of things, you'll need to do them in a different way or not do them at all.
This is not a simple project, but it's a great one and will teach you a lot about microcontroller programming!

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


text:
What is a faster alternative to parseInt()?
I'm making an LED spectrum analyzer with an Arduino Due and my PC. The audio processing is done on the PC, and then sent to the Arduino. The exact data sent is a 'coordinate', or more specifically, a number representing a particular band, and another number representing the maximum amplitude of that band. There are 11 bands. Each coordinate has a x and a y value, separated by a comma, and then sent on a new line.
This is my code as of now:
void loop() {
  if (Serial.available()) {
    xCoord = Serial.parseInt();
    yCoord = Serial.parseInt();
    if (xCoord != 0) {
      int r, g, b;
      for (int i = 0; i < 8; i++) {
        int fromCoordToIndex = ((xCoord - 1) * 8) + i;
        //
        //do some calculations for the color
        //
        strip.setPixelColor(fromCoordToIndex, strip.Color(r, g, b));
        strip.show();
      }
    }
  }
}

The problem is parseInt seems to be very very slow (it's not the timeout issue, it's set to 1). From what I can see, it seems to be skipping some data, so every now and then a band gets missed out. The only way I can fix this is to insert a delay between each coordinate being sent. I found that 40 ms works ok, but remember there are 11 bands, so that means about half a second to refresh the whole board, which feels like a slide show...
I've tried inputting individual characters and then using toInt, I've tried parseInt obviously, I've tried native USB (it's a Due), and I've tried fiddling with baud rates. None seems to have had any effect.

Do you send some form of separator character between your numbers?

@LookAlterno it's not rigid but would take 2 seconds to make it rigid, the format is x,y (including the comma as a separator, and it's sent as a line)

I don't understand what you mean

A much faster alternative is to not require parsing at all. Send binary data instead.

But doesn’t that come out as a string, I’ll still have to parse it to use it won’t I?

And I have some other calculations to do removed from above, will I still be able to do that if they are binary?

MatthewInglis you have to specify the format. That is where to start. Which number can be a byte which numbers are larger, can they be negative, and so on. Once you have specified that, turn it into a fixed/ridig format as @LookAlterno is trying to tell you. After that, you could add a checksum, or STX and ETX (starting and ending markers). Or specify that there is always a LineFeed or CarriageReturn at the end. But first specify the format, edit you question and add that to it.

It's more likely that those calculations you do after you get the data is the slow part. Floating point operations are pretty slow on arduino due to lack of floating point hardware instead prefer fixed point calculations using integral types only.

@ratchetfreak yes, of course, and a timeout of 1ms will make the parseInt abort (depending on baudrate, which we don't know). But we first have to determine the protocol of the serial data.

First hint is to read all the data before processing and displaying. Also avoid sending additional data before the previous is completed. The second is to check the Due hardware serial implementation that it actually is interrupt driven and buffers.

⇒ It is okay to ask this question somewhere else, but don't try to hide that from us. You should have given a link to http://forum.arduino.cc/index.php?topic=508343.0

move strip.show(); out of the loop for a bigger speedup than type conversion overhead

@dandavis good point, thanks, I should have seen that...

The annoying thing about parseInt() is not its speed, it's the fact
that it relies on a timeout. If the timeout is too long, it slows you
down. If it's too short, it may induce errors.
A safer way to parse the sort of messages you are using is to buffer all
the incoming characters until you find a carriage return, then parse the
whole line. For example:
// Just echo the messages with a different separator.
void parse(char *buffer)
{
    char *s = strtok(buffer, ",");
    int x = atoi(s);
    s = strtok(NULL, ",");
    int y = atoi(s);
    Serial.print(x);
    Serial.print(':');
    Serial.println(y);
}

void loop()
{
    static char buffer[BUFFER_SZ];
    static size_t lg = 0;
    while (Serial.available()) {
        char c = Serial.read();
        if (c == '\r') {        // carriage return
            buffer[lg] = '\0';  // terminate the string
            parse(buffer);
            lg = 0;             // get ready for next message
        }
        else if (lg < BUFFER_SZ - 1) {
            buffer[lg++] = c;
        }
    }
}

Note that you should add some error checking when you call strtok().

#include <SoftwareSerial>
SoftwareSerial s1(5,6);

void setup {
s1.begin(9600);
s1.setTimeout(50); //sets the timeout of parseint() to 50ms

}

Please note that lowering the timeout too much can cause errors, i would not go below 10.

Instead of using parseint, send the data for the 11 bands in a very specific form to the Arduino so the Arduino can 'parse' it very easily.
Maybe instead of sending text, send 33 bytes for RGB (3) times 11 bands are the levels (0-255) of the consecutive channels. Than there is no conversion needed (except for reading the bytes).

Well I don't need to send the color, I just need to know how high each band should be. So sending extra values would just be pointless.

In that case 11 bytes would be enough, one value for each band.

Excuse my ignorance, but what exactly do you mean by byte? If each band has a number between (and including) 0 and 13 how do I represent that as a byte?

A byte is 8 bits (8 zero's or ones). WIth a byte (8 bits) you can store a number between 0 and 255 (or 256 different values). You could even send 2 values from 0-13 in one byte by putting by calculating value1 * 13 + value2 (which will always be less than 256). Or more according bits: value1 << 4 + value2... The << operator shifts the bits four to the left, which is equally as multiplying by 16. Value1 will be in the left (MSB) four bits, and Value2 in the right (LSB) four bits. So if your system changes to 16 channels you don't have to change anything (compared to the 11 channels using this).

Ok, so if I send "025" to the arduino with serial, could I use serial.readBytes()? And if I do that, would converting it to an integer be slow like from a string?

Well you can better not send "025"  because that is 3 characters (bytes). You can send for example the first two by 0 * 16 + 2 = 2... so send a byte with value 2 (that's not character 2).

I seem to have fixed it by lowering the baud rate from 115200 to 9600. This answer inspired the change. Apparently, the higher the baud the faster the information is sent, but the higher the likelihood of an error, and the lower the baud rate, the slower it is sent, but the more reliable it is.


text:
Arduino timer ctc mode 4 vs 14
I'm trying to gain an understanding of the Arduino timer and interrupts, particularly the CTC-modes 4 and 12. I wrote a small example in which I generate interrupts while the mainloop sleeps for 1 second and the display how many interrupts occured. It can toggle between mode 4 and 12 with the #if 1.
This works fine for mode 12 ( 50 interrupts/sec ) but in mode 4 it gives -12k interrupts / seconds... unless when I set OCR1A to 39999 again inside the ISR then it does give the expected 50 interrupts/sec, but I'd like to know why.
I think my confusion might be related to not understanding the table-header explaining the modes where it says "Update of OCR1x at". What is meant with that ( who updates it, and to what value? or do I need to update it in the ISR ) ?
Why would OCR1x be updated in mode 12 ( the table seems to state that it is) ? And it seems to work, even if I don't update it...?
Also, the only difference between mode 4 and 12 seems to be the register used for comparing to the timervalue (OCR1A vs ICR1)... but what is so fundamentally different between those? Why are there 2 options and what is the argument to choose for either mode 4 or 12 ?
Update: The issue seems to be related to initialization-order. If OCR1A is set to 39999 at the current location it gets reset to 0 a few lines further. When moving it after TCCR1A = TCCR1B = 0; then OCR1A keeps the value. So it's not necessary to set it on every interrupt.
This also explains why we get -12k counts on mode 4 (because we are comparing OCR1A in that mode, comparing to 0 and generating loads of interrupts)...
Any insight into why the initialization-order matters in this case would be appreciated.
Thanks in advance!

volatile int isr1 = 0;

ISR(TIMER1_COMPA_vect)
{
  // this is called every time our timer-compare matches to ICR1 or OCR1A
  isr1++;

  // when using the #if part below, we need to do this, or we end up with weird values for isr1 ( around -12.000 )
  // If we set it to the original value then we get 50 interrupts per second...
  OCR1A= 39999;
}

void setup() {

  Serial.begin(115200);
  delay(50);

  ICR1 = 39999;                   // 50Hz signal @ 16MHz clock
  OCR1A= 39999;

//TIMSK1 |= 1 << ICIE;            // bit 5: Input Capture Interrupt Enable (execute interrupt when TIFR1.ICF flag is set)
  TIMSK1 |= 1 << OCIE1A;          // bit 4 : Enable the Timer-Output-CompareA-Match Interrupt

  TCCR1A = TCCR1B = 0;            // reset timer-config flags
   // An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCF1A or ICF1 Flag,
   // depending on the actual CTC mode. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value.
#if 1
  // Arduino Datasheet 20.12.2. : The counter value (TCNT1) increases until a compare match occurs with OCR1A, and then TCNT1 is cleared.
  TCCR1B |= 1<<WGM12;             // code 4 (CTC, compare with OCR1A, Immediate update of OCR1x, overflow on MAX)
#else
  // Arduino Datasheet 20.12.2. : The counter value (TCNT1) increases until a compare match occurs with ICR1, and then TCNT1 is cleared.
  TCCR1B |= 1<<WGM13 | 1<<WGM12;  // code 12 (CTC, compare with ICR1, Immediate update of OCR1x(?), overflow on MAX)
#endif

  // using a prescaler of 8, which "slows down" the clockticks by factor 8.
  // 1 clocktick takes 0.5 microseconds, so 39999 clockticks need 19999,5 microseconds
  // 1 second = 1.000.000 microseconds, so we get 50 interrupts per second
  TCCR1B |= 1<<CS11;   // timer CS11 = clki/o/8, 1 tick per 0.5 microseconds
}

void loop()
{
  delay(1000);            // wait 1 second
  Serial.println(isr1);   // print how many interrupts we had in that second
  isr1 = 0;               // and reset for the next second.
}

As described in the operation part of the datasheet section, OC1x is double-buffered; the code sets a shadow buffer to a given value and then at some point the hardware copies the shadow buffer to the register that controls operation. "Immediate" means that the buffer is completely transparent since the value is copied immediately.
The difference between modes 4 and 12 is that mode 4 allows the use of ICP1 for input capture and mode 12 allows the use of OC1A for waveform generation.

Thanks you for your reply but it's still not entirely clear to me.
Mode 4 compares to OCR1A, mode 12 to ICR1.
Printing "OCR1A" to serial output every loop, OCR1A is set to 0 ( for both mode 4 and 12), even though it was  initialize to 39999.
That would explain why in mode 4 ( using OCR1A for comparison) it results in -12423. The timer compares with 0 and basically instantly has a hit and triggers the next interrupt, overflowing isr1.
But why/where is OCR1A being set to zero. I can't find a description of that behaviour in the datasheet.

Which device are you using?

An Arduino-Uno (chinese)

So an ATmega328P?

When uploading: "avrdude: Device signature = 0x1e950f (probably m328p)", so yes... ah it also says " AVR Part: ATmega328P"

Well, I don't see anything in the code or datasheet that would explain this, and I can't test the code out myself ATM. It is possible that the MCU is actually a knockoff, but I can't prove that either.

Let us continue this discussion in chat.

Heh, it seems to be related to the initialization order, if we set OCR1A slightly later it's ok.  So I don't need to set it every time in the ISR, but just "later" on init - for whatever reason...  When moving it after TCCR1A = TCCR1B = 0; then OCR1A keeps the value.


text:
cannot get low power with Adafruit Trinket
I want to get as low power use during sleep as possible with an Adafruit Trinket. Based on results presented on various places in the internet (blogs etc), I expect to be able to go down to 50 - 100 micro amps on the ATTiny85 of the Trinket. I am aware of the fact that using a board such as Trinket may add a bit of consumption, and I physically removed the power LED and the power regulator. I am feeding 5V directly on the 5V pin.
I am using the simplest sketch I can think about for low power, with nothing connected to any pin:
#include <avr/sleep.h>          // library for sleep

#define adc_disable() (ADCSRA &= ~(1<<ADEN)) // disable ADC (before power-off)

void setup() {
  // put your setup code here, to run once:
  delay(10000);

  // power_all_disable();
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  adc_disable();
  sleep_enable();
  sleep_mode();

}

void loop() {

}

But I cannot get less than around 1.3 milli amps consumption during sleep. Do you know what may be the cause of using ~1mA instead of ~100 microA? Any idea how I can decrease this further?
Edit 1: it should be even much less than ~50 - 100 micro Amps: ATtiny85: Power consumption vs clock speed ; even though this the libraries are maybe primary intended for the ATMega328P, it looks like it should work also with ATTiny85 as well: http://www.technoblogy.com/show?KX0
Edit 2: I had an ATMega328P-based Adafruit Metro Mini lying around. I took away the ON LED, and then using exactly this sketch, feeding power directly on the 5V pin of the Metro Mini, leads to a power consumption of around 150 micro Amps during sleep, which is more like what I expect. Strange it is 10 times more with the ATtiny while it should have been less (?). Am I missing something or is it maybe just broken library on ATtiny? This is a bit ironic, as I went for the lesser ATtiny85 based board for saving current compared with the ATMega328P...

Are you waking from sleep? Are you taking into account the 10 seconds at the start when it's running on full power?  Put something in loop() that could indicate that it's woken up (maybe turn on an LED or something).

I know that it is awake for the first 10 seconds (then power consumption is about 13 mA), after this period the power consumption drops to the 1.3 mA I was mentioning. ;)
I could of course wake it up with the watchdog, but I do not think this is the point of this sketch; I only want to measure sleeping power consumption, so I think getting it to sleep in the setup and letting it sleeping is ok. I also got it to sleep in the main loop in another sketch, get similar results.

A trinket uses an ARM core processor.  Getting the power down is not trivial.  You probably have hours of reading the Atmel then the ARM core specifications before you start in on designing your own "sleep / low-power" Arduino libraries.  At which point you can start contributing back to the effort of improving the ARM BSP software for Arduinos as they are (were?) full of bugs.

@st2000: ok, that sounds a bit strange as http://www.gammon.com.au/power gets to the micro-amps domain while using just the standard libraries (and I think the same chips architecture), but I may be missing something?

Sorry, my bad, the trinket uses an Atmel ATtiny85.  Still, your link to the power web page says it is intended for the Atmega328P.  Also, I am not sure the BSP is the same for these 2 processors.  You might check on that to make sure you are not up against using 2 different version of sleep libraries.  One for each processor.

No problem ;) I agree, the link to Nick Gammon says it should be for ATMega328P, but I use it with ATtiny. However, it looks like this code should work also on the ATtiny: http://www.technoblogy.com/show?KX0 https://forum.arduino.cc/index.php?topic=372982.0

If you're serious about low power, you should probably look directly to the device data sheet and verify that everything you don't need is turned off, like ADCs, voltage references, etc.  Divide the clock if possible.  Shut down clocks you don't need.  Also, at tiny currents, you have to worry about power being supplied or taken by I/O pins, and things like the burden voltage of your meter.  Often it's hard to get a meter to both pass the run current and measure the sleep current!

Ok, fair enough for the need to go through the datasheet for very low power. But still, it is a bit strange / sad i cannot get to the 100s of microamps domain.

Please have a look at the schematics:
https://cdn-learn.adafruit.com/assets/assets/000/010/774/original/adafruit_products_trinket5.png?1378223478
The USB connector uses a resistor (1500 Ohms) against the 5V net and a 3.6 Volt Z-Diode on it's (D-)-Pin. In addition to the current that is drawn by the microcontroller, this part of the circuit draws some extra current. (5[V] - 3.6[V])/1500[ohm] = 0.0009333... ~= 0.001 [A].
Even though I'm not completely sure without making some tests, that seams plausible to me.
EDIT
(Answer to the OPs comment below.)
The schematics uses a normal diode symbol but has a 3.6 Volt label next to it. I assume that it should be a Zener diode with a reverse voltage drop of 3.6 Volts. If I'm right, the Diode is used to limit the 5 Volts to 3.6 Volts (for what reason ever). The Zener Diode effectively limits  the Voltage over it to 3.6 Volts. The rest of the voltage of 5 Volts must be dropped over the resistor. i.e. 5V - 3.6V = 1.4V. This voltage drop tells us  by Ohms Law that the current through the  resistor is:
I = U / R
I[A] = 1.4[V] / 1500[Ohm]  = (about) 1 mA.

This value is very reasonable for your observations and the current is drawn from the 5V connect, hence you can measure it, even if you would desolder the microcontroller.

Mmmh, it looks like this diode is going against the polarity provided by the +5V and is here only to protect the pin or something like this, right? It should not be able to draw current from the 5V I think (?).

@Zorglub29:  I've edited the answer in reply.

Many thanks for the explanation, you are definitely right :) Very strange that 1) the drawings are using the 'wrong' symbol 2) they use such a circuit on a 'low power' board. Will contact Adafruit. Why do you think they decided to use a set voltage on this pin?

I guess they use the USB connetion to a 5V controller that has no native USB port. It is common to limit the Voltage on the D- and D+ pins of the USB connect to stay within the specifications. As far as I know does Adafuit recomment to use the newer M0 (ARM) Trinket. (Guess why! ;-) ) My favorit microcontrollers are the MSP430 / MSP432 series from Texas Instruments. That's real low Power. ;-) And the Energia IDE is nearly the same as the Arduino IDE. (Although I use an Eclipse based IDE, so I have not much experience). I heard the STM32 s (e.g Blue Pill) are also very low power devices.


text:
Arduino not recognizing when a timer reaches 0
Alright, so I'm attempting to make a timer that will turn on a light after an hour. Currently I have it set to 5 seconds for testing. What is happening is whenever I start the program it won't recognize when the timer reaches 0.
Here is my code
/*
Hour Alarm
An hour long alarm that allows breaks
Created by: Jaxon Reid
Last Edited: 19/5/2017

Pins:
Pin 13 = Led
Pin 2 = Button
*/
int secLeft=5;
const int led=13;
const int button=2;
const int buttonIn=4;
int buttonValue=0;
// Declares the button to reset as 2 and the lightbulb on pin 13
//the secLeft means the seconds until the light turns on and button value is for wether or not the button is pushed

void setup() {
  Serial.begin(2400);
  Serial.print("On  ");
  pinMode(13,OUTPUT);
  pinMode(button,OUTPUT);
  pinMode(buttonIn,INPUT);
}
// makes the led pin an input and opens the channel for the debugger
void loop() {
  int buttonValue=digitalRead(button);
  Serial.println("Checking time");
  if (secLeft<=0) {
    Serial.println("No time remaining");
    digitalWrite(13,HIGH);
    Serial.println("Light On");
    // If the time remaining is 0 then turn on the light
  }
  if (secLeft>0) {
    Serial.println("Time Remaining");
    digitalWrite(led,LOW);
    secLeft=(secLeft--);
    Serial.println(secLeft);
  }
  if (buttonValue==1) {
    int secLeft=5;
    Serial.println("Reset Timer");
    Serial.println(secLeft);
  }
  delay(1000);
}

Whenever I start it up it just starts reading
On 5
Checking time
Time remaining
5
Checking time
Time remaining
4
Checking time
Time remaining
3
Checking time
Time remaining
2
Checking time
Time remaining
1
Checking time
Time remaining
0
Checking time
Time remaining
-1
Checking time
Time remaining
-2

etc...
So where did I go wrong is what I'm asking.
Thanks!

The problem is int secLeft=(secLeft2--); where you are creating a second variable called secLeft within the scope of the if block.  Ditch the int.  This is the second question I have seen with this issue in the last 30 minutes.  You probably also have the same issue with secLeft2

Now its not decreasing the secLeft at all

Noter that you still have an int secLeft in the reset section

As per comment and Majenko's answer you are current creating local variables called secLeft and secLeft2 inside the 'if block.  These take precedence over the ones you have defined globally.  Removing the in declarations from inside the if block will stop doing that and point you at the globally defined variables.
As to the rest of the code. If you have
secLeft=(secLeft2--);
secLeft2=(secLeft);

Then that translates to this sequence of instructions

Assign secLeft with the value of secLeft2
Decrement secLeft2
Assign secLeft2 with the value of secLeft

And in the end you do not change anything.
This is because you are using post-decrement on secLeft2  EG secLeft2--.  This is a feature of C style languages.
I am not sure what you are even trying to do at this point.

Got it thankyou I was thinking it would decrement beforehand

To get pre-decrement you have to do --secLeft.  C and C++ have both and they are both useful in their own way.

int secLeft=(secLeft2--);
int secLeft2=(secLeft);

You are making 2 new variables there instead of using the existing ones.

alright how do i fix that?

By not declaring new variables.

I have picked this up yesterday i learned C++ yesterday aswell what do i remove?

Remove the int from each line. Also, do you really want to reset secLeft2 to what it was before decrementing it? The second line looks a bit daft.

Now i just get 5,5,5,5,5 ...

Edit your question and add your updated code to the end so we can see what you have done.

I think you are getting muffled with your variables. There is no reason for secLeft2 to even exist.

I created secleft 2 cause before when i had secLeft=(secLeft--) i was afraid it was looping and reducing it to 0 immetiately btw codes updated

That format is incorrect but not wrong.  It has a redundant assignment since secLeft-- subtracts one and saves the result.

Besides problems mentioned in other answers, your use of button and buttonIn variables is messed up.
With button equal to 2, the pinMode(button,OUTPUT) statement initializes pin 2 to be an output.  Pin 2 is low after reset and pinMode() doesn't change it.
When you say int buttonValue=digitalRead(button); the low value at pin 2 will be read into buttonValue.  In the sketch, buttonValue will never be anything but low.
To fix this problem, get rid of buttonIn, and in setup() use pinMode(button,INPUT) to set button to be an input, not an output.


text:
ESP12E motorshield analogWrite issue when powering DC motor
I am relatively new to adruino and this whole space. I am currently trying to power a DC motor using an ESP12E motor shield and an ESP8266 Module
Motor Shield - https://www.amazon.com/gp/product/B078CPZDW1/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1
ESP8266 - https://www.amazon.com/gp/product/B010O1G1ES/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1
DC Motor - https://www.amazon.com/gp/product/B07MTT7B88/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1
Here is my code
#define DIRA 0
#define PWMA 5
#define LED 2

void setup() {
  Serial.begin(9600);
  Serial.println();
  Serial.println("Starting...");

  Serial.println("Preparing motor...");
  pinMode(DIRA, OUTPUT);
  pinMode(PWMA, OUTPUT);
  analogWrite(PWMA,0);
  digitalWrite(DIRA,1);
  delay(5000);

  Serial.println("Starting motor...");
  analogWrite(PWMA,5);
  delay(5000);

}

void loop() {
}

Here is how I have wired it up

Note: This setup is similar to what I have but not exactly, I have 4 AA batteries connected and only 2 motors
I am expecting the motor to start once I upload this code but nothing is happening. If I change the analogWrite to digitalWrite, the motor runs but I want to be able to control the speed, rather than just having it run at one speed.
I have tested using analogWrite by changing the intensity of an LED and it was working, although the output pin was not the same as the one I use for the motor.
Would greatly appreciate any help as I have already gone through pages of google searches without any luck. I have been using this example as a reference, https://hackaday.io/project/8856-incubator-controller/log/29291-node-mcu-motor-shield.

5 is nowhere near big enough to get the motor out of its stalled state.

You've connected 2 Motors to the output and drive these two motors with about 2% of the full Voltage. As @Majenko stated, that's not enough power to start two motors. I do not know your Max Voltage ( two batteries but are these normal 1.2 Volt accus or ~4 Volt LiPos or ...). Say you have max 8 Volt, your motor starts with 1.5 Volt then you need at least 5-6 % better 10% of the max Voltage which you can regulate with the PWM duty cycle. You used analogWrite(PWMA,5); I would suggest analogWrite( PWMA, 25 );.

@PeterPaulKiefer I tried with 4 1.5v AA batteries with two motors and one motor. This picture isn't my exact setup but pretty close, only difference is the number of batteries I have attached (4) and the number of motors (2). My mistake for not pointing that out, I have updated the details. I also tried analogWrite(PWMA, 10), analogWrite(PWMA, 50), analogWrite(PWMA, 100) but still nothing

Sorry I made a mistake. The max value for analogWrite is  1023 not 255. You powered the shield with about 6 Volts. To be sure, you should uses at least 3 Volts to drive the motors. Use a duty cycle of 50% `analogWrite(PWMA, 512);. A value of 100 is just 10% (i.e. a mean voltage of about 0.6 Volts.) If this is still not enough, try if the motors run if you connect them to 2 or 3 of your batteries directly. If not, you batteries might be discharged or the motor is defect. If the motor runs with direct connected batteries, the shield might be defect. Have you tried the 2nd motor too?

@PeterPaulKiefer you were right! Once I increased the analogWrite to 512 the motor started spinning. Thank you so much!

This answer is the summary of the comments of the question. The idea of the solution was originally mentioned by @Majenko.
You powered the shield with about 6 Volts. The statement analogWrite(PWMA, 5); gives you (5/1024) ~ 0.5% of this 6 Volts at the output pin PWMA. This 0.03V are not enough to drive the motor.
You should use at least 3 Volts to drive the motor (as of the specs).
This can be achieved by using a duty cycle of the PWM signal of about 50%.  analogWrite(PWMA, 512); should do the trick.


text:
GPS Speedometer value didnt come out
I'm building a GPS speedometer. I use Neo-6M module for GPS, Arduino uno and 128x64 OLED screen for monitoring the value. I've checked the GPS module. It gives me data about latitude and longitude. But on the OLED screen it didnt come out value. I NEED HELP. this is the code.
    /*
  Connections:
  GPS TX -> Arduino 0 // Disconnect Arduino 0 to upload this sketch
  GPS RX -> Arduino 1
  Screen SDA -> Arduino A4
  Screen SCL -> Arduino A5
*/

#include "U8glib.h" // Call U8glib library to control OLED screen

U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_DEV_0|U8G_I2C_OPT_NO_ACK|U8G_I2C_OPT_FAST); // Fast I2C/TWI
static const int RXPin = 3, TXPin = 4;
static const uint32_t GPSBaud = 9600;

#define GPS Serial // Define the serial connection as the GPS module

const unsigned char UBLOX_INIT[] PROGMEM = {
  // These lines of code request data from the satellites. Most are disabled and turned off.
  // Disable NMEA
  0xB5,0x62,0x06,0x01,0x08,0x00,0xF0,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x24, // GxGGA off
  0xB5,0x62,0x06,0x01,0x08,0x00,0xF0,0x01,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x2B, // GxGLL off
  0xB5,0x62,0x06,0x01,0x08,0x00,0xF0,0x02,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x32, // GxGSA off
  0xB5,0x62,0x06,0x01,0x08,0x00,0xF0,0x03,0x00,0x00,0x00,0x00,0x00,0x01,0x03,0x39, // GxGSV off
  0xB5,0x62,0x06,0x01,0x08,0x00,0xF0,0x04,0x00,0x00,0x00,0x00,0x00,0x01,0x04,0x40, // GxRMC off
  0xB5,0x62,0x06,0x01,0x08,0x00,0xF0,0x05,0x00,0x00,0x00,0x00,0x00,0x01,0x05,0x47, // GxVTG off

  // Disable UBX
  0xB5,0x62,0x06,0x01,0x08,0x00,0x01,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x17,0xDC, // NAV-PVT off
  0xB5,0x62,0x06,0x01,0x08,0x00,0x01,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x12,0xB9, // NAV-POSLLH off
  0xB5,0x62,0x06,0x01,0x08,0x00,0x01,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x13,0xC0, // NAV-STATUS off

  // Enable UBX—this is the key information we require
  0xB5,0x62,0x06,0x01,0x08,0x00,0x01,0x07,0x00,0x01,0x00,0x00,0x00,0x00,0x18,0xE1, //NAV-PVT on
  //0xB5,0x62,0x06,0x01,0x08,0x00,0x01,0x02,0x00,0x01,0x00,0x00,0x00,0x00,0x13,0xBE, //NAV-POSLLH on
  //0xB5,0x62,0x06,0x01,0x08,0x00,0x01,0x03,0x00,0x01,0x00,0x00,0x00,0x00,0x14,0xC5, //NAV-STATUS on

  // Rate
  0xB5,0x62,0x06,0x08,0x06,0x00,0x64,0x00,0x01,0x00,0x01,0x00,0x7A,0x12,    // (10Hz)
  //0xB5,0x62,0x06,0x08,0x06,0x00,0xC8,0x00,0x01,0x00,0x01,0x00,0xDE,0x6A, // (5Hz)
  //0xB5,0x62,0x06,0x08,0x06,0x00,0xE8,0x03,0x01,0x00,0x01,0x00,0x01,0x39  // (1Hz)
};

const unsigned char UBX_HEADER[] = { 0xB5, 0x62 };

struct NAV_PVT { // This sets the GPS navigation data
  unsigned char cls;
  unsigned char id;
  unsigned short len;
  unsigned long iTOW; // GPS time of week of the navigation epoch (ms)

  unsigned short year;     // Year (UTC)
  unsigned char month;     // Month, range 1..12 (UTC)
  unsigned char day;       // Day of month, range 1..31 (UTC)
  unsigned char hour;      // Hour of day, range 0..23 (UTC)
  unsigned char minute;    // Minute of hour, range 0..59 (UTC)
  unsigned char second;    // Seconds of minute, range 0..60 (UTC)
  char valid;              // Validity Flags (see graphic below)
  unsigned long tAcc;      // Time accuracy estimate (UTC) (ns)
  long nano;               // Fraction of second, range -1e9 .. 1e9 (UTC) (ns)
  unsigned char fixType;   // GNSSfix Type, range 0..5
  char flags;              // Fix Status Flags
  unsigned char reserved1; // Reserved
  unsigned char numSV;     // Number of satellites used in Nav Solution

  long lon;           // Longitude (deg)
  long lat;           // Latitude (deg)
  long height;        // Height above Ellipsoid (mm)
  long hMSL;          // Height above mean sea level (mm)
  unsigned long hAcc; // Horizontal Accuracy Estimate (mm)
  unsigned long vAcc; // Vertical Accuracy Estimate (mm)

  long velN;                // NED north velocity (mm/s)
  long velE;                // NED east velocity (mm/s)
  long velD;                // NED down velocity (mm/s)
  long gSpeed;              // Ground Speed (2-D) (mm/s)
  long heading;             // Heading of motion 2-D (deg)
  unsigned long sAcc;       // Speed accuracy estimate
  unsigned long headingAcc; // Heading accuracy estimate
  unsigned short pDOP;      // Position dilution of precision
  short reserved2;          // Reserved
  unsigned long reserved3;  // Reserved
};

NAV_PVT pvt;

void calcChecksum(unsigned char* CK) {
  memset(CK, 0, 2);
for (int i = 0; i < (int)sizeof(NAV_PVT); i++) {
  CK[0] += ((unsigned char*)(&pvt))[i];
  CK[1] += CK[0];
  }
}

long numGPSMessagesReceived = 0;

bool processGPS() {
  static int fpos = 0;
  static unsigned char checksum[2];
  const int payloadSize = sizeof(NAV_PVT);

  while ( GPS.available() ) {
    byte c = GPS.read();
    if ( fpos < 2 ) {
      if ( c == UBX_HEADER[fpos] )
        fpos++;
      else
        fpos = 0;
  }
  else {
    if ( (fpos-2) < payloadSize )
      ((unsigned char*)(&pvt))[fpos-2] = c;

    fpos++;

    if ( fpos == (payloadSize+2) ) {
      calcChecksum(checksum);
    }
    else if ( fpos == (payloadSize+3) ) {
      if ( c != checksum[0] )
         fpos = 0;
    }
    else if ( fpos == (payloadSize+4) ) {
      fpos = 0;
      if ( c == checksum[1] ) {
        return true;
      }
    }
    else if ( fpos > (payloadSize+4) ) {
       fpos = 0;
     }
   }
 }
 return false;
}

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

  u8g.setColorIndex(1);

 // Send configuration data in UBX protocol
 for (unsigned int i = 0; i < sizeof(UBLOX_INIT); i++) {
   GPS.write( pgm_read_byte(UBLOX_INIT+i) );
   delay(5); // Simulate a 38400baud pace (or less),
             // or otherwise commands are not accepted by the device

  }
}

long gSpeed = 0;
int numSV = 0;
unsigned long lastScreenUpdate = 0;
char speedBuf[16];
char satsBuf[16];

char* spinner = "/-\\|"; // Symbol for the spinner on screen to
                         // show communication
byte screenRefreshSpinnerPos = 0;
byte gpsUpdateSpinnerPos = 0;

void loop() {
  if (processGPS()) {
    numSV = pvt.numSV;
    gSpeed = pvt.gSpeed;
    gpsUpdateSpinnerPos = (gpsUpdateSpinnerPos + 1) % 4;
  }

  unsigned long now = millis();
  if (now - lastScreenUpdate > 100) {
     updateScreen();
     lastScreenUpdate = now;
     screenRefreshSpinnerPos = (screenRefreshSpinnerPos + 1) % 4;
  }
}

void draw() {
  u8g.setFont(u8g_font_courB24);
  u8g.drawStr( 36, 45, speedBuf);
  u8g.setFont(u8g_font_fur11);
  u8g.drawStr( 2, 12, satsBuf);
}

void updateScreen() {

  int kmh = gSpeed * 0.0036;
  sprintf(speedBuf, "%3d", kmh);
  sprintf(satsBuf, "%c %c %d", spinner[screenRefreshSpinnerPos], spinner[gpsUpdateSpinnerPos], numSV);

  u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );
}![enter image description here](https://i.sstatic.net/Asw5t.jpg)![This is what it shown on my OLED but the value didnt change]

run OLED example code

What have you tried to debug the code? Can you display literal text? Does the data get correctly read by the Arduino? What is actually happening on the display? (Really nothing, or just not the correct data) Please give us more information

Instead of tackling two potential problems at once, do it one after the other. 1. Make sure you that you received the position correctly. You may use the serial connection and the IDE's serial monitor for this. 2. Make sure that you can write arbitrary contents on the display.


text:
RPM measurement using quadrature encoder
I am trying to build a RPM controller for my project. I am using a quadrature encoder (ppr=400) and Arduino Uno for this purpose. I am using the code given below inorder to caluculate the RPM of the DC motor. I get a reading on my serial Monitor. However, this RPM doesn't match with my manual calculation (i.e when I calculate the RPM Manually using a stop watch- for lower speeds).
EDIT-> Eg- Manually I get around 10 RPM, but my program shows 60 and more.
I have used one interrupt pin on my Arduino UNO.
#define encoder0PinA  2
#define encoder0PinB  3
int power=6; // to power up the encoder
int gnd=4;  // to provide ground to the encoder
int motor=11; //motor PWM pin
int dir=10;
volatile unsigned int encoder0Pos = 0;

void setup() {
  pinMode(encoder0PinA, INPUT);
  digitalWrite(encoder0PinA, HIGH);       // turn on pull-up resistor
  pinMode(encoder0PinB, INPUT);
  digitalWrite(encoder0PinB, HIGH);       // turn on pull-up resistor
  pinMode(power,OUTPUT);
  pinMode(gnd,OUTPUT);
  digitalWrite(power,HIGH);
  digitalWrite(gnd,LOW);
  pinMode(motor,OUTPUT);
  pinMode(dir,OUTPUT);
  digitalWrite(dir,LOW);

  attachInterrupt(0, doEncoder, RISING);  // encoder pin on interrupt 0 - pin 2
  Serial.begin (9600);
  Serial.println("start");    // a personal quirk
  analogWrite(motor,120); // to set a particular test RPM to the motor.
}

void loop() {
  encoder0Pos=0;
  delay(1000);
  float rpm=encoder0Pos/(400);
  Serial.println(rpm);
}

void doEncoder() {

  encoder0Pos++;
  }

Also I tried the very first code on the following link "https://playground.arduino.cc/Main/RotaryEncoders".. In this case my Arduino stops transmitting completely. I tried the same code on one of my friend's setup.. surprisingly it works there.
Can't understand where I am going wrong... Is my coding approach correct?? Please enlighten me...
Thank you.

When you say your calculation doesn't match -- please describe the values each produces. There are many ways in which something can "not work"

sure sir, I will edit it ASAP.

Is your quadrature encoder optical or mechanical?

It's an optical quadrature encoder

Encoder link- https://m.aliexpress.com/item/32816515228.html

Ensure the encoder outputs 400 pulses on each phase. It could be 200 on each phase for one rotation
Rather then clearing your pulseCount, figure out the time it take to make one rotation (as close as you can tell) and turn the motor on for only that amount of time, and then off again. This will allow you a more controlled environment to test your code in, and it will be the same(almost) every time.
You are calculating revolutions per second with your code, not per min
number of pulses/400(if this is correct number)=Revolutions     which you are clearing ever 1000ms
Ensure good connections on your wiring as it does not take much to allow the interrupt to fire twice when it should have only fired once.
Use the second phase of the encoder, this is what gives the ability to decipher bad signals and change of dirrection,   ie- multiple A pulses in a row(without any B pulse) does not equal movement, it means either the motor is hanging out right on a phase line, or something is causing the interrupt to fire more often then it should.

Why is the code from Arduino playground not working?

Getting direction is not an issue for me... Getting Rpm or RPS is my main concern..


text:
Sending Float values from Python to Arduino via serial communication
I want to Control the current flowing through a circuit using an Arduino. I have trained a PID controller for this purpose. I am using a current sensor to determine the error. It runs successful on my Arduino.
In my next step I want build a system where I can send the Current setpoint (deter mined by my python code) value to the Arduino through serial communication. I am able to send integer values to Arduino. But I am unable to send and receive float values from Python to Arduino. I want to know the necessary code to be written in both sender and receiver.
I tried of converting float to string and then send it to Arduino. But I failed. Please help.
Arduino Code(edit- Sorry previous code was an old file. Here is the correct one):
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
//pinMode(13,OUTPUT);
}
float f;

void loop() {
 if(Serial.available())
      {f=Serial.parseFloat();
        Serial.println(f);
      }
    delay(1000);
   }
//count=count+1;
      //delay(1);
//}

Python Code (edit- Sorry, the previous code was from an old file. Here is the correct one):
import serial
import time
import struct

ser = serial.Serial('/dev/ttyACM0', 9600, timeout = 1) # ttyACM1 for Arduino board
data=5.7

while True:
        ser.write(str(data))
        time.sleep(1)
        ser.flush()

When I run this code I get the following output on the Arduino Serial Monitor. As shown in the figure below.

Thank you.

Start by removing the "delay(1000);" in loop(). Why would you want that? And change the order of "time.sleep(1)" and "ser.flush()". Last but not least add a space character between writing numbers.

@Mikael Patel... Thank you for the response. It works. Thanks again.

You are sending 5.75.75.75.75.75.75.75.75.75.7.

It would seem you managed to solve your problem with
Serial.parseFloat(). This is probably the easiest solution, but it has
one serious drawback: it is a blocking function. Which means, during
all the time needed by the serial port to transfer the number, your
Arduino does nothing but wait for the incoming characters. This is an
issue if your program has other task to do like, e.g., manage a PID
regulation.
I suggest you consider reading the serial port in a non blocking
fashion instead. This should make your PID happier, as it won't feel
neglected while you read the incoming data. Look Alterno's answer is a
good example of a non-blocking function that combines reading and
parsing. However, I would like to point out that you do not need to
implement your own number parser if you don't want to. A very common
pattern is to instead store the incoming characters in a buffer and,
when you see the character chosen as a terminator (e.g. ASCII LF), you
parse the buffer at once using either strtod() or atof(). For
example:
void setup() {
    Serial.begin(9600);
}

void loop() {
    static char buffer[32];
    static size_t pos;
    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\n') {  // on end of line, parse the number
            buffer[pos] = '\0';
            float value = atof(buffer);
            Serial.print("received: ");
            Serial.println(value);
            pos = 0;
        } else if (pos < sizeof buffer - 1) {  // otherwise, buffer it
            buffer[pos++] = c;
        }
    }
}

Well sir, even this code has the same outcome as that of Alterno's code. The serial monitor is just empty. Again my python code is still the same.

@CR7: Your Python code is buggy: it fails to send a line terminator. You should ser.write(str(data) + "\n").

Thank you sir, it works. Takes less time too. Thanks once again.


text:
Custom bootloader for battery level indicator
For a project I need to be able to read the battery level of the device regardless of the sketch currently running.
For this I plan on adding a custom routine in the Arduino bootloader that reads the battery level and shows it can be accessed even when the current sketch is overwritten with another sketch.
Is creating a custom bootloader a good solution for this? If so how should I go about create that bootloader?
Edit:
The battery level will be shown using 3 leds indicator every time a specific button is pressed; I don't want to store the battery level. I need this to happen in every sketch, that's why I think I should do this on the bootloader, having that code on the sketch isn't an option. This is needed because I am developing a custom board and this function will be default on each board.

How should be battery level be shown/accessed? And when? When you use a bootloader, it will only work while the bootloader is running

You will have to store the battery level somewhere safe. In the EEPROM for example. Then you can access it afterwards. So to me this sounds feasible. Even I don't understand why I has to live inside the bootloader. Is it supposed to prevent the sketch from being executed on low battery?

With out knowing the overall goal this is difficult to solve. Sure you could spend time to understand and modify the boot loader.  But the resulting code will likely leave less memory for the application. On top of that, @chrisl is correct, the application & boot loader do not run at the same time. This is not a real OS. So no new battery measurements unless you waste space duplicating the code or figure out a way to jump to boot loader code from the Application. Instead, consider using a 2nd Arduino to measure the battery level.  A much simpler and cheaper approach if this is a 1 off project.

if your Arduino board uses a second microcontroller for the USB interface, then you could use that for your battery monitor


text:
SD Card and Lora module arduino uno
Background: When working on the 2 modules separately they were working perfectly.
Problem: In the code attached we tried integrating them but Lora wouldn't receive any data unless we commented out parts of the SDC function. Is there a fix to this?
This is where the problem occurs:
Serial.print("Data received: ");
 Serial.print(received);

 if(received=="ANEMO"){

No matter how much we feed it with TRUE data from another Lora with these codes it simply shows blank and false.
Please Help this poor lamb. This for our school project. Hopefully, you can spare me some of your time. Thank you so much in advance.
for the CS pins:
Lora: pin 10,  SD: pin 5
other SPI pins follow the standard pins.
PS: In the code, we have commented out some of the lines within the SDC function as based on our observation:
myFile = SD.open("HG.txt", FILE_WRITE);
   myFile.close();

These 2 lines are the ones causing our Lora to not display the data it is receiving in the (String receive variable).
Thank you, good sir/ma'am, once again hopefully you can assist me.
Here is the complete code:
#include <SPI.h>
#include <SD.h>
#include <RH_RF95.h>
#define RFM95_CS 10
#define RFM95_RST 9
#define RFM95_INT 2
#define RF95_FREQ 868.0
RH_RF95 rf95(RFM95_CS, RFM95_INT);
unsigned long millisecs;
int cnt;
float valu;
String jh;
int code=1;
String received;

File myFile;

void setup(){
 Serial.begin(115200);
 if (!SD.begin(5)) {
    Serial.println("Card failed, or not present");
    while (1);
  }
  else{
  Serial.println("card initialized.");
  }

  delay(100);

 pinMode(RFM95_RST, OUTPUT);
 digitalWrite(RFM95_RST, HIGH);
 while (!Serial);
 Serial.println("Arduino LoRa RX Test!");
 digitalWrite(RFM95_RST, LOW);
 delay(10);
 digitalWrite(RFM95_RST, HIGH);
 delay(10);
 while (!rf95.init()) {
 Serial.println("LoRa radio init failed");
 while (1);
 }
 Serial.println("LoRa radio init OK!");
 if (!rf95.setFrequency(RF95_FREQ)) {
 Serial.println("setFrequency failed");
 while (1);
 }
 Serial.print("Set Freq to: "); Serial.println(RF95_FREQ);
 rf95.setTxPower(23, false);
}

void lorA(){
  while(code==1){
if (rf95.waitAvailableTimeout(1000)){
 Serial.println("dayun ");
 uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
 uint8_t len = sizeof(buf);
 if (rf95.recv(buf, &len)){
 cnt++;
 Serial.print("Data number: ");
 Serial.println(cnt);
 received=(char*)buf;
 Serial.print("Data received: ");
 Serial.print(received);

 if(received=="ANEMO"){
 uint8_t data[] = "And hello back to you";
 rf95.send(data, sizeof(data));
 rf95.waitPacketSent();
 Serial.println("Sent a reply");
 code=0;
 }
 }
 else{
 Serial.println("Receive failed");
 }
 }
 }
 }

void SDC(){
  while(code==0){
  Serial.println("SDC");
//  File dataFile = SD.open("HG.txt", FILE_WRITE);
//  String dataString="Hans";
//  if (dataFile) {
//  dataFile.println(dataString);
//  dataFile.close();
//    Serial.println("closed");
//    Serial.println(dataString);
    code=1;
//  }
//  else {
//    Serial.println("error opening datalog.txt");
//  }

  }
  }

void loop(){
  Serial.println("loop");
  lorA();
  Serial.println("mid");
  SDC();
}

what does TRUE data mean? .... you have a lot of print statements in your code but i see no mention of the printed data in your post ..

Sir, I'm sorry. Allow me to clarify, by TRUE what I meant was for the condition "if(received==" ANEMO")". If you notice on the complete code if the condition is satisfied the code is supposed to print "Sent a reply" but in our case, it didn't happen and we suspect the SD card code to be the one affecting it. We came to this idea as we tried commenting out some line of the SDC function(function for SD card) specifically the "myFile = SD.open("HG.txt", FILE_WRITE)". After we commented it out the Lora started working properly again such that when it receives ANEMO in the serial it displays Sent.

most SD modules disturb the SPI bus and other SPI devices not work with them

Damn sir/ma'am... That's going to be a huge problem. Aren't there any workarounds for the problem? Anyways thank you, sir/ma'am.

all of your problem can be solved through a simple trick ... Just follow it...

Use Sdfat library insted of SD
just follow SPI datasheet..

follow below code ... it works with LORA AND SD both together
...

#include <SdFat.h>
#include <SPI.h>
#include <RHReliableDatagram.h>
#include <RH_RF95.h>

SdFat sd;
SdFile myFile;

#define chipSelect 4

#define RFM95_CS 10 //
#define RFM95_RST 9
#define RFM95_INT 2

// Singleton instance of the radio driver
RH_RF95 rf95(RFM95_CS,RFM95_INT);
//RH_RF95 driver(5, 2); // Rocket Scream Mini Ultra Pro with the RFM95W

// Class to manage message delivery and receipt, using the driver declared above
RHReliableDatagram manager(rf95, 2);

void setup() {

  Serial.begin(9600);
  while (!Serial) {}  // wait for Leonardo

  delay(100);

  // Initialize SdFat or print a detailed error message and halt
  // Use half speed like the native library.
  // change to SPI_FULL_SPEED for more performance.
  pinMode(RFM95_CS, OUTPUT);
  digitalWrite(RFM95_CS, HIGH);
  digitalWrite(4, LOW);

  if (!sd.begin(chipSelect, SPI_HALF_SPEED)) sd.initErrorHalt();

/*

/*
 * //Open file and write  ...
 *
  // open the file for write at end like the Native SD library
  if (!myFile.open("mrinmoy.txt", O_RDWR | O_CREAT | O_AT_END)) {
    sd.errorHalt("opening test.txt for write failed");
  }

  // if the file opened okay, write to it:
  Serial.print("Writing to test.txt...");
  myFile.println("testing 1, 2, 3.");

  // close the file:
  myFile.close();
  Serial.println("done.");
  */

  /*
  // open the file for reading....

  if (!myFile.open("mrinmoy.txt", O_READ))
  {
    sd.errorHalt("opening test.txt for read failed");
  }

  Serial.println("mrinmoy.txt:");

  // read from the file until there's nothing else in it:
  int data;

  while ((data = myFile.read()) >= 0) Serial.write(data);
  // close the file:
  myFile.close();
  */

  // manual reset
  digitalWrite(RFM95_RST, LOW);
  delay(10);
  digitalWrite(RFM95_RST, HIGH);
  delay(10);

  digitalWrite(RFM95_CS, LOW);
  digitalWrite(4,HIGH);

  while (!manager.init()) {
    Serial.println("LoRa radio init failed");
    while (1);
  }
  Serial.println("LoRa radio init OK!");

 // digitalWrite(RFM95_CS, LOW);

}

void loop()
{
   uint8_t data[] = " Hi.. This is node 1.";
 //   unsigned char sd_data[50];
// Dont put this on the stack:
 // uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
   uint8_t buf[50];
  // nothing happens after setup

  //LoRa.setPins( LoRa_CS, LoRa_RST, DI0 );
  digitalWrite(4,HIGH);    //  deselet SD Card SPI
  digitalWrite(RFM95_CS, LOW);    //  SELECT (low) LoRa SPI
  SPI.begin();

  // Send a message to manager_client
  if (manager.sendtoWait((uint8_t*)data,sizeof(data),1))
  {
    Serial.print("successfully sent to: ");
    Serial.println(1);
  }
  else
  {
    Serial.println("send failed");
  }

  // receiver ....

   // Now wait for a reply from the server
   uint8_t len = sizeof(buf);
   uint8_t from;

   if (manager.recvfromAckTimeout(buf, &len, 2000, &from))
    {
      Serial.print("Got Response From : 0x");
      Serial.print(from, HEX);
      Serial.print(": ");
      Serial.println((char*)buf);
    }
    else
    {

    }
 //   digitalWrite(4, LOW);
   SPI.end();

   digitalWrite(4, LOW);    //  deselet SD Card SPI
   digitalWrite(RFM95_CS,HIGH);    //  SELECT (low) LoRa SPI
   SPI.begin();

 if (!myFile.open("mrinmoy.txt", O_READ))
  {
    sd.errorHalt("opening test.txt for read failed");
  }

  Serial.println("mrinmoy.txt:");
  char ch;
  String str;
  int i=0;
  uint8_t sd_data[50];

  while (myFile.available()>0)
  {
    ch= myFile.read();
    str+=ch;
  }

  String str2=str;
  Serial.println(str2);
  Serial.println(str2.length());

  myFile.close();
  SPI.end();

  delay(500);
}

use this trick ... your system will work perfectly ...


text:
Raspberry pi pico I2S work on byte by byte transfer but not on buffer read writes
I'm using a raspberry pi pico W and testing audio loopback (microphone to speaker in a loop) using INMP441 microphone and MAX98357 amp board.
Followed functions from this page https://arduino-pico.readthedocs.io/en/latest/i2s.html
I arrived at this code:
#include <I2S.h>

I2S* I2SOutputDevice = nullptr;
I2S* I2SInputDevice = nullptr;
#define I2S_SAMPLE_RATE 44100
#define I2S_BITS 24
#define BUFFER_LENGTH 256
#define I2S_BUFFER_SIZE 1024

uint8_t* data;

// the setup function runs once when you press reset or power the board
void setup() {

    I2SOutputDevice = new I2S(OUTPUT);
    I2SOutputDevice->setBCLK(16);
    I2SOutputDevice->setDATA(18);
    I2SOutputDevice->setBitsPerSample(I2S_BITS);
    I2SOutputDevice->setFrequency(I2S_SAMPLE_RATE);
    I2SOutputDevice->setSysClk(I2S_SAMPLE_RATE);
    I2SOutputDevice->setBuffers(2, BUFFER_LENGTH);

    pinMode(19,OUTPUT);
    digitalWrite(19,HIGH);

    I2SInputDevice = new I2S(INPUT);
    I2SInputDevice->setBCLK(20);
    I2SInputDevice->setDATA(22);
    I2SInputDevice->setBitsPerSample(I2S_BITS);
    I2SInputDevice->setFrequency(I2S_SAMPLE_RATE);
    I2SInputDevice->setSysClk(I2S_SAMPLE_RATE);
    I2SInputDevice->setBuffers(2, BUFFER_LENGTH);

    pinMode(LED_BUILTIN,OUTPUT);

    data = new uint8_t[I2S_BUFFER_SIZE];
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);

    I2SOutputDevice->begin();
    I2SInputDevice->begin();
}

// the loop function runs over and over again until power down or reset
void loop() {

    // does not work
    size_t actuallyRead = I2SInputDevice->readBytes(data, I2S_BUFFER_SIZE);
    I2SOutputDevice->write(data, actuallyRead);

    // works

    //int32_t L, R;
    //I2SInputDevice->read24(&L, &R);
    //I2SOutputDevice->write24(L, R);

}

As indicated in the code reading one sample at a time and writing works fine I can hear on speaker what I speak into the microphone.
however if I go the buffer read and write route all I get is noise form the speaker that does not react or correspond to any microphone input .
If I add a serial print to see how many bytes were read then it is a positive number the same as size of the buffer, so it is reading data but playback is missing in this case
what am I doing wrong?
Bonus question: INMP441 seem to have very low sensitivity , you have to speak very close to it which is nearly impractical , is this normal?

Please extend your test code to print the number of read bytes in each loop. Are you aware that both I²C transfers and serial transmissions need time, and therefore the playback can have another sampling rate?

I did print the read bytes and its always the full size of the buffer


text:
D1 Mini + TFT & I2C Connector Shield not going into deepSleep
I'm trying to write a sketch to use a Wemos D1 mini connected to several shields including a LOLIN TFT & I2C Connector Shield (v1.1.0). This powers a small ePaper display (LOLIN 2.13" diagonal ePaper/eInk display) with a TFT e-Paper Cable.
The problem I'm running into is that I can't get the board to either boot properly or get out of deepSleep due to the pin assignment of the TFT display.
I have placed the following code before the void setup() as described in the manufacturer's GitHub example for the board:
/*D1 Mini*/
#define EPD_CS D0
#define EPD_DC D8
#define EPD_RST -1  // can set to -1 and share with microcontroller Reset!
#define EPD_BUSY -1 // can set to -1 to not use a pin (will wait a fixed delay)

By doing this, however, it results in the board entering a boot loop when I try to connect D0 --> RST
If I leave the D0 --> RST disconnected, the board will successfully run the sketch and enter into deepSleep but will not be able to Wake Up after a predetermined amount of time (10seconds).
I see the Builtin LED flash after 10seconds and there is some activity on the serial monitor so I suspect that the board is trying to wake up however it is unable to with the D0 disconnected to the reset pin.
If I try to connect the D0 --> RST after the board has gone to deepSleep and before the timer ends, it continues to sleep until the 10 seconds is completed, then starts its boot loop again with the Built-In LED flashing constantly.
Has anyone else had success in this?  I suspect I'm missing something very simple but cannot find much info on this shield anywhere.

you can use any pin as CS, it doesn't need to be D0. some pins on esp8266 have constraints https://electronics.stackexchange.com/questions/402066/esp8266-free-gpios-for-relay-switching/404845#404845

Thanks for your reply, Juraj.  I have the sketch successfully running now using your suggestion and remapping the CS to another pin.  However, unless I'm doing it incorrectly, this means I have to connect each pin individually between the D1 mini and the display using jumper cables without being able to use the TFT e-Paper Cable.  So now I am wondering if it is possible to remap the pin outputs so I can still use the ePaper cable with one connection between the board and display?

I would remove the CS wire from the connector on the shield  end and extend it with with a jumper wire


text:
Problem with inaccurate delays between sensor readings
During the last two months I have been working on a project that consists of using a Seeeduino Stalker V2.3, two AM2305 sensors, a TSL2561 sensor, an HC-05 XBee module, a 1,800 mAh 3.7V LiPo, a 7 cm x 7 cm 5V solar cell, and a waterproof suction box, to assemble a portable and waterproof environmental data logger that can be used to take samples on a continuous basis (1 sample every 30 minutes, 48 samples per day).
After struggling to make my logger work, I finally did it last week. It all runs fine, except that the intervals between readings are incorrect. When I program my board to store samples every 30 minutes (1,800,000), it takes them every 30 minutes and some extra seconds. When I try the same but with a rate of 1 sample every 10 seconds, my device logs data every 13 seconds more or less...
Here is the code I have been using:
#include "SPI.h"
#include "Wire.h"
#include "SD.h"
#include "DS3231.h"**

DS3231 clock;
RTCDateTime dt;

#include "DHT.h"

#define DHTPIN 8
#define DHTTYPE DHT21
DHT dht1(DHTPIN, DHTTYPE);
#define DHTPIN2 7
DHT dht2(DHTPIN2, DHTTYPE);
#include "TSL2561.h"
TSL2561 tsl(TSL2561_ADDR_FLOAT);

const int chipSelect = 10;
int XBEE = 5;
int FLASH = 4;

void setup() {
  pinMode(5, OUTPUT);
  digitalWrite(XBEE, HIGH);
  Serial.begin(9600);
  Wire.begin();
  clock.begin();
  analogReference(INTERNAL);
  pinMode(10, OUTPUT);
  pinMode(4, INPUT);
  SD.begin(10);
  dht1.begin();
  dht2.begin();
  Serial.println("EcoLOGGER DE PRUEBA PARA GENERACION DE DATOS ...");
  Serial.println(" ");
  delay(3000);
  Serial.println("RECUERDA QUE ESTE PROYECTO NO HUBIERA SIDO POSIBLE SIN LA AYUDA DE LA COMUNIDAD ARDUINO...");
  Serial.println(" ");
  delay(3000);
}

int counter = 0;

void loop() {
  float h = dht1.readHumidity();
  float t = dht1.readTemperature();
  float f = dht1.readTemperature(true);
  float h2 = dht2.readHumidity();
  float t2 = dht2.readTemperature();
  float f2 = dht2.readTemperature(true);
  dt = clock.getDateTime();
  if (tsl.begin()) {
  } else {
    while (1);
  }
  tsl.setGain(TSL2561_GAIN_0X);
  tsl.setTiming(TSL2561_INTEGRATIONTIME_402MS);
  uint16_t x = tsl.getLuminosity(TSL2561_FULLSPECTRUM);
  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;
  float vis = full-ir;
  Serial.print("Muestreo: ");
  Serial.println(counter);
  Serial.print("Fecha: ");
  Serial.print(dt.day);
  Serial.print('/');
  Serial.print(dt.month);
  Serial.print('/');
  Serial.println(dt.year);
  Serial.print("Hora: ");
  Serial.print(dt.hour);
  Serial.print(':');
  Serial.print(dt.minute);
  Serial.print(':');
  Serial.println(dt.second);
  Serial.print("Temperatura sistema: ");
  Serial.print(clock.readTemperature());
  Serial.println("*C ");
  Serial.print("Voltaje bateria: ");
  Serial.print(analogRead(A7) * (1.1 / 1024)* (10+2)/2);
  Serial.println(" V ");
  Serial.print("Carga bateria: ");
  Serial.print(-149.4 + 59.52 * (analogRead(A7) * (1.1 / 1024)* (10+2)/2));
  Serial.println("% ");
  Serial.print("Luz FULL: ");
  Serial.println(full);
  Serial.print("Temperatura ambiente: ");
  Serial.print(t);
  Serial.println(" *C ");
  Serial.print("Humedad relativa: ");
  Serial.print(h);
  Serial.println("%");
  Serial.print("Temperatura suelo: ");
  Serial.print(t2);
  Serial.println(" *C ");
  Serial.print("Humedad suelo: ");
  Serial.print(h2);
  Serial.println("%");
  Serial.println(" ");
  digitalWrite (FLASH, HIGH);
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.print(" Muestreo: ");
    dataFile.print(counter);
    dataFile.print(",");
    dataFile.print(" Fecha: ");
    dataFile.print(dt.day);
    dataFile.print('/');
    dataFile.print(dt.month);
    dataFile.print('/');
    dataFile.print(dt.year);
    dataFile.print(",");
    dataFile.print(" Hora: ");
    dataFile.print(dt.hour);
    dataFile.print(':');
    dataFile.print(dt.minute);
    dataFile.print(':');
    dataFile.print(dt.second);
    dataFile.print(",");
    dataFile.print(" Temperatura sistema: ");
    dataFile.print(clock.readTemperature());
    dataFile.print("*C ");
    dataFile.print(",");
    dataFile.print(" Voltaje bateria: ");
    dataFile.print(analogRead(A7) * (1.1 / 1024)* (10+2)/2);
    dataFile.print(" V ");
    dataFile.print(",");
    dataFile.print(" Porcentaje carga: ");
    dataFile.print(-149.4 + 59.52 * (analogRead(A7) * (1.1 / 1024)* (10+2)/2));
    dataFile.print("% ");
    dataFile.print(",");
    dataFile.print(" Luz FULL: ");
    dataFile.print(full);
    dataFile.print(",");
    dataFile.print(" Temperatura ambiente: ");
    dataFile.print(t);
    dataFile.print(" *C ");
    dataFile.print(",");
    dataFile.print(" Humedad relativa: ");
    dataFile.print(h);
    dataFile.print("%");
    dataFile.print(",");
    dataFile.print(" Temperatura suelo: ");
    dataFile.print(t2);
    dataFile.print(" *C ");
    dataFile.print(",");
    dataFile.print(" Humedad suelo: ");
    dataFile.print(h2);
    dataFile.print("%");
    dataFile.println("");
    dataFile.close();
    digitalWrite (FLASH, LOW);
  } else {
    Serial.println("");
    Serial.println("IMPOSIBLE GUARDAR DATOS");
    Serial.println("");
  }
  counter++;
  if (counter > 5) {
    delay (1000);
    digitalWrite (XBEE, LOW);
    delay (1799000);
  } else
    digitalWrite (XBEE, HIGH);
  delay (10000);
}

I have been trying to find possible solutions, but I am just lost. Do any of you have an idea of what could be going on?
Thank you in advance :)

How accurate do you think delay() is? And how much time does the sketch take when not in delay(). All this adds up. Check for instance how accurate the clock crystal/resonance is. Consider using an external RTC or try getting the Arduino Team to implement something that actually could work as a stable timer (< 1 second drift per month).

It might also matter that most Arduinos are slow, that means all data transfer and calculations take time.

Thank you @MikaelPatel, I now realize that delay() is good for learning arduino but not for implementing real world ideas... I will try to use the DS3231 RTC that comes on the Seeeduino stalker V2.3 to trigger my readings... I still have to think of a way of implementing this idea on code... Any advices?

The problem is that you are using delay().
delay() will wait, from the moment delay() is called, for the given number of milliseconds.
That is, in more structured terms:

Do something
Do something else
Do something more
Wait 30 minutes

That will only take precisely 30 minutes if steps 1 to 3 take absolutely no time at all.  And that will never be the case. Things take time. Reading from sensors, writing to SD cards, etc, all take time.
So waiting for 30 minutes between doing things means that every 30 minutes will be slightly later than the one before.
And as you saw the difference is more pronounced when you have 10 seconds instead - it ends up as 13 seconds.  So your other actions - reading from sensors, writing to SD card, etc, must be taking about 3 seconds each time.
So instead of "Stop everything for half an hour", you need to think slightly differently:

Look at the time.
Decide if 30 minutes have passed since the last time you ran the code
Remember the time so you can know when 30 minutes have elapsed next time
Do your sensor/SD actions.

Since you're now keying things happening on the difference between now and when you last started to do things you get a 30 minute total delay, rather than a 30 minute delay plus other bits.
For an example of how this is done programatically you can look at the BlinkWithoutDelay example in the Arduino IDE.

Thank you for your comment. I have been reading some info about your statements and it seems that there are several ways to get rid of delay() function... I think the "Millis()" function is a very straightforward technique, but if it depends on a clock that is prone to give outputs with only 90% of accuracy (on-board clock cycle, as mentioned by @PaulMurrayCbr) I don't think it is going to be useful for my porpues. So I'm thinking of "asking the time" to the Stalker's on-board DS3231 RTC, but I cannot think clearly of its implementation on code... I suppose I should use if, else...

Do you have any recomendations? Thank you again for your help :)

You can use an RTC in just the same way as millis(). Take a look at the Time.h library for help manipulating times.

The second problem is that delay() on the arduino uses the on-board clock cycle. This is powered by a resonator, which can be off by as much as 10%. If you need accurate timings and timestamps, you will want to use a Real-Time Clock (RTC) module.
Instead of using delay, the loop() asks the RTC what time it is, and uses that to determine if it's time to take another reading.
Another very common thing for this type of monitoring is for the arduino to go into sleep mode and be woken by a tick from the RTC every second (or longer), in order to extend the battery life.


text:
How to transmit serial data from laptop USB out to Teensy?
I want to send serial data from my laptop to a Teensy LC chip through the laptop's USB port. I am not sure how to do this. From reading I have found two possibilities, which both seem to have problems:

Get a USB to serial adapter cable, connect the USB to the laptop, the serial to a MAX232 chip, the MAX232 chip to the UART serial on the Teensy. The ambiguity in this option lies in the fact that the MAX232 chip requires a minimum 4.5V input, and the specs on the Teensy LC say it has 3.3V and one 5V digital output (would this one output be compatible with a MAX232?). Also, it has only 3.3V input, so it sounds like 5V coming from the MAX232 chip would be too much (I guess I could incorporate a chip like https://www.adafruit.com/product/735 ?). Now if I were to go this route with a Teensy 3.1, which says its input pins are 5V tolerant, its voltage output is also only 3.3V (and there is no mention of any 5V output). I guess the answer here would be to incorporate a chip like https://www.adafruit.com/products/1787 ?
The second possibility I looked into would be a USB-to-TTL adapter cable to go straight to the Teensy LC, but I read somewhere that the serial UART with Arduino is different in some way and I wasn't sure if the serial communication coming through the USB-to-TTL cable would be compatible with the Teensy. I was looking at one of these cables at Sparkfun, and I think I would connect the TxD from the cable to the RX on the Teensy, the RxD from the cable to the TX on the Teensy, and the GND cable to a ground on the Teensy.

Could someone point me in the right direction regarding sending serial data through a laptop's USB out to the Teensy?

Is there any particular reason why you don't want to use the existing USB connection for serial communications?

Yes. I was going to use the usb port to connect to another laptop as its keyboard, and transfer the incoming serial keystrokes to the other laptop through the teensy usb-keyboard interface.

Your second option is the easiest.

a usb to ttl adapter cable to go straight to the Teensy LC, but I read somewhere that the serial UART with Arduino is different in some way

Without seeing what you read, perhaps they were just talking about the fact that the Arduino is not "true" RS-232, it's only at TTL (or 3.3V) levels.

and wasn't sure if the serial communication coming through the usb to ttl cable would be compatible with the Teensy.

It should be compatible, especially since you note that the Teeny is 5V-tolerant.

I was looking at one of these cables at sparkfun, and I think I would connect the TXD from the cable to the RX on the Teensy, the RXD from the cable to the TX on the Teensy, and the GND cable to a ground on the Teensy.

That's it in a nutshell!


text:
Capacitive sensor switch
I am trying to get relays to switch on or off based on if I touch a capacitive sensor, basically a light switch. For some reason, I get two readings that are high capacitive readings when I do a printout. I am not really sure why this is happening. I tried delays in case it was reading my touch too fast but with no luck.
The hardware is basically a 1M resistor between send and receive.
// capactitive sensing
#include <CapacitiveSensor.h>
CapacitiveSensor   cs_7_6 = CapacitiveSensor(7,6);
// 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil
const int numReadings = 5;
int index = 0;                  // the index of the current reading
int readings[numReadings];      // the readings from the analog input
int total = 0;                  // the running total
int average = 0;
int relay = A2;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;
boolean lightState = false;
// sound sample
const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;
//other
boolean isRelaysOn = false;

// capacitive sensor
void setup() {
  cs_7_6.set_CS_AutocaL_Millis(0xFFFFFFFF);
  // turn off autocalibrate on channel 1 - just as an example
  Serial.begin(9600);
  for (int thisReading = 0; thisReading < numReadings; thisReading++)
    readings[thisReading] = 0;
  // other
  pinMode(relay, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  turnRelayOff();
  Serial.begin(9600);
}

boolean state = false;
boolean lastState = true;
boolean lightTurnedItOff = false;

void loop() {
  Serial.println(capReading());
  if(capReading() >= 3000) {
    Serial.println("threadhold reached");
    lightState = !lightState;
    controlRelay();
  }
}

boolean isOn = false;

void controlRelay() {
  if(lightState == true && isOn == false) {
    turnRelayOn();
    //delay(1000);
  }
  if(lightState == false) {
    turnRelayOff();
    // delay(1000);
  }
}

void turnRelayOn() {
  int delayAmount = 100;
  digitalWrite(relay, LOW);
  delay(delayAmount);
  digitalWrite(relay2, LOW);
  delay(delayAmount);
  digitalWrite(relay3, LOW);
  delay(delayAmount);
  digitalWrite(relay4, LOW);
  delay(delayAmount);
  digitalWrite(relay4, HIGH);
  delay(delayAmount);
  digitalWrite(relay4, LOW);
  isOn =true;
}

void turnRelayOff() {
  digitalWrite(relay, HIGH);
  digitalWrite(relay2, HIGH);
  digitalWrite(relay3, HIGH);
  digitalWrite(relay4, HIGH);
  isOn = false;
}

int capReading () {
  // get average.
  total= total - readings[index];
  readings[index] =  cs_7_6.capacitiveSensor(30);
  total= total + readings[index];
  index++;
  if (index >= numReadings)
    index = 0;
  average = total / numReadings;
  delay(100);
  return average;
}

The output doesn't make much sense sometimes either, here are a few samples:

11 16 21 22 32 61 74 threadhold reached 6191 threadhold reached 6167
  threadhold reached 30 15 11 12
6 10 17 44 2144 3745 threadhold reached
  -475 threadhold reached
  -3129 22 10 12 13
15 13 7 20 23 725 2726 2735
  -6373
  -3197 threadhold reached 4127 2714 54 40 43 34 24 27 31

In this line:
readings[index] =  cs_7_6.capacitiveSensor(30);

...you are assigning an "int" the value from a method of type "long".
Likely you will want to change all your types used to track the capacitance value, including the type of your "capReading" method, to "long".

oh, look at that. Didn't even realize that library returned a long. Looking at examples for library shows it definitely does. Will try this fix.