text:
send and recieve analog data from one arduino to another arduino via web/ethernet
i am able to send audio signal through mic and send it via arduino and receive it on speaker.
i need two things
1.) The voice i am hearing on speaker has on speaker has lots of noise with it. i need to reduce it
2.) I need to send that analog signal received  from the mic via Ethernet/web to another arduino. i have Ethernet shield i am able data from switch but not from mic.
let me start from the beginning, i have attached mic to the audio amplifier and have attached output of the amplifier to the a0 pin of the arduino. The arduino is connected to the DAC(PCF8519) with a5 and a4 pin of the aurdino. The output of the dac is connected to the LM386 audio amplifier module and its output is connected speaker. when i speak via mic i am able to hear it on speaker but it has has some noise attached to it. IF you can suggest solution for that it will be great.
now i want to send the data of the mic to another arduino via web/Ethernet. i am able to get the data of the switch but not been able to get proper data from the mic.So pls help out with that.
here is my audio amplifier circuit:

here is my code for one arduino code that worked
`#include "Wire.h"`
 #define PCF8591 (0x90 >> 1)
 void setup()
  {
    Wire.begin();
    pinMode(0,INPUT);
   }
 void loop()
   {
     Wire.beginTransmission(PCF8591);
     Wire.write(0x40);
     Wire.write(analogRead(0));
     Wire.endTransmission();
   }

I need to reduce the noise on the speaker and i want to send the data of the mic via web/Ethernet to another arduino.

do you get the noise if the arduino is not in the circuit?

"i need two things".  Unless you have reason to think the two problems are interrelated to the point where one can't be solved without solving the other, pick one and make your question about that.

Streaming audio over ethernet or (heaven forbid) the web is a very hard thing to do. Not something we can help you with on here. Also the Arduino really cannot do audio, and an I2C DAC is probably the second worst idea for audio ever.

Isn't this the same question as here? https://arduino.stackexchange.com/questions/81780/generate-a-true-analog-signal-using-arduino See my answer there, same solution, the sample rate and the output capacitor, C4.

Dorian, their is no error with c4 capacitor

@sanketjain It is in any configuration you have. Again the same explanation, the ADC works only with positive voltages. C4 is removing the the DC component and your mic signal is just floating between -0.7V and 5.7V limited only by the input clamping diodes. If you use the default 5V reference for  ADC just short C4. That will give ADC input a clean and stable signal around 2.5V

@dorian I have already done that that's why I said there's no error with c4

I don't understand, in this moment C4 is still there or not? You shorted C4, nothing happened and after that you removed the short or not?

ADC input has 100Mohm impedance. By placing C4 the signal at the ADC input has no DC path, is just floating between -0.7v and 5.7v , limited only by the input clamping diodes.
ADC can convert only voltages between 0 and the voltage reference, I suppose you use the default 5V reference.
But your signal is floating, and the ADC will cut any peaks outside of the conversion area giving the noise you hear.
Another issue I see here is that the data sheet of LM386 specifies a load between 4ohm and 32ohm. There is no warrantee that it will work without a load as in your case. Most likely not.
So you might want to connect C4 to a proper load and take the signal for ADC straight from pin 5 of LM386 which is auto balanced at half of the voltage supply.

simulate this circuit – Schematic created using CircuitLab
Later edit after I found the source of the schematic, there are also comments there that the schematic will never work with Arduino with the capacitor connected, the only working application was a sound detector where the signal distortion does not matter.
Please do not trust the content of any unknown website published by an anonymous just because it looks like a tutorial made by somebody who knows something.
Edit to add some info on how to debug the issue.
First, in the above schematic replace the resistor with a speaker and see if the sound is good. If not than see what is wrong with your amplifier.
If it's good and loud without any distortion then put the resistor back.
Use a binary mode serial monitor like Realterm to see how your data looks, the Arduino serial monitor works only in Ascii mode which turns a byte into three ascii chars which is slow.
Something like that
void setup() {
    Serial.begin(230400); // opens serial port, sets data rate to or maximum supported by your board to minimize latency
}

void loop()
   {
     unsigned int temp;
     temp = analogRead(0);
     temp = temp>>4; //strip low bits to fit in a single byte
     Serial.write(temp);
   }

Then see how your data looks, if you have to many 00 or to many FF than you know that your data us upper or lower limited or what is wrong with your signal.
I hope you are aware that the ADC conversion takes 100us and the wire transmission also around 200us the maximum sample rate you can expect is around 3khz and a maximum bandwidth of the audio signal of 1.5kHz which is half of the telephony bandwidth, you might want to use a faster DAC and use some non blocking ADC reading to use the time while ADC is working like in this article


text:
Is there GUI to flash a sketch with new variables?
I'm dabbling in a project and would like to add a feature, but I need some help from the community.
My project returns a response from the wunderground api and lights an led based on the temperature in the response. I plan to enclose the circuits and use a single led on the enclosure to display the temperature. I have most of the sketch logic knocked out, but need help with sharing the project.
If I gave this project to someone, they would need to update the sketch to include their wifi name and password, as well as the zip code where they live.
Is there a way I can do this without using the arduino ide? A use case for this would be: the user plugs the arduino into their machine, the gui loads, the user would enter variables, and then the board would get flashed with the new variables.
Is this a pie in the sky proposition, or something that could be implemented?
Thanks for your input.

Without the IDE? Store the variables in eeprom and then flash just the eeprom maybe??

@jsotola thanks for pointing out the typo. Do you have any suggestions or ideas on how to implement a solution?

some kind of a script that generates the necessary eeprom image file and then calls avrdude in order to transfer the image file to arduino's eeprom .... but i would go with the answer from @per1234

what are you using for the wifi module??

if you are using something like an ESP8266, then it is possible that you do not need the arduino at all.

The common way to do this is to build the configuration UI into your program. Then the user has no need to be messing with the firmware.
Since your device has WiFi this can easily be done by serving a configuration web page that is loaded in the browser. But how can you make a connection before the credentials for the WiFi router have been configured? The answer is for the device to serve as an access point (AP). So you connect a computer with WiFi to the device's AP, open the configuration page in the browser on that computer, and then configure the credentials as well as any other configurations you might like.
The configuration parameters are written to EEPROM so that they will be preserved.
In its most simple form there would be a specific IP address that must be opened in the browser but more user friendly is to create a captive portal so that after connecting to the AP any URL opened in the browser will load the configuration page.
Of course all this will increase the memory usage of your program and apparently you are using the Arduino Uno so this is fairly scarce to begin with. You'll need to determine whether there is enough extra memory for it.

I had wondered if having a configuration UI on a web page would be a possible solution. I think your answer should give me enough information to do some research. Thanks.

source: Stack Exchange

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

sort: votes


text:
Are there documented Arduino class or file name restrictions?
I ran into a strange problem were the compiler could not find a header file that I knew existed.
The problem was I created a class called ArduinoEvent and put it in ArduinoEvent.hpp,  but when I tried to include it in a client file, the compiler complained that the file did not exist.
In file included from sketch/NetworkConnection.hpp:4:0,
                 from /home/john/development/arduino/esp_pump_monitor/app.ino:4:
sketch/MyEvent.h:5:28: fatal error: ArduinoEvent.hpp: No such file or directory
 #include "ArduinoEvent.hpp"
                            ^

After realizing that the compiler copies the files into another directory,  I took a look and found that it had copied the ArduinoEvent.hpp file to
ArduinoEvent.hpp.cpp.  Since all the other files were copied fine, I simply renamed the file to BrduinoEvent.hpp and then everything was fine.
After searching I could not find anything that would imply that I could not name a class / file ArduinoBlah, so I was going to open an issue, but wanted to see if this restriction was documented somewhere and I just could not find it.
Update
I originally assumed the problem was due to the file being called ArduinoXxxx, but I hit this again with another file.  I think the issue is related to the files being in the "top" folder.  I noticed the process copies the xxx.ino files to xxx.ino.cpp,  so I think that's what is happening and somehow it thinks various files are .ino files while they are not.  As a workaround I moved all my class files to a lib folder and include them from there #include "./lib/xxx.hpp" for example.  This seems to be working.

A partial answer may be found at: https://github.com/arduino/Arduino/wiki/Build-Process

Try renaming *.hpp → *.h.

same thing happens,  but if I use the name .cpp or even include an empty .cpp file it seems ok

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


text:
4x4 Keypad Interface issues
I have not used arduino until now. I thought of interfacing my 4x4 keypad. But when I press keys 1, 4, 7 and *, key values A, B, C and D are sent out to serial terminal respectively. All other keys are working fine. My HW is fine and tested keypad with Atmel Studio. Here is the arduino code. Also attached the schematic. I am using custom shield with arduino nano board on it and pins are marked in the schematic. Shorting links are placed on JP3 and JP2. What could be the reason?
#include <Keypad.h>
#include <util/delay.h>
#include <Wire.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'D', '#', '0', '*'},
  {'C', '9', '8', '7'},
  {'B', '6', '5', '4'},
  {'A', '3', '2', '1'}
};
byte rowPins[ROWS] = {A0, A1, A2, A3}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {12, 3, 2, 13}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {

  char key = keypad.getKey();

  if (key != NO_KEY) {
    Serial.println(key);
  }
}

Edit:
Below is the working code I wrote using avrgcc compiler. Note that pinMode is custom macro, works similar to arduino pinMode, but with small difference.
#include "CL_keypad.h"
#include <util/delay.h>

#ifndef IOPORTB
#define IOPORTB 0
#endif
#ifndef IOPORTC
#define IOPORTC 1
#endif
#ifndef IOPORTD
#define IOPORTD 2
#endif

#define IOPB0  0
#define IOPB1  1
#define IOPB2  2
#define IOPB3  3
#define IOPB4  4
#define IOPB5  5
#define IOPB6  6
#define IOPB7  7
#define IOPC0  8
#define IOPC1  9
#define IOPC2  10
#define IOPC3  11
#define IOPC4  12
#define IOPC5  13
#define IOPC6  14
#define IOPC7  15
#define IOPD0  16
#define IOPD1  17
#define IOPD2  18
#define IOPD3  19
#define IOPD4  20
#define IOPD5  21
#define IOPD6  22
#define IOPD7  23

