text:
Taking data from main 120V 50/60Hz power
How can I take data from my house main power and reconstruct it signal? I used an transformer and an inverter amplifier to low voltage to 5 volts and read it with A0 analog pin, but I got a very strange datan and just a few numbers
data = analogRead(A0);
 Serial.println(data);

What kind of data are you trying to retrieve?

The Sin wave at 60Hz

Please show us the sketch you used that gave you the "...very strange data and just a few numbers".

Please show us a complete sketch and a sample of the corresponding data

The Serial output on an Arduino is quite slow. By printing your output, you will slow down the readings so much that it will appear to be nonsense.
You should collect a series of readings into a C array of floats in RAM, stop recording, and then log that array of values.
Note that you don't have a lot of RAM to work with on most Arduinos, so you will only be able to record a small number of values. A Mega 2560 has a lot more memory than others (8KB). It's still not a lot, but better than other boards. One of the ARM based Arduinos will have both a much faster processor and a lot more RAM.

I have working code which could be added to this answer after a little cleanup https://github.com/jandrassy/Regulator/blob/4c1f15e00f51d618293ae441706c3f6027a56405/util/RegulatorDev/RegulatorDev.ino#L243

Is the speed of data transmission really such a big problem here, that you need to buffer the data? I mean, it's only 60Hz. I would think, that is is sufficient to choose a higher baudrate.

"Is the speed of data transmission really such a big problem here...?" Yes. Imagine a Serial.write() takes 1/10th of a second. You need what, 10 readings per full cycle of a sine wave to get a crude picture of its shape? That would mean you would need 600 readings/second. If instead you get 10 readings per second, out of phase with the wave, you're going to see seemingly random readings.


text:
How to check if a LED is on?
I have a circuit board / device that can be in different states. It indicates in which state it is by turning on one of three LED's. Now I want to use an ESP8266 to tell me (over the network) the current state. What kind of circuit would I need for this? (I have thought about using photodiodes, but I would much rather solder something directly to the board)

Can you measure the voltage that the "circuit board" uses to switch the LED on and off?

If you are talking about the LED voltage drop, its 2.7v.

What voltage does the "circuit board" operate at? Is it the same as the ESP8266?

As its powered via USB, i assume its operating at 5v.

If the device turning the LEDs on / off runs on 3.3 Volts (has ground to 3.3 Volts outputs), then you might consider directly connecting the 3.3 Volt outputs to the GPIO pins of the ESP8266.  If the device turning the LEDs on / off runs on higher voltages consider either using the appropriate level shifter or the appropriate optical isolator:

An optocoupler's input takes e.g. 1.7V as Vf :  With a 100 Ohms resistor you add another 10 mA load to the  LED's 2.7V .  Pin 4 = GND,  Pin3 = INPUT_PULLUP should be LOW when LED is on, and HIGH when off.

source: Stack Exchange

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

sort: votes


text:
Detecting how many button presses(single tap, double tap etc) with two simultaneous buttons
noob here
So what I am trying to do is output a different number depending on the number of button presses e.g. for 1 button press it should output 1 and so forth. After that I only really want the outputs for 1 to 4 presses. I am using these inputs for a game.  Right now, it does work and counts up until 4 and then resets back to 0. The problem that I am having is it continues after 1 click to 2 clicks; what I want it to do is count 1 click when its clicked once, twice when its clicked twice etc. I am trying to use a debouncing code to distinguish between single tap, double tap, triple tap etc
@VE7JRO kindly provided a great solution to this problem, albeit it was for one button. I am trying to adjust the code to accommodate 2 separate buttons (on separate pins), but it is giving me an error.
This is the code:
#include <Bounce2.h>

// Connect both buttons in series with one connection
// to GND and the other to a digital pin.
const int buttonPin1 = 2;
const int buttonPin2 = 3;

class Button
{
  private:

    int m_buttonPin1;
    int m_buttonPin2;
    int m_counter;
    unsigned long m_buttonPressTimeout;
    unsigned long m_previousMillis;

  public:

    Button(int button):
      m_buttonPin1(buttonPin1),
      m_buttonPin2(buttonPin2),
      m_counter(0),
      m_buttonPressTimeout(1500), // Button press timeout 500 ms.
      m_previousMillis(0){}

    void Update()
    {
      int valA = digitalRead(button1); // read button stateint
      int  valB = digitalRead(button2); // read button state
       if (valA == LOW &&valB == LOW)
       {
      if(m_counter > 0 && millis() - m_previousMillis >= m_buttonPressTimeout)
      {
        Serial.print("Count from Update() just before it's re-set to 0 = ");
        Serial.println(GetCounter());
        m_counter = 0;
      }
    }

    void IncrementCounter(){
      m_counter++;
      if(m_counter > 4){m_counter = 4;}
      if(m_counter == 1){
        m_previousMillis = millis();
      }
    }

    byte GetCounter(){
      return m_counter;
    }

};

Bounce button1Debouncer = Bounce();
Bounce button2Debouncer = Bounce();
Button MyButton(buttonPin1);
Button MyButton(buttonPin2);

void setup(){

  Serial.begin(9600);

  pinMode(buttonPin1, INPUT_PULLUP);
  button1Debouncer.attach(buttonPin);
  button1Debouncer.interval(5);
  pinMode(buttonPin2, INPUT_PULLUP);
  button2Debouncer.attach(buttonPin);
  button2Debouncer.interval(5);

}

void loop(){

  // Call the Update function as fast as possible.
  MyButton.Update();

  // Button pressed.
  if(button1Debouncer.update() && button2Debouncer.update())
  {
    if(button1Debouncer.fell() && button2Debouncer.fell()){
      MyButton.IncrementCounter();
      Serial.print("Count from Button Debouncer = ");
      Serial.println(MyButton.GetCounter());
    }
  }

}
}

The error is: "'buttonPin1' is not a type", I do not understand this error as it didn't give that error for when a single button was used.

You write that you want it for a game. So probably you do not want count the presses but just see which button was pressed right? Do not call "digitalRead" many times if you want be fast. A better solution would be to read 7 pins with a single call with PIND, so you read pin 0 to 7 (advanced). Or, when I analyze your code, you just want to be notified of changes, you can use interrupts.

@Adriano I actually do want the number of presses. I think I should make it a little clearer: Fair point...I never really explained it
So, I have a player that needs to jump onto different platforms to collect coins and in each level the platform and coin numbers differ and because I am using the input device as a clicking distraction so in each level the amount of clicks needed to make the character move, changes
So in one level you need to press the buttons twice, thrice in the next level etc

I don't understand the problem you are trying to solve. How many separate buttons do you have? Is each button on a separate pin, or do you have a matrix of buttons? Can the user press more than one button at a time, and you want to detect how many are pressed at the same time? Let's call that numberOfButtonsPressed. Then are you also looking for the user to single-tap, double-tap, triple-tap, etc, some number of buttons? So you both have the number of buttons being pressed, and the number of times they are pressed?

You will need to handle "slop" in the input, where the user presses the different buttons at slightly different times. If they are trying to press 4 buttons, you might detect first one, then 2, then 3, then 4 buttons pressed. And because of bounce, you might see some of those button inputs switch rapidly between not-pressed and pressed for a few milliseconds before settling down.

You might try 20-50 mS. If you don't detect any change in button state for that long, you can consider the button state as stable and take a reading.

@DuncanC I have 2 buttons that are connected on separate pins, but the user has to press both buttons at the same time to register one push. So, the problem I am having is how to distinguish between one push and two pushes etc. So, you suggest that I handle "slop" in this instance?

You need to debounce your buttons. That can be done pretty easily in software. Do a google search, but the basic idea is that when you detect a button press (or a 2-button press, in your case) you record the value of millis(), and ignore changes in the digital inputs for some constant waiting period. (20-100 mS is a good range to work with, depending on the situation.)

@DuncanC I was actually thinking I could get away without debouncing this (as it works well without that till this point), but it seems like I have to delve into that. Thank you

Writing your own debouncing code is actually pretty easy. You just need to record the millis() reading when a first button changes state, and ignore further state changes for a small interval.

@DuncanC I have tried a debouncing code today but now the serial monitor isn't outputting anything. Could you take a look at my updated code?

If it’s possible to connect the 2 buttons in series, then this sketch may give you the desired results.
#include <Bounce2.h>

// Connect both buttons in series with one connection
// to GND and the other to a digital pin.
const byte buttonPin = 2;

class Button{

  private:

    byte m_buttonPin;
    byte m_counter;
    unsigned long m_buttonPressTimeout;
    unsigned long m_previousMillis;

  public:

    Button(byte buttonPin):
      m_buttonPin(buttonPin),
      m_counter(0),
      m_buttonPressTimeout(500), // Button press timeout 500 ms.
      m_previousMillis(0){}

    void Update(){
      if(m_counter > 0 && millis() - m_previousMillis >= m_buttonPressTimeout){
        Serial.print("Count from Update() just before it's re-set to 0 = ");
        Serial.println(GetCounter());
        m_counter = 0;
      }
    }

    void IncrementCounter(){
      m_counter++;
      if(m_counter > 4){m_counter = 4;}
      if(m_counter == 1){
        m_previousMillis = millis();
      }
    }

    byte GetCounter(){
      return m_counter;
    }

};

Bounce buttonDebouncer = Bounce();
Button MyButton(buttonPin);

void setup(){

  Serial.begin(9600);

  pinMode(buttonPin, INPUT_PULLUP);
  buttonDebouncer.attach(buttonPin);
  buttonDebouncer.interval(5);

}

void loop(){

  // Call the Update function as fast as possible.
  MyButton.Update();

  // Button pressed.
  if(buttonDebouncer.update()){
    if(buttonDebouncer.fell()){
      MyButton.IncrementCounter();
      Serial.print("Count from Button Debouncer = ");
      Serial.println(MyButton.GetCounter());
    }
  }

}

EDIT
Based on your last update to the question:

I am trying to adjust the code to accommodate 2 separate buttons (on separate pins), but it is giving me an error.

I have updated the sketch to use 2 buttons on separate digital pins.
#include <Bounce2.h>

// Connect each button with one connection
// to GND and the other to a digital pin.
const byte buttonPin = 2;
const byte buttonPin2 = 3;

class Button{

  private:

    byte m_buttonPin;
    byte m_counter = 0;
    unsigned long m_buttonPressTimeout;
    unsigned long m_previousMillis;

