Selection of presence sensor For one of my university projects I need to detect the presence of a person in the shower. In order to do that what I have in mind is use a proximity sensor. If the target is in a distance range (let's say 20 to 50 cm) It will assume that the person is in the shower when the distance measure is no longer in this range then it will mean that the person left the shower. I need to detect all the time of the person in the shower (meaning when he/she gets in and then out). I have read a lot of info and forums to properly choose the type of sensor. However I still don't have a clear answer. About the Ultrasonic proximity sensors I know that they are cheap and more accurate by it can be affected by Temperature, humidity and some ambient noise, all of them which happen in a shower. The other option an Infrared one gets affected by lightning conditions and the surface of the target. The last option I checked is a PIR sensor I know it senses Temperature of the target, but I don't know if it will be affected by the running hot water and also is more expensive. In general, I don't know how the running hot water will affect the detection of the person in shower. Also,so again I don't know how this will work. Sorry for the huge amount of  questions, I am a little bit confuse with all the factors to have in mind. I am hoping someone out there can help a lost newbie like me and give me a suggestion. Thanks a lot :)

There is no one sensor that is perfect, but some are more reliable than others.

Yes, the temperature and humidity can play an important role in your sensing, and has to be taken into account. That's not to say that things like Ultrasound don't have a place in the scheme of things.

There's one word you need to think about here: Correlation.

If one single sensor isn't completely reliable then add a second that works in a different way. If both of them agree that there is someone in the shower (i.e., the sensors correlate) then the probability that there is actually someone in the shower is considerably higher.

The great thing about a shower is you are working in a defined enclosed space. That makes it much easier and there are plenty of sensors which, when combined with others, would be quite good at reliably sensing the presence of someone in that enclosed space.

Some ideas:

Ultrasound above the person's head

Pros:

Simple to arrange.
Safe.

Cons:

Can be fooled by the water from the shower head.
Steam isn't good for them.

Infra-red distance

Pros:

Accurate
Can be sealed

Cons:

Expensive
Harder to work with
Can be blocked by steam

Horizontal infra-red beam

Pros:

Can be positioned outside the shower glass with a reflector inside
Safe

Cons:

Small sensing area
Can be blocked by steam

Pressure sensor

Pros:

People weigh more than water so is very reliable
Simple to interface

Cons:

Hard to install safely
Needs to be completely waterproof and sealed.
Could be a shock hazard if not waterproof

You notice I haven't mentioned PIR. I'm not a fan of PIR for sensing the presence of humans. They work by detecting moving heat sources. If the person is moving (entering an area, walking round a room, etc) then they get detected. If the person stands still (as is often the case in a shower) it "forgets" they are there.

Of the choices above (and I am sure someone would come up with others) I would probably opt for the infra-red beam. Maybe split it into a V shape to cover more area - that is, the beam enters the side of the shower at an angle, strikes a reflector on the shower wall, and is reflected back at another angle. The detector is then placed away from the emitter. You could also have a second set to give better coverage.

Infra-red distance measuring in/on the ceiling could be used to improve correlation and thus the probability that there is actually someone there.

I'd stay away from pressure sensing unless you can get hold of a proper waterproof pressure sensing mat designed for in-shower use. Don't try and make one yourself, waterproofing isn't an easy task, especially when people stand on it all the time.


Arduino UNO USART problems I need to send 6 bytes value from Arduino UNO to the actuator using serial port in order to make it extends. I have added a button to send the data. For example, 0 20 1 1 0 0. The communication settings are 9600 baud rate, 8 data bits, no parity and 1 stop bit. I have used MAX 232 to build a TTL to RS232 circuit. The actuator does not move. Are there any problems on my program? I am new to create USART code. I think I have some problems on transmit function. I am using the build in USART with c code. Here is my code:

#define BAUD_PRESCALER 0x67
int buttonPin1 = 4;
int buttonState1 = 0;

void setup() {
    // put your setup code here, to run once:
    pinMode(buttonPin1, INPUT_PULLUP);
}

unsigned char data1 = 0x00; // 0
unsigned char data2 = 0x14; // 20
unsigned char data3 = 0x01; // 1
unsigned char data4 = 0x01; // 1
unsigned char data5 = 0x00; // 0
unsigned char data6 = 0x00; // 0

void USART_Init(void) {
    /*Set baud rate */
    UBRR0 = BAUD_PRESCALER;
    UCSR0A = 0x00;
    /*Enable receiver and transmitter */
    UCSR0B = 0x08;
    /* Set frame format: 8data, 1stop bit */
    UCSR0C = 0x06;
}

void USART_Transmit( unsigned char data ) {
    /* Wait for empty transmit buffer */
    while ( !( UCSR0A & (1<<UDRE0)) )
    {
        ;
    }
    /* Put data into buffer, sends the data */
    UDR0 = data;
}

void loop() {
    // put your main code here, to run repeatedly:
    buttonState1 = digitalRead(buttonPin1);
    if (buttonState1 == LOW)
    {
        USART_Init();
        USART_Transmit(data1);
        USART_Transmit(data2);
        USART_Transmit(data3);
        USART_Transmit(data4);
        USART_Transmit(data5);
        USART_Transmit(data6);
    }
}

The first thing I do when I have a transceiver that doesn't work is a loopback test. This rules out a lot of potential issues like the wrong pin being used or MAX 232 not being connected correctly.

Receiving your transmission on a PC using USB to RS232 adapter (if you have one) would also be a helpful test.


Where to declare timer interrupt variables? I have a situation where the majority of the code is residing inside timer interrupt functions.

Setup() does what it has, loop() basically reads ADCs and then all the code is inside timer interrupts.

void loop()
{
  //Read the ADCs
  while((ADC->ADC_ISR & 0x1CC0)!=0x1CC0);   // wait for ADC 0, 1, 8, 9, 10 conversion complete.
  in_ADC0=ADC->ADC_CDR[7];                  // read data from ADC0
  in_ADC1=ADC->ADC_CDR[6];                  // read data from ADC1
  POT0=ADC->ADC_CDR[10];                    // read data from ADC8
  POT1=ADC->ADC_CDR[11];                    // read data from ADC9
  POT2=ADC->ADC_CDR[12];                    // read data from ADC10
}

void TC4_Handler()
{
 if (effect==0)       {/*HERE THE CODE FOR EFFECT 0*/}
  else if (effect==1)  {/*HERE THE CODE FOR EFFECT 1*/}
    else if (effect==2){/*HERE THE CODE FOR EFFECT 2*/}
      else             {/*HERE THE CODE FOR EFFECT 3*/}

  // We need to get the status to clear it and allow the interrupt to fire again
  TC_GetStatus(TC1, 1);
}

The user selects the effect he wants via a button and a hardware interrupt.

What happens when the timer interrupt function ends? Do we go back to loop(), or the timer function is re-run?
In this example, all the vars needed inside each functino of the timer interrupt are declared globally.

I was considering if i can declare variables inside each function in the Timer Interrupt function.
Therefore, we would save space, by not declaring variables that are not run at the moment. And we would only initialize variables for the effect we want.

Is this possible? Because if the effect i have just selected just re-loops, maybe its not wise for vars to get re-initialized  (and their values re-set) each and every time it is looped.

So ultimately, variables taht will be used inside a timer interrupt function, globally or locally?

If they are only used in the interrupt then yes they can be declared in the interrupt. If you want them to retain their value from one call to another they must be declared static, and then they will be the same as global variables as far as memory allocation is concerned.


PWM Input Pins Never Receive a Value from Working Receiver? I have a very simple sketch that's supposed to intercept the signal from an RC receiver and print the pulse duration from that channel.

Sketch

int PwmPin = 9;
unsigned long duration;

void setup() {
  pinMode(PwmPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  duration = pulseIn(PwmPin, HIGH);
  Serial.println(duration);
}

Output

0
0
0
...

My setup is the normal one that would occur without an Arduino, and only the battery is connected through the ESC to provide power to the receiver. The Arduino is connected via USB because I'm just trying to read values.

I have been trying to plug between the receiver's data pin to the Arduino's PWM pin and read the pulses from the rudder channel. (I have previously tested the channel with a servo and know that it works correctly). However, no signal (0) is being printed to the serial monitor. I have difficulty understanding why.

I checked the documentation for pulseIn(), and it seems simple enough. I tested PWM pins D3, D5, D10... none of them works. I don't understand where the problem is at this point. Update: I am now connecting from the receiver's negative pin to one of the Arduino's GNDs.

This is a simplistic scenario, so I don't see what's going wrong (my programming experience is good, but my experience with Arduino is near nil).

The goal of this experiment is to program lights to change according to throttle input, and asymmetric thrust through two motors for a boat. I know that pulseIn isn't the best function to use, but for the moment I just want to do some quick development before getting into the weeds.

Update:
I am attempting to follow this video, except that connecting the Arduino to the receiver didn't work, possibly because the ESC's BEC sends some sort of power signal that arms the receiver. (The receiver's LEDs usually make a visual signal, but they just turn on without a signal when connected through the Arduino).

According to the manual on page 6 and page 8, "receivers have an operational voltage range of 3.5 to 9 volts", with an ideal voltage being above 4.8V (because servos tend to brownout sooner). This should fall within Arduino range at 5V.

What misled me is the pin numbers. I was referencing this diagram:

I thought that all the pins were numbered sequentially, so that pinMode(9, ...) would set D6 (09 in the diagram). However, this sets D9. Connecting to the correct pin works fine.


Do the libraries of the Arduino Uno work with the Arduino Mega? I did a project with the Arduino Due and the libraries for the VS1053 MP3 Shield were not compatable with the Due. Are the libraries that work with the Uno compatable with the Arduino Mega?

Are the libraries that work with the Uno compatable with the Arduino Mega?

Sometimes.

They have a higher chance of being compatible, due to them both using the same AVR core, but since internal peripherals differ slightly there is a chance that, depending on what the library does, it won't work right.

You just have to try it and see.


What could make an LCD stop working permanently after being connected for 5 seconds to Arduino? I was using a 20x4 LCD connected to Arduino Uno via a common I2C adapter board. Everything was working perfectly, including the LCD. I had it running like this for a couple of days without any problems.

My next step was to connect the LCD to a Nano instead in order to make the package smaller. The exact same code from the Uno was uploaded to the Nano, and I connected the wires in the exact same way. The major difference here was that I soldered the wires onto the Nano, because I didn't want to use headers. I did a continuity test for shorts and the connections seemed to be fine. There are only 4 wires between the Arduino and LCD adapter board: 5v, ground, SDA and SCL.

The Nano powers up fine, and the LCD powers up fine, but immediately the LCD shows the following:

That had never happened when I had the LCD connected to the UNO.

After that, the LCD stops working completely, even when I move it back to the UNO. It just constantly displays those 2 lines. (Adjusting the contrast makes the boxes appear or disappear).

After the first LCD seemed permanently broken like that, I tested it on a 2nd brand-new LCD. First I connected it to the same Uno with the same code, and everything was working perfectly. I re-uploaded that same code again to the Nano, just to make sure everything was in sync. Then upon connecting the 2nd LCD to the Nano, immediately it displayed those 2 lines. I disconnected it right away (within 5 seconds), and tried to put it back on the Uno, but still the display is corrupted. I've tried other sketches, but both of these displays seem to be broken and never display anything except for those 2 lines.

Even if I just connect 5v and ground to the LCD, no matter from what source, it just constantly displays those 2 lines.

Any ideas as to what could "break" an LCD so quickly like that, and if it's possible fix it?

Edit:
As per Gerben's suggestion, I removed the I2C backpack and hooked the LCD up directly. This was the 2nd one I had broken, the one where I'm more certain of its entire (short) history. I ended up with the exact same result. Adjusting the pot only makes the boxes appear or disappear. I tried skipping the Arduino completely and giving it 5v power from an adapter, and it still has the same result.

It's unlikely that you have killed the unit as this is pretty hard to do from the data interface and your picture is typical for an LCD that has not gone through the initialization sequence.  A dead LCD driver will usually display nothing and what your picture shows is that the LCD controller itself is operating.  If anything is dead, I would suspect the I2C interface board as this would yield the same result you are seeing.  It may also be that the timing of the I2C interface is right on the edge which may explain why a long cable'd setup is working.

Note that if the initialization is not done, no other commands will work.  Note also that the initialization timing and sequence of events is ABSOLUTELY CRITICAL and missing any single step or time requirement will give the result you are showing.

Starting at page 10 of this instructional PDF is my favorite and the basis of my driver that I have been using since the 80's.

The driver I use works on every display I have ever hooked to it, regardless of changes in the particular project's processor clock speed because I paid strict attention to the worst case timing requirements.  If the timing of the I2C interface violates one LCD it may not violate another, i.e. one display can tolerate bad timing while another can't.  There are also issues if the LCD driver uses the busy flag or not:  Blind data transmission without reading the LCD's busy state will work if the LCD is fast enough and the driver is slow enough, otherwise 'No bueno!' plus the interface is not going to operate at its maximum speed.  When using the busy flag (Bit 7 of the interface) there is solid handshaking which confirms (Instead of "Trusts") that the LCD is ready for the next cycle and allows operation right up to the limit of performance.

What I would suggest is that you put the interface on a logic analyzer and verify that the timing is not being violated.

Timing tolerances and variation between parts is like lug nuts on a car... If you car has 5 lug nuts per wheel, it will probably work with 3 or even 2 but NOT UNDER ALL CONDITIONS.  SOME LCDs will be happy with bad timing but ALL LCDs NEVER will be.


How fast is a SD page read from a file? For a project I would like to do, I asked a question about whether to use SD or EEPROM (see Question

I checked how much memory I would need without any restrictions which is like 2 MB (or more) so a SD card seems the best solution.

However, I'm a bit worried about the speed. In one of the answer comments is mentioned that 20 ms is an eternity for a microcontroller. However, I might need to do the following within 20 ms:

Parse a MIDI event (CPU power only, does not take long)
Read one or two SD pages (1/2 times block of 512 bytes)
Change/add/remove the MIDI event (CPU power only, negligible)
Send out MIDI data (barely no time, mostly hardware)

In worst case I can get like 10-20 MIDI events I need to handle within 20 ms. Especially for step 2 I don't know how much time it will.
My plan is to create a big file with a PC program to be stored on the SD card. Than I can let the Arduino read pages of 512 bytes from predefined places (with seek in a file).

I'm intending to keep the file open at all times and use seeks to go to the right place and read 512 bytes every time (assuming it doesn't matter to read 1 or 512 bytes since the page size is 512 bytes anyway).

So my question: is 20 ms enough to read like 50 pages of 512 bytes from an SD card which are located on different (but known) file offsets within a 2+ MB file?

(btw, I want to try first on an Uno, but probably I will later go to a Mega (or add more SRAM to store temporary data).

So my question: is 20 ms enough to read like 50 pages of 512 bytes from an SD card which are located on different (but known) file offsets within a 2+ MB file?

Let us do the numbers: 50 * 512 = 25 Kbyte in 20 ms is 1.25 Mbyte/s. As the max speed for SPI is 1 Mbyte/s (on Arduino AVR, 16 MHz) we do not have to go any further. The answer is: No.

Cheers!


Choosing a proper power source for for basic RC car with 4 motors Help me to choose a power source for the below project:

4x DC Motors (3V~6V DC each with ~170mA),
1x Micro Servo Motor (4.8V~6V),
1x Ultrasonic sensor
1x Bluetooth sensor

It is basically an RC car. The project runs on Arduino UNO and it uses Motor Shield (1.2) to power up those five motors. The motor shield does support external power supply. Shall I go for that, or Arduino can power up the entire system altogether?

2S LiPo with 5V UBEC is what you want.  Hit your favourite RC model seller for those.  I use HobbyKing (as the links show).

The capacity choice of the LiPo depends on

How much power your motors etc need, and
How long you want it to run for

You could also go for 3S or 4S to get more power if your chosen UBEC supports the voltage.


Arduino crashed my computer when I plug in the USB cable I have a 2008 Mac that hardly ever crashes. But from time to time (not always) it crashes (the whole computer shuts down as if the power has been cut off) when I plug in an Arduino via USB.

What could cause this?

I've done some testing and the constant in when this occurs seems to be a cheap PIR sensor from eBay. It works some of the time.

Should I get another sensor? Or is there something about PIR sensors that makes them prone to this? It has a lot of caps... Is there another kind of motion sensor?

It could possibly be that there is a fault that is causing a short circuit. This short circuit could be in the board itself or the USB cable that connects the Arduino. The USB port on the Mac should have protection to protect against a short circuit. Your comments have indicated that you have tested for a short and found none - but this is helpful for others that are looking for a solution.

In your comments you mention that you solved this by changing the positive rail of your potentiometer from 3.3V rail to the 5V rail.


Update class attribute with attachInterrupt I want to refactor this code

/*
YF‐ S201 Water Flow Sensor
Water Flow Sensor output processed to read in litres/hour
Adaptation Courtesy: www.hobbytronics.co.uk
*/
volatile int flow_frequency; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor = 2; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;
void flow () // Interrupt function
{
   flow_frequency++;
}
void setup()
{
   pinMode(flowsensor, INPUT);
   digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
   Serial.begin(9600);
   attachInterrupt(0, flow, RISING); // Setup Interrupt
   sei(); // Enable interrupts
   currentTime = millis();
   cloopTime = currentTime;
}
void loop ()
{
   currentTime = millis();
   // Every second, calculate and print litres/hour
   if(currentTime >= (cloopTime + 1000))
   {
      cloopTime = currentTime; // Updates cloopTime
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency = 0; // Reset Counter
      Serial.print(l_hour, DEC); // Print litres/hour
      Serial.println(" L/hour");
   }
}

Originally found here: source

to an Class based solution:

/*
YF‐ S201 Water Flow Sensor
Water Flow Sensor output processed to read in litres/hour
Adaptation Courtesy: www.hobbytronics.co.uk
*/
class FlowSensor {
  volatile int flow_frequency;
  unsigned int l_hour;
  unsigned char pin;
  unsigned long currentTime;
  unsigned long cloopTime;
  public:
    void flow () {
      flow_frequency++;
    };
    void setup() {
      pinMode(pin, INPUT);
      digitalWrite(pin, HIGH); // Optional Internal Pull-Up
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(pin), flow, RISING); // Setup Interrupt
      sei(); // Enable interrupts
      currentTime = millis();
      cloopTime = currentTime;
    }
    void loop() {
      currentTime = millis();
      // Every second, calculate and print litres/hour
      if(currentTime >= (cloopTime + 1000))
      {
        cloopTime = currentTime; // Updates cloopTime
        // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
        l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
        flow_frequency = 0; // Reset Counter
        Serial.print(l_hour, DEC); // Print litres/hour
        Serial.println(" L/hour");
      }
    }
    FlowSensor() {
      setup();
    };
};
FlowSensor flowsensor_intake;
void setup()
{
   flowsensor_intake = FlowSensor();
}
void loop ()
{
   flowsensor_intake.loop();
}

But i get the following error in the Arduino IDE:

  /tmp/087639235/water_flow/water_flow.ino: In static member function
  'static void FlowSensor::flow()':

  /tmp/087639235/water_flow/water_flow.ino:17:19: error: cannot call
  member function 'void FlowSensor::update_flow()' without object

  update_flow()

  ^

  exit status 1

I understand that flow is not a static function and that i cannot make it static because it is midifying a non static member.

But i cannot think of an alternate solution to this Problem. My goal is to monitor multiple flow sensors by creating an object in the setup() function, and updating them with every loop() call.

You've run into a classic trap.  There are a couple of things to think about.  First off, if this is a singleton class (as in there will only ever be one instance) then you can just have a non-member function that you use with attachInterrupt and have that function just call the member function you want.  Normally what I would do would be to create the instance in the .cpp and put an extern declaration for it in the header so that it can just be used without creating it.  Look at how Serial works for an example.  Then put all the configuration type stuff into a begin or init method to call from setup.  That way the non-member function for the interrupt can be part of the header and the user never has to see or mess with it and it feels like it's part of the class.

If this is not a singleton class and you might one day have several instances of this in one program then you have to start asking yourself how will the interrupt know which instance to act upon.


Linear acceleration from MPU 6050 When reading the MPU 6050 has accelerometer and gyro, I assumed it was linear acceleration, but now I second guess that.  From this video https://www.youtube.com/watch?v=qmd6CVrlHOM it seems like they are using acceleration and gyro to make one rotation direction.  I need to know what direction the mpu is moving, not just a rotational value.  Is there a way to extract this information?

The MPU6050 has an accelerometer and a rate gyro (which tells you how fast it is rotating). The accelerometer will tell you which direction is down and in a motionless situation, that is all the information you have.

You'll probably want something like the MPU9150, it has a compass, which will give you the directional information you're asking for.


I2C Master-Slave Arduino system to control array of steppers trying to make a system where one master Arduino makes moving 9 steppers 28BYJ-48 by 3 stepper on each slave arduino.
While all the parts on their way to me, wonder to check with professionals.
Maybe I've missed something?
Any suggestions and tips are welcome.
Thank you.

I don't quite understand the problem. A
 arduino mega would have no problem controlling 9 of these steppers alone. If you are asking about i2c protocol please be more specific about what you need help with.


How to know my Arduino core version and its location on my Ubuntu laptop? Bakground:

When compiling a demo project about e-paper, I got this problem

./GxEPD/src/GxIO/GxIO_SPI/GxIO_SPI.h:39:5: error: ‘SPISettings’ does not name a type
     SPISettings _spi_settings;
     ^

which on the Internet, people often say your Arduino core is not up-to-date and the one installed from

sudo apt install arduino-core

is ancient. And you have to install the latest version.

Regardless of whether this solves my original problem or not, I want to have the latest Arduino core on my  laptop.
From arduino.cc I grabbed a zipped file and ran ./install.sh which did not provide enough results to know what it exactly did. Now, I am concerned that I have multiple installation in several places.

Main question:

When I run my make file and it is processed by arduino-mk, which version of arduino-core is it referred to and where is it located?

I am looking for a full proof method. I do not want to open somewhere from / directory accidentally. Because maybe this is not the arduino-core in use.

The ancient version installed by apt lives in
/usr/share/arduino/hardware/arduino/cores/arduino.

If you download and unpack a recent version, it will stay wherever you
left it. For example, I have an Arduino core in
/home/edgar/Downloads/arduino-1.8.10/hardware/arduino/avr/cores/arduino.
The installation script doesn't really install those files. It does
install some icons and desktop shortcuts, but neither the core nor the
Arduino IDE. Instead, it assumes the downloaded package will stay
wherever it was when you ran the script.

If you want a somewhat cleaner installation, I suggest you move the
package to /opt, recursively chown it to root, and run the setup script
there. The core will then be in
/opt/arduino-<version>/hardware/arduino/avr/cores/arduino.


Melzi 2.0 Board Firmware Upload problem I'm trying to flash the repetier Firmware to my Prusa i3 3D Printer, which uses Melzi 2.0 board. I uploaded it successfully 2 days ago with same settings  but now is failing always.

@avrdude -p m1284p -b57600 -c arduino -P COM%x% -e -U flash:w:%filename%.hex
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.02s
avrdude: Device signature = 0x1e9705 (probably m1284p)
avrdude: erasing chip
avrdude: reading input file "newa.hex"
avrdude: input file newa.hex auto detected as Intel Hex
avrdude: writing flash (114266 bytes):
Writing |                                                    | 0% 0.00s
avrdude: stk500_paged_write(): (a) protocol error, expect=0x14, resp=0x64
avrdude: stk500_recv(): programmer is not responding

How do I solve this problem?

The Electronics Stackexchange question avrdude error - stk500_paged_write() protocol error has answers that suggest three different tactics for protocol errors:

• Upgrade the Arduino IDE from 1.00 to 1.05, or install "AVR-GCC Toolchain" via Homebrew;
• Disconnect everything from TX / RX (Arduino digital pins 0 and 1);
• Use shorter or different USB cables, hooked to a USB port on computer instead of on a hub

I've seen dozens of answers here on arduino.stackexchange with such suggestions, as well as webpages elsewhere with ideas like those in an answer to AVRDUDE Error (Arduino Leonardo).

You could go through this list of programmer-is-not-responding arduino.stackexchange questions, and report back on what works and what doesn't:

• "avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program,
• How do I resolve "avrdude: stk500_recv(): programmer is not responding"?,
• avrdude: stk500_recv(): programmer is not responding after serial,
• avrdude: stk500_recv(): programmer is not responding + avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x47,
• avrdude: stk500_rcv :programmer is not responding,
• Arduino Nano Update failure - avrdude: stk500_recv(): programmer is not responding,
• avrdude: stk500_getsync(): not in sync: resp=0x00,
• Arduino Uno cannot upload any sketch: avrdude: stk500_recv(): programmer is not responding,
• "avrdude: stk500_recv(): programmer is not responding" when uploading sketch,
• Arduino not working / not uploading [duplicate],
• Problems uploading sketch to Arduino Due,
• FTDI stdk 500k not responding,
• Arduino Prototype on Breadboard: "avrdude: stk500_recv(): programmer is not responding",
• Arduino Nano - programmer is not responding,
• How do I resolve "avrdude: stk500_recv(): programmer is not responding"?,
• Arduino not in sync unique error,
• Arduino nano stopped working,
• Not in sync: resp=0x00,
• How to troubleshoot the Arduino Mini and Arduino usb2serial?,
• Atmega328P-PU: Programmer is not responding,

Note, click the “see more linked questions…” link in the sidebar to get a nice webpage with the above list and the opening lines of each question.


Can I have Arduino to read and write data using SDcard? I'm doing a project and I have a simple doubt. I want a code so that whenever a admin rfid card is read it takes the next rfid card and stores it to a database like excell sheet or any other way of storing data on the sd card. And whenever a normal card is shown it checks the database or excell sheet or anything else to see if the the rfid code exists if it does open the door something like that .
I want to do all the reading and writing using a sd card and storing rfid is limited to one or two ways give all the possible methods you can think of and connecting to internet and using any internet based database is also an option but I do not know how to create a web based database and write or read data from it

Yes, you can. You need to find an Arduino shield (or other board) that lets you attach SD cards to your board, and use that. (A quick Google search on "arduino SD card shield" reveals this SD card reader shield, for example. There are also "breakout boards" that are not shields. You'd have to attach wires to those rather than plugging a shield into your Arduino's headers.) This one, also from Adafruit, apparently has a built-in 5V-3V regulator, as well as voltage level shifters, so it should work well.
The specifics of how you read/write to the SD card will depend on the shield you buy.
Note that Arduinos include a certain amount of flash memory that is available for your program to read and write. If your storage requirements are modest, and you aren't writing data very frequently, that flash memory might work also. (Note that the built-in flash memory has a pretty low lifespan. If you write to it to many times, it will eventually fail. I forget the number of times, but you could look it up on Arduino's site.


Reset fuses on atmega328p using Arduino I bought a few atmega328p chips but unfortunately they came with the Arduino bootloader and they are set to use the external clock. I want to reset their fuses using avrdude so I can use the internal 8mhz clock but it's not working. How can I (if even possible) reset their fuses using the Arduino? I have no other programmer and here are the arguments I use for avrdude as well as the response:

avrdude -C .\avrdude.conf -p m328p -c arduino -P \\.\COM12 -b 115200 -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m

Response:

avrdude.exe: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude.exe: Device signature = 0x1e950f
avrdude.exe: reading input file "0x62"
avrdude.exe: writing lfuse (1 bytes):

Writing |  ***failed;
################################################## | 100% 0.06s

avrdude.exe: 1 bytes of lfuse written
avrdude.exe: verifying lfuse memory against 0x62:
avrdude.exe: load data lfuse data from input file 0x62:
avrdude.exe: input file 0x62 contains 1 bytes
avrdude.exe: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.00s

avrdude.exe: verifying ...
avrdude.exe: verification error, first mismatch at byte 0x0000
             0x62 != 0x00
avrdude.exe: verification error; content mismatch

avrdude.exe: safemode: lfuse changed! Was 62, and is now 0
Would you like this fuse to be changed back? [y/n]

You cannot set the fuses using the Arduino bootloader, since they cannot be self-programmed. You must use either serial or parallel programming via ArduinoISP or an external programmer to set them. Since the chip is configured to use an external crystal you must either connect a crystal up to the chip appropriately (see sections 9.3 or 9.4 of the datasheet) or use parallel programming. You will then be able to use the lfuse, hfuse, and efuse memory types to read and write the fuse bytes.


LCD Weather Station - "Press To Start" Function I've been trying to make a weather station using a I2C LCD Display and a DHT11, I know, the DHT11 is a bit low res and all that, but it came with the kit I ordered, so it's okay.

However, I'm trying to have it display like a "title" screen, and after a 2sec delay it should proceed to say "Welcome!" and "Press to Start", and wait there until the button is pressed, and after the button is pressed it should proceed to show the temp and humidity.

However it doesn't seem to mind any of the functions added, unless I set the "if" statement at the beginning of the loop to "LOW", then for some reason, the program stops at "Welcome!" and "press to start".
If I change the "if" statement condition to "HIGH" it just proceeds straight through to the temp and humidity.

#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

//CONSTANTS
#define DHTPIN 3
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

LiquidCrystal_I2C lcd(0x27, 16, 2);

//Variables
int chk;
float hum;  //Stores humidity value
float temp; //Stores temperature value

const int buttonPin = 6;

int buttonState = 1;

void setup()
{
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
  dht.begin();
  lcd.begin();
  lcd.clear();
  delay(1000);
  lcd.setCursor(0, 0);
  lcd.print("WeatherMate");
  lcd.setCursor(0, 1);
  delay(250);
  lcd.print("Press 'Start'");
  delay(1000);;
  if (buttonState = 0)
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Welcome!");
    lcd.setCursor(0, 1);
    lcd.print("Press Start");
  }
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState = 1) {
  delay(500);

  hum = dht.readHumidity();
  temp = dht.readTemperature();
  if (temp <= 25) {
    digitalWrite(13, LOW);
    digitalWrite(12, HIGH);
  }
  if (temp >= 25) {
    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
  }
  Serial.print("Humidity: ");
  Serial.print(hum);
  Serial.print(" %, Temp: ");
  Serial.print(temp);
  Serial.println(" Celsius");

  lcd.setCursor(0,0);
  lcd.print("Temp: ");
  lcd.print(temp);
  lcd.print(" ");
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print("Hum:  ");
  lcd.print(hum);
  lcd.print(" %");

  delay(500); //Delay 2 sec.

}
}

Anyone? I'm stuck on this one.

As Majenko points out in his comment, a couple of your if statements have the assignment operator (ie. =) whereas you are actually after the comparison operator (ie. ==).

if (buttonState = 0)

should be:

if (buttonState == 0)

And

if (buttonState = 1) {

should be:

if (buttonState == 1) {

When an assignment is used, the if statement will execute if the value being assigned is a non-zero. For more information see Using assignment as a condition expression? over on Stack Overflow.


Connecting Seeeduino XIAO 3.3 V out to dual H-bridge driver module (L298N) with TTL compatible inputs The H-bridge module uses TTL compatible logic, but the chip allows these values (based on the L298N data sheet):

Symbol
Parameter
Min.
Max.

ViL
Input Low Voltage (pin 5, 7, 10, and 12)
-0.3 V
1.5 V

ViH
Input High Voltage (pin 5, 7, 10, and 12)
2.3 V
VSS

Am I correct to assume that I do not need to step-up the logic signal (from 3.3 V to 5 V) for this to work, but can I connect straight to the input?
Schematic in mind:

Am I correct to assume that I do not need to step-up the logic signal (from 3.3V to 5V) for this to work, but can connect straight to the input?

You are correct. The input has to be above 2.3V to register as HIGH and below 1.5V to register as LOW. You have 3.3V for HIGH and near 0V for LOW, which fits those criteria perfectly.


ESP8266-01 WifiScan not working I have a ESP8266-01 and am trying to get it to work. I am using the example WiFiScan code shown below.

#include "ESP8266WiFi.h"

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

  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0) {
    Serial.println("no networks found");
  } else {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}

I have a voltage regulator producing 3.3 V connected to CH_PD and the Arduino powers the ESP's VCC via the 3.3 V pin. TX is connected to TX and RX is connected to RX. GPIO0 is connected to ground. I can upload, but it cannot find any networks. It always states no networks found. Now I'm not even sure how to proceed... Any help would be appreciated.

You should provide a good power source for the VCC. One that can supply 170 mA for WiFi operations of esp8266. You should use the power regulator to supply 3.3 V to VCC and there is no reason to use other power source for the CH_PD pin. CH_PD pin is "enable" pin, it doesn't need a strong power supply.
IO 0 should be connected to ground only for upload, not for normal operation.


Arduino + UltraSensor - Serial Monitor outputs garbage I am trying to connect an HC-SR04 to an Arduino Uno. For some reason when I run this code on the serial monitor it outputs wingdings in a straight line.

ýòøÿüÿøÿüòý÷ÿ÷ýÿÿúýÿýúÿòý÷ûòûòû÷ýÿøÿøÿÿ÷øÿüÿýÿþòøòÿÿøûüÿøÿÿòÿ÷ûòûòý÷ûòûòûöû÷ÿûû÷øÿÿ÷øÿüÿýÿüÿûöþÿý÷ûòûòûòûöûûûûûò

No breaks. Sometimes when I hit "Tools/Fix Encoding and Reload" it outputs

Ping: 0 cm
Ping: 0 cm
Ping: 0 cm

followed by more wingdings.

I've looked up some similar problems and it was usually fixed by changing baud to a lower value, 9600. I've done this and I still have problems.

Would you be able to help me out? I'd very much appreciate it.

const int trigpin = 9;
const int echopin = 10;
long duration;
int distance;

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

void loop() {
  pinMode(trigpin, OUTPUT);
  pinMode(echopin, INPUT);
  digitalWrite(trigpin,LOW);
  delayMicroseconds(2);
  digitalWrite(trigpin, HIGH);
  delayMicroseconds(5);
  digitalWrite(trigpin,LOW);
  duration = pulseIn(echopin,HIGH);
  distance = duration *0.034/2;
  Serial.print("Distance: ");
  Serial.println(distance);
}

Updated Solution

After testing out Joel's code to check the sensor was in order, I found some new sample code which worked to display the distance in inches of a HC SR04 sensor.

  // set up variables

  int trigpin = 13; // Trig Pin is connected to Arduino pin 13
  int echopin = 11; // Echo Pin is connected to Arduino pin 11

 // now we need variables which we will be measuring

 float pingtime; // Time for ping to travel to target and return
 float targetdistance; // Distance from sensor to target
 float speedofsound = 776.5; // speed of sound in miles per hour at 77 F

void setup() {
Serial.begin(9600); // Turn on serial port
pinMode(trigpin, OUTPUT); // Sensor trig pin is output
pinMode(echopin, INPUT); // input is reading from echopin

 }

void loop() {
digitalWrite(trigpin, LOW);// set trigger pin low
delayMicroseconds(2000); // pause to let signal settle
digitalWrite(trigpin, HIGH); // set trigger pin high
delayMicroseconds(15); // pause in high state, make sure sensor reads
digitalWrite(trigpin, LOW); // bring trigpin back low

   pingtime = pulseIn(echopin, HIGH);

// sensor will be sending HIGH pulse, measure pingtime at echopin
// ping time is in microseconds

  pingtime = pingtime / 1000000.;

// converts pingtime to seconds because speed of sound is miles per hour

  pingtime = pingtime / 3600.;
  // converts pingtime to hours
  // add a period to make float to avoid int mistakes

  targetdistance = speedofsound * pingtime;
  // calculates distance in miles traveled by ping

  targetdistance = targetdistance / 2;
  // accounts for roundtrip of ping to target

  targetdistance = targetdistance * 63360.;
  // convert target distance to inches
  // 63360 inches in a mile

Serial.print("The distance to the target is:");
Serial.print(targetdistance);
Serial.println("inches");
delay(1000);

 }

Check your serial monitor baud rate. This is definitely caused by your serial monitor being set to a different baud rate than the 9600 you specified in the program.

If it had anything to do with the sensor than this line would be printed properly Serial.print("Distance: ");

Once you change the serial monitor baud rate then try running this program, to verify that it is set properly:

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

void loop() {
  Serial.println("Hi There!");
}

If that prints "Hi There!" then the program your serial monitor is set up properly.


Failed HC-05 Bluetooth sketch upload - (port and board correct) I'm running this project with HC-05 https://create.arduino.cc/projecthub/millerman4487/view-serial-monitor-over-bluetooth-fbb0e5 and I am getting connection error. I have ensured my port selected and board is accurate but no such luck. The Arduino uno is powered by 3.7v batt (output ~8v with reg) so it is simply just a battery connection and BT module, but when uploading the sketch, it fails. I am relatively new to arduino, and am not sure where to begin this debug.
I am using PC windows, and using a BT dongle receiver for connection (maybe this affects port comm?)
Thanks in advance
Here us the error message
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"

Sketch uses 1954 bytes (6%) of program storage space. Maximum is 32256 bytes.

Global variables use 250 bytes (12%) of dynamic memory, leaving 1798 bytes for local variables.
Maximum is 2048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for
suggestions.

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x04

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x04

when uploading the code, did you ensure disconnecting the Rx, Tx pins from the Arduino? Coz this is a similar error you get when you upload code with your comm pins connected. Try uploading the code with no wires connected.


Best Header for Arduino Nano I would like to be able to create permanent projects with my arduino Nano but be able to remove the nano in order to use it in other projects. The arduino Nano has 30 pins so I would be looking for some kind of female 30 pin header. Most of the headers that I found like that are too narrow because they are for IC's. Any ideas?

The Nano boards that I have used all have pins on 0.1" (2.54mm) spacing.  There are single-row female connectors that are designed to accept 0.025" square pins.  One example is Samtec 32 position female header but there are many others.

Note that these female headers are available to accept either 0.018" round or 0.025" square pins.  My great preference is for the 0.018" round pins but those are less common in hobby circles.

The really huge advantage of the smaller round pins is that you can safely insert them into solderless breadboards without damaging the contacts in the breadboard.  But you would want to standardize on one style or the other.


Cant compile for Uno I'm getting this error while compiling the code for my mp3 shield.

    C:\Users\Kami\Documents\Arduino\libraries\MP3Shield_Library_Demo\SFEMP3Shield.cpp:9:9: error: 'prog_uint16_t' does not name a type

 PROGMEM prog_uint16_t bitrate_table[14][6] = { {0,0,0,0,0,0},

         ^

C:\Users\Kami\Documents\Arduino\libraries\MP3Shield_Library_Demo\SFEMP3Shield.cpp: In member function 'uint8_t SFEMP3Shield::begin()':

C:\Users\Kami\Documents\Arduino\libraries\MP3Shield_Library_Demo\SFEMP3Shield.cpp:43:8: error: 'volume' was not declared in this scope

   if (!volume.init(&card)) return 2; //Serial.println("Error: Volume ini");

        ^

C:\Users\Kami\Documents\Arduino\libraries\MP3Shield_Library_Demo\SFEMP3Shield.cpp:45:23: error: 'volume' was not declared in this scope

   if (!root.openRoot(&volume)) return 3; //Serial.println("Error: Opening root"); //Open the root directory in the volume.

                       ^

exit status 1
Error compiling for board Arduino/Genuino Uno.

Googling some of those terms (especially "prog_uint16_t bitrate_table"), it looks like you may have an old version of the library, since that code was removed back in 2012.

This appears to be the latest version: https://github.com/madsci1016/Sparkfun-MP3-Player-Shield-Arduino-Library

I would start by grabbing that (using the "Download ZIP" button if you don't use git/GitHub) and trying the example from there. The examples are within the SFEMP3Shield folder.


Unable to upload sketch on Mac OSX El Capitan I recently dusted off an old Arduino Duemilanove to play with. I can connect it to my Mac laptop with the same USB cable I used previously and I'm able to monitor the serial port and see the output from the last sketch I uploaded (five years ago). Everything is unplugged from the board.

When I try to upload a new sketch, the Arduino IDE gets stuck on Uploading... indefinitely:

Using Port                    : /dev/cu.usbserial-A800eGZI
Using Programmer              : arduino
Overriding Baud Rate          : 19200

The board itself has the green PWR LED and amber TX LED on solid once the currently loaded sketch starts running. Initiating an upload causes the amber L LED to blink three times, then the RX LED blinks twice, and finally the TX LED on solid.

Here is the exact board: https://www.sparkfun.com/products/retired/666

My research into this issue produced many suggestions that have not resolved the problem...

I disabled the built-in FTDI driver:

sudo kextunload -b com.apple.driver.AppleUSBFTDI

And made sure the FTDI driver from ftdichip.com was loaded:

sudo kextload /Library/Extensions/FTDIUSBSerialDriver.kext

I tried csrutil enable --without kext against my better judgement and saw no change.

I also tried a completely separate machine -- my PC running Windows 10 -- and the upload hung there too.

I have tried timing the upload to coincide with a board reset, hoping to sneak my upload in before the current sketch starts running. I did this a lot and got no satisfaction.

I haven't given up yet; there are too many signs of life to think that it's unrecoverable. I'm looking for more suggestions on how to troubleshoot.

I have already ordered another Arduino -- hopefully I can use it to burn the bootloader on the Duemilanove.

Possibly the boot-loader baud rate in the IDE's boards.txt file is wrong. I have older (less than 6 years) '328p chips whose boot-loaders expect 57600 baud, but the boards.txt file in more recent Arduino IDE's try to talk to them at 115200 baud. I've had to duplicate the Arduino Uno entry in boards.txt and make one that specifies 57600 baud, to use these chips.


Serial.parseInt() takes longer time than desired My whole code for master. Please head to void read() where I've used parseInt()

#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>

RF24 radio(7, 8); //Set up nRF24L01 on CE pin and CSN pin respectively

const uint64_t pipe = 0x0ABCDEF; //Address for communication between master and slave
uint16_t data[7];
const uint16_t buffer_size = sizeof(data); //Size of the payload for the RF
int i, flag;
int tx_counter = 0;

void read();
void setup() {

  Serial.begin(115200);

  radio.begin();
  radio.setChannel(2);
  radio.setDataRate(RF24_1MBPS);
  radio.setPALevel(RF24_PA_MIN);
  //radio.powerUp();
  radio.openWritingPipe(pipe);
  //radio.setPayloadSize(7);
  radio.stopListening();

  //Default values range from 100 to 700
  for (i = 0; i < 7; i++) {
    data[i] = 100 + (100 * i);
  }
  flag = 0;
  Serial.println("Enter 7 values");
}

void loop() {

  read();

  if (flag) {
    bool tx_ok = radio.write(data, buffer_size);
    tx_counter++;
    Serial.print("Transmission count:\t");
    Serial.println(tx_counter);
    print();
    if (tx_ok) {
      Serial.println("Transmitted Successfully");
      Serial.println("\nEnter Next set of 7 numbers");
    }
    else Serial.println("Transmission failed");

  }
}

void print() {
  for (i = 0; i < 7; i++) {
    Serial.println(data[i]);
  }
  flag = 0;
}

void read() {
  while (Serial.available()) {
    for (i = 0; i < 7; i++) {
      data[i] = Serial.parseInt();
    }
    flag = 1;
  }
}

My problem is that Serial.parseInt() takes some time. The code prints out the values to the serial monitor after sometime. I have timed it and it appears to be around 7 seconds. The arduino page on the function says default timeout is 1 sec. So I think 7 elements in the array takes 1 sec each. If I use Serial.setTimeout(2000), the same thing takes 14 seconds.

This has got to have a simpler way. I want it to behave like when we use Serial.read. Please help me on this.

this is what you want:

void read() {
  for (i = 0; i < 7; i++) {
    while (!Serial.available()); // wait forever for some input
    data[i] = Serial.parseInt();
  }
  flag = 1;
}


Atmega328p clock and safe operation zone im not used to write in english but i hope you guys can understand. I have some doubts about using the arduino pro mini 3v3@8Mhz

I know its possible to change the clock to 1 MHz with the fuses easily by setting CKDIV8 to '0'. But i dont understand if its possible to divide the internal 8 MHz clock to intermediate values like 4 MHz and 2 MHz.
I know i can divide the clock with program running. The problem is i would like to run the arduino with a voltage less than 2,4V and arduino will start at 8MHz(out of safe operation area) for later change the clock to 4MHz(inside of safe operation area). Is there another way by software to always be in the safe zone ?

Just let CKDIV8 set (it just sets system clock prescaler to /8). And you can set different system clock prescaler later.

For changing system clock prescaler you need:

#include <avr/power.h>

And:

clock_prescale_set(clock_div_2); // possible values are clock_div_1 ... clock_div_256

Just don't forget that millis, delays and basically everything based on F_CPU might be slower/faster when prescaler gets changed.


Can you pass params to an arduino sketch? I was wondering if there is a way to pass parameters to an arduino sketch at the upload step.

Edit: The reason this would be helpful is because I have a bunch of esp8266 units that need to have details about their specific location but changing variables around per upload feels tedious.

If this is not possible the other solution that I am probably going to try is to have a sketch to just flash these details to eeprom and then read it from there whenever it is needed. Also storing them in eeprom feels a bit better than as literals in these sketches.

Every ESP8266 has a unique MAC address. You could that information to distinguish between the different units.

Something like if( mac='00:0a:95:9d:68:16' ){ ... }


How to exclude a ino/pde file from Arduino projects I would like to be able to exclude from the auto-including process of the current project (without renaming the extension or delete it) a sketch with pde or ino extension that is used in certain circumstances only.

How can I do this?

I currently use Visual Micro to manage projects on Arduino.

One possible approach is to guard the body of that sketch with an #ifdef ... #endif pair, and use Visual Micro's  “Project Properties” to define (or not) a preprocessor symbol.  [If the .ino or .pde in question is used as a #include file, you would instead guard all the #include instances.]

Refer to the “Project Defines” page at visualmicro.com for how to define a preprocessor symbol and its value. [Via: Tools > Options > Visual Micro > Compiler > Show Build Properties]  Also see  How do I add additional compiler switches in Visual Studio.

If necessary, you can use other tests besides #ifdef to control compilation.  The first link above shows the following example.

#if USBPORT > 3
....your code here....
#endif


Need help with on off switch to power arduino. I am trying to add an on and off power switch to my arduino project.  My project is running off a 9v battery and I would like to save as much power as I can.  There might be a better why that I don’t know.  I added SLEEP_MODE_PWR_DOWN to my project and from what I can tell, the arduino enters sleep mode.  I am having a hard time getting the arduino to wake from sleep mode.  Am I able to do this from a full power down?  I have been reading this link. http://www.gammon.com.au/forum/?id=11497  and others.

Since you are using an Arduino Uno board, putting the MCU (the ATmega328P-PU) to sleep won't save you much battery juice. Putting the MCU to sleep won't make a difference because the voltage regulator on the Uno will waste a lot more power than anything else on the board. The ON LED will also draw significant amount of current on that board.

To really save power you should look into getting an Arduino board that has a more efficient voltage regulator, or use no regulator at all by changing your 9V battery by, say, 4 NiMH AA cells.

Here's some more information about the issue for you to look at: What are (or how do I use) the power saving options of the Arduino to extend battery life?


How can I make my Arduino Uno press Space on my laptop keyboard? So I wanna build something which, when it receives a remote signal, presses the spacebar on my laptop keyboard. I tried using the Keyboard.press() but it is available only for Leonardo. Is there any way I can use it in my Uno, without having to mess with the firmware?
If not, what else can I use to accomplish my goal?

if you have some knowledge in Java or Python you can interface your Arduino board to PC, through Arduino's SerialPort.
When Arduino sends a byte, for example, 0xAB, your Java or Python script sends a fake key-press event.
I hope this can help. Good luck!


Cannot connect through /dev/ttyACM0 (Ubuntu 18.04) I am using an Arduino UNO which worked fine until today. My system: Ubuntu 18.04

Now, the IDE can no longer connect to it:

Cannot do any sketch upload
Cannot ask for board info
No USB ports shown in tools --> port (only 2 serial ports shown)
ttyyACM0 not showing up in /dev

However, both lsusb and dmesg show that the board is recognized somehow.

lsusb output:

Bus 001 Device 012: ID 03eb:2fef Atmel Corp.

dmesg output:

[ 2922.171042] usb 1-1.3: new full-speed USB device number 12 using ehci-pci
[ 2922.282047] usb 1-1.3: New USB device found, idVendor=03eb, idProduct=2fef
[ 2922.282052] usb 1-1.3: New USB device strings: Mfr=0, Product=1, SerialNumber=0

The problem is the same on 2 different computers, which leads me to suspect that there is something wrong with the board. Is it possible that a board be shown by both dmesg and lsusb and still be malfunctioning ?

The board was bad. I just replaced it and it now works.

So, to answer my own question, an Arduino board can show up on lsusb and dmesg and yet be faulty. This is what the dmesg output is for a healthy board:

[10492.388028] usb 1-1.4: new full-speed USB device number 13 using ehci-pci
[10492.500520] usb 1-1.4: New USB device found, idVendor=2341, idProduct=0043
[10492.500526] usb 1-1.4: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[10492.500529] usb 1-1.4: Manufacturer: Arduino (www.arduino.cc)
[10492.500533] usb 1-1.4: SerialNumber: 55736323739351010292
[10492.520354] cdc_acm 1-1.4:1.0: ttyACM0: USB ACM device
[10492.520832] usbcore: registered new interface driver cdc_acm
[10492.520835] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

And here is the lsusb output:

Bus 001 Device 013: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)

Judging on the difference with the previous outputs from both commands (when the faulty board was connected), it seems that my board had reverted to the basic Atmel USB interface and that the Arduino specific USB handshake was not working. Can anyone confirm ?


How to change Arduino Nano MODEL_ID I'm working on a project using a set of different Arduino Nano connected to a Raspberry Pi through USB.
Now my question is: "how can I, from the Pi's point of view, differentiate all of those Arduino and associate them with their respective tty?"

I found some part of my answer in this question. The answering guy proposes to manually change the Arduino MODEL_ID when compiling and to use it afterwork to identify the device. The problem is that I don't know how to achieve that.

I tried to edit the boards.txt file to add a new board configuration with custom vid.x and pid.x (why all those 4 different values?) but after selecting my board and uploading, the MODEL_ID still stays the same:

ID_MODEL_FROM_DATABASE=HL-340 USB-Serial adapter
ID_MODEL_ID=7523

Can't I just specify somehow the USB_PID macro to the compiler command line?

How to change Arduino Nano MODEL_ID?

The Arduino Nano used a special USB-Serial adapter (FTDI FT232RL). You can change the ID but this requires some special hacking. Please see the provided links.

Cheers!


Problem receiving full serial event+SMS I wrote code in Arduino to read SMS. I have a problem with receiving it from serial.

String str;

void setup() {
  Serial.begin(9600);
  Serial.println("AT+CMGF=1");
  delay(1000);
}

void loop() {
  Serial.println("AT+CMGF=1");
  delay(2000);
  Serial.println("AT+CMGR=1");
  delay(5000);
  while (Serial.available()>0) {
    str = char(Serial.read());
    Serial.print(str);
  }
  Serial.println();
}

I have an A6 GSM modem. When I read the serial I just get:

+CMGR: "REC READ

Nothing more!

I should get something like this:

+CMGL: 1,"REC READ","+989207201219",,"2017/08/26,21:54:56+05"
test 20

I changed my code to:

int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;
  if (readch > 0) {
    switch (readch) {
      case '\n': // Ignore new-lines
        break;
      case '\r': // Return on CR
        rpos = pos;
        pos = 0;  // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  // No end of line has been found, so return -1.
  return -1;
}

void setup() {
  Serial.begin(9600);
  Serial.println("AT+CMGF=1");
  Serial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
}

void loop() {
  Serial.println("AT+CMGF=1");
  Serial.println("AT+CMGR=1");
  static char buffer[80];
  if (readline(Serial.read(), buffer, 80) > 0) {
    Serial.print("You entered: >");
    Serial.print(buffer);
    Serial.println("<");
  }
  delay(3000);
}

But I get nothing.

The arduino is a "small memory" device. So it probably does not have a big serial buffer. On say "linux on a PC" you get a 4096 byte buffer, but on an arduino, probably only say 16. Now as luck will have it "+CMGR: "REC READ" is precisely 16 characters....

From the code that I see, you seem to be sending commands to the modem and then reading/echoing them. I would have liked to use two different serial ports or something like that.

In any case, if it sort of works for those first 16 characters, remove all the delays and put one of them near the end of the loop() function. Remove the initial print to the modem in the setup function.


Relay built in to cable with arduino interface To be able to switch 220 volt stuff on and off using arduino, I need a relay (I assume). Is there really no nice extention cable with built in relay so you dont need to cut and connect high voltage.

I imagine a Power strip With a simple input port that can be controlled from the andruino, just like a relay board. When I Google this I get a lot of USB controlled and remote controlled, but none that works with an andruino project.

PowerSwitch Tail is what you are looking for.


Read signal from USB mouse on an Arduino ? I've got a project where I'd need to read my mouse's signal. My mouse is a G700S (so USB) and the thing was I don't really know how to do and even if it's feasible.
I'm using an Arduino Micro and my initial idea was to get a PS/2 to USB Adapter (I already have one) and then to plug it to something like this wired to my Arduino.
So my question basically is "will it work ? and if not, why ?"

The main idea is not to use USB (like an USB Host Shield) because Arduino doesn't have any USB mouse driver.

Thank you in advance

This would be possible only if the mouse actually supports PS/2. USB to PS/2 adapters are entirely passive, and in order to function it requires that the controller in the mouse is designed to communicate in both protocols. Modern mice, especially wireless ones don't tend to have this capability anymore as PS/2 is all but a dead standard.


How to stop sending the last received char of UART echo function? I developed a code for uart based ISR with linear buffers, the problem is that it keep sending the last received char in Arduino IDE.

Here's the application code:

#include "uart_new.h"

void setup() {
uart_init_new(103);
DDRB = 0xff;
}

void loop() {
uint16_t c;
c = get_char();
if (c & NO_DATA)
{
  PORTB |= (1<<PB5);
  _delay_ms(500);
  PORTB &= ~(1<<PB5);
  _delay_ms(500);
}
else
{
  put_char(c);
}
}

The header file:

#ifndef uart_new_H_
#define uart_new_H_

#define NO_DATA     0x0100
#define Buf_OF      0x0200
#define FR_Er       0x0400
#define DOR_Er      0x0800
#define PARTY_Er    0x1000

#define buf_s 32
#define buf_mask Buf_s - 1
#define baud_rate 9600

void uart_init_new(uint16_t ubrr);
void put_char(uint8_t data);
uint16_t get_char(void);
void put_s(uint8_t *str);

#endif // uart_new_H_

The source code:

#include <avr/io.h>
#include <Arduino.h>
#include "uart_new.h"

/*******************************************
If you want to prevent reading a string
backwards then you need FIFO implementation
*******************************************/

static volatile uint8_t rx_buf[32],tx_buf[32];
static volatile uint8_t rx_p,tx_p,rx_cnt,tx_cnt;
static volatile uint8_t rx_errors,tx_sBuf,rx_sBuf;

void uart_init_new(uint16_t ubrr)
{
    rx_p=0,tx_p=0,rx_cnt=0,tx_cnt=0;
    UBRR0H = (uint8_t)(ubrr>>8);
    UBRR0L = (uint8_t)ubrr;
    UCSR0B = (1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0); //Enable Rx and Tx & Receive interrupt
    UCSR0C = (1<<USBS0)|(3<<UCSZ00);            //Set frame format: 8data, 2stop bit
}

uint16_t get_char(void)
{
    if (rx_cnt == 0)
        return NO_DATA;
    else if (rx_p < rx_cnt)
        return rx_buf[rx_p++];
}

void put_char(uint8_t data)
{
    if (tx_cnt < 32)                        // start count the input data
        tx_buf[tx_cnt++] = data;            // 1st input location tx_cnt

        UCSR0B |= (1<<UDRIE0);
}

void put_s(uint8_t *str)
{
    while (*str)
        put_char(*str++);
}

ISR(USART_RX_vect)
{
    if (rx_cnt < 32)                        // start count the received data
        rx_buf[rx_cnt++]=UDR0;              // 1st output location rx_cnt
    else
        rx_cnt = 0;                         // when the counter reached max value, reset it, overwrite everything

if (!(UCSR0A & (1<<RXC0)))
        UCSR0B &= ~(1<<UDRIE0);
}
ISR(USART_UDRE_vect)
{
    uint8_t i;
    if (tx_p < tx_cnt)                      // check if pointer < counted data
        UDR0 = tx_buf[tx_p++];
        else
        {
            for (i=0;i<tx_cnt;i++)
                tx_buf[i]=0;
            tx_p = 0;                       // when the pointer reach max value, reset it
            tx_cnt= 0;                      // also reset counter for new transmission
            UCSR0B &= ~(1<<UDRIE0);         // disable empty data register interrupt
        }
}

If the there's a received char, then ISR is executed, the function exit the LED blink loop, but when the receive stops and there're no more data it doesn't return the blink state and keeps sending the last received char. How to solve this problem?

There are many, many problems with this code. The most fundamental flaw
is that it uses linear buffers, where you should be using circular
buffers instead. I'll come to this later. Now, if we look
at the details, in the header file:

#define Buf_OF      0x0200

This, and a few other macros, serve no purpose. Do not put "TODO" items
in the code: put them in a TODO file, or as comments. Strive to always
have your code in a clean state. More so when you post it in a public
place.
#define buf_mask Buf_s - 1

This is presumably intended to be used as a bit mask, but it will not
work reliably. For example, if you try to complement the mask as
~buf_mask, the preprocessor will expand that to ~Buf_s - 1, and the
compiler will interpret it as (~Buf_s) - 1, which is not what you
want. You should always parenthesize any expression you use in a macro,
as
#define buf_mask (Buf_s - 1)

Later,
void put_s(uint8_t *str);

If you want to be able to issue calls like put_s("Hello!");, then you
should declare the function as:
void put_s(const char *str);

Now, in the implementation, you have:
static volatile uint8_t rx_errors,tx_sBuf,rx_sBuf;

All those are unused. Remove them. Again, this is supposed to be a
program, not a TODO list.
Later,
uint16_t get_char(void)
{
    if (rx_cnt == 0)
        return NO_DATA;
    else if (rx_p < rx_cnt)
        return rx_buf[rx_p++];
}

The compiler should have warned you about this: what if both conditions
are false? In this case the function will return by reaching its end,
with no specified return value. This is undefined behavior. You should
probably return NO_DATA in this case. But then, that's what you should
return every time you are not returning valid data, so the function can
be simply written as:
uint16_t get_char(void)
{
    if (rx_p < rx_cnt)
        return rx_buf[rx_p++];
    else
        return NO_DATA;
}

Later, in ISR(USART_RX_vect),
if (rx_cnt < 32)
    rx_buf[rx_cnt++]=UDR0;
else
    rx_cnt = 0;

If you set rx_cnt to zero without updating rx_p, then the subsequent
characters that you will put in the buffer will be ignored by
get_char() until you fill the buffer up to rx_p. Thus you presumably
want to set rx_p to zero also. And if you do this at the start if the
ISR, you ensure that at least the current character is not lost:
// when the counter reached max value, reset the buffer
if (rx_cnt >= 32) {
    rx_p = 0;
    rx_cnt = 0;
}
rx_buf[rx_cnt++]=UDR0;

Further in the ISR:
if (!(UCSR0A & (1<<RXC0)))
    UCSR0B &= ~(1<<UDRIE0);

This makes no sense: if you have no pending character in the receive
register (which you should not have, as you have just read that
register), then you disable the ISR that serves the transmitter. The
transmitter and the receiver should be able to work independently:
remove those lines.
Then, in ISR(USART_UDRE_vect):
for (i=0;i<tx_cnt;i++)
    tx_buf[i]=0;

This serves no purpose. If you handle your buffers properly, you should
never access uninitialized data in them. Thus you will never read the
zeroes you are writing here. Again, remove those lines.
If you implement all the fixes above, you should end up with a code that
“kind of” works. There are still a couple of issues though:
Race conditions
If get_char() gets interrupted by ISR(USART_RX_vect), you can get
what is known as a “race condition”, which can lead to incoherent
behavior or data corruption. For example, testing rx_p<rx_cnt is not
atomic: the CPU has to read rx_cnt from RAM, then read rx_p, then
compare them. If the interrupt fires between the two memory reads, the
ISR can set both values to zero, then the test will compare the old
rx_cnt with the new rx_p (which is now zero) and incorrectly assume
there is valid data to be returned.
There are other places where this can byte you. For example, rx_p++ is
not atomic either, it's a read-modify-write sequence that can very well
be interrupted in the middle. And there are similar issues if
put_char() gets interrupted by ISR(USART_UDRE_vect).
The fix for these issues is to disable interrupts while you are in the
“critical sections” that access data shared with the ISRs. This can be
done using noInterrupts()/interrupts() pairs or, if you prefer the
avr-libc style, with atomically executed code blocks. For
example:
#include <util/atomic.h>

uint16_t get_char(void)
{
    uint16_t result = NO_DATA;
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        if (rx_p < rx_cnt)
            result = rx_buf[rx_p++];
    }
    return result;
}

A similar protection is needed in put_char().
Linear buffers
This is the main flaw, because it will require you to rethink a
significant part of your code. Imagine what can happen if the UART
transmitter lags slightly behind your program calling put_char(). Say
you reach tx_p = 30 and tx_cnt = 32. Then your
buffer has 30 “empty” cells (from 0 to 29 the space is available, as
that data has already been sent) and two cells with bytes pending to be
sent (at positions 30 and 31). If you call now put_char() to send an
extra byte, that byte will be lost (because tx_cnt<32 is false). This
is unacceptable: you should not loose data when the buffer is almost
empty!
The solution is to put the extra byte at position 0, the next one at
position 1, etc. But this creates a complication: now the pending bytes
are at positions 30, 31, 0, 1... At this point your buffer becomes a
circular buffer. It's not a big deal, but you must
read about the subject before you try to implement it.
Note that the same issue applies to the receive buffer: both buffers
should be made circular.


The easiest and most time efficent way to connect to the internet regardless of the cost I am working on my graduation Project. I want to use the cayenne (mydevices) platform to control my Arduino. Mainly I want to be able to control a servo Motor through the Cayenne app and I want to use a gyro sensor that would also control the servo using the app after obtaining the readings from the sensor. The Options are:
1- Yun arduino
2- Arduino Ethernet
3- Arduino uno (which I currently have) + Arduino Ethernet shield or arduino wifi shield

Cayenne (mydevices) APP supports all of the above Options

What is the easiest to implement? I have short time period and working on the mechanical design for the Project in the same time.

Your help is appreciated

The Arduino Uno and Arduino Ethernet are very simple to program, to connect it to the Internet.

I never used the Yun Arduino, but it seems a little bit harder.


Micro USB to USB adapter m/m I'm looking into working with an Arduino micro, and I'd like to be able to plug it into my computer directly(without a cable). I've been looking around, and the best thing that I found was this. The reason I haven't bought the linked adapter is because I've seen a number of bad reviews of the seller with close to half of the reviews being 1-star. Anybody have an idea where I can find something similar?

EDIT: I'm going to be using this for security testing, emulating a rubber ducky usb, so I need the computer to recognize the Arduino as an HID, not an arduino, but I also (obviously) need to be able to load my code onto it

That adapter is not suitable. Not only is it the wrong gender on the large end, but it is designed for a completely different purpose.

That is an "On The Go" adapter which is designed for connecting things with a USB A plug (such as a memory stick, etc) to a mobile phone's USB socket.  It is not suitable for connecting things to an Arduino.

I have never heard of an adapter like you want, but I have heard of Arduino-like boards that plug direct into a computer like you want. One example is the Digispark from Digistump which is an ATTiny85 on a USB plug.


SdFat initialization blocks HC-SR04 I appreciate the help of this forum very much and it`s my first time to ask you experts befor driving crazy...

ArduinoUno and SDcard-BreakOutboard and DistanceSensor HC-SR04 are not working well together. The problem - as far as I found out - is in this statement:

if (!sd.begin(sdChipSelect) || !file.open("DATALOG.TXT", O_CREAT | O_WRITE | O_APPEND)) {
// Replace this with something for your app.
Serial.println(F("SD problem"));
//while(1);
}

When it is erased the distance sensor works perfectly, if it is in place it shows 0 cm (and that for days! ;-) ). I read something that SdFat ist doing something with Pin10 but also putting it on OUTPUT - HIGH or LOW didn't do the trick. Any ideas?

Kind regards

Rob

The "minimal" code:

/*
SD card datalogger

This example shows how to log data
to an SD card using the SdFat library.

The circuit:
* analog sensors on analog ins 0, 1, and 2
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 7 (for MKRZero SD: SDCARD_SS_PIN)
*/
#include <SdFat.h>
const uint8_t sdChipSelect = 7;
// SD file system.
SdFat sd;
// Log file.
SdFile file;

// Hook up HC-SR04 with Trig to Arduino Pin 9, Echo to Arduino pin 10
// Maximum Distance is 400 cm
unsigned long echo = 10;
int ultraSoundSignal = 9; // Ultrasound signal pin
unsigned long ultrasoundValue = 0;

void setup() {
// Serial Port
Serial.begin(9600);
// Pin 9 = TriggerPin
pinMode(ultraSoundSignal,OUTPUT);

// Initialize the SD and create or open the data file for append.
if (!sd.begin(sdChipSelect) || !file.open("DATALOG.TXT", O_CREAT | O_WRITE | O_APPEND)) {
// Replace this with somthing for your app.
Serial.println(F("SD problem"));
//while(1);
}
Serial.println("card initialized.");
delay(1000);
}

void loop() {
Serial.println("Beginn");
// Distanzmessung mit HC-SR04
int x = 0;
x = ping();
Serial.print(x); Serial.println(" cm");
delay(1000); //delay 1/4 seconds.
}

unsigned long ping()
{
  pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output
  digitalWrite(ultraSoundSignal, LOW); // Send low pulse
  delayMicroseconds(2); // Wait for 2 microseconds
  digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
  delayMicroseconds(5); // Wait for 5 microseconds
  digitalWrite(ultraSoundSignal, LOW); // Holdoff
  pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
  digitalWrite(ultraSoundSignal, HIGH); // Turn on pullup resistor
  // please note that pulseIn has a 1sec timeout, which may
  // not be desirable. Depending on your sensor specs, you
  // can likely bound the time like this -- marcmerlin
  // echo = pulseIn(ultraSoundSignal, HIGH, 38000)
  echo = pulseIn(ultraSoundSignal, HIGH,38000); //Listen for echo
  ultrasoundValue = (echo / 58.138);// * .39; //convert to CM then to         inches
  return ultrasoundValue;
}

Pin 10 is the SS pin for SPI. Since you are using SPI for the SD card pin 10 must be an output (for SPI to operate in master mode). Ideally you will use that pin as the SS (or CS, whatever you want to call it) for the SD card.

You can't use it as the echo input of an ultrasound range finder and use SPI.


How to avoid electromagnetic interference on ESP32 input I've realized a simple circuit like the following, in order to implement a rain gauge that I can access via HTTP:

With the following sketch:

#include <WebServer.h>
#include <WiFi.h>
#include <WiFiClient.h>

/**
 * This constant is calculated with the following procedure:
 * - Area of pluviometer is 55 cm^2
 * - Volume of test water is 100 cm^2
 * Resulting height of water is 1.82 cm. Using this water quantity, generates 40 ticks of the pluviometer. So every tick is 0.455 mm of rain.
 */
const double millimetersPerTick = 0.455;
const char* ssid = "*********";
const char* password = "*********";

WebServer server(80);

/* LED pin */
byte ledPin = 2;
/* pin that is attached to interrupt */
byte interruptPin = 14;
/* hold the state of LED when toggling */
volatile byte state = LOW;
volatile int interruptCounter = 0;
int numberOfInterrupts = 0;
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;

void IRAM_ATTR handleInterrupt() {
  portENTER_CRITICAL_ISR(&mux);
  interruptCounter++;
  portEXIT_CRITICAL_ISR(&mux);
}

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

  // WIFI initialization
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  pinMode(ledPin, OUTPUT);
  /* set the interrupt pin as input pullup*/
  pinMode(interruptPin, INPUT_PULLUP);
  /* attach interrupt to the pin
  function blink will be invoked when interrupt occurs
  interrupt occurs whenever the pin change value */

   // Notify wifi connection
  digitalWrite(ledPin, HIGH);
  delay(2000);
  digitalWrite(ledPin, LOW);

  attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, RISING);

  server.on("/", []() {
    server.send(200, "text/plain", String(millimetersPerTick * numberOfInterrupts));
    numberOfInterrupts = 0;
  });

  server.onNotFound([]() {
    server.send(404, "text/plain", "Not found");
  });

  server.begin();
}

void loop() {
  server.handleClient();

  if(interruptCounter>0) {
    portENTER_CRITICAL(&mux);
    interruptCounter--;
    portEXIT_CRITICAL(&mux);

    numberOfInterrupts++;
    Serial.print("An interrupt has occurred. Total: ");
    Serial.println(numberOfInterrupts);
    state = !state;
    digitalWrite(ledPin, state);
    delay(100);
    state = !state;
    digitalWrite(ledPin, state);
  }
}

The main issue of this circuit is that if I connect the AC plug it suffers from interferences from the household electricity. For example if I turn on the light, the interrupt is called. I tried also to buy an EMI filter like this but it doesn't reduce the problem. What can I do to avoid this?

I have to check better, but it seems that other have this issue with reed switches that in some configuration act like antennas and receive interferences (see here and here).


HC-SR04 quits pinging when distance < 0 || distance < MAXDISTANCE so here is the issue. I have a mega 1280, a handful of neopixels and a HC-SR04. I am using the New Ping library (tried both 1.5 and 1.6). I am trying to make a device that will tell my mom when she has pulled into the garage enough so she don't get hit by the garage door AND doesn't run into the wall. I wrote a bunch of code to handle the lights and what colors to do when and this part works perfectly. My issue is with the sensor. It works great except for 2 specific conditions.

if you are too close. I normally either cover one of the 2 sonic sensor part or just barley touch then with a piece of cardboard (or anything for that matter
If you go outside the scope of the max distance

when either of this are met, the ping sensor stops clicking and it just returns all 0's for the output. I am including the code less the part for the lights because even if i remove that part of the code, it still fails on those 2 conditions.

#include <Adafruit_NeoPixel.h>
#include <avr/power.h>
#include <NewPing.h>
#define TRIGGER_PIN  52
#define ECHO_PIN     53
#define MAX_DISTANCE 120
#define PIN 6
#define LEDNUM 8

int codeFact = (MAX_DISTANCE / (LEDNUM * 3));
Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDNUM, PIN, NEO_RGB +     NEO_KHZ800);
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  strip.begin();
    strip.show();
    for(uint16_t i=0; i<strip.numPixels(); i++)
    {
      strip.setPixelColor(i, strip.Color(0, 255, 0));
      strip.show();
      delay(50);
    }
    for(uint16_t i=0; i<strip.numPixels(); i++)
    {
      strip.setPixelColor(i, strip.Color(255, 255, 0));
      strip.show();
      delay(50);
    }
    for(uint16_t i=0; i<strip.numPixels(); i++)
    {
      strip.setPixelColor(i, strip.Color(255, 0, 0));
      strip.show();
      delay(50);
    }
    for(uint16_t i=0; i<strip.numPixels(); i++)
    {
      strip.setPixelColor(i, strip.Color(0, 0, 0));
      strip.show();
      delay(50);
    }

Serial.begin(115200);
}

void loop()
{
 delay(2000);
  int uS = sonar.ping();
  int dis = uS / US_ROUNDTRIP_CM;
  Serial.println(dis);
  /*
  Light code normally goes here
  */
}

The HC-SR04's range is 2cm to 300 cm, if you exceed this range or come below this range, which is exactly what you are doing, the utrasonic sensor will not receive any echo and hence there will be no data on the output.
If you bring it too close and since both the transmitter and receiver located close to each other, the receiver will not receive any ultrasonic.
Put a function that checks if the ultrasonic comes down to 2-3. If it becomes true beep a buzzer that tells you that you are too close. Don't let it reach 0.


Need some explain before desigin my own custom Arduino Due board I'd like to ask you some questions about ARM processor from Atmel like the SAM3X8E, the one used in the Arduino Due. I have found this [AVR programming guide] from abcminiuser on avrfreaks very helpful.

Q1. Why are there no ICSP pins in Arduino Due to use it to program the SAM3X8E from an external programmer instead of the USB port in the Due board?

Q2. If I want to program an Arduino Due from an external programmer which of the programmers in abcminiuser guide will do the job and give me the ability to program 8/16/32bit AVR and ARM chips from Atmel at the same time?

Q3. On the Arduino Due website I read this:

  "Uploading sketches to the SAM3X is different than the AVR Microcontrollers found in other Arduino boards because the flash memory needs to be erased before being re-programmed. Upload to the chip is managed by ROM on the SAM3X, which is run only when the chip's flash memory is empty. "

What is that mean?

Because it is not needed. The chip comes with the bootloader pre programmed in  ROM, not in Flash. It cannot be replaced, upgraded, removed, etc like other more sensible chips. So there is no real need for ICSP since the main use for that is putting the bootloader on.
Unknown.
Unlike the AVR chips, whose bootloader always runs first for about 2 seconds, the SAM3X's boot loader only runs if the flash is empty. As a result there is a way to empty the flash built in to the Arduino code, so that it can be erased by software. That means that the software has to be working right though, which isn't always the case, since people write bad code which crashes the chip. As a result they added a erase button to the board so you can manually erase the chip and get the bootloader to run.

I have always maintained that the SAM3X is a really idiotically designed chip and I wouldn't ever use it in a design of my own.


How to send AT command to sim800l with SoftwareSerial I have SIM800l module connected to Arduino and I'm trying to initialize it in my setup function with this code:

#include <SoftwareSerial.h>

//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 6
//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup()
{
  Serial.begin(38400);
  while(!Serial);
  serialSIM800.begin(38400);
  Serial.println("wait for .... it");
  delay(10000);

  // comments added just for example, both commands return junk
  //serialSIM800.write("AT\r\n");
  //serialSIM800.write("AT+SAPBR=3,1,\"Contype\",\"GPRS\"\r\n");

  Serial.println("command sent");
  delay(2500);

  Serial.write(serialSIM800.read());
}

But Serial.write returns junk.

When I use this code in loop:

  //Read SIM800 output (if available) and print it in Arduino IDE Serial Monitor
  if(serialSIM800.available()){
    Serial.write(serialSIM800.read());
  }
  //Read Arduino IDE Serial Monitor inputs (if available) and send them to SIM800
  if(Serial.available()){
    serialSIM800.write(Serial.read());
  }

and send AT+SAPBR=3,1,"Contype","GPRS" or just AT command with serial monitor, everything works fine.

Can someone help with this?

NeoSWSerial would be better for this.  It can read and write at the same time, unlike SoftwareSerial, and it doesn't disable interrupts for the entire character receive time (~1ms!).  AltSoftSerial would be even better, but you can only use it on pins 8 & 9 (on an UNO, different pins on other Arduinos).


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

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


'OUTPUT' was not declared in this scope - ATtiny85 with Arduino Uno r3 as ISP I'm trying to follow this this tutorial to program an ATtiny85 micro-controller using my Arduino Uno r3 as the ISP.

I am up to the final step on the tutorial, but get an error when attempting to compile my sketch:

'OUTPUT' was not declared in this scope

I have tried multiple "Blink" scripts, but none have seemed to work.

My full error log:

Blink.ino:10:21: error: Arduino.h: No such file or directory
Blink.ino: In function 'void setup()':
Blink:15: error: 'OUTPUT' was not declared in this scope
Blink:15: error: 'pinMode' was not declared in this scope
Blink.ino: In function 'void loop()':
Blink:20: error: 'HIGH' was not declared in this scope
Blink:20: error: 'digitalWrite' was not declared in this scope
Blink:21: error: 'delay' was not declared in this scope
Blink:22: error: 'LOW' was not declared in this scope

I have also tried including Arduino.h, no help, and changing "OUTPUT" to "0x01", as it is defined to said value in Arduino.h, but instead got this error:

error: 'pinMode' was not declared in this scope

Any ideas as to what is happening?

Create an Arduino.h in ...\Arduino\hardware\attiny45_85\cores\attiny45_85 containing

#include <WProgram.h>

From here
https://electronics.stackexchange.com/questions/87328/arduino-as-isp-for-attiny


Wire with MCP23008 I/O expander with I2C I'm trying to read from an MCP23008 I/O expander using the Wire library over I2C. The MCP23008 is wired to address 0x04, giving an effective device address of 0x24. Writing to the device GPIO seems to work fine, and I'm a bit confused on how to read from the GPIO.

So I set it up for read as follows:

#define MCP23008_DEVICE_I2C_ADDRESS 0x20
#define MCP23008_SLAVE_I2C_ADDRESS  0x04

#define MCP23008_REGISTER_IODIR     0x00
#define MCP23008_REGISTER_GPIO      0x09

#define IO_ALL_PINS_INPUT           0xFF

inline void eeprog::_read_enable()
{
    Wire.beginTransmission(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS);
    {
        Wire.write(MCP23008_REGISTER_IODIR); // Set I/O direction
        Wire.write(IO_ALL_PINS_INPUT);       // Set all pins as input
    }
    Wire.endTransmission();
}

after which I attempt to read from it, by first addressing the GPIO register and then requesting a byte to read:

inline uint8_t eeprog::_read()
{
    Wire.beginTransmission(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS);
    {
        Wire.write(MCP23008_REGISTER_GPIO); // Select the GPIO register
    }
    Wire.endTransmission();

    Wire.requestFrom(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS, (uint8_t)1);

    return Wire.read();
}

Looking at my logic analyzer this is what I get:

The NACK seems to indicate that the read went wrong.. actually a bit unsure what "Data read: 07" means in this context, did it read the value 7, or did it try read address 07?

Any ideas what I could be doing wrong? Am I missing something obvious from the documentation?

Everything is fine and nothing is wrong.
You are reading the GPIO register and its contents is 0x07.

The NACK at the end is not an error, it is a way to communicate between the Master and Slave.

When the Master reads data, the Master gives an ACK after each databyte from the Slave. The Master is not trying to tell the Slave that it was received, but rather it tells the Slave that another byte is going to be read.
After the last databyte, the Master send a NACK and after that a STOP.

Since only one byte is read, the Master sends a NACK and a STOP. The Master is telling the Slave that no more data is needed.

The I2C bus is only two wires. There are START, STOP, ACK and NACK conditions and the clock pulse can be stretched by a Slave. The possibilities are limited. For example when the Master wants to read 6 bytes and the Slave has only 1 byte. The Slave has no way to tell the Master that it has only 1 byte, and the Master will read those 6 bytes, valid or not.


Where to go after Arduino? I apologise in advance if this question is not right for this Stack or if it has been answered before but here goes. I have been learning C/C++ using the Arduino Uno and have gotten the hang of it now (I have knowledge of other programming languages so it wasn't too difficult to get in the rhythm). I was wondering how I would go about creating a standalone solution if I wanted to display information on four or five displays similar to These. I would pull data from a network to display on them too so I would also need to accommodate an ethernet or WiFi shield.
I appreciate any help or pointers in the right direction that can get me started on my journey to creating some custom embedded systems (if that is indeed what I am describing).

There are a lot of much more powerful boards available (especially if you move from ATmega to ARM).  I'm partial to the Teensy boards myself but Adafruit also makes some nice ARM-based boards.  For example, I'm currently developing a multi-user, Arduino-compatible Unix-ish OS on one of the latter (48MHz ARM, 256kB flash, 32kB SRAM) and it runs great.  Honestly, controlling 5 non-graphical LCDs over I²C is should be easily doable on an Uno but if you need more power there are lots of options available.
(No affiliation to either of those companies)


connect USB keyboard to Arduino using clk and data wires Edit:
What I'm looking for is some kind of library which could be used with an arduino to read the HID protocol output from the Data+ and Data- cables of the USB.
==========
If I cut the cable of a usb keyboard, plug in power and ground can I use the clk and data wires to read keystrokes into the Arduino? If so any pointers to libraries and schematics?
Simple I instructions? The "for dummies" version?
EDIT
Following some of the suggestions below I found this:
https://github.com/julianschuler/USBKeyboard
Which looks like what I want to do, basically hook up the lines into the arduinio and read from the keyboard using the HID protocol in this library.
EDIT 2
That doesn't do what I want. Does anyone know how this could be accomplished?

USB doesn't have data and clock lines. It has a pair of data lines with inverted polarity (D+ and D-). The USB protocol is considerably more complex than you seem to imagine.
However there is a caveat: some keyboards have the ability to work in IBM PS/2 mode. For this you will need a USB to PS/2 adaptor (pictured below) and then use the PS2Keyboard.h library. Your mileage may vary, though, as not all keyboards will work.


I Can't Connect to my MQTT server via arduino I have mosquitto MQTT installed on my VPS server which I can subscribe and publish to it using paho client thorugh websockets. However when I tried to connect to it through Arduino, I get the following error:
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

I uploaded the following code to arduino:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "IOT";
const char* password = "11112222";
const char* mqtt_server = "burooq.com";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

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

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("test", "hello world");
      // ... and resubscribe
      client.subscribe("test");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  unsigned long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("test", msg);
  }
}

i checked my server mosquitto ports which shows
mosquitto 10436       mosquitto    4u  IPv4   46043      0t0  TCP 127.0.0.1:1883 (LISTEN)

I checked my conf file and it has
listener 1883 localhost

so how what's wrong within my code or settings that prevents me from connecting to my server?`

This is the problem:

mosquitto 10436       mosquitto    4u  IPv4   46043      0t0  TCP
127.0.0.1:1883 (LISTEN)

Your MQTT server is listening only on port 127.0.0.1.  That will accept local incoming connections only but nothing from another IP address.
The IP 127.0.0.1 is the LOCAL ONLY IP address.  You need to reconfigure your MQTT server to listen on either IP 0.0.0.0 or whatever that server's actual IP address is.
Check your mosquitto.conf file and look for the line that begins with "bind_address":
listener 1883 localhost

change this to:
listener 1883 0.0.0.0

and restart your MQTT server.