#define IOBitSet(ioport, bit) (((ioport)==IOPORTD)?(PORTD|=1<<(bit)):((ioport)==IOPORTB)?(PORTB|=1<<(bit)):((ioport)==IOPORTC)?(PORTC|=1<<(bit)):0)
#define IOBitClear(ioport, bit) (((ioport)==IOPORTD)?(PORTD&=~(1<<(bit))):((ioport)==IOPORTB)?(PORTB&=~(1<<(bit))):((ioport)==IOPORTC)?(PORTC&=~(1<<(bit))):0)
#define IOBitDirOut(ioport, bit) (((ioport)==IOPORTD)?(DDRD|=1<<(bit)):((ioport)==IOPORTB)?(DDRB|=1<<(bit)):((ioport)==IOPORTC)?(DDRC|=1<<(bit)):0)
#define IOBitDirIn(ioport, bit) (((ioport)==IOPORTD)?(DDRD&=~(1<<(bit))):((ioport)==IOPORTB)?(DDRB&=~(1<<(bit))):((ioport)==IOPORTC)?(DDRC&=~(1<<(bit))):0)
#define IOBitInvert(ioport, bit) (((ioport)==IOPORTD)?(PORTD^=1<<(bit)):((ioport)==IOPORTB)?(PORTB^=1<<(bit)):((ioport)==IOPORTC)?(PORTC^=1<<(bit)):0)

// Read the entire port and return the value read. Individual bits are not tested
#define portRead(ioport) (((ioport)==IOPORTD)?(PIND):((ioport)==IOPORTB)?(PINB):((ioport)==IOPORTC)?(PINC):0)

#define pinMode(pin,mode) (((mode)==OUTPUT)?IOBitDirOut(((pin)/8),((pin%8))):IOBitDirIn(((pin)/8),((pin)%8)))
#define digitalWrite(pin,value) (((value)==LOW)?IOBitClear(((pin)/8),((pin)%8)):IOBitSet(((pin)/8),((pin)%8)))
#define digitalRead(pin) ((portRead((pin)/8))&(1<<((pin)%8))?HIGH:LOW)
#define digitalInvert(pin) (IOBitInvert(((pin)/8),((pin)%8)))

#define NUM_ROWS 4          // Number of rows in the keypad
#define NUM_COLS 4          // number of columns in the keypad
#define NO_KEY_DETECTED '\0'   // When no key is detected, return '\0'
#define SWITCHING_DELAY 1      // 2 msec delay between row switching.

unsigned char readSwitch(unsigned char columnNum)
{
    //check if key is pressed.
    if(!digitalRead(columnNum))
    {
        //Key De-bounce crude method. To be changed later
        _delay_ms(KEY_DEBOUNCE_TIME);
        if(!digitalRead(columnNum))
        {
            return(1);
        }
    }
    return(0);
}

// Assign port pin numbers  based on the hardware connectivity
uint8_t rowBitNumbers[NUM_ROWS] = {IOPB4,IOPD3,IOPD2,IOPB5};
uint8_t columnBitNumbers[NUM_COLS] = {IOPC0,IOPC1,IOPC2,IOPC3};

        unsigned char keyAssignments[4][4] = {
        {'D', 'C', 'B', 'A'},
        {'.', '9', '6', '3'},
        {'0', '8', '5', '2'},
        {'*', '7', '4', '1'},
    };

    // Initialize keypad need not be called if port pins are not shared
// In case same pins are used as output in some cases, it could be re-initialized.
void initializeKeyPad(void)
{
    unsigned char loopCnt;

    for(loopCnt=0;loopCnt<NUM_ROWS;loopCnt++)
    {
        pinMode(rowBitNumbers[loopCnt],INPUT);
    }

    for(loopCnt=0; loopCnt<NUM_COLS; loopCnt++)
    {
        pinMode(columnBitNumbers[loopCnt],INPUT);
        // In case  of external Pull ups are used, no need to configure row Port pins.
        // Otherwise enable pull ups.

        // Enable pull up resistors if required
        digitalWrite(columnBitNumbers[loopCnt],HIGH);

    }
}

// Function to read the key that is being pressed.
// Returns the value of the key pressed.
// First one row will be set low and then all the columns are read.
// Process is repeated for all the rows.

//////////////////////////////// IMPORTANT   ///////////////////////////////////
// Some delay needs to be given between row switching to avoid capacitance effect

unsigned char getKeyStatus(void)
{
    unsigned char rowLoopCount;
    unsigned char columnLoopCount;
    unsigned char retValue=NO_KEY_DETECTED;
    //Loop for maximum rows configured
    for(rowLoopCount=0;rowLoopCount<NUM_ROWS;rowLoopCount++)
    {
        // Make the Row as output port. So row will be low (No need to set low because default is low)
        pinMode(rowBitNumbers[rowLoopCount],OUTPUT);
        // Give small delay for settling
        _delay_ms(SWITCHING_DELAY);
        //  Read each column.
        for(columnLoopCount=0;columnLoopCount<NUM_COLS;columnLoopCount++)
        {
            //Read  the status of the switch
            if(readSwitch(columnBitNumbers[columnLoopCount]))
            {
                pinMode(rowBitNumbers[rowLoopCount],INPUT);
                return(keyAssignments[rowLoopCount][columnLoopCount]);
            }
            _delay_ms(SWITCHING_DELAY);
        }
        // At the end, change the direction as input so that port goes to high impedance
        pinMode(rowBitNumbers[rowLoopCount],INPUT);
        //CL_delay_mS(SWITCHING_DELAY);
    }
    return(retValue);
}

Here is the Schematic

So you seem to print out the values from the wrong column (leftmost instead of rightmost)? Did you double check the column wiring?

possible bad keyboard .... connect only one column at a time and test ...... also, get rid of the external pullup resistors and enable the internal pullups

Code written using AVR GCC works fine with same hardware. Updated first post with same code.

@jsotola Internal pull ups on PC0 to PC3 not enough. I had faced spurious input problems many times without external pull ups.


text:
DAC using Arduino Leonardo
I am as new to Arduino as it can get. To start off, I am trying to build a DAC using an Arduino Leonardo. I have a digital signal coming from my dual differential comparator. I want to convert this to an analog signal.
First, I will read the digital signal in a digital pin (can someone point me which is good? There are so many of them. I was overwhelmed). Then I send out a PWM signal (confused with the pin again). Then I use a simple RC circuit to filter out the PWM signal to produce a simple sine wave.
Am I going towards the correct direction? If not, please any suggestion would be helpful.

Which dual differential comparator you are using. It would be great if you could add your circuit and any details of what you have tried and what didn't work.

A dual differential comparator is a type of comparator which gives digital signal as output

@sa_leinad LM2903

please describe the signals at the comparator inputs and how they relate to the final analog output

@sa_leinad: please check the edited picture. I have added my circuit diagram. I have a hall sensor which varies its output voltage with respect to the magnetic field. This output is connected to the Comparator. which outputs a digital signal.

How did you come to this circuit? I don't think see how the 100k feedback resistor is doing anything.

You want to convert the input into a sine wave? It's pretty simple to filter a PWM signal into a varying voltage, but getting a variable sine wave out of it might be asking too much. Are you looking to vary the frequency of the output wave with the input, the amplitude, or both? And what frequency of sine wave are you hoping to generate?

Yes you are going in the right direction.
Comparators
You haven't as yet detailed how you plan to connect the 2 comparators to the Arduino, but I imagine it would be something similar to this:

simulate this circuit – Schematic created using CircuitLab
In the circuit above, X and Y are either high or low based on the analog voltages of A, B, C & D. I have created a truth table below with some arbitrary voltages to output. The value column corresponds to the value needed for the analogWrite() function.

Note: If you need your analog output to be able to source some current you can add an Op-Amp in a unity gain configuration at the output of the RC filter.

Examples To Read
To output the analog value, the 4 best suited inbuilt examples/tutorials to look at are:
Dimmer: Send serial values to change the brightness of an LED.
Fading: Use an analog output (PWM pin) to fade an LED.
Analog In Out Serial: Read an analog input pin, map the result, and then use that data to dim or brighten an LED.
Read ASCII String: Parse a comma-separated string of integers to fade an LED.
What all of these examples have in common is the analogWrite() function:
// writes the analog value (range from 0 to 255):
analogWrite(pin, value);

Dimmer is a simple example where a serial value is read and then output on one of the PWM pins.
Fading is probably the most basic example of using the analogWrite() function (PWM output).
I included Analog In Out Serial as it uses the map() command.
I included Read ASCII String as it shows how to parse multiple values on the serial string.

PWM Pins
You can use pins 3, 5, 6, 9, 10, 11, and 13 on the Arduino Leonardo to output the PWM using the analogWrite() function.

Control
I recommend the following tutorials for your control. You could either use the if-else command or the switch-case command.

Thanks for your detailed reply. But I have only 1 comparator, how do I modify this to my need?

What analog voltages do you need? (One for your LOW signal and one for your HIGH). What you have tried and what didn't work?

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


text:
PWM and Analog Signal Quality
I'm converting a 0-5v PWM signal to an analog signal using an LM358D. I've connected the output to an oscilloscope to look at the signal but I'm not really sure what I'm looking at. The PWM looks ok but I'm unsure of the analog signal.
Here's some images, please let me know what you think.
Both pics are at 50% signal strength. The oscilloscope is set to defaults, simply connected the probe.
Thanks

EDIT:
Here's the schematic for the PWM to analog converter. The cap is a tantalum. The dip switch changes the analog from 5v to 10v, the signal looks the same on both and is correct voltage so seems to be ok?

What are you expecting to see? That looks like a 50% PWM duty cycle so are you expecting 2.5V on the output (as a straight line)?

The voltages check out but I'm not sure of the analog signal. When I see other images the line is smooth curve at top and bottom but I don't know if that's a setting on scope or I have a bad signal? If the triangles look good I'm happy.

You need a resistor and capacitor to smooth the signal. Do you have those? Perhaps edit your post to show your schematic.

What do you mean with "smooth"? the signal has an amplitude of 584mV according to the measurements of your scope. Is that smooth enough? If you want to compare the image of the signal, you need to set the same y-div setting as in the reference image

Something like this should work:

With this code on a Uno:
void setup () { }

void loop () {
  analogWrite (3, analogRead (A0) / 4);
}

For slightly more details see my post about doing that.

Thanks, that's actually the same I'm using and guess what, I got the original from you. ) I knew your name looked familiar. I'm using a tantalum 10uf cap but resistor is only 220 ohm and I have an extra resistors someone said to add, I'll add the schematic.

You have a much lower resistor (220Ω vs 4700Ω) than I did. The higher value resistor will charge the capacitor more slowly, thus smoothing out the signal and effectively giving you an average, which is what I assume you are trying to do.

My op-amp was configured for unity gain, I don't know why you need those extra components.

The PWM looks ok but I'm unsure of the analog signal.