  public:

    Button(byte buttonPin):
      m_buttonPin(buttonPin),
      m_counter(0),
      m_buttonPressTimeout(750), // Button press timeout in ms.
      m_previousMillis(0){}

    void Update(){
      if(m_counter > 0 && millis() - m_previousMillis >= m_buttonPressTimeout){
        Serial.print("Count from Update() just before it's reset to 0 = ");
        Serial.println(GetCounter());
        m_counter = 0;
      }
    }

    void IncrementCounter(){
      m_counter++;
      if(m_counter > 4){m_counter = 4;}
      if(m_counter == 1){
        m_previousMillis = millis();
      }
    }

    friend void IncrementCounter(Button&);

    void IncrementCounter(Button&){
      IncrementCounter();
    }

    byte GetCounter(){
      return m_counter;
    }

};

Bounce buttonOneDebouncer = Bounce();
Bounce buttonTwoDebouncer = Bounce();
Button ButtonOne(buttonPin);
Button ButtonTwo(buttonPin2);

void setup(){
  Serial.begin(9600);
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  buttonOneDebouncer.attach(buttonPin);
  buttonTwoDebouncer.attach(buttonPin2);
  buttonOneDebouncer.interval(25);
  buttonTwoDebouncer.interval(25);
}

void loop(){

  // Call the Update function as fast as possible.
  ButtonOne.Update();
  ButtonTwo.Update();

  // Button one pressed.
  if(buttonOneDebouncer.update()){
    if(buttonOneDebouncer.fell()){
      if(digitalRead(buttonPin2) == 0){
        ButtonOne.IncrementCounter();
      }
    }
  }

  // Button two pressed.
  if(buttonTwoDebouncer.update()){
    if(buttonTwoDebouncer.fell()){
      if(digitalRead(buttonPin) == 0){
        ButtonOne.IncrementCounter(ButtonTwo);
      }
    }
  }

}

thank you, I will try this. Does this use an external library? @VE7JRO

Yes, the Bounce2 library. It's available in the IDE library manager.

Ah okay, I will try this out thank you @VE7JRO

Thank you; it works rather well...now just have to figure out how to connect two separate buttons on two separate pins @VE7JRO

@user19964 - It's easy to add another button. Define another variable such as buttonPin2, then do something like this Bounce buttonDebouncer2 = Bounce(); and this Button MyButton2(buttonPin2);. A bit of copy / pasting should get 2 buttons working quickly. The most difficult part will be to change the logic in the loop() to work with two buttons.

for the loop() couldn't you just add something like: if(button1Debouncer.update() && button2Debouncer.update())
{
if(button1Debouncer.fell() && button2Debouncer.fell())}} ? @VE7JRO

@user19964 - I think you could do something like that. Perhaps, when one of the buttons is pressed, "it's" function in the loop() could also do a digitalRead on the "other button". That piece of information could be useful to determine if both buttons are actually pressed at the same time, at that very moment in time.

Let us continue this discussion in chat.

@VE7RO I have only seen this now and I tested it immediately. As I hadn't seen this, I had still been struggling for days with this question :(. THANK YOU SO MUCH!! Just tested it and it works well; I really do appreciate all the help that you've given me with this question :). Have an awesome day!

You SHOULD pay attention to the following issues:
1. Floating input problem:
Symptom: the reading value from the input pin is not matched with the button's pressing state.
Cause: input pin is NOT used pull-up or pull-down resistor.
Solution: Use pull-up or pull-down resistor. See Arduino Button (with pull-up/pull-down)
2. Chattering phenomenon
It should be considered in only some application that needs to detect exactly number of the pressing.
Symptom: Button is pressed one, but Arduino code detects several times.
Cause: Due to mechanical and physical issues, the state of the button (or switch) is quickly toggled between LOW and HIGH several times
Solution: Debounce. See Arduino Button Debounce

Thank you for the tips. I Have a pull up resistor on both my buttons and I had implemented a debounce code in this code. I am getting pretty much the same thing as before @Rozona Zoro

Your updated code has lots of problems. To do button debouncing, try something like this:
//Adjust debounceTime as desired. Shorter times will make fore faster button
//response, but make the debouncing less effective. 50 is 1/20th of a second.
#define debounceTime 50

unsigned long nextButtonCheckTime = 0;
bool buttonAState = false;
bool buttonBState = false;

void loop() {
  //Only check the buttons if the debounce time has passed
  if (millis() > nextButtonCheckTime)
    bool newButtonAState = digitalRead(buttonAPin) == LOW;
    bool newButtonBState = digitalRead(buttonBPin) == LOW;
    //If one or both buttons have changed state
    if  (buttonAState != newButtonAState || buttonBState != newButtonBState)) {
      nextButtonCheckTime = millis() + debounceTime;
      buttonAState = newButtonAState;
      buttonBState = newButtonBState;
      //Handle change of button state
    }
  }
}

That is pseudocode. It almost certainly contains syntax errors. You should use it as a guide, and rewrite it to suit your needs. Do not say "I copied your code into my sketch and it won't compile."

Thank you; this does help as a guideline indeed. I will use it accordingly @DuncanC

It is likely you are experiencing problems associated with button contact bounce. This is where the processor is so fast that it "sees" the button make several contacts when the user only intends for 1 contact to be seen by the program. Consider using this button de-bounce library instead of reading the state of the buttons directly in the sketch.
The code for the above debounce Arduino library is hosted here at github.com. In general, people using github.com will have an "example" folder along with the source code and documentation folders.  The debounce Arduino library example folder is here.  There are about half a dozen Arduino sketch examples including this 2 button example which might be used as the starting point for the project in the question.
There may be a logic problem in the code when interpreting the number of button presses into "a", "b", "c" & "d".  The modulo operator "%" is used.  And in the first test, the number of button presses % 1 is tested. If the result is zero the test is true.  As any number % 1 has no remainder this test will always be zero and therefor always true.  As all other tests are nested inside "else" statements none of the other tests will be executed.  Instead consider using a switch / case statement where the code switches on the number of button presses and the case statements are "case 1:", case 2:", "case 3:" & "default:".  It is good coding practice to always have a "default:" case in a switch statement.  Here we use "default:" instead of "case 4:". After using the value representing the number of button presses, always remember to clear this value before the next iteration.  Remember, any "global" values (values defined outside a function) will retain their values between calls to that function. Any "local" value (values defined inside a function) will not retain their values and need to be initialize each time they are used.

are there any examples showing how to implement this library...I have it imported to my project but am not sure how to implement it @st2000

I'll add where to find examples in my answer.
Also, I appreciate you editing your question to make it better.  I added text to your question to make it clear more information was added and what that information is showing.

yes, I see that you've edited my question: thank you...it reads much better now. Yes, those examples would be much appreciated @st2000

@st2000just thought to mention that the counter is working now, but it isn't working exactly how I would like it to.

You are using the Modulo "%" operator.  I do not think that is what you want.  For instance, you can divide any integer by 1 and not get a remainder.  So 1 % 1 is 0, 2 % 1 is 0 anything % 1 is 0.  That statement is always true and nothing below it will execute.  You will always print out "a".  Do you want me to alter my answer again?

ah yes, this makes sense...so much sense. When I used if(buttonPushCounter ==1) etc, it didnt work either l. Yes, i would appreciate that @st2000

Thank you very much for your extensive answer. I did go through the solutions there and added it to my own solution. As required. The counter works now, it outputs as it should and it resets when it should too: all as intended. I have edited my question accordlingly @st2000

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


text:
Is there some better documentation somewhere for Arduino classes and API's?
For example, it looks like Serial extends HardwareSerial, which extends Stream, which extends Print. But I don't think you can figure this out by reading the reference documentation on https://www.arduino.cc/ and it doesn't appear that you can easily navigate the class hierarchy in the Arduino IDE. They seem to go out of their way to hide the class hierarchy?
I guess I'm spoiled by modern languages that have automatically generated documentation, but it seems like there should be a more complete reference somewhere?

I use Eclipse with Sloeber plugin. It gives me super powers in Arduino world

The point of Arduino is that it's targeted at people that don't need (or care) about such level of detail in the documentation.

There's an addon to MS VisualStudio (VisualMicro.com) to provide you with a real IDE allowing to drill down the provided core libraries.

What I did/do when loading a new core is generating a doxygen visualisation help class hierachy in HTML. Although most of the core libs have no detailed doxygen documenation the dot/graphviz solves the problem without installation of other IDEs (which also have their specific problems, or need a lot of learning). As an added bonus I can document my source code in a clean and transparent way available in most IDEs and OS.