The “analog signal” looks like the PWM smoothed by a first-order
low-pass filter. It still has some oscillations, 584 mV
peak-to-peak. If you can tolerate that, then it's perfectly fine. If
not, then increase the time constant of your filter.
A first-order low-pass filter behaves, in its stop band, like an
integrator. Thus, a square signal is turned into a triangle. You are
seeing exactly the expected behavior.

The oscilloscope is set to defaults

There are no “default” settings in the oscilloscope. You probably used
the “autoset” button instead. This button tries to find some settings
that let you see something on the screen. I mean, some kind of signal,
not just straight line. If the signal is almost flat, the autoset will
increase the gain until you can see it is not flat. In this case, it
increased the gain by a factor 10 (200 mV / division instead of
2 V used previously). It also added a negative offset in order to
avoid the trace going out of the screen. See the small pentagon on the
far left with a “1” inside? On the first picture this tells you where
the zero (the reference potential) is relative to your signal. On the
second picture, the polygon pointing at the bottom of the chart tells
you the zero is off-scale.
If you want to really appreciate the smoothing action of the filter, you
have to look at its input (the PWM signal) and its output (the “analog”
signal) using the exact same settings. Connect the input, hit “autoset”,
and look. Then connect the output, do not change the settings (do not
hit “autoset”) and look at the output.
Better yet: forget the autoset button, adjust the settings manually and
mind their values.
Better yet: as you have a two channel scope, display both signals
simultaneously, using the exact same settings on both channels.

Thank-you for the detailed reply, I appreciate it! I updated the original post with schematic. What's an "acceptable" peak-to-peak? If a resistor or cap would improve that would be good. You can see I have PWM freq at 1000 Khz, is there a "magic" number? I use pca9685. I couldn't see any difference on scope, only PWM. My scope does have a "default" button and "autoset", latter was useless as it zoomed out so I manually set to view, I did use same settings for both signals just had to change voltage scale so I could view better. Thanks!

@tryingHard: 1. It is up to you to decide what you would consider “acceptable”. It's your application! 2. If you want less residual oscillations, increase the value of R78. 3. The PWM frequency is 1 kHz, not 1000 kHz. 4. There is no magic.

Thanks, impossible for me to know what is acceptable when I don't know what the number means, not something you can understand after an hour of reading. Maybe 500mV isn't bad or maybe it's horrible. I will see what happens with R78 and thanks for clarifying frequency.

@tryingHard: Re “acceptable”: it depends on your application, on what you want to do with that signal. “Acceptable” means “acceptable by whoever will be the consumer of the signal”.

I hear you, it's for LED drivers and aquarium power heads.

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


text:
Make an LED Turn
//Make an LED Turn ON after pressing a push button switch for five times. Add a reset switch to turn OFF the LED whenever the reset switch is pressed

**void setup()

{

  pinMode(11, OUTPUT);

  pinMode (4,INPUT);

}

void loop()

{

  int y= digitalRead(6); // push button 2

  static int counter {} ;

  int x= digitalRead(4);// push button 1

  if (x==1&& y==0 )

    counter++;

else if (counter == 5) // If counter is pressed 5 times

{

  digitalWrite(11, HIGH); // Turn on the LED

}

if (counter >= 5) // If counter is greater than 5 led will still on

{

  digitalWrite (11, 1);

}

  else if

   (y==1&& x==0 ) // if pressed push button 2  led of
  {

    digitalWrite(11,0);

}

  counter = 0; // Make counter variable = 0

}

Is that a school assignment? What have you tried so far? Where exactly is your problem in implementing this? Have you looked at some of the numerous tutorials online, which teach how to blink an LED and how to read buttons? Btw: For button reading I can suggest the Bounce2 library, which is really helpful

my problem i don't know how to make LED on after press push buttons five times

Remember using either a pullup resistor or INPUT_PULLUP in the setup.

You can try implementing a counter system in your Arduino program.
For example, if this is your loop() function:
void loop(){
int buttonState = digitalRead(1); // Give the variable buttonState the value of pin 1, or whatever your button is connected to
static int counter{}; // Have a counter variable. Static means it doesn't reset to 0 after loop() restarts

if (buttonState == HIGH) // If the button is pressed
{
  ++counter; // Increase the value of counter by 1
}

else if (counter == 5) // If counter is pressed 5 times
{
  digitalWrite(11, HIGH); // Turn on the LED
}
// RESET:
if (counter > 5) // If counter is greater than 5 (you clicked the button again)
{
  digitalWrite (11, LOW);
  counter = 0; // Make counter variable = 0
}
}

Edit In the comments, Python Schlage made very good suggestions: to change buttonState to a boolean and change int to byte to save space on board the Arduino
Try following this tutorial: https://www.arduino.cc/en/Tutorial/BuiltInExamples/Button and modifying it to work with the counter.
Hope this helps! Please let us know if you need help with the setup() function or if anything is unclear.

For saving memory, buttonState can be changed into a Boolean and counter can be a byte. The else part is pretty useless, because it will just turn the LED off all the time, although it already is on LOW.

Good points Python Schlange! I'll add in a modified version with your suggestions


text:
How can I control 2 servos without an external power supply?
I've been trying to implement a project that's been in my head for a while, I want to wirelessly control my light and fan switches using an ESP32 and 2 servos (one for each switch) through an HTML page, and then later integrate it with Alexa
I have seen how one servo can be controlled by connecting the servo's power cable to the ESP32's Vin pin, but how can I control two? I want to avoid using an external power supply like a battery pack because I want it to be a completely automated process, and I don't want to have to keep switching out batteries often for the thing to work. I'll be using a 5V wall outlet to power the ESP32 using a USB.
Also, if anyone can provide a few more tips on how I can make my project more efficient or point out where I might be making a mistake, I'd be glad. I'm still new to the microcontroller world.
Thanks
EDIT :  I've attached a picture of the circuit diagram, just have a look and let me know if it is workable

The power wire is just needed, well, to power the servo. The control is done via the third wire (the other wire being Ground).
You can connect the second servo's power in parallel, only the control wire must be separated from the first servo's control wire.
Note: You need to make sure that the current consumption of both servos does not exceed the provided power.

Oh okay, thanks for that. But I have one doubt, how exactly do I calculate if current consumption of the servos is lesser than what the ESP can provide? I'm using an ESP-WROOM-32, one SG90 servo and one MG90 servo. If anybody can do the calculations as to whether I can control the servo using the ESP32, it'll be very helpful, as I'm still new to this stuff, and another opinion is always better :)

Your servos should be documented, and you are looking for the maximum current of each. Add them. Then add the maximum current of the ESP32, it should be in its documentation, too. The total must be less than the maximum current your 5V wall wart provides.

This is the safe way. If you are sure that your servos never block, the current is much lower, see their documentation. Also the ESP32 consumes in average less current. Only at startup and when peak calculation power is needed, it rises. You might simply try. If the provided current is insufficient, you will notice that your project behaves strange and/or unreliable.

So it IS possible for me to just try it out right? As in, if the servos do demand more than the ESP32 can provide, it won't cause any fatal damage to the servos or the ESP, right?

Since you said that you connect your servos to Vin of the ESP32, which is the same point where you connect your supply device, the ESP32 has nothing to do with it. Its copper line from the USB to this pin should be able to handle the servos current. -- If this is not correct, please edit your question (there is a little link below the question) and show us your circuit. You can draw it with any graphic tool you know.

Right, there seems to be a misunderstanding from my side, I was unaware that the Vin pin and the USB port are connected. Seems like my lack of knowledge of microcontrollers has caught up to me :p. Anyways, I have edited my question and added a picture of the circuit diagram, have a look and tell me if it is workable


text:
Arduino Nano IoT Power Consumption
I am trying to reduce the power of my Arduino Nano IoT. I would like to run it using a battery over a longer time period. I thought this would be possible when putting it to sleep most of the time. However, at the moment I can only reduce the power consumption to 10mA by

disabling wifi using the WiFiNINA library
putting the arduino to sleep using the ArduinoLowPower library
removing both LEDs
powering it through a 4,5V battery

Is there anything else I can do to further reduce power consumption? If not, is there another, more suitable device I can use instead for this project? It has to support wifi and use very low power during sleep.

use an ESP32 only

The power consumption can also be reduced by increasing the voltage input, see this link in the "How to power the Arduino Nano 33 IoT" section: https://github.com/ostaquet/Arduino-Nano-33-IoT-Ultimate-Guide This may or may not be possible for your project.

Two of those 10mA come from the ATECC608 crypto chip which idles at 2mA.  That leaves 8mA for you to track down.
The WiFi-NINA module has multiple "sleep" modes that range from 30mA down to 4.5µA. Since you can't be in the 30mA "modem sleep" mode (it's too high for your measurements) I suspect it enables "light sleep" at 800µA.
The switching regulator uses 200µA.  So those two together probably account for 1mA in total, leaving you 7mA more to find.
The accelerometer can be up to 1.25mA. I'll assume that since you don't mention it, you haven't set that to "power down" mode.  5.75mA left.
The main MCU is actually quite hungry for power, even when sleeping. Looking at the datasheet it can be between 1.3mA and 2.4mA for the different "idle" modes. Only "standby" mode (where clocks are switched off, etc) drops it below 1mA. With it running a simple program you are looking at 4-6mA.
So it could be that the MCU isn't actually sleeping properly, or that other modules that you think are in low power aren't.
I would suggest manually disabling chips completely (pull their respective RESET pins if available LOW if available) to see how that affects the current.


text:
Arduino Killing USB-C Mini Dock
I've been having some issues with my Arduino Mega Board. I built a PCB that would sense LM35 reading, low-pass filter it and send it to A0 into the Arduino. This is the input for a PID controller based on Brett Beauregard library. The schematics is really simple, a voltage divider after de PWM output, that polarizes the base of a TIP 122, causing current to close the circuit for a wound wire resistor.
1)
I was feeding the PCB board with 12V 2A switching supply (but not the arduino). On the other side, my PC was connected to a USB-C / USB mini dock to the Arduino, and the Arduino conected to the PCB board ( LM35 Output and PWM Input).
While using it my computer lagged a lot, but I didn't do anything, untill it killed my mini dock's USB port.( the power supply GND was connected to the Arduino's GND)
2) I did a new PCB board, filtering even more the LM35 signal, and doing some extra changes. While doing some examinations for the filter (succesfully) and using a lab's regulated power supply for the PCB (12V), everything went okay...Untill I wanted to examine if the PWM signal was causing any noise into the LM35 reading, so I started apply the PWM signal to a header pin in the PCB. After a while my computer stopped recognizing the Arduino and finally killed a second USB mini dock.
I'm pretty sure there's not a shortcircuit or any stupid mistake... but I cannot find whats going on.

Why is the +12V net connected to the Arduino power plug. And how did you connect your Arduino power plug  to the PCB? I do not say it's an error. I simply do not understand what happens there. ;-)

I think the electrical engineering stackexchange might be a better place for this question.  https://electronics.stackexchange.com/


text:
How to use I2S in ESP boards?
I have researched this a lot, but haven't found anything on which I can trust.
I want to use a particular ESP board to play audio. To play audio, I2S support is required. But, I know that not every ESP board break out the I2S pins from the chip. According to me, buying an ESP32 only to use the I2S would be a waste of money. So, my question is, if I just want to use I2S, which board is would be suitable? Please provide some references if you can.

Few months ago I tested successfully I2S with this library, I used the default pins:
bck_io_num = 26
ws_io_num = 25
data_out_num = 22

which are available on many boards such as Lolin D32.

Can we use any pin for the I2S?

I don't think so, those pins should be internally wired to the I2S peripheral (but I'm not sure)

You have to use the dedicated I2S pins.


text:
Streaming audio to ESP8266 over WiFi
I am thinking of making a wireless speaker using the ESP8266 chip. I have some questions regarding this.

Which pin of the ESP8266 chip can be used as I²S output? I have an ESP chip of this type :

Which ESP chip would be the best choice for this purpose?
I know about the MAX98357A which is used to convert digital I²S data to analog. But, for stereo output I need to use 2 of those. Is there any alternative to this chip which supports stereo output by default?
I have found many tutorials which shows how to play audio from SD card of ESP8266. But, how can I stream audio over standard WiFi connection?

Which pin of the ESP8266 chip can be used as I²S output?

I uses GPIOs 2, 3, and 15. You only have GPIO2 available, and that's also one half of the UART interface.  Also you usually need to generate a "master" clock (usually something like 256x the bit clock) for oversampling. So you can't with that module.

Which ESP chip would be the best choice for this purpose?

ESP32, without a shadow of a doubt.

I know about the MAX98357A which is used to convert digital I²S data to analog. But, for stereo output I need to use 2 of those. Is there any alternative to this chip which supports stereo output by default?

Yes, there are plenty. The search term you want is "CODEC". Personally I use the TLV320DAC3101.
You never use two separate mono CODECs for stereo, since I²S is a (normally) stereo protocol for connecting to a stereo CODEC. Reliably splitting a stereo I²S stream into two mono ones is not easy.

I have found many tutorials which shows how to play audio from SD card of ESP8266. But, how can I stream audio over standard WiFi connection?

By implementing a suitable protocol, and that depends entirely on what your audio is and how it is generated.

For number 3 I am thinking of this technique : https://electronics.stackexchange.com/questions/295889/using-two-mono-amplifiers-to-make-one-stereo-amplifier

Can you please elaborate on the last answer? I simply want to stream MP3 audio.

There is no such thing as "simply" streaming MP3. Streaming involves buffering, then decoding (in a timely manner) the audio from compressed MP3 format into a PCM format. Then feeding that through other buffers to the I²S hardware. If you are streaming a live stream (radio, for example) then you have to be able to cleanly handle "xruns" (buffer under- or over-runs) where the sender isn't sending at the same speed as you're playing. So your project really comprises three parts: 1. Getting the data. 2. Decoding the data. 3. Sending the data to I²S. All three of those are difficult tasks.

What did you mean by usually something like 256x the bit clock) for oversampling. So you can't with that module.?

You don't have the required pins available. So you can't with that module. On top of that you have to usually generate a master clock. And there's no pin for that on that module. So you can't with that module. You just can't with that module.

Will the ESP32 be able to fulfil all those requirements?

More than likely, yes. Google for some projects.


text:
Is it possible to compile and upload code witout the IDE?
I just got started with Arduino, and found out that I need the IDE to compile and upload codes, which works perfectly fine. This is my code:
# pragma GCC optimize ("Ofast")

char i = 0 ;
unsigned long time, lastTime ;

void setup() {
    pinMode(LED_BUILTIN, OUTPUT) ;
}

void loop() {
    time = millis() ;

    if (time > lastTime) {
        lastTime = time + 100 ;
        i = ~i ;
        digitalWrite(LED_BUILTIN, i  ? HIGH : LOW) ;
    }
}

But the biggest problem is that the IDE is written in Java and it uses 1 GB of system's memory, and it's very heavy.
So is there a way I can use the Linux command line to compile and upload the code to the Arduino UNO?

You can also try PlatformIO, which offers a similarly integrated experience. It uses VScode which is Electron based, so it's only slightly lighter.

Yes, I haven't used it but on the official page it is mentioned, called Arduino CLI (command line interface), available for Mac and Linux.
https://www.arduino.cc/pro/cli
Excerpt:

Arduino CLI is a command line tool that contains all you need to
easily build applications around the Arduino ecosystem. Parse the JSON
output of the CLI or implement it as an always-on service that accepts
commands via a gRPC interface using your language of choice.
Arduino CLI is the backbone of the Arduino Create Web Editor serving
over a million users.

Also, it's open source and can be found on GitHub at https://github.com/arduino/arduino-cli/releases

I use arduino-cli all the time now. It's so much better than fighting with the IDE - at least for someone like me brought up on programming in vi...

@Majenko vi is a long time ago for me ... at my current project I'm using Visual Studio as I stubbed all Arduino and Arduino library functions so I have a working executable on my PC, and since it's in the same directory as the .ino file I only hit the 'Compile' (and or  upload) button of the Arduino IDE which is the only thing I use. (btw, I'm intending to move to platformio and using ESP32 soon). For me the Arduino IDE is also quite a bad IDE (good for very small one file programs (which as OO programmer is barely the case for me).


text:
24/14 second countdown timer or shot clock for basket ball start/stop button doesn't respond well
Start button doesn't respond correctly, i can't figure out whats wrong with the code ? pls help,
this code is for 24 second and 14 second countdown timers in a same unit
comes with three physical push buttons

start/pause
reset
shift (Arduino pin 8 as shift button)

both 1 and 2 uses arduino pin 2 and 3 for interrupts,
by pressing reset counter sets for 24 second timer and shift+reset will set the timer for 14 seconds and by pressing start button will start the countdown and press again will pause the timer,
to display it uses two seven segment displays with 74LS47 Binery code decoder
here is the code
//Declaring and Initializing Variables
int p4 = 4;
int p5 = 5;
int p6 = 6;
int p7 = 7;
int p9 = 9;
int p10 = 10;
int Buzzer = 12;
boolean Standby = true;
unsigned long newTime, oldTime = 0;
const long timeDelay = 1000;
volatile int Num1 = 0;
volatile int Num2 = 0;
volatile int Zero = 0;
volatile byte Press = 0;
volatile boolean Ready = false;
volatile boolean Shifter = false;
volatile int Shift = 8;

void setup() {
  pinMode(Shift, INPUT);//Shift pin button
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);

  pinMode(9, OUTPUT);//FirstDigit
  pinMode(10, OUTPUT);//SecondDigit

  pinMode(12, OUTPUT);//Buzzer
  attachInterrupt(0, Starting, HIGH);
  attachInterrupt(1, ReStarting, RISING);
  digitalWrite(12, LOW); //Set it LOW first
}

void refresh() {
  SecondDigit();
  FirstDigit();
}

void Starting() {
  //Running and Stopping here
  if (Ready == false) {
    Press = 0;
  }

  Press++;
  if (Press >= 4) Press = 2;
} //End of Starting

void ReStarting() {
  //Restart sequence
  Zero = 0;
  if (Press == 0) {
    Num2 = 2;
    Num1 = 4;
    Ready = true;
    Press = 1;

  }

  if (digitalRead(Shift) == HIGH) Shifter = true;

  if (Shifter == false) {
    if (Zero == 3)Press = 1;
    Num1 = 4;
    Num2 = 2;
    Zero = 0;
    Ready = true;
    Press = Press;
  }
  else {
    if (Press == 2) {
      if ((Num1 + (Num2 * 10)) < 14) {
        Num1 = 4;
        Num2 = 1;
        Zero = 1;
        Ready = true;
        Press = 2;
      }
    }
    else {
      if (Press == 1 || Press == 3) {
        //Uncomment the next line to disable the 14 seconds reset if time is greater than 14 seconds
        if ((Num1 + (Num2 * 10)) < 14) {
          Num1 = 4;
          Num2 = 1;
          Zero = 1;
          Ready = true;
          Press = 1;
        }
      }
    }
  }
}//End of ReStarting

void Display() {
  if (Press == 2) {
    if (Zero <= 3) {
      Num1--;
      if (Num1 == 0)Zero++;
      if (Num1 == -1) {
        Num1 = 9;
        if (Num2 > 0)Num2--;

      }
    }
  }
  for (int Transition = 0; Transition < 500; Transition++) {
    FirstDigit();
    SecondDigit();
    if (Ready == true) {

      if (Zero == 3)BuzzMaker();
    }
  }
} //End of Display

void FirstDigit() {
  //Display 4 BCD digits of Number in First LED Segment
  digitalWrite(10, LOW);
  digitalWrite(9, HIGH);
  if (digitalRead(Shift) == HIGH) Shifter = true;
  digitalWrite(4, bitRead(Num1, 0));
  digitalWrite(5, bitRead(Num1, 1));
  digitalWrite(6, bitRead(Num1, 2));
  digitalWrite(7, bitRead(Num1, 3));
  delay(1);
  Shifter = false;
} //End of FirstDigit

void SecondDigit() {
  //Display 4 BCD digits of Number in Second LED Segment
  digitalWrite(9, LOW);
  digitalWrite(10, HIGH);
  if (digitalRead(Shift) == HIGH) Shifter = true;
  digitalWrite(4, bitRead(Num2, 0));
  digitalWrite(5, bitRead(Num2, 1));
  digitalWrite(6, bitRead(Num2, 2));
  digitalWrite(7, bitRead(Num2, 3));
  delay(1);
  Shifter = false;
} //End of SecondDigit

void BuzzMaker() {
  //Configuring Buzzer frequency and setting go with the counting numerals
  digitalWrite(9, HIGH);
  digitalWrite(10, HIGH);
  digitalWrite(12, HIGH);

  delay(1000);
  digitalWrite(12, LOW);
  delay(200);
  digitalWrite(12, HIGH);

  delay(500);
  digitalWrite(12, LOW);

  Press = 2;
  Zero = 0;
  Ready = true;
  Shifter = false;
}//End of BuzzMaker