text:
esp32, brownout on 3.3v?
I'm using a powerbump, input: 3.7v-6v Outputs: 3.3v, to provide the power I'm using 2 CR2025 coin cell batteries(3v each), meaning the powerbump gets 6v, the esp gets the exact 3.27v(I've measured with a multimeter),
But the chip still keeps on brownouting, when I start BLE on the chip

The ESP32 is quite power hungry when using the bluetooth or WiFi. Read this: https://lastminuteengineers.com/esp32-sleep-modes-power-consumption/ - button cells provide very little current. You may find it's not enough. Add one more button cell and see if that improves things. Maybe replace one CR2032 with a pair of CR2016's to use the same space but double the voltage (with reduced capacity for reduced runtime of course).

@Majenko The third cell adds another 3 V to the supply voltage. The regulator is specified with 6V and now gets 9V. I think that's not a good idea. The third cell has the same inner resistance than the other ones. So if the current goes above a certain amount the voltages breaks down. So I do not think this would help. One could use two or three pairs in parallel. But the best solution would be to replace the cells by a more powerful source.

If it's the powerbump I designed then it's 16v max input, not 6v, and it's a buck regulator, so the higher the voltage in the higher the current you can get out.

@Majenko If you have two cells you double the voltage and also the inner resistance of both cells together. The current where the inner voltage drop gets so high that the voltage breaks down and can not feed the converter, stays the same. The converter is not the problem, the cells are. Event if you have more voltage on then bug converter and so it needs less current to draw, I doubt that would be enough to avoid the effect. And the cells also discharge very quickly. If the converter is specified with 16V max then my warning is obsolete. Sorry, I didn't know about that.

@PeterPaulKiefer There comes a point where the current being required from the batteries needed to provide the desired output current is low enough that the internal resistance of the batteries doesn't provide enough voltage drop to cause a brownout any more. What input that voltage is at though is the main unknown at the moment. As for battery drain, sleep modes can mitigate most of that. But I certainly agree that button cells are a poor choice unless you are specifically using circuitry designed to run at very low currents. The ESP32 isn't really that.

well, the most important for my batteries, is to be small, coins cells are very small, and the best solution I could find was them, btw the chip will be in deep_sleep most of the time

and yes, it is @Majenko powerbump, thought you said it was 6v in a earlier post

just realized I wrote the wrong number, its cr2025

@Majenko I fully agree with you.  I wanted to say something about the possibility the two cells will work, but due too my bad English I failed obviously.  I know the e.g. CR2025 has a capacity of about 170 mAh and serve a typical current of ~ -0.2 mA, I think there is a significant drop, if one draws e.g. -50 mA from the cells. The cell quickly looses the stored energy and after a short time the voltage of the cell sinks because of that. The buck converter gets less voltage and needs more current. So as you wrote too, cell coins are a poor solution.

Marius, there are other solutions that may fit your needs. Cell coins may work or not, but if they work, then not for along time. And the mentioned types are not re-loadable. I don't know how often the ESP wakes up and activates bluetooth. But do you really want to change batteries every 2 hours of operation? Perhaps accus fit better with your needs. There are LiPo Packs that provide 3.7V. There are small packs available:  e.g.  6mmx35mmx37mm (2 CR2025 need 2.5mmx40mmx25mm w/o the holder).

is the lipo rechargeable?


text:
How to document a custom library in Arduino
I have created my own library and it is working flawlessly. Now I want to add some documentation to it that the Arduino IDE can understand.
For the functions from the Arduino IDE itself like delay(ms) you can right click them and then select Find in Reference. How can I add this feature to my own library?

I uv your question because I'm also interested to know if that is possible at all. As far as I know the REFERENCE_LINK is a link to Arduinos own main reference. Libs can only have an extra folder to put docs into it, but that is completely ignored by the IDE.

OK, time for my most comprehensive answer on StackExchange so far (tanks to @Juraj for helping out with this).
To demonstrate all the steps needed for this, this answer will use an example library that will be called Foo.
Here we go:
To add documentation to your library that the Arduino IDE can work with, you first need to place your library in the correct directory. Thats either in your library folder in your sketchbook folder (you can locate it by selecting File>Preferences>Sketchbook location, by default this is
C:\Users\YourUsername\Documents\Arduino\libraries

or
InstallationDirectoryOfYourIDE\portable\sketchbook\libraries

if you are using a portable installation) or in
InstallationDirectoryOfYourIDE\libraries

In which of the two places you put your library is up to you, both work (except if you put in both places at the same time). You should keep this in mind though: If you put your library in the libraries folder of your sketchbook, only you will have access to that library. If there are other users on the same PC that shall be able to use your library, you have to put in in the general libraries folder (if you don't have access to that folder because it belongs to another user and you are not the admin, then too bad, sorry ;).
Your library has to contain at least a file Foo.h which can be located directly in the folder of your library (old standard) or in a subfolder src in your library folder (up to date standard). What the file contains is for the sake of this example absolutely arbitrary (e.g. just leave it empty).
Next you need a valid library.properties file for your library. You can create and edit it with any text editor like notepad. This file has to be placed directly into the folder of the library.
Here is a bare minimum example for this file that works:

name=Foo
  version=1.0.0
  author=Your name
  maintainer=Your name
  sentence=Something
  paragraph=Whatever
  url=http://example.com

More information on how this file works (and other things to consider when creating a library) can be found at the Arduino Library Specification.
Now we can specify which words the IDE shall highlight and which of them shall link to which reference page (to make sure that this works in principle it is not necessary to create your own .html files yet). To do this, create a file keywords.txt in the folder of your library. In it you write something like this:
foo KEYWORD2    Foo

In this example foo is the keyword that will be highlighted in the IDE (and on right click present the option Find in Reference). KEYWORD2 specifies how exactly foo will be highlighted (colour, boldness, etc.), in this case it will appear like normal text in orange (once again, see the Arduino Library Specification for more details on this). Foo is the name of the .html file (without the extension) that is opened when you right click foo in the IDE and select Find in Reference. It has to be located in this folder:
InstallationDirectoryOfYourIDE\reference\www.arduino.cc\en\Reference

The three words are separated by true tabs (not multiple space characters). Before creating your own .html file you can just copy one of the files there and rename it to Foo. Note that your library doesn't have to contain anything else besides the three mentioned files and some file in the reference folder for this to work. At this point you should restart your IDE and check whether your keyword foo is highlighted and offers the option Find in Reference when you right click it. If so, success! You can now move on to create your own .html file to put in the reference folder.
You could start by just changing one of the existent files to fit the style of the Arduino API, but you could also create your entirely own files. The probably best option however is to write your library according to doxygen standards and then let doxygen do the work for you creating the file automatically.
Just one more thing to be mentioned: This method works for any keywords that are used in the way yourKeyword or something.yourKeyword, but not Something::yourKeyword (this is how you would use a static function or variable in your library). According to @Juraj this is something caused by the IDE. There is a workaround for this though: Replace each line in the keywords.txt file
yourKeyword KEYWORDX    ReferenceFile

with
yourKeyword KEYWORDX    ReferenceFile
YourLibrary::yourKeyword    KEYWORDX    ReferenceFile

This way yourKeyword will be highlighted as you would expect it but occurrences like YourLibrary::yourKeyword will also bring up the option Find in Reference when right clicked.
That's it for today. Thanks and bye bye!

So, it requires modifying the reference folder in the Arduino installation as well as installing the library? Are there any ways to automate this, or does the user have to download each part individually?

Arduino uses the keyword.txt file to highlight words and to define a reference page to keywords. But the reference page must be in reference folder of IDE installation and the keyword.txt contains only a filename, not the path.

REFERENCE_LINK This field specifies the Arduino Language Reference page to open via Right Click > Find in Reference or Help > Find in Reference when the cursor is on that keyword. Generally it does not make sense to define the REFERENCE_LINK field for 3rd party library keywords since they are not likely to be in the Arduino Language Reference.

I have a library which implements WiFiClient and WiFiServer like the Arduino WiFi library, so I can link in keywords.txt to Arduino reference like this:
WiFiClient  KEYWORD2    WiFiClient
WiFiServer  KEYWORD2    WiFiServer
WiFiUDP     KEYWORD2    WiFiUDPConstructor

The names used are names of html files in Arduino\reference\www.arduino.cc\en\Reference.

the answer is that it is not possible

I updated the answer

the reference names in keyword.txt are names of html files located somewhere in reference folder

the keywords.txt must use tabs to separate the fields. did you restart IDE?

sorry, the file must be in C:\Program Files (x86)\Arduino\reference\www.arduino.cc\en\Reference

do you have the keywords.txt file in the library folder next to library.properties? does your library match the 1.5 library specification?

here it works. as soon as I put the third field in keyword.txt the "Find in reference" is enabled even if the file name is not valid. Now I see, that the text cursor must be on the word too.

the library is WiFiEspAT (in Library Manager), but I published it without keywords.txt. To test this answer I copied keywords.txt from Arduino WiFi library and added a line for beginAP which doesn't exist in Arduino WiFi library. and I added the reference file to the Reference folder

This library works. What do I have to do for my own library to work like this? Could you please provide a minimal example for a custom library?

https://github.com/jandrassy/lab/tree/master/Foo

I just found out something very interesting. When writing the keywords from my library in the IDE just by themselves or in the form something.keyword it works as intended. But if I write them in the form Library::keyword (as is done with static things from the library) the keyword is highlighted but the function to find it in the reference does no longer work. Why is this and how do you fix this?

I can't change how IDE works


text:
What are exactly XTAL1 and XTAL2 pins in Arduino Uno/Nano?
I know that the blow red encircled component is the 16MHz Crystal Oscillator (XTAL):

But PB6 and PB7 pins are called XTAL1 and XTAL2 pins which are not accessible by the Arduino board.
Are these pins where the 16MHz crystal oscillator is connected. But if so why are they two of them? I searched net but couldn't find explicit information about these.
How many clocks in total this board have?

Yes they connect to the crystal. There's two of them because a crystal has two pins.

But what is the difference between them? One is not ground. So they have difference in implementation or use. Is that something to do with CMOS or TTL interfacing? Im looking for a more detailed answer.

Look up some typical crystal oscillator circuits. All but the crystal is inside the chip.

Im asking what is the difference between XTAL1 and XTAL2 explicitly not how to connect a crystal osc to them.

One is the drive output and the others the sense input. To understand what they do you first have to understand how a crystal oscillator circuit works.

https://www.electronics-tutorials.ws/oscillator/crystal.html scroll down to the CMOS oscillator. The gates are inside the mcu. Where the crystal fits in that circuit are the xtal1 (gate input) and xtal2 (junction between two gates).

I marked in red to be sure is it something like that: https://i.stack.imgur.com/gvcMB.png ??

Yep, that's right.

The Crystal in Red is for the Atmega16U2 that manages the USB interface with its high speed connection to the PC (12 MHz for USB2 I think).
The Resonator in Yellow is for the Atmega328P.  It is less precise than the crystal oscillator.
PB6 and PB7 are dedicated to the external crystal or resonator by the fuse settings used for Arduino.
You can read more about the XTAL1, XTAL2 pins and the fuses from the device datasheet
https://www.microchip.com/wwwproducts/en/ATMEGA328P
You can connect a crystal to the pins, but you will also need 22pF caps to connect from the pins to Gnd. And remove the resonator.  Current Uno layout does not really support making those connections.

XTAL1 is the input and XTAL2 is the output of the oscillator.
Using 8MHz internal RC oscillator instead of the crystal, you can use PB6 and PB7 as I/O, like other I/Os.


text:
Arduino - Extracting Multiple Strings from Serial Read
I am trying to write an Arduino code that reads a long string, example <11,22,33>, through the Serial Monitor and then stores the 11,22, and 33 into separate bins of a matrix array.
So the user could input: <11,22,33>
And the code would store the three entries into a matrix of strings:
matrix[0]=11;

matrix[1]=22;

matrix[2]=33;

Whenever I try to run the code the only result that's outputted is
matrix[0]=33;

matrix[1]=33;

matrix[2]=33;

But the strange part is when I put print commands after the Matrix[i]=data line in the code, the output shows the correct numbers! I'm not sure where the issue is and if somehow I made all entries the final entry. Any help is appreciated!
// Example 3 - Receive with start- and end-markers

const byte numChars = 32;
char data[numChars];    //data entry for appending Serial data
char *matrix[numChars]; //matrix of data entries
static byte i=0;  //matrix index

boolean newData = false;

void setup() {
    Serial.begin(9600);
    Serial.println("<Arduino is ready>");
}

void loop() {
    recvWithStartEndMarkers();
    showNewData();
    Serial.println(matrix[1]);
}

void recvWithStartEndMarkers() {
    static boolean recvInProgress = false;
    static byte ind = 0;  //data index
    char startMarker = '<';
    char midMarker = ',';
    char endMarker = '>';
    char rc;    //Serial read character

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (rc == startMarker) {
            recvInProgress = true;  //if startMarker arrives then enter secondary if below
        }

        else if (recvInProgress) {  //begin appending characters if startMarker activated switch

            if (rc == midMarker) {  //if midMarker is reached...
                matrix[i]=data;     //append data to i-th entry in matrix
                i++;                //add to matrix index
                data[0] = '\0';     //clear data
                ind = 0;            //reset data index
            }
            else if (rc == endMarker) {     //if endMarker is reached...
                matrix[i]=data;             //append data to last entry in matrix (ensures last data is appended)
                data[ind] = '\0';           // terminate the string
                recvInProgress = false;
                ind = 0;                    //reset counters for data and matrix
                i = 0;
                newData = true;
            }
            else {
                data[ind] = rc;           //eppend Serial character into data
                ind++;                    //add to data index
                if (ind >= numChars) {
                    ind = numChars - 1;
                }
            }
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(matrix[0]);
        Serial.println(matrix[1]);
        Serial.println(matrix[2]);
        newData = false;
    }
}

You define pointers for each value as :
char *matrix[numChars]; //matrix of data entries

However, in all cases you let it point to data:
matrix[i]=data;

Than you set the value starting from that address. So what happens is after you read the first value (11), and matrix[0] contains '11', than matrix[1] points to the same data which you write the value 22 to. And you do the same for 33. So you end up with 3 pointers to the same address (data) containing/overwriting the last value (33). So you get three times 33.
You should either continuing writing the string in data and refer to the correct part inside the string data.  If you want to do a Serial.println, you have to end the strings with \0, so the string data and matrix references should be:
index:    0   1  2  3  4  5  6  7  8
data:     1   1 \0  2  2 \0  3  3 \0
matrix:  [0]       [1]      [2]
i:        0         1        2

It will help if you change
matrix[i]=data;

to
matrix[i]=&(data[ind]);

I'm not sure I understand your corrections. If I change matrix[i]=data to matrix[i]=&(data[ind]) what's printed is blank.

I didn't try the program, so it's a bit hard to verify out of my head. I think you should change the line at the end of my answer in both cases (if (rc == midMarker) and (rc == endMarker). Also in the midMarker case, I think you have to put i++ before the matrix[i] assignment.
However, I suggest you test this function not on an Arduino but in e.g. VisualStudio on a PC. Call the function and step with a debugger through the code so you can see immediately what is wrong.


text:
LED GPS Speedometer Not Registoring Speed Above 0
I'm trying to make a speedometer that will change colors depending on the speed on which I am traveling.
If the speed is decreasing at any time or below 5 mph LEDs be red.
And if the speed is above 5 mph or increasing speed the LEDs will be a different color.
I am using an Adafruit 24 NeoPixel ring for LED's and a u-blox NEO-6 GPS module.
And the GPS is sometimes not registering the speed or any other GPS values and not switching colors when speed is at certain values or when it is increasing or decreasing. It tends to stay only one color no matter the speed. Also the GPS is not registering speeds above zero when I ride my bike or in a moving car.
I added a picture of the values I am getting, it seems to be connecting to satellites and getting correct GPS coordinates but as soon as I as I take it to real world test, the speed inst changing and LEDs are not changing. I also included a picture of the Arduino configuration I am using.
I am a very new to coding so any help would be very grateful.
(if anyone could help with the accelerating and decelerating code to that would be absolutely amazing!!!!)

#include "TinyGPS++.h"
#include "SoftwareSerial.h"
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define LED_PIN  6
#define LED_COUNT 24
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_RGB + NEO_KHZ800);
SoftwareSerial serial_connection(10,11);
int speedM;
TinyGPSPlus gps;

void setup() {
  #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
#endif
  strip.begin();
  strip.show();
  strip.begin();
  Serial.begin(9600);
  serial_connection.begin(9600);
  Serial.println("Project Red Stop");
}
void loop() {
speedM = gps.speed.mph();
//int val = speedM;
 while(serial_connection.available())//While there are characters to come from the GPS
  {
    gps.encode(serial_connection.read());//This feeds the serial NMEA data into the library one char at a time
  }
  if(speedM < 5)
  //   if(speedM < 5 & val--)
  {
    Serial.println("Speed MPH:");
    Serial.println(gps.speed.mph());
    Serial.println("Satellite Count:");
    Serial.println(gps.satellites.value());
    Serial.println("Latitude:");
    Serial.println(gps.location.lat(), 6);
    Serial.println("Longitude:");
    Serial.println(gps.location.lng(), 6);
    colorWipe(strip.Color(0,100,0), 100);
   // strip.setPixelColor(0, strip.Color(0,100,0));                   // gps works faster with this:
    strip.show();
    delay(10);
  }
  else if(speedM > 5)
  //   else if(speedM > 5 & val++)
  {
    Serial.println("Speed MPH:");
    Serial.println(gps.speed.mph());
    Serial.println("Satellite Count:");
    Serial.println(gps.satellites.value());
    Serial.println("Latitude:");
    Serial.println(gps.location.lat(), 6);
    Serial.println("Longitude:");
    Serial.println(gps.location.lng(), 6);
    colorWipe(strip.Color(0,100,100), 100);
    strip.show();
    delay(10);
  }
}
void colorWipe(uint32_t color, int quick) {
  for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
    strip.setPixelColor(i, color);         //  Set pixel's color (in RAM)
    strip.show();                          //  Update strip to match
    delay(0);                           //  Pause for a moment
  }
}

why do you expect the color of the LEDs to change if you cannot determine the speed?

I am just looking for help. You are right if i cant get speed i cant get color change. but i figured i just ask for help.

Separate your code into two parts: measuring speed with the GPS, and displaying LED colors according to acceleration & velocity (which you would provde as constants or terminal inputs). Get each part working, then recombine them. It's much easier to build up your application piece by piece, substituting trivial code - called 'stubs' - for the parts that don't exist yet, than it is to write the whole app and then try to debug everything at once. The stubs just provide made-up data instead of trying to get it from a complex devices like a GPS.

Why didn't you edit your first question. It is the same. You should delete one of them

Im very new to this site, i did not know i could edit previous posts, thank you for that fact ill try to remove the older post.

5 mph is slow (about 2.2 meters/second). And 2 meters accuracy is difficult to obtain (according to this stack exchange Q/A) for a normal GPS (and that is if the GPS signal isn't scrambled). Consider an alternative such as an acceleration sensor for such slow speeds and for such small speed changes.


text:
Difference between L298 and L298N motor driver
I was planning to buy a motor driver for my project purpose, but I don't understand which motor driver will suit my purpose. As there are two motor drivers available online. Can someone explain me the main difference between the two :
L298N : https://www.amazon.in/L298N-Based-Motor-Driver-Module/dp/B01N1H97CL
L298 : https://www.amazon.in/Robodo-L298-Motor-Driver-Module/dp/B00N4KWYDE?tag=googinhydr18418-21

Have you looked into the datasheet?

L298 is the name of the chip. The most often used variant is the L298N. The so called Multiwatt L298.  I would say, both boards use the same chip. L298N. The other variant are L298HW and L298P (horizontal Multiwatt and SOIC packaging).

The chip itself can drive up to 4A but the boards may differ. The L298N called board is specified with 2 Ampere.  The L298 called board is described with 2A too.

Those are exactly the same boards just viewed from different angles.


text:
Including keypad library removes sound from my piezo element
I am using the keypad library to include keypad and input numbers. when a specific number is entered a sound must be made.
However when I input using the serial monitor , sound is working. But when I include keypad , it only inputs numbers but not sound.
Help please , how can I make both work?
Thanks.
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {12, 11, 10, 9}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8,7,6,5}; //connect to the column pinouts

Then I get the input from keypad and store as result
char guess = 'n';
 char keypressed = keypad.getKey();
  if (keypressed != NO_KEY) {
    char guess = keypressed;
in void loop, it get result(key from keypad) and must play it: Tried separate sketch it works. but with keypad only input is , not sound.
Serial.print("You guessed:");
      Serial.println(guess);
      result = checkYourself(guess);
      Serial.println(result);
      playSound(result);
check yourself takes in guess from keypad ,checks then returns as result.
play sound function works when tried in another sketch( sorry not posting too much code its very long)

it is difficult to determine the problem area without seeing your code ... please include minimal sketch that still exhibits the undesired behavior

I just posted it thanks.

which pin are you using for the buzzer?

using pin 9 ....

which pins does the keypad use?

5,6,7,8,10,11,12 removed pin 9 because not using a row

how di you tell your code that it is not to use pin 9 for the keyboard?

I was able to solve it , piezo dissent work in pin 9 but works when connected to pin 13.

Please make sure that the pin connected to piezo does NOT used by keypad


text:
Common button on two Arduinos and two computers
We have two computers giving two presentations that need to    be triggered in sync. I know how to send the space button via Arduino, but I want to check it will be safe for the computers. If each Arduino is connected to their computer via USB, both data pins togeather and both grounds togeather (not sure if I can find a dt momentarily push button in two days). Is there anything I should keep in mind incase both sides are not at the same voltage as eachother?

The ground of both computers are connected also via their power lines. You get a ground loop that might result in malfunctions and/or defects.
Think about using a galvanically separated connection, for example via an optocouple.

As long as you don't have to send anything from the pcs to the arduinos (or at least not with both) you can simply connect the arduinos TX with both pc's RX. This way you need only one arduino. Use series resistors (1k) to handle voltage differences between the pcs.
If you need two arduinos you're fine without galvanic isolation, but I recommend series resistors on the reading gpios as well (just in case you configure the ports as outputs accidentially). In case you use laptops which usually don't have PE, you have to connect the arduinos grounds as well.


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:
Distorted audio from mcp3002
I have setup a MCP3002 to convert an analog signal to digital signal. When I read it directly through serial and convert it to a wav file, it sounds relative clear. Serial is limited for samples per second though, I can get about 7000 sps.
When I send the signal directly to a server I can reach around 17.500 sps. however when I convert this to a wav file, it also sounds relative clear, but with a slight distortion/'robot voice' through the audio.
Is there a simple way to prevent this, or why is this happening?
The code how I read the SPI is in this question:
Reading data from MCP3002

Without any code we cannot do much. Having a robot voice sounds like a sampling frequency issue. How do you set a sampling frequency and how did you measure the sample frequency?

Does your ADC reach saturation? You can check whether you have samples with values 0 or 1023. Are you sure your sampling rate is strictly constant? Unless your SPI is clocked from a timer it probably isn't.

@chrisl the code for reading mcp is added in the link (from another question, where you have also helped me =) )

@EdgarBonet I added the code how I read the code, the ADC is between 100 - 200 so no saturation. My SPI is set at a constant frequency if that is what you mean?

And how are you sending the signal directly to a server? That is not in the code of your previous question. That can be very important, since it may screw up your timing, thus producing an unstable measurement frequency.

I can add this tonight, it is a 'windowed' buffer which are send through UDP. Good thing to look at this indeed!

From the code you linked to, it appears the SPI port is completely
controlled by the software:
void loop() {
    ...
    msb = SPI.transfer(cmd);
    lsb = SPI.transfer(0);
    ...
}

This means that the timing of the SPI transaction (when exactly it
starts) and, by extension, the timing of the ADC conversion, is
dependent on the timing of your code execution. You have no good control
on that timing. It depends on what other things may be in your loop, and
on the other interrupt sources (timers, network...).
The least you can do is set up a timer interrupt, and run the SPI from
the interrupt handler. Your timings should then be more consistent. You
will still have some jitter due to the interrupt handler being delayed
by some critical sections, including other interrupts. But it may be
good enough for your application.
For best results, you would ideally want the timing to be completely
controlled by hardware. Maybe there is a way to trigger the SPI port
from a timer. This depends on the specific MCU you are using: you will
have to dig into the datasheet.


text:
Arduino beginners kit example not working
I bought a beginners kit and can get all but one of the examples to work. I have tried different board layouts and varied the code with no success. When I first run the code the LED is off. When I ground pin 9 the LED comes on and stays on. Grounding pin 8 does not turn off the LED once it is lit.
int ledPin = 5;
int buttonApin = 9;
int buttonBpin = 8;

byte leds = 0;

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
}