void loop() {
  if (Press == 0)refresh;
  refresh();
  newTime = millis();
  if ((newTime - oldTime) >= timeDelay) {
    oldTime = newTime;

    if (Num2 == 0 && Num1 == 0 && Press == 2) {

      Press = 1;
    }

    //Here we are going to access each case with each different routine by case
    switch (Press) {

      case 0://Initial

        Display();
        break;

      case 1://Stop - Displaying 24 but still not yet running

        Display();
        break;

      case 2://Running

        Display();
        // PlayTime();
        break;

    }
  }//End of millis() condition

} //End of main loop function

What do you mean by "doesn't respond correctly"? Can you tell us what it's doing and what it should be doing?

Without going through your (messy) code: have you debounced the button?

i am apologizing for my indentations... doesn't respond means at the first when i press start button it starts at once then i press again it wont pause i have to press start two or three times to pause it the again to start same sometimes it respond quickly some times not at all

one of the person from a forum told me to add a debounce which i dont know how to add... i already add a physical debounce using diode capacitor and resistor which gives some clearing up but still the start button response isn't smooth

In the Arduino IDE there is a "Auto format" key kombo, Crtl + T that will fix the formatting of the code.


text:
How to use void swap with multi-dimensional array to control motor with openCR board
i am a beginner.
About my problem, there is an "invalid conversion' error in the swap(goal_positionall)
#include <DynamixelWorkbench.h>

#define Device_Name ""
#define BAUDRATE 57600
#define DXL_ID_1  1
#define DXL_ID_2  2
#define DXL_ID_3  3
#define DXL_ID_4  4
#define DXL_ID_5  5
DynamixelWorkbench dxl_wb;

int32_t goal_positionall[3][5] ={{0, 1024, 2048, 3072, 4080},
                                 {0,1000,0,3000,0},
                                 {1000,1000,500,700,2048}};

const uint8_t handler_index = 0;

    void setup()
    {
      Serial.begin(57600);
      while(!Serial);

      const char *log;
      bool result = false;

      uint16_t model_number = 0;
      uint8_t dxl_id[5] = {DXL_ID_1, DXL_ID_2, DXL_ID_3, DXL_ID_4,DXL_ID_5};

      result = dxl_wb.init(Device_Name, BAUDRATE, &log); //To initialize the
motor
      if (result == false)
      {
        Serial.println(log);
        Serial.println("Failed to init");
      }
      else
      {
        Serial.print("Succeeded to init : ");
        Serial.println(BAUDRATE);
      }

      for (int X = 0; X < 5; X++) //To do the actions 5 time
      {
        result = dxl_wb.ping(dxl_id[X], &model_number, &log); //Ping the 5 motors
        if (result == false)
        {
          Serial.println(log);
          Serial.println("Failed to ping");
        }
        else
        {
          Serial.println("Succeeded to ping");
          Serial.print("id : ");
          Serial.print(dxl_id[X]);
          Serial.print(" model_number : ");
          Serial.println(model_number);
        }

        result = dxl_wb.jointMode(dxl_id[X], 0, 0, &log);  //Change joint mode for 5 motors
        if (result == false)
        {
          Serial.println(log);
          Serial.println("Failed to change joint mode");
        }
        else
        {
          Serial.println("Succeed to change joint mode");
        }
      }

      result = dxl_wb.addSyncWriteHandler(dxl_id[0], "Goal_Position", &log); //Add Sync write handler
      if (result == false)
      {
        Serial.println(log);
        Serial.println("Failed to add sync write handler");
      }

    }

    void loop()
    {
      const char *log;
      bool result = false;

      result = dxl_wb.syncWrite(handler_index, &goal_positionall[0][0], &log);
      if (result == false)
      {
        Serial.println(log);
        Serial.println("Failed to sync write position");
      }

      delay(1000);

      swap(goal_positionall);
    }

void swap (  int32_t **array[][5] )
    {
      int32_t tmp = array[0][5];
      array[0][5] = array[1][5];
      array[1][5] = array[2][5];
      array[2][5] = tmp;

    }

please format your code ... select the code and click the {} button

No wonder, the int32_t **array[][5] means int32_t *** array[5], so you're passing 2 dimensional array into the 4 dimensional parameter.

what should i do to avoid this?

Either fully define the size of the 2 dimensional array or don't specify the size at all


text:
XBee not connecting
Recently, I bought an XBee shield along with a dongle and two XBee's. After assembling them, I tried to connect them using XCTU. Although the XBee on the dongle connected correctly, the computer did not detect the XBee on the shield. I tried switching the XBee's, and there was no difference. I continually an error message telling me to reset the shield. Nothing happens when I reset the shield. Although the computer recognizes that the Arduino is plugged in, it seems as though it doesn't recognize the XBee.
I have tried this with every possible configuration, and I keep getting the same message. I have also tried many other things I found online.
I have been stuck on this problem for over a week, and any help would be
Here are the materials I am using
2x Series 1 XBee
1x Sparkfun XBee Explorer Dongle
1x Sparkfun XBee Shield
1x Arduino Uno R3
Thanks in advance!

Check baud rate and ensure the cable you are using is not just a power only cable.

I checked the baud rate, and it still doesn't work.

Also, the cable seems to have no problem

Does a different COM port appear when you plug in a shield? For example of both the arduino and the shield are connected do you see two COM ports in xCTU? In windows control panel device manager what is the usb driver name of the shield?

Check the baud rate on xctu software, make sure it is on 9600 or you can click on default button and make sure you connect the xbee on the right port


text:
Using Arduino and Motor Shield
I am a beginner in Arduino.I want to connect 2 motors to Arduino.
Do I require a motor shield?And if yes please tell why?
Also can i use an amplifier to increase the voltage for the motors?
And one last important question, I have just seen the motor shield's pic. Does it restrict arduino's pin usage? I mean we can't use the arduino pins if we use the motor shield right?
PS: I am talking about this model: SLAEX039 L293D Motor Shield
Thank a lot

Yes. To use standard D.C. motors, you must use a motor shield or the L239D chip. This is mainly due to motor noise, and control to run the motor at different speeds and directions. Also you get very easy to use libraries!

Can we use amplifiers then?

Please don't recommend the L293 (or L298) these are horribly antiquated, lossy devices which cause users no end of problems.  One should pick modern motor shield with an FET bridge instead, for example the ones with the TB6612FNG.  Additionally, the basic explanation of this answer is wrong - the need is not due to "motor noise" or directional control but rather the required motor current.   H-bridges have basically the exact same output structure as ATmega pins, but are built to handle the required current and possible voltage range, while ATmega pins are not.


text:
Transistor amplifier to drive speaker using Arduino PWM
I have been working on a project lately which uses Arduino to play a wav file from SD card. I am using TMRPCM library which made the job very easy. But the problem is that the output sound in the speaker is very low. I am using the below single transistor circuit with my Arduino to drive 1.2W / 8ohm speaker

But the Audio output is barely audible. And i have tried many speakers with different wattage but same result.
I am wondering that is there is something wrong with the Wav file i have used for my project. It is 16000Hz/ 8 bit unsigned PCM coded. So in a nutshell my questions are
1) How can i improve the sound obtained from my speaker by making modifications in the transistor amplifier circuit?
2) Was the less audible sound is due to the Wav file i have used?
Kindly help me out, thanks in advance.

I had some success using an LM386 audio amplifier after an CRC band-pass filter (to remove the DC and the PWM frequency). It's a very common and cheap (less than $1) amplifier specifically designed to drive a speaker. See the datasheet for the proper wiring.

Can you play the WAV file on your PC?  Is it quiet on there?  Can you play another WAV file, or use another audio source?

Hi @EdgarBonet , I have tried hooking up with a LM386 based amplifier but very little improvement. May be i will try with the CRC filter before feeding it to transistor. Am not quite whether its quiet in PC i would say its fine. Other wav files are less audible as well. However i have tried default Arduino melody tones which sounds pretty good with the same setup

you need to at least block the dc component with an rc filter. edit: basically, what Majenko has shown.

Ditto with @Edgar.  There are Arduino LM386-based amplifier modules available for peanuts.  They can drive a decent speaker.

Your amplifier arrangement is fundamentally flawed. At the moment you are "tickling" the top end of the electromagnet in the speaker - that is, you are energising it when the Arduino outputs a HIGH, and leaving it energised to de-energise by itself when the Arduino outputs a LOW.  Coupled with that the fact that a PCM file outputs PWM with a carrier frequency much higher than a tone() function (and ideally above human hearing frequencies) you end up with almost nothing happening on the speaker.
The classic Class A amplifier has a different arrangement:

simulate this circuit – Schematic created using CircuitLab
With that arrangement the transistor and R1 form a simple RTL inverter. Size R1 to give the output current you need for your speaker (lower resistor = more power = more heat = bigger transistor as well). R3 and C2 remove the high frequency switching from the PWM (you could also replace R3 with a suitable inductor if you want less losses from the resistor). C1 removes the DC offset from the signal to give the full swing to the speaker and prevent excess clipping and heating.
It's not an efficient design by any means. A better "first stage" (replacing R1 and Q1) would be a high drive output logic gate (one of the CD4000 series, since it can run from 12V). I have seen AND gates used before - this also gives the benefit that you can use the second input to the AND gate as a MUTE signal. The rest (R3, C1, C2) remains the same.
The advantage of using a logic chip instead of the RTL arrangement is that it gives a more efficient "Push-Pull" output which can deliver much more current with far less heat losses.
Instead of the speaker you could connect an audio power amplifier to the output of C1 to then drive a more powerful speaker. In this case you can most likely remove the first stage (Q1/R1/R2) and drive the RC filter directly from the Arduino.

Thanks for the circuit. Tried it but no luck the sound has even dropped. Double checked to make sure i have hooked up everything correctly. Also the transistor is heating up, any idea why this is happening?

The transistor is heating up because it's a tiny little 2N2222. If you look in a real audio amplifier you will see TO220 style transistors and big heat sinks. Using PCM audio on an Arduino is pretty silly anyway. You should invest in a proper audio shield, or a more powerful MCU that can do real audio.