void loop()
{
  if (digitalRead(buttonApin) == LOW)
  {
    digitalWrite(ledPin, HIGH);
  }
  if (digitalRead(buttonBpin) == LOW)
  {
    digitalWrite(ledPin, LOW);
  }
}

Code should read:

Does pin 9 stay grounded after the LED turns on? If you ground both pins with that code you will have the LED at about half intensity, since you are turning it off and on very fast

Pin 9 is only grounded momentarily but the LED stays on afterwards. After I press the button and release I assume both 8 and 9 are floating, but neither are grounded until I press a button again.

I have tested this with your wiring and your code and it works like a charm. I can turn off the LED with the button at pin 8. You must have done something different, than you stated in your question

Thanks Chris. I will have another go. I have tried a few times now with no success and different configurations.

Maybe you can post a good photo of your actual circuit. And some breadboards have the outer rails divided in two parts. If that is the case, button 8 would not be connected to ground. Please check that.

Thanks Chris. Works now. May have been a bad connection.

A multimeter can be useful in troubleshooting hardware setups. You could use it to check that pin 8 is actually being shorted to ground when the button is pressed, for example. (Set the meter to continuity mode, attach one lead to a spare ground on the Arduino, and the other to the pin 8 section of your breadboard. The meter should beep when you press the button. If not, start working backwards until you figure out where you have an open circuit.

touch the yellow button to ground instead of pressing the button

If you have conected it exactly like in the image, maybe you've got breadboard with power rails separated in the middle (I've got plenty of them and they all have this "feature"). However it's also displayed by colored lines next to it. If there is a space in the middle, it's not connected

This kind of button has 4 pins. These pins are internally connected in pairs. It's easy to make a mistake when wiring. Please post the real picture of your wiring. Or you can refer to read more about button pin in this post


text:
ESP8266 WiFi doesn't reconnect
I've been reading this post while trying to optimize the usage of the WiFi module on my ESP8266.
My main goal was to be able to connect/disconnect (respectively turn on/off) the WiFi module so I can optimize electricity consumption of the chip (I am trying to solar power it).
So, the way I integrated the proposed solution is as follows as I am no where calling deepSleep:
#include <RelayModule.h>
#include <ESP8266WIFI.h>
#include <rdm6300.h>
#include <string.h>
#include <ctime>

extern "C" {
    #include "user_interface.h"  // Required for wifi_station_connect() to work
}
/*...*/
#define RFID_PIN 13
#define RELAY_PIN 10
#define FPM_SLEEP_MAX_TIME 0xFFFFFFF
#define RELAY_OPEN_DURATION 6

RelayModule relay(RELAY_PIN);
Rdm6300 rdm6300;

int relayTurnedOnAt = 0;

void WiFiOn();
void WiFiOff();

void connectToWifi() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
     delay(500);
  }
}

void setup() {
  connectToWifi();
  rdm6300.begin(RFID_PIN);
  /*...*/
}

void openFrontDoor() {
  WiFiOn();
  if(relay.isOff()){
    relay.on();
    relayTurnedOnAt = time(0);
  }

  /*Perform some business logic which makes a reference to Services hosted on the Internet*/
}

void lockFrontDoor() {
  relay.off();
  WiFiOff();
}

void loop() {
  // RFID TAG WAS SCANNED
  if (rdm6300.update()){
    openFrontDoor();
  }

  if (relay.isOn() && abs(time(0)-relayTurnedOnAt) > RELAY_OPEN_DURATION)
    lockFrontDoor();
}

void WiFiOn() {
    wifi_fpm_do_wakeup();
    wifi_fpm_close();

    //Serial.println("Reconnecting");
    wifi_set_opmode(STATION_MODE);
    wifi_station_connect();
}

void WiFiOff() {
    //Serial.println("diconnecting client and wifi");
    //client.disconnect();
    wifi_station_disconnect();
    wifi_set_opmode(NULL_MODE);
    wifi_set_sleep_type(MODEM_SLEEP_T);
    wifi_fpm_open();
    wifi_fpm_do_sleep(FPM_SLEEP_MAX_TIME);
}

The problem here is that once disconnected, I can not get the WiFi module connected back. I need to reset/restart the chip and then I get connected to the internet once again. I would like to be able to fully disable the module when not needed (and save power) and when I need it to submit some stuff to the internet - wake it up, do the job and then bring it back to suspended mode.

Perhaps the method wifi_station_disconnect(); drops you WIFI connection at all. Perhaps you have to perform connectToWifi(); again. But as I don't know the user_interface.h,  it is just a guess ;-)..

why do you use the SDK API. the Arduino WiFi API has all functions to turn off WiFi an turn it back https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/generic-class.html#mode


text:
Pulse Sensor Working Bottom-Side-Up Better?
i recently bought me an pulse-heartbeat sensor.
Connected him to my brand new M1 mini as well.
I wrote a piece of Code which just outputs the Raw ADC Value from A0 (where the pulse sensor is connected).
Now I'm confused.. When i open Serial Plotter, i get this:

Which is confusing because i don't get useable Values when putting the sensor up side down, which is the promoted way to do this (i guess!!)
When i press the other side against my wrist, i get this:

Which i can work with..
But it still doesnt look like some of those perfect diagrams on the internet.
Any can help me understand why i get this type of behaviour?
thanks, nice friday , luca

is that the correct usage of the device? ... what happens if you put your finger on the sensor?

Need to build a watch  So there are some significant  cons to put it on finger

place the sensor as it is in the picture ... cover the sensor so that extraneous light does not get to it ... wrap a towel around your wrist, for example

„cover the sensor so that extraneous light does not get to it ..“, thanks mate nice tip

From what I see, this is a pulse sensor that work with light. It emits a bright light beam, that is reflected by the pulsing blood. To work, it must send the light directed to your veins. It should work well on your finger, because the probability to target a vein directly is much greater with a small finger then e.g. a wide wrist. Also the veins in your finger are closer to your skin and the oxygen situation is more different while pulsing, so the blood has more impact on the reflection.
The second curve might be a light source in your room, or an electrical wave. (?) I doubt it is your heart, because, if the numbers below the graph are milliseconds, then your heartbeat would be between 10-15 beats / second, i.e. 600 - 900 per minute. That would be too much even for a hummingbird ;-).

Thanks for the input!


text:
wake from powerDown to check sensor then put back to sleep
I am using an Arduino Pro Mini with various sensors.  I am powering it with 2 3.7v 3400mA batteries which I recharge with a solar panel.  I take a reading from the batteries and if the  reading is above a certain number I disconnect the solar panel from the batteries using a relay.  Then when the battery reading gets below a certain number I switch back on the solar panel using the same relay.  This all works fine.
To conserve energy I want to delay the loop to the Arduino's activities for say two hours.
Right now I call lowPower(); at the end of the loop{.
void lowPower(){ is
LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);

Which I continually repeat for the two hours I want.
The problem is during this two hours the high or low limit of the battery charge could be reached but I wouldn't know it.
What I would like to do is repeat
LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);