Hi, I'm curious whether I should be able to hear the difference in sound quality between the Class A amplifier and the circuit given by the OP?  Wiring them both, couldn't tell the difference, but the OP circuit generated the same "loudness" at 11mA which the Class A amplifier took 110mA.  The OP circuit seems 10x lower power for comparable loudness.  (I couldn't tell the difference in sound quality, using an 8R, 3W speaker, at 5V playing Jesu by Bach on an Arduino)

You might try an audio transformer in the circuit, following a low-pass filter to smooth the PCM signal.  Here's a picture of suitable inexpensive transformers (from alexnld.com; but similar transformers are available on Ebay etc.):

The effect of the transformer in the circuit is transforming the high voltage, high impedance output of the transistor driving circuit to the low voltage, low impedance needed at the speaker.  The impedance ratio of the transformers in the picture is 1300 Ω to 8 Ω.

First, do not get fooled by some that answer that 16kHz is a pretty high, nearly unhearable frequency. You're talking about sampling rate here. Then 16khz is pretty low end (although maybe on the edge of what's possible with the microcontroller, I don't know that off the top).
I would recommend introducing a negative supply rail to majenko's design as you can not expect a circuit to output negative voltages (i.e the negative halfwaves of an audio signal) without a negative supply...
As others already pointed out the transistor you use is a pretty poor choice. There is a transistor selection guide available here.
It has an audio section, take a look at that!

"It is 16000Hz"
That's pretty high frequency. Is your hearing good enough for that? Many folks couldn't hear it.


text:
Triggering actions in Android smartphone via Bluetooth from Arduino
Am working on a wearable using Arduino Micro and I am thinking it would be cool if I can trigger some events in my smartphone using Arduino. Say for example a button press in my wearable should trigger events like opening music player, reducing/increasing volume or opening some Android Apps.
Sorry for providing just a rough view of the idea. So I want to know to perform similar actions listed above, Do I need to create a Android app for it? I don't find any readymade app that fits my requirement. Or Is there any feasible way to achieve what I need without having to break my head with Android developing?
Thanks in advance.

So it's going to be one tough road isn't it? Any advice on where to get started or which IDE I should choose. Any tips ? :-P

For the volume there are standard Media Control bluetooth commands. The simplest way of doing those may be to hack wires into a cheap Media Keys BLE device ($5 or so on eBay).

@Majenko Any link to those commands ?


text:
ATTiny85 USB Troubleshooting. Device is not recognized when programmer asks to plug in device
I have bought this cheap AVR Programmer Board and I thougth that I would be OK just plugging it into my USB port. Then after I did that nothing happened so I passed last 4 hours trying to understand what was going wrong. I learned that ATTiny85 microchips often come with no bootloader.

So first I tested it with Arduino as ISP and simple blink code. It worked. Then I downloaded micronucleus and i flashed it via Arduino as ISP. I think this process worked pretty well as the output show
> avrdude -C ../etc/avrdude.conf -c arduino -p t85 -P COM3 -b 19200 -U flash:w:/micronucleus/firmware/releases/t85_default.hex

 avrdude: AVR device initialized and ready to accept instructions

 Reading | ################################################## | 100%
 0.01s

 avrdude: Device signature = 0x1e930b (probably t85) avrdude: NOTE:
 "flash" memory has been specified, an erase cycle will be performed
          To disable this feature, specify the -D option. avrdude: erasing chip avrdude: reading input file
 "/micronucleus/firmware/releases/t85_default.hex" avrdude: input file
 /micronucleus/firmware/releases/t85_default.hex auto detected as Intel
 Hex avrdude: writing flash (8166 bytes):

 Writing | ################################################## | 100%
 0.09s

 avrdude: 8166 bytes of flash written avrdude: verifying flash memory
 against /micronucleus/firmware/releases/t85_default.hex: avrdude: load
 data flash data from input file
 /micronucleus/firmware/releases/t85_default.hex: avrdude: input file
 /micronucleus/firmware/releases/t85_default.hex auto detected as Intel
 Hex avrdude: input file
 /micronucleus/firmware/releases/t85_default.hex contains 8166 bytes
 avrdude: reading on-chip flash data:

 Reading | ################################################## | 100%
 0.09s

 avrdude: verifying ... avrdude: 8166 bytes of flash verified

 avrdude: safemode: Fuses OK (E:FF, H:DF, L:62)

 avrdude done.  Thank you.

Problem that I'm now facing is that when I try to upload a code using ATTiny Development Board via arduino IDE (selecting Attiny85 digispark default 16.5mhz) and it asks me to plug in the device, device is not recognized.
I already installed drivers downloaded from github release section of DevicestumpArduino repository, tried installing micronucleus configuration driver via zadiag like i read in this question but nothing worked.
What am I missing?

From your AVRDude output:

avrdude: safemode: Fuses OK (E:FF, H:DF, L:62)

It does not appear that you have programmed the AVR configuration fuses.
One for thing, E:FF, is extended fuse value 0xFF, which is missing the SELFPRGEN (self-programming) fuse that would allow Micronucleus to load your code onto the AVR, that is allow the AVR to execute instructions to program itself.  So, assuming it managed to show up on USB, you wouldn't actually be able to use it to put code on your chip.
You can see what they should be where the makefile fuse target defers to your t85_default configuration:
FUSEOPT = -U lfuse:w:0xe1:m -U hfuse:w:0xdd:m -U efuse:w:0xfe:m

The fuses that are actually preventing it from showing up on USB are more likely the clock related fuse bits in the low fuse byte.  In particular CKDIV8 (factory default) is set to divide-by-8 where it is not in the makefile.  The CKSEL bits are set to 0x2 (factory default) for the 8Mhz internal RC oscillator whereas the makefile wants them to be set to 0x1, for internal PLL (phase locked loop) that generates higher clock rates from the RC oscillator.  In short, your chip is running at 1MHz rather than 16Mhz.  The Micronucleus code may also be written such that it needs PLL for bit-banging USB, though I haven't looked into that to be certain.


text:
Using millis() instead of delay() when playing a melody
I want to make my Arduino to play several simple melodies, and also be able to skip a melody by pressing a button and go on with the next song. therefore I cannot use delay() because the code should constantly check if a button is pressed. So I wanted to use millis(), but dont't know how to implement it.
this is how song code looks like with delay():
#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
//etc...

int tempo=144;

// change this to whichever pin you want to use
int buzzer = 11;

int melody[] = {

  //Based on the arrangement at https://www.flutetunes.com/tunes.php?id=192

  NOTE_E5, 4,  NOTE_B4,8,  NOTE_C5,8,  NOTE_D5,4,  NOTE_C5,8,  NOTE_B4,8,
  // etc...

};

// sizeof gives the number of bytes, each int value is composed of two bytes (16 bits)
// there are two values per note (pitch and duration), so for each note there are four bytes
int notes=sizeof(melody)/sizeof(melody[0])/2;

// this calculates the duration of a whole note in ms (60s/tempo)*4 beats
int wholenote = (60000 * 4) / tempo;

int divider = 0, noteDuration = 0;

void setup() {
  // iterate over the notes of the melody.
  // Remember, the array is twice the number of notes (notes + durations)
  for (int thisNote = 0; thisNote < notes * 2; thisNote = thisNote + 2) {

    // calculates the duration of each note
    divider = melody[thisNote + 1];
    if (divider > 0) {
      // regular note, just proceed
      noteDuration = (wholenote) / divider;
    } else if (divider < 0) {
      // dotted notes are represented with negative durations!!
      noteDuration = (wholenote) / abs(divider);
      noteDuration *= 1.5; // increases the duration in half for dotted notes
    }

    // we only play the note for 90% of the duration, leaving 10% as a pause
    tone(buzzer, melody[thisNote], noteDuration*0.9);

    // Wait for the specief duration before playing the next note.
    delay(noteDuration);

    // stop the waveform generation before the next note.
    noTone(buzzer);
  }
}

I found this code on internet but I don't know how to implement this in above code. when I try to, I get some kind of cursed sound.
unsigned long previousMillis = 0;
boolean outputTone = false;

if (millis() - previousMillis >= noteDuration) {
    previousMillis = millis();
    if (outputTone) {
        noTone(buzzer);
        outputTone==false;
    } else {
        tone(buzzer, melody[thisNote], noteDuration*0.9);
        outputTone==true;
    }
}

edit1: I tried this:
    unsigned long previousMillis = millis();
    int thisNote = 0;

    while (thisNote < notes * 2) {

        // calculates the duration of each note
        divider = lied1[thisNote + 1];
        if (divider > 0) {
            // regular note, just proceed
            noteDuration = (wholenote) / divider;
        } else if (divider < 0) {
            // dotted notes are represented with negative durations!!
            noteDuration = (wholenote) / abs(divider);
            noteDuration *= 1.5; // increases the duration in half for dotted notes
        }

        // play the note
        tone(buzzer, melody[thisNote]);

        check();//check if button is pressed, and if so, changes number to 2
        if (number ==2){
            thisNote=notes*2;
        }
        if ((millis() - previousMillis) >= noteDuration){
           thisNote = thisNote + 2;
           // stop the waveform generation before the next note.
           noTone(buzzer);
        }

     }

but it doesn't work, and I don't really understand why
edit2: I changed something, this is probably the closest I have been to a working melody without "delay()". But it is extremely slow.
    boolean outputTone = false;
    unsigned long previousMillis = millis();
    int thisNote = 0;

    while (thisNote < notes * 2) {

        // calculates the duration of each note
        divider = lied1[thisNote + 1];
        if (divider > 0) {
            // regular note, just proceed
            noteDuration = (wholenote) / divider;
        } else if (divider < 0) {
            // dotted notes are represented with negative durations!!
            noteDuration = (wholenote) / abs(divider);
            noteDuration *= 1.5; // increases the duration in half for dotted notes
        }

        if (millis() - previousMillis >= noteDuration) {
            previousMillis = millis();
            if (outputTone) {
                noTone(buzzer);
                outputTone==false;
            } else {
                tone(buzzer, melody[thisNote], noteDuration*0.9);
                outputTone==true;
                thisNote = thisNote + 2;
            }
        }

        check(); //checks if button is pressed, and if so, changes number to 2.
        if (number ==2){
            thisNote=notes*2;
        }
     }

I don't quite understand the code snippets, that you added to your question afterwards (they are partly incomplete). But I will propose my own solution to the problem.
A melody is a list of notes and pauses. Each note has a pitch and a duration. A pause has only a duration. We can now define a struct for holding a note:
struct Note {
    unsigned int pitch;
    unsigned int duration;
};

Since a pause does not have a pitch, we can use our struct for a note by setting the pitch to an invalid value (for example zero). For building a melody we are now  defining an array of Notes. But since we want multiple melodies, so that we can switch between them, we are using a 2 dimensional array for defining all melodies in one array:
#define NR_MELODIES  2
#define MELODY_LENGTH 8
Note melody[NR_MELODIES][MELODY_LENGTH] = {
    { // melody 0
        {0      , 4}, //pause
        {NOTE_E5, 4},
        {NOTE_B4, 8},
        {NOTE_C5, 8},
        {NOTE_D5, 4},
        {NOTE_C5, 8},
        {0      , 8}, // pause
        {NOTE_B4, 8}
    },
    { // melody 1
        {0      , 4}, //pause
        {NOTE_B4, 8},
        {NOTE_C5, 8},
        {NOTE_D5, 8},
        {NOTE_C5, 4},
        {NOTE_B4, 8},
        {0      , 8}, // pause
        {NOTE_E5, 4}
    }
};

Here I used the divider (part of the whole note), just like you did in your code. A 4 means a quarter note, 8 an eight note. For preventing loosing the first note, I inserted a quarter pause at the start.
We also need a variable to hold the current position in our melody, one for the current melody and a timestamp variable for the timestamp of the last played note:
unsigned int current_note = 0;
unsigned int current_melody = 0;
unsigned long last_note_timestamp = 0;

Now in void loop() we check for our timestamp and the duration of the current note. If the current note should end, we end it, increment to the next note and start playing it:
if(millis() - last_note_timestamp > wholenote/melody[current_melody][current_note].duration){
    last_note_timestamp += wholenote/melody[current_melody][current_note].duration; // increment timestamp to start of next note
    noTone(buzzer); // stop current note
    current_note++; // increment to next note
    if(melody[current_melody][current_note].pitch){ // next note is not a pause
        tone(buzzer, melody[current_melody][current_note].pitch, wholenote/melody[current_melody][current_note].duration); // start note
    }
}

And after the if statement we can add an if statement for checking the melody change button. You didn't include the button check code in your question, so I will just use a placeholder function here.
if(change_melody_pressed()){
    // incrementing current melody and wrap around, if we reached last melody
    current_melody = (current_melody + 1) % NR_MELODIES;
    // reset current note to play melody from start
    current_note = 0;
}

Now we still need to think about, what happens, when a melody finishes. 3 possibilities:

We could restart the current melody: We need to check for the last note in a melody, and then reset current_note:
  if(current_melody >= MELODY_LENGTH ){
      current_note = 0;
  }

We can increment to the next melody: Like above, but we add the melody incrementing line in the if statement:
  current_melody = (current_melody + 1) % NR_MELODIES;

We can stop playing: Here I would use the above if statement and set current_note to -1. Then we need to check in our first if statement, if current_note is not -1:
  if(current_note != -1 && millis() - last_note_timestamp > wholenote/melody[current_melody][current_note].duration)

Note: I have not tested the above code, but I compiled it to try finding syntax errors.

In essence you will need to break your for loop open and use a global variable for thisNote, incrementing it each loop (with the millis example so that proper timing is still adhered to).
This isn't the only approach to this problem. Your existing code could check for the button press within the for loop and escape the for loop when pressed.

thanks for your comment! I don't fully understood what you meant, but I tried something (I edited my post). I changed my for loop in a while loop. but it still does not work.


text:
[SOLVED]how to send command to Gsm module from Arduino via serial port
Am using SIM7600X 4G HAT module (GSM) and Arduino Uno
after I start the module and Arduino, I receive data from Gsm module but I can't send any command to it.
On my Arduino board when I get data RX led flashing, and when I send command TX led flashing.
#include <SoftwareSerial.h>
SoftwareSerial myserial(3, 4); // gsm_TX, gsm_RX

void setup(){
  myserial.begin(9600); //Initialize GSM serial port
  Serial.begin(9600); //Initialize Arduino default serial port
}

void loop(){
  while(1){
    while (myserial.available()) {
      //Serial received data, output via mySerial.
      Serial.write(myserial.read());
    }
    while(Serial.available()) {
      //myserial received data, output it via Serial.
      myserial.write(Serial.read());
    }
  }
}

As the picture I send "AT" command or any command it no response.
it show only module start up command.

My circuit

I solved my problem, On my circuit GSM module use an external source and my Arduino Uno use serial port source, So it cant communicate via pin because both ground of them did not connect to each other then the answer is connected GSM module GND to Arduino Uno GND.


text:
[SOLVED]SIM7600 Module Power up by Arduino Uno doesn't work
Am using SIM7600X 4G HAT with Arduino Uno
I follow to manual to Power up the module and it works well, The NET light flashing.

But when I connect to Arduino Uno and use DigitalPin 2 write (High -> Delay500ms -> Low) for "power on pulse" it doesn't work, The NET light still not flashing.

My code:
#include <Waveshare_SIM7600.h>
// Pin definition
int POWERKEY = 2;

char phone_number[] = "XXX";      //Store the phone number you want to call

void setup() {
  Serial.begin(9600);
  sim7600.PowerOn(POWERKEY);
  sim7600.PhoneCall(phone_number);
}

void loop() {

}

code from Waveshare (Waveshare_SIM7600.h):
/**************************Power on Sim7x00**************************/
void Sim7x00::PowerOn(int PowerKey = powerkey){
   uint8_t answer = 0;

  Serial.begin(9600);

  // checks if the module is started
  answer = sendATcommand("AT", "OK", 2000);
  if (answer == 0)
  {
    Serial.print("Starting up...\n");

    pinMode(PowerKey, OUTPUT);
    // power on pulse
    digitalWrite(PowerKey, HIGH);
    delay(500);
    digitalWrite(PowerKey, LOW);

    // Stuck in below loop because Send AT command and no response ///////
    // Becuase NET light not flashing (not connect) //////////////////////

    // waits for an answer from the module
    while (answer == 0) {     // Send AT every two seconds and wait for the answer
      answer = sendATcommand("AT", "OK", 2000);
      delay(1000);
    }

  }

  delay(5000);

  while ((sendATcommand("AT+CREG?", "+CREG: 0,1", 500) || sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0)
    delay(500);
}

How is everything powered? SIM modules can draw rather big current (I remember something in the range of 900mA, though I'm not sure). You don't want to draw that current through the Arduino. If you don't provide enough current, the module might brown out and thus fail to work.

I don't know much about schematics but i following this youtuber guy, my SIM7600 module is like him, and arduino board is similar but i stuck at 2:20 in the video. int the video it work well. https://www.youtube.com/watch?v=KOig5ndq2ek&ab_channel=cytrontech

The GSM module requires a 5V 2A source and my Arduino Uno cant draw for it, my solution is to use a power bank that can draw 5V 2A for powering the GSM module and jump PWR pin to GND (manual said) the NET led start flashing and module can working but TX, RX pin still there for comm.


text:
Can 1 wiegand output for 2 controllers?
recently I have this project which needs to read 2 wiegand signal using Arduino Mega 2560.
I have an access control device which will output wiegand signal once the user is allow to enter, and there's a RFID reader which will transmit the card no in wiegand signal to my access control device.
So I need to get card no from the RFID reader and also from the Access control device, so I connect them like the attachment given, using a library here: ( https://github.com/ugge75/Wiegand-V3-Library-for-all-Arduino ), everything works fine at first, but once a while, I can't read signal from the RFID Reader, and sometimes I can. Could anyone let me know why is this happening?

In the readers there is switch transistors that pull down voltage provided from controllers, in other words is shutting signal to the ground. In my practice i tested many solutions and simplest one is with diodes from each controller D0 D1 in direction to the reader. In that case is not crossing voltage from controllers. For 2 controllers and 1 reader you need 4 diodes - 2 on each line.
Controller 1 - D0 --> anode on Diode 1 --> cathode to common connection for line D0
Controller 1 - D1 --> anode on Diode 2 --> cathode to common connection for line D1
Controller 2 - D0 --> anode on Diode 3 --> cathode to common connection for line D0
Controller 2 - D1 --> anode on Diode 4 --> cathode to common connection for line D1
Common connection D0 --> reader D0
Common connection D1 --> reader D1
Works fine up to 20 meters since every diode makes voltage drop.
For diodes 1N4001/4007 works fine.
Noise is not a problem, this is very slow connection with 5v amplitude.

There is missing information.  Assuming a 5V Arduino and all D0s and D1s swing from 5V to 0V as the Wiegand protocol defines.  This despite the 12V power supply in the question's diagram.
Examining the driver code on GitHub, we see it's falling edge interrupt driven.  So any noise when the line is expected to be at a steady 5V will cause the driver to run.  And there are a number of locations in the code where data is dumped because it is considered bad. It appears that any unexpected noise during a valid signal will cause missing data.
Consider the possibility of noise affecting the RFID data.  Shorten the length of the RFID's Wiegand cable in an effort to improve the RFID reliability.
Consider re-writing the driver code to improve noise rejection.  Currently, it appears the driver code will accept any falling edge as valid data to be processed.  Alternatively, the driver code could detect a falling edge then sample the same input a fixed interval of time later.  A valid signal is assumed to last longer than noise.  Therefor any falling edge interrupt followed by a high sample can assumed to be noise and ignored / not-processed.

Thanks for your reply, I'm using same source of power 12V for both the access control device and Arduino (VIN), may I know if it's really the problem of rejection, could I use this modue to improve: https://www.rfideas.com/products/converters/wiegand-splitter
Is it the problem of me using the 1 output of wiegand for 2 controllers?

I don't think you need to split the signal. And the way you power devices sounds fine. Just make sure you are using an Arduino that is running at 5V (not 3.3V) internally. When researching this question, it was difficult to find Wiegand circuit examples. That is why I left that part of the answer brief. It was frustrating that the data rate or termination resistances are not talked about more. I really think you are picking up noise which causes the missing data. And I really think the code could be improved upon as described in my answer. Do test short cables to verify if noise is a problem.


text:
I2C - Confusion
It's not often I ask a question. This one has me a little stumped though.
Scenario:
I have an 328PB (internal 8mhz), it speaks to a multiplexer on Wire1 (the PB's second IC2 - Minicore lib). The multiplexer speaks to many sensors. That is all working just fine.
I have a logic analyser hooked up to the key points so I can see what is going on.
I have a Nano (external 16mhz) hooked up to Wire (the PB's first I2C), it sends a master request.
The PB is master on Wire1 and slave on Wire.
For some reason the Nano's request on (address 8) is acknowledged by the PB but then the subsequent reads deliver a zero byte and an NACK.
I'm just asking for one byte to troubleshoot. Previous attempts at multiple bytes would deliver the expected bytes but all of them zero.
Strange thing I'm seeing on the logic analyser is that the PB to Multiplexer communication seems to be slower than the Nano to PB (much slower).
I've looked through the libraries and both Wire and Wire1 seem to calculate the speed down to 100khz. I'm using the standard Arduino Wire on the Nano. Given that the initial Address comms gets an ACK. I'm stumped why the subsequent read gets zero and a NACK.
Any help to restore my sanity is much appreciated.
Chances are I'm having a dumb moment. My suspicions are that the clock differences are to blame (but logically they shouldn't be).

Edit:
This is the analyser recording. The dodgy byte is highlighted in Blue.

The communication from the Atmega328pb to the multiplexer and then on to the temperature sensor is working fine. Not all of the multiplexer channels have sensors at the moment hence the NACKs but you can see success on channel 1 to the right of the screenshot. The Nano to Atmega328pb communication starts off good but I'm expecting to see 0X41 in the blue box not 0x00.
This is going to end up being something simple, I'm going to kick myself.
Nano code:
#include <Wire.h>

void setup() {
  Wire.begin();
  Serial.begin(9600);             // start serial for output.
}

void loop() {
  Wire.requestFrom(8, 1);         // request 1 byte from slave device #8
  char c = Wire.read();           // receive a byte as character
  Serial.print("The character: ");
  Serial.println(c);              // print the character
  delay(1000);
}

Atmega328pb requestEvent code:
void requestEvent() {
  Wire.write("A");
}

Edit:
There are other wires for programming etc, but they are disconnected during test.

Edit:
I commented out all the usage of Wire1 in the PB code. And the result was that the Nano got it's byte. I wove the usage of Wire1 back into the code. Right up until it was actually active i.e. communicating with the multiplexer. At that point the Nano started getting a zero byte again.
It seems to be when they are both active. Which suggests it is something in the Wire/Wire1 library by Minicore.
I suspect there is something in the registers but scanning the datasheet for the PB is not yielding any insights. Except for this:
26.1 - Device can Operate as Transmitter or Receiver
There is no elaboration in the document that I can see.
I've tried staggering the communication so that neither is active at the same time. Still the same result.
Still hoping that someone here has the answer ;-)

Can you draw a picture showing the structure? I've not yet grasped what boards are hooked up to what I2C bus and which role each board has on these busses. Also please show us the code in question

chrisl - thanks for your response, I will draw some diagrams. I'll also post the whole code for each MCU. Many thanks.

The 328 is a bare atmega, not an arduino, right? You have to clear the clock divison fuse, otherwise the effective mcu frecuency is 1MHz, not 8MHz.

@SimSon - Thanks for the pointer. I had the fuse set wrong  on the 328PB. Set it to 8Mhz and now the speeds are looking better. Still got my problem though.

We'll, a drawing would help us to understand your setup better.

@SimSon - One drawing coming up.

i've been having a similiar issue, not being able to operate as master on SDA0/SCL0 and as slave on SDA1/SCL1 (and vice versa). Different than in your fix above (calling begin() and end()) does not work for me. If i operate both i2c interfaces as master or both as slave the communications works fine. Could you give some insights how you configured your uC as slave and master on the two interfaces?
Would be very much appreciated!!

@Th3o - (Sorry for the late reply) I ditched the WIRE library for what I was doing. Just could not get a master and slave working on the same MCU with WIRE library. In Amtel studio I had to write a lot more code which took a lot more time but I got very fine control over the interfaces. The MCU is capable of doing it and at blistering speeds!

I've been rebuilding using Atmel Studio. After a long time bringing my C++ skills up to scratch I've managed to get it to work very reliably. I like the greater level of control it brings. I suspect that I was trying to do something in Arduino IDE that cannot be done with the Wire library. I had to effectively rewrite the Atmel Start Slave driver  to get it to behave as I expected it to. I have no other experience of using I2C. So I cannot say whether it is the Atmega328pb that is different or not.
I'm going to stick to Atmel Studio for this project, thanks for all the responses.

I  got it to work ... sort of. I had to move some lines from init to the loop.
I found that by delaying the Wire1 communication (pb to multiplexer) I could get Wire (Nano to pb) to work. Then as soon as the Wire1 communication had finished Wire no longer worked. Interestingly Wire continued to work while Wire1 was also active.
This has lead me to believe the end of the Wire1 communication is leaving something in a conflicted state (the events on Wire were not connected any longer). The blunt answer was to re-initialise on each loop. This seems to work but is not particularly elegant.
void loop()
{
    Wire1.begin();
    getTemperatures();
    Wire1.end();
    Wire.begin(8);                                               // Join i2c bus 0 with address #8
    Wire.onReceive(receiveEvent);                                // Register event.
    Wire.onRequest(requestEvent);                                // Register event.
}

I'm going to continue with this and see if it offers an appropriate degree of reliability. I'm still hunting for the root issue though.


text:
Running loop for a specific time period
I currently have a loop that runs without a time condition:
unsigned long previousMillis = 0;        // will store last time LED was updated

int WET=4;//wet line
int DRY=5;//dry line
int Inhale=1000;//msec
int Exhale=1000;//msec
//int Noflow=3000;//msec

void setup() {
  // put your setup code here, to run once:
  pinMode (WET, OUTPUT);
  pinMode (DRY, OUTPUT);
}

void loop() {
  //inhale
  digitalWrite(WET,LOW);
  digitalWrite(DRY,HIGH);
  delay (Inhale);
  //exhale
  digitalWrite(WET,HIGH);
  digitalWrite(DRY,LOW);
  delay (Exhale);
  //No flow
  //digitalWrite(WET,HIGH);
  //digitalWrite(DRY,HIGH);
  //delay (Noflow);
}

Then i have tried to code a "timer" for each cycle,but i got error:"
exit status 1
Error compiling for board Arduino/Genuino Uno."
Code with timer:
unsigned long previousMillis = 0;        // will store last time LED was updated

int WET = 4; //wet line
int DRY = 5; //dry line
//int Inhale=1000;//msec
//int Exhale=1000;//msec
//int Noflow=1000;//msec
int BPM = 60;
int IE = (((60 * 1000) / BPM) / 2);

void setup() {
  // put your setup code here, to run once:
  pinMode (WET, OUTPUT);
  pinMode (DRY, OUTPUT);
}

void loop() {
  for (int i = 0; i = 20;)
    int BPM = BPM + 10;
#include <elapsedMillis.h>

  elapsedMillis timeElapsed;
  unsigned int interval = 60000; //one minute in ms

  while (timeElapsed < interval) {

    //inhale
    digitalWrite(WET, LOW);
    digitalWrite(DRY, HIGH);
    delay (IE);
    //exhale
    digitalWrite(WET, HIGH);
    digitalWrite(DRY, LOW);
    delay (IE);
    //No flow
    //digitalWrite(WET,HIGH);
    //digitalWrite(DRY,HIGH);
    //delay (2000);
  }
}

Target ouput: to run every cycle of the loop for 1 min.
Any one familiar with this error?
Many thanks for your help

Your for loop won't run as initially i is equal to 0 and you are comparing it with 20 also you didn't have any 3rd variable refreshing condition in your for loop.
You are declaring BPM new every time your loop run which is wrong
Also you are including header file in between your program run which will mess up your code and it is totally wrong practice.

Your code has a number of problems:
Don't put #include statements for header files in the middle of your code. They belong at the top, before any other code. (What is the header file elapsedMillis.h?)
Another thing: Your for loop is a mess. It should read something like: for (int i = 0; i < 20; i++) (That would cause the for loop to run 20 times, with the value of i ranging from 0 to 19.) However, what do you want to happen in your for loop? Without braces after that code, the ONLY line that will execute 20 times is the int BPM = BPM + 10; line (which doesn't make any sense.)
You really shouldn't use time-based while loops inside your main loop function. That defeats the purpose of using timers instead of delay statements. And you should get rid of your calls to delay() and use millis() to manage all your timing. Do a search on "Arduino blink no delay" and study the examples for information on how to restructure your code.


text:
Can an Arduino act as a GATT Server (Bluetooth LE)
I know it's pretty standard to set up an Arduino system as a BLE client, and use something like an app running on a smartphone as the GATT server, which receives the data and does something with it.
In my scenario I have a BLE sensor that is not connected directly to the Arduino system, and I want the Arduino to be able to respond to the sensor output (a wearable accelerometer) and, for example, initiate various lighting sequences depending on the data being received.
I would prefer not to introduce a third component (ie: mobile device as GATT server) into the equation. I'd like for the Arduino to listen to the remote device's services and characteristics, analyze the incoming data and then make some decisions about what LEDs to illuminate based on that analysis.
Can an Arduino run as a GATT server?

You have it precisely backward. The GATT server is the peripheral device. The client is typically a mobile device. That said, I'm looking into this exact thing right now. The Arduino 101's Nordic module is capable of running in Central mode, but I'm unable to find any info on loading the S120 Soft Device. I have read that the Arduino lib doesn't have an API for it though. Theoretically possible, but I haven't figured out how to do it yet.

Does it have to be an Arduino or can it be Arduino IDE compatible? - e.g. something like the Adafruit Feather Bluefruit LE module?

Sure, I think @Simon

@Tom Auger There is an Adafruit Feather 32u4 Bluefruite LE module, you can interact with the BLE part using AT commands, it's pretty basic and can only act as a Server/Peripheral device. It doesn't support notifications or indications, but you can define a custom service with it's own characteristics.

@ Tom Auger The ESP32 modules also support BLE, but I haven't played with that aspect of the module. Looking at the examples available for the ESP32, that can be both a GATT Client and a GATT Server.

@SimonPeverett I'm a big fan of the ESP32, but I haven't played with one recently. This could be a good idea. The project is a gesture-driven bicycle signal. I don't want to have to use a phone as an intermediary.

An ESP32 module (Arduino IDE compatible) can act as both a GATT Client and Server, and there are module examples for each of these, as well as github projects.

I'll be checking that out soon. To make your answer more complete, you might post some example code or at the minimum some links, for the benefit of others that Google this question.

I got this link here that could be helpful - link at the bottom. It is a tutorial that shows you how to control your Arduino with a custom app on an Android. It uses the MIT app creator, an app that lets you create an app. You program it with there IDE in some Java I believe. You can add button to your app so that is sends a message to your Arduino then program the Arduino to do something when it receives that message. For the Arduino side, you could buy an HC-05 Bluetooth module. It is both an transmitter and receiver. It is quite cheap and very popular so there is many libraries out there. I think this is a good module you should get and I recommend to get them in pairs so you can connect them together with 2 Arduinos.
https://www.youtube.com/watch?v=E-1w7dL3Cps

Not applicable to the question asked.  An HC-05 is a classic bluetooth device.  This question is about BLE aka BTLE which is a very different standard, arguably having little more than the word "bluetooth" in common with one another.

authors: Урош Петровић