for 15 minutes and then check the batteries and turn on or off the solar charger as need.
Then repeat the whole thing until two hrs is reached.
At that point I would rerun the loop{ to check all sensors etc.
I have tried the following
   void loop(){
    //code to run other sensors etc.
    if (Delay ==4) {
  delay(180000);
//check the battery to begin with
sensorBatValue = analogRead(batteryInPin);
  delay(500);
if(chargeSwitch ==1){
 if(sensorBatValue < batteryNoCharge) {
  }
 else if(sensorBatValue > batteryNoCharge) {
     digitalWrite(10,HIGH);
   delay(1000);
   digitalWrite(10,LOW);
   chargeSwitch = 2;
  }
   }
else if(chargeSwitch ==2){
    if(sensorBatValue > batteryCharge) {
    }
    else if(sensorBatValue < batteryCharge) {
      digitalWrite(13,HIGH);
    delay(1000);
   digitalWrite(13,LOW);
   chargeSwitch = 1;
    }
  }
//put to sleep
lowPower();
//check battery again
delay(180000);//real
sensorBatValue = analogRead(batteryInPin);
  delay(500);
if(chargeSwitch ==1){
 if(sensorBatValue < batteryNoCharge) {
  }
 else if(sensorBatValue > batteryNoCharge) {
     digitalWrite(10,HIGH);
   delay(1000);
   digitalWrite(10,LOW);
   chargeSwitch = 2;
  }
   }
else if(chargeSwitch ==2){
    if(sensorBatValue > batteryCharge) {
    }
    else if(sensorBatValue < batteryCharge) {
      digitalWrite(13,HIGH);
    delay(1000);
   digitalWrite(13,LOW);
   chargeSwitch = 1;
    }
  }
// put to sleep
lowPower();
//repeat for total of 2 hours.
}

 void lowPower(){
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    //repeat until 15 minutes is reached
}

This doesn't seem to work.  The Arduino waits the correct time but from what I can tell the battery is never checked.
Or should I try
    void loop(){
    everything
    if (Delay ==4) {
  delay(180000);//real
  sensorBatValue = analogRead(batteryInPin);
  delay(500);
if(chargeSwitch ==1){
 if(sensorBatValue < batteryNoCharge) {
  }
 else if(sensorBatValue > batteryNoCharge) {
     digitalWrite(10,HIGH);
   delay(1000);
   digitalWrite(10,LOW);
   chargeSwitch = 2;
  }
   }
else if(chargeSwitch ==2){
    if(sensorBatValue > batteryCharge) {
    }
    else if(sensorBatValue < batteryCharge) {
      digitalWrite(13,HIGH);
    delay(1000);
   digitalWrite(13,LOW);
   chargeSwitch = 1;
    }
  }
    //include the checking of the battery inside the lowPower
    void lowPower(){
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    etc.
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    //check battery after 15 min.
    delay(500);
       sensorBatValue = analogRead(batteryInPin);
    delay(500);
    if(chargeSwitch ==1){
     if(sensorBatValue < batteryNoCharge) {
     }
     else if(sensorBatValue > batteryNoCharge) {
         digitalWrite(10,HIGH);
       delay(1000);
       digitalWrite(10,LOW);
       chargeSwitch = 2;
      }
       }
    else if(chargeSwitch ==2){
        if(sensorBatValue > batteryCharge) {
       }
        else if(sensorBatValue < batteryCharge) {
          digitalWrite(13,HIGH);
        delay(1000);
       digitalWrite(13,LOW);
       chargeSwitch = 1;
        }
      }
    //then repeat to two hours
    }

Do I need to do something to wake up the Arduino and Turn on the battery sensor pin and turn back on ADC?
Not sure how to do this Please HELP.

Please don't post pseudo code (how should we know what condition is?) and indent your code properly. I'm not going to solve that puzzle...

You have to note that if you go in "power down" mode, you will not be able to get the time as millis() will return the wrong time.
If you just want 15 minutes, you can just put it inside a for loop:
for(int j=0;j<112;j++) LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);

So the next instruction will be executed approximately after 15 minutes (15 * 60 / 8 = 112).
I made a similar project with a Teensy. With it you have more functions for the time. Just remember that with the power down, you will not be able to have any time function without an external time module on the Arduino.
Battery measurement schematics is also important. If you insert 2 resistors like 1M and 4M you will not be able to measure it since the measurement is done internally over multiple measurements and the current is not enough to measure it more than 1 time every 10-20ms. You have to add a capacitor to read a good value.

Try to use an external timer. I have the same problem approximatly.

I don't want to use an external timer as that adds energy costs.  There should be a way to do this.

In your function lowPower(), instead of repeating the LowPower.powerDown(), loop over that call enough time to make up the total sleep-time you need. That's the general case. For your specific case, where you need 15-minute intervals and 2-hour intervals, lowPower() should loop 113 times (15:04, since 15 *60 doesn't divide evenly by 8). In your loop() function, loop over lowPower() 8 times (to make 2 hours), and each time it returns, check your battery. When the loop over lowPower() exits, it's time to do your "every 2 hours" jobs.
Because the 8s doesn't evenly divide 15 minutes, this timing isn't exact (but neither is the watchdog timer!), so you may want to tweak things a little, such as using a 4-second sleep, which does divide evenly.
Also, when I indented your code, I found void lowPower() nested inside the loop() function. C doesn't support that. If that was unintentional, check the pairing of your braces.


text:
Please help. Error message “sendSMS not declared in this scope” im frustrated. :(
//INCLUDED LIBRARIES
 #include <GPRS_Shield_Arduino.h>
#include <SoftwareSerial.h>
#include <Wire.h>

//SERIAL PIN ASSIGNMENT, BAUDRATE, PHONE NUMBER, MESSAGE
#define PIN_TX    2
#define PIN_RX    3
#define BAUDRATE  9600
#define PHONE_NUMBER "+639158848570"       //CELLPHONE NUMBER
#define MESSAGE  "Notice: Please be informed that your area is under Level 1 advisory with 4-inches flood depth. Continuous flood is expected due to the heavy rainfall. Be prepared and secure your important documents and belongings in high places. Avoid wirings from getting wet to prevent further injuries and accidents."  //COMPOSE YOUR MESSAGE HERE
#define MESSAGE_LENGTH <=500
char MESSAGE1;

//SERIAL PIN ASSIGNMENT, BAUDRATE, PHONE NUMBER, MESSAGE
#define PIN_TX    2
#define PIN_RX    3
#define BAUDRATE  9600
#define PHONE_NUMBER "+639379488989"       //CELLPHONE NUMBER
#define MESSAGE  "Notice: Please be informed that your area is under Level 1 advisory with 4-inches flood depth. Continuous flood is expected due to the heavy rainfall. Be prepared and secure your important documents and belongings in high places. Avoid wirings from getting wet to prevent further injuries and accidents."  //COMPOSE YOUR MESSAGE HERE
#define MESSAGE_LENGTH <=500
char MESSAGE2;

//SERIAL PIN ASSIGNMENT, BAUDRATE, PHONE NUMBER, MESSAGE
#define PIN_TX    2
#define PIN_RX    3
#define BAUDRATE  9600
#define PHONE_NUMBER "+639357120147"       //CELLPHONE NUMBER
#define MESSAGE  "Notice: Please be informed that your area is under Level 1 advisory with 4-inches flood depth. Continuous flood is expected due to the heavy rainfall. Be prepared and secure your important documents and belongings in high places. Avoid wirings from getting wet to prevent further injuries and accidents."  //COMPOSE YOUR MESSAGE HERE
#define MESSAGE_LENGTH <=500
char MESSAGE3;

char phone[16];
char datetime[24];

GPRS GSMTEST(PIN_TX,PIN_RX,BAUDRATE);//RX,TX,BAUDRATE

void loop() {
      // read the output on digital pins:
  int Level1 = digitalRead(5);
  int Level2 = digitalRead(6);
  int Level3 = digitalRead(7);

  // print out the value you read:s
  if (Level1 != 0){
    Serial.print("Level 1 =  "); Serial.print(Level1); Serial.print("   ");
    sendSMS();
  }
  else if (Level2 != 0){
    Serial.print("Level 2 =  "); Serial.print(Level2); Serial.print("   ");
    sendSMS();
  }
  else if (Level3 != 0){
    Serial.print("Level 3 =  "); Serial.print(Level3); Serial.println("   ");
    sendSMS();
  }
  delay(1);//delay ms

//void setup() {
//  loop();
//}

void sendSMS() {
  Serial.begin(9600);
  while(!GSMTEST.init()) {
      delay(1000);
      Serial.print("INIT ERROR\r\n");
  }
  Serial.println("GSM INIT SUCCESS");
  Serial.println("START TO SEND MESSAGE ...");
  Serial.print("..");
  delay(1000);
  Serial.println(".....");
  delay(1000);

  GSMTEST.sendSMS(PHONE_NUMBER,MESSAGE); //DEFINE PHONE NUMBER AND TEXT

}

void readSMS(){
     //READ THE INCOMING SMS MESSAGE
   Serial.println("   ");
   Serial.println("   ");
   messageIndex = GSMTEST.isSMSunread();
   if (messageIndex > 0) { //AT LEAST, THERE IS ONE UNREAD SMS
      GSMTEST.readSMS(messageIndex, message, MESSAGE_LENGTH, phone, datetime);
      //IN ORDER NOT TO FUL SIM Memory, IS BETTER TO DELETE IT
      GSMTEST.deleteSMS(messageIndex);
      Serial.print("FROM NUMBER: ");
      Serial.println(phone);
      Serial.print("DATE/TIME");
      Serial.println(datetime);
      Serial.print("RECEIVED MESSAGE: ");
      Serial.println(message);
   }
}

What is wrong with my code? :(

it is incomplete again and you didn't post the error messages. one of the libraries has a variable called message so don't use this name

That is all the code.
The error message is sendsms is not declared in this scope.

You forgot to close your loop() function - so the sendSMS() function is inside it and never gets declared.

Where is that? :(

As @Majenko said, count the number of curly brackets after the "void loop() {" line.  You will find there is none which match w/the curly bracket in the "void loop () {" line of code. So you confused the compiler.  And now you are getting errors from the compiler which are confusing you.  (Fair's fair :)! )

Consider editing your original question instead of re-posting. You need to make more of an effort to make your questions clear. Add text to the question explaining the problem. And make the title specific to the problem And try to format the code by highlighting the code and picking "code" from the menu. Remember: The point of stack exchange sites is to create clear and concise questions & answers that other people can find and use over and over again.


text:
Having trouble figuring out CTC on Timer 1 with ATTiny85
I'm using Timer1 on the Attiny85 clocked at 1MHz to toggle an LED every 1 second. However, I'm having some issues regarding prescaler and OSC value selection.
I'm using this formula, which I found in the datasheet for the Attiny.
fOCnx = fclk/(2*N*(1+OCRnx))

N = Prescaler
I'm taking fOCnx = 0.5Hz as I want a square wave
So based on the above formula, I tried the following cases

N = 2048, OCR1C = 243
N = 4096, OCR1C = 122
N = 8192, OCR1C = 61
N = 16384, OCR1C = 30

The LED toggles after an interval of 1s for cases 3 and 4. However, for cases 1 and, it seems to toggle after 2 seconds. Can anyone tell me why this is happening? Eventually, I want to use this to time data acquisition from a sensor I have so I need to be accurate.
Here's my code
#include <SoftwareSerial.h>

int ledPin = 1;
int state = 0;

SoftwareSerial ser(3, 4);
void setup() {
  // put your setup code here, to run once:
  TCCR1 |= 0x8F;
  OCR1C = 30;
  TIMSK = (1 << OCIE1A);
  pinMode(ledPin, OUTPUT);
  ser.begin(9600);
}

ISR(TIMER1_COMPA_vect)
{
  state = !state;
  digitalWrite(ledPin, state);
  ser.println(state);
}

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

Have you double checked your settings for each case. I don't want to say you made a mistake. But what happens is hard to explain otherwise.  My values would be (TCCR1, OCR1C) -> (0x8f,30), (0x8e,61), (0x8d,122), (0x8c,244). I only see one of them in the code, so I can not say if you used the others. If you by accident use (0x8c,122) and then made just subtract 1 and double for the next text (0x8b,244)  the observation could be explained.  I also have a problem with the 2 in the formula. Where does it come from?

Ah, I see why you used 2 in the formula. You don't want 0,5 Hz, you want 2 Hz to toggle 2 times in a period of 1 second (0.5 sec from toggle to toggle. 0.5 Hz would be 2 sec from toggle to toggle).

I wrote 0.5Hz because the period of the cycle (On+Off) = 1+1 = 2s so 0.5Hz. I hope I could clarify.

yes, then I misunderstood. But then I have no glue why there is the 2 in the formula. fOCnx = fclk/(2*N*(1+OCRnx)) I mean I have no glue why it is in the nominator of the fraction. If I I insert one of the value pairs above I get 1 Hz. If I multiply both sides with 2. I get 2 Herz but not 0.5 Hz. Do you see my problem?

Well, unless there is some serious problem with my understanding, all the values calculated satisfy the formula, which I found from the datasheet on page 72. What is the formula you're using?

Ah, I see. The formula is used to compute the frequency of a squared waveform, but for a full wave length (High and LOW phase included).  So they have to toggle the output pin two times for one wave length. With this formula the interrupt routine where you toggle the pin is fired twice as often as you want it to. The values you computed are correct for this formula, and you get 1 Hz which each pair. But this 1 Hz means a square wave with a frequency of 1 Hz. But you need the IRQ routine to be fire with 1 Hz. To achieve that you had to remove the 2 from the formula and recompute the values.

Yes, but the problem is I'm achieving 1Hz for only cases 3 and 4. What's going on that's giving me the problem?

You're right, we drifted away from that. So I asked you if you've double checked the value you used in the program. I would use the following values: (TCCR1, OCR1C) -> (0x8f,30), (0x8e,61), (0x8d,122), (0x8c,243). I don't want to waste time thinking about other possibilities of failure if this is not clarified.

Ahh now I understand your confusion. The values I've used are given in my question and they're all the same as you've mentioned. I've just given one case in my program, which is case 4 as per the question.

Any solution @Peter Paul Kiefer? I tried all the values you've suggested and only the first two pairs works.

Sorry I didn't see your second last comment, I was not notified.  As I understand, you used exact the same values. Then, the only explanation I have is, that the Software serial must switch off the interrupts globally when it operates (print). I added an answer to explain my assumption. Another finding is that your set the register values with a combined or |= operation. If, for what reason ever, the register has some 1s in it, the resulting value is not what you expected. say  TCCR1 == 0x01 then the assignment TCCR1 |= 0x8E; results in TCCR1 == 0x8F

Ahh I see! I'll try to turn off the Software Serial and check the result. Also I'll try not to mask the output using |= as you've suggested.

The only explanation I have is, that the Software serial switch off the interrupts globally when it operates (print). If interrupts are locked when the timer completes, you loose a tick. It does not explain the different behavior of the four value pairs, but there are some issues reported in a german forum. They did not find an answer, but the assumed it depends on the 'delay()' function, that is used for the software serial and the fact that the interrupts are locked to make the delay function more exact.
If you want to be sure, you can try this by completely removing the Software Serial from your program. If you make the values switchable by e.g. a button press you can change it without having to reload the program. Then it's easier to see different  blinking intervals.
int ledPin = 1;
int state = 0;

int regValues[] = { 0x8f, 0x8e, 0x8d, 0x8c };
int cntValues[] = { 30, 61, 122, 243 };

const int buttonPin = 2;
int buttonState = LOW;

long lastDebounceTime = 0;
long debounceDelay = 80;
int lastButtonState = LOW;

int pairIndex = 0;

void setup()
{
  TCCR1 = regValues[ pairIndex ];
  OCR1C = cntValues[ pairIndex ];

  TIMSK = (1 << OCIE1A);

  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

ISR(TIMER1_COMPA_vect)
{
  state = !state;
  digitalWrite(ledPin, state);
}

void loop()
{
  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState)
  {
    lastDebounceTime = millis();
  }

  if ( (millis() - lastDebounceTime) > debounceDelay)
  {
   if (reading != buttonState)
   {
      buttonState = reading;

      if (buttonState == HIGH)
      {
        if ( ++pairIndex > 3 )
        {
          pairIndex = 0;
        }

        TCCR1 = regValues[ pairIndex ];
        OCR1C = cntValues[ pairIndex ];
      }

    }

  }

}

I wrote this code without having a attiny to testing it. So hopefully all is correct. If you would try it, can you please report any errors, so I can correct them?

Ahh thank you so much! I'll try this code out and get back to you.

I tried out your suggestions. Looks like it started worked once I changed the assignment to = instead of |= as I was doing earlier. I guess some other bit was influencing the timer value. Thanks for your help!


text:
Trouble with PID code, variable error_x acting strange
I'm trying to get error_x and error_y to display the difference between the target and the position. For some reason I cannot get error_x to function correctly. error_y has the same code, but works correctly. Can anyone help?
Here is the code on my Arduino:
void setup() {
  Serial.begin(9600);
  Serial.print("Starting...\n");
}

int previousTime = 0;
float lastError_x = 0;
float lastError_y = 0;

void loop() {
  //pid variables
  float Kp = 1;
  float Ki = 0;
  float Kd = 0;
  float pos_x;
  float pos_y;
  float target_x;
  float target_y;
  float error_x;
  float error_y;
  int currentTime;
  int elapsedTime;
  float cumError_x;
  float cumError_y;
  float rateError_x;
  float rateError_y;
  float output_x;
  float output_y;

  //invkinematic variables
  float inVec[4] = {1, -1.5, 3};
  float height = 3.5;
  float B = 4;
  float L = 3;
  float U = 3.5;
  float plateRadius = 5.5;
  float alpha[4] = {0, 0, 0};
  float normVec[4];
  float p1[4] = {0,0,0};
  float p2[4] = {0,0,0};
  float p3[4] = {0,0,0};
  float crosskv[4] = {0,0,0};
  float normSave;
  float dotSave;
  float radius;
  float gamma;
  float beta;

  //serial variables
  char buf[32];
  char str_temp1[6];
  char str_temp2[6];
  char str_temp3[6];

  //PIXY CAMERA CODE (outputs x and y)

  pos_x = 1;
  pos_y = 1;

  //DETERMINE TARGET LOCATION
  //default:(0,0)
  target_x = 0;
  target_y = 0;

  //PID CODE (inputs x and y and outputs normal vector and height)

  error_x = target_x - pos_x;
  error_y = target_y - pos_y;

  dtostrf(error_x, 5, 3, str_temp1);
  dtostrf(error_y, 5, 3, str_temp2);
  sprintf(buf, "error1:%s error2:%s\n", str_temp1, str_temp2);
  Serial.print(buf);

  currentTime = millis();
  elapsedTime = currentTime - previousTime;
  if(elapsedTime==0){elapsedTime = 1;}

  cumError_x += error_x * elapsedTime / 1000;
  cumError_y += error_y * elapsedTime / 1000;
  rateError_x = (error_x - lastError_x)/(elapsedTime/1000);
  rateError_y = (error_y - lastError_y)/(elapsedTime/1000);

  output_x = Kp*error_x + Ki*cumError_x + Kd * rateError_x;
  output_y = Kp*error_y + Ki*cumError_y + Kd * rateError_y;

  inVec[0] = output_x/plateRadius;
  inVec[1] = output_y/plateRadius;
  inVec[2] = plateRadius;

  lastError_x = error_x;
  lastError_y = error_y;
  previousTime = currentTime;

  //INVKINEMATIC (inputs normal vector and height and outputs alpha values)

  normVec[0] = inVec[0]/(sqrt(inVec[0]*inVec[0]+inVec[1]*inVec[1]+inVec[2]*inVec[2]));
  normVec[1] = inVec[1]/(sqrt(inVec[0]*inVec[0]+inVec[1]*inVec[1]+inVec[2]*inVec[2]));
  normVec[2] = inVec[2]/(sqrt(inVec[0]*inVec[0]+inVec[1]*inVec[1]+inVec[2]*inVec[2]));

  p1[0] = normVec[2];
  p1[2] = -1*normVec[0];
  normSave = sqrt(p1[0]*p1[0]+p1[1]*p1[1]+p1[2]*p1[2]);
  p1[0] = plateRadius*p1[0]/normSave;
  p1[1] = plateRadius*p1[1]/normSave;
  p1[2] = plateRadius*p1[2]/normSave;

  crosskv[0] = normVec[1]*p1[2] - normVec[2]*p1[1];
  crosskv[1] = normVec[2]*p1[0] - normVec[0]*p1[2];
  crosskv[2] = normVec[0]*p1[1] - normVec[1]*p1[0];
  dotSave = normVec[0]*p1[0] + normVec[1]*p1[1] + normVec[2]*p1[2];
  p2[0] = -0.5*p1[0] + crosskv[0]*0.866 + normVec[0]*dotSave*1.5;
  p2[1] = -0.5*p1[1] + crosskv[1]*0.866 + normVec[1]*dotSave*1.5;
  p2[2] = -0.5*p1[2] + crosskv[2]*0.866 + normVec[2]*dotSave*1.5;
  normSave = sqrt(p2[0]*p2[0]+p2[1]*p2[1]+p2[2]*p2[2]);
  p2[0] = plateRadius*p2[0]/normSave;
  p2[1] = plateRadius*p2[1]/normSave;
  p2[2] = plateRadius*p2[2]/normSave;

  p3[0] = -0.5*p1[0] + crosskv[0]*-0.866 + normVec[0]*dotSave*1.5;
  p3[1] = -0.5*p1[1] + crosskv[1]*-0.866 + normVec[1]*dotSave*1.5;
  p3[2] = -0.5*p1[2] + crosskv[2]*-0.866 + normVec[2]*dotSave*1.5;
  normSave = sqrt(p3[0]*p3[0]+p3[1]*p3[1]+p3[2]*p3[2]);
  p3[0] = plateRadius*p3[0]/normSave;
  p3[1] = plateRadius*p3[1]/normSave;
  p3[2] = plateRadius*p3[2]/normSave;

  p1[2] = height+p1[2];
  p2[2] = height+p2[2];
  p3[2] = height+p3[2];

  radius = sqrt((p1[0]-B)*(p1[0]-B)+p1[1]*p1[1]+p1[2]*p1[2]);
  gamma = atan2(p1[2],sqrt((p1[0]-B)*(p1[0]-B)+(p1[1])*(p1[1])));
  beta = acos((L*L+radius*radius-U*U)/(2*L*radius));
  alpha[0] = 3.1416 - (gamma + beta);

  radius = sqrt((p2[0]+0.5*B)*(p2[0]+0.5*B)+(p2[1]-0.866*B)*(p2[1]-0.866*B)+(p2[2])*(p2[2]));
  gamma = atan2(p2[2],sqrt((p2[0]+0.5*B)*(p2[0]+0.5*B)+(p2[1]-0.866*B)*(p2[1]-0.866*B)));
  beta = acos((L*L+radius*radius-U*U)/(2*L*radius));
  alpha[1] = 3.1416 - (gamma + beta);

  radius = sqrt((p3[0]+0.5*B)*(p3[0]+0.5*B)+(p3[1]+0.866*B)*(p3[1]+0.866*B)+(p3[2])*(p3[2]));
  gamma = atan2(p3[2],sqrt((p3[0]+0.5*B)*(p3[0]+0.5*B)+(p3[1]+0.866*B)*(p3[1]+0.866*B)));
  beta = acos((L*L+radius*radius-U*U)/(2*L*radius));
  alpha[2] = 3.1416 - (gamma + beta);

  dtostrf(normVec[0], 5, 3, str_temp1);
  dtostrf(normVec[1], 5, 3, str_temp2);
  dtostrf(normVec[2], 5, 3, str_temp3);
  sprintf(buf, "a1:%s a2:%s a3:%s\n", str_temp1, str_temp2, str_temp3);
  Serial.print(buf);

  //OUTPUT alpha to servos

  delay(1000);
}

Here is the output with the error:
Starting...
error1: error2:-1.000
a1:  NAN a2:  NAN a3:

error1: error2:-1.000
a1: a2:-0.033 a3:

error1: error2:-1.000
a1: a2:-0.033 a3:

error1: error2:-1.000
a1: a2:-0.033 a3:

error1: error2:-1.000
a1: a2:-0.033 a3:

Try to print the errors directly with multiple Serial.print() statements, ditching all the dtostrf() and sprintf().

Consider enlarging your character arrays.  When creating strings an extra character is likely necessary to indicate the end of a string.  This is usually the null character or zero.  If missing, many string related features will not see an end of a string and likely cause unexpected results.

What I think happened, the 1st dtostrf() call created a properly formed string.  however, the null character likely ended up at the beginning of the next character array.  Which likely got over written by the 2nd dtostrf() call.

I'm actually getting a whole new error. Something seems very wrong now.

The serial output is now: Sta⸮⸮⸮⸮⸮⸮⸮⸮⸮

So the 1st print in setup() is not working?  Likely something else is wrong. You have a huge number of floats for an embedded processor project.  This requires a lot of memory.  And most of the floats are local variable so are on the stack.   That means memory is set aside for them as you run your program.  So running out of memory is not easily check at compile time.  You might be running out of memory.  This depends on the actual stack usage and the specific processor your Arduino platform is using.  Try cutting back on the number of floats variables.

Also, I appreciate getting the answer marked as correct.  But you may want to remove that until it is understood why the program does not work so that others do not skip over your question.  Debugging a program in a stack exchange Q/A never works well as the question usually changes over time making a mess of the Q/A.  In future, simplify your program to the minimum which still exhibits the unexpected results then post your question.


text:
How to swap ground and power for multimeter
I'm trying to create a multimeter that measures resistance and capacitance for a school project and the code must be under 30 lines. I have made both a resistance meter and a capacitance meter but the only problem is that on for my resistance meter, ground is connected to the to the known resistor and the arduino's output goes through the unknown component. Where as my capacitance meter is the opposite (ground to unknown, output to known), just wondering if their is an easy fix or if i need to rethink my entire project. Any help is appreciated, thanks.

You could use an H-bridge to reverse the polarity

Please show your schematic. It is unclear what you mean.

Arduino have a lot of pins, can you use one pin for resistance and other for capacitance?


text:
How to call a PHP script with Arduino?
I have Arduino Mega and ESP-12F module.
Via AT commands I am on my wifi.
Now, I need to call my script on my pages.
Can you tell me how?
This command can conenct to my pages:
Serial3.print("AT+CIPSTART=0,\"TCP\",\"www.artware.cz\",80\r\n");
But that's all, I am not able to call the script.
Sorry, if this is dumb question.
Thank you

there are 'WiFi' libraries which handle the esp8266 AT commnands for you and have an example for GET request. WiFiEsp library or my WiFiEspAT (the second only if the AT firmware is 1.7 (SDK 3) and you don't need SSL (https))

Which library do you recommend?

my WiFiEspAT, if you can flash the AT firmware 1.7 (SDK 3) and you don't need SSL (https) https://github.com/jandrassy/WiFiEspAT

Do you know which HTTP method the PHP script accepts ? It will be either GET or PUT. If it is the GET method you should be able to simply test it by issuing a command such as www.artware.cz/myApp.php?par1=52 etc. The next step is to issue that URL from your ESP-12 (somehow) and maybe parsing the results.


text:
How to read input pin on MCP23017?
I'm working to develop a simple code for MCP23017 that I want to use to run LCD128x64.
I was succeeded to set IODIRB as output and blink LED as a test.
Now I want to read the pin state, but I couldn't. Here's my code. I'm using the nice twi library that comes with Wire library.
uint8_t mcp23017_read(uint8_t add_reg){
    uint8_t data;
    twi_writeTo(MCP23017_ADD,add_reg,2,1,0);
    twi_readFrom(MCP23017_ADD,data,1,1);

    return data;
}

I've tried this version too:
uint8_t *mcp23017_read(uint8_t add_reg){
    uint8_t data[1];
    twi_writeTo(MCP23017_ADD,add_reg,2,1,0);
    twi_readFrom(MCP23017_ADD,data,1,1);

    return *data;
}

==================================================
Here's Arduino call function:
void loop() {
  // put your main code here, to run repeatedly:
  data = mcp23017_read(GPIOB);
  Serial.println(data);
  delay(100);
}

how do you know that you cannot read the pin state?

I'm connecting the pin with a resistor to 5V or GND.

here is an example about reading inputs https://tronixstuff.com/2011/08/26/arduino-mcp23017-tutorial/

Is there a reason why you use TWI but not Wire?

Yes, I can same like 300 bytes of the flash memory. And I want to learn how to study other people's code. The twi is a very good example. I learned how ISR work and how functions should handle buffered TX/Rx data.

I don't know how this lib works. But I'm pretty sure that you have to pass a pointer onto the data variable into the twi_readFrom method.
uint8_t mcp23017_read( uint8_t add_reg )
{
    uint8_t data;
    twi_writeTo( MCP23017_ADD, add_reg, 2, 1, 0 );
    // I inserted an & below
    twi_readFrom( MCP23017_ADD, &data, 1, 1 );

    return data;
}

Or in case of the second function:
// I removed the star operator
uint8_t mcp23017_read(uint8_t add_reg)
{
    uint8_t data[1];

    twi_writeTo( MCP23017_ADD, add_reg, 2, 1, 0 );
    // you pass the pointer to the array element 0
    twi_readFrom( MCP23017_ADD, data, 1, 1 );

    // I returned the element 0
    return data[0];
}

Update:
Just for completeness: The OP found also a failure on the write function. He had posted a separate answer, I voted up to mark it. Because this is the accepted answer, I also copied his post to here for completeness and the readers convenience.
Original post by R1S8K:

OK, I found a the answer and it was a good lesson in dealing with
  functions that receives pointers.
I forgot that the writeTo function also receives a pointer and I have
  to pass an array for both read/write functions.
void mcp23017_read(uint8_t *add_reg, uint8_t *buffer){
    twi_writeTo(MCP23017_ADD, add_reg, 1, 1, 1);
    twi_readFrom(MCP23017_ADD, buffer, 1, 1);
}

It isn't working ! I don't know what I'm doing wrong. Should I launch a repstart or not ... etc.

Yep, that's very nice :) Thanks for improving my thread.

OK, I found one little mistake in my coding.
I forgot that the writeTo function also receives a pointer and I have to pass an array for both read/write functions.
void mcp23017_read(uint8_t *add_reg, uint8_t *buffer){
    twi_writeTo(MCP23017_ADD, add_reg, 1, 1, 1);
    twi_readFrom(MCP23017_ADD, buffer, 1, 1);
}


text:
How to wait a certain time before doing something while running other code?
I have a project where I'm using the HX711 library with a loadcell to weigh in a fruit that is on a conveyor belt. Each fruit has a weight which needs to be classed. The bigger fruits (200g) are class A so they have to "fall down" the conveyor belt at a later stage. The smaller fruits fall down earlier. This has to be done on a timed basis.
What I want to do is get the fruit size , calculate the class (using weight) and then send an interrupt to the dropping mechanism after x time. But while it must wait to drop the next fruit will be have come in and might be smaller than the first.
I can already weigh in and calculate the class of fruits. I've also done this in C using multithreading but adruino uno doesn't support that.
I also have to mention that there is about 50-200 fruits on a single conveyor belt at any given time.

Non-blocking code with millis() is the answer. Look at the BlinkWithoutDelay example, that comes with the Arduino IDE

You can use timestamp to avoid the blocking code. See BlinkWithoutDelay example

while this is true, it was answer many times. you should search for a duplicate