Dust sensor for Arduino in open and windy environment I intend to create a DIY dust sensor, specifically Particulate Matter up to 10 micrometer in size (PM10) using Arduino UNO for the region surrounding a building which is located next to a factory that produces wood-based products. Is there any specific sensor that should suit my need, that is to collect and measure dust particles in an open environment and possibly a windy condition?
Any implementation ideas are also welcome.

A popular option is the Shinyei PPD42 sensor. There are a few well-documented blogs that describe how to connect it to an Arduino. Some of the users determined that the sensors are more accurate when a fan is placed on the unit to blow air through it, but this might not be necessary in an outdoors and windy environment.

I have two of these sensors hooked up to an Arduino, one monitoring indoors and one outdoors. I found that the indoors unit needed a fan on it to help it detect particles better (otherwise I was getting too many zeros). But the outdoors unit seems fine without the fan.

I mainly followed this blog's instructions for the code:
http://www.howmuchsnow.com/arduino/airquality/grovedust/

I think I read a few months ago that the next best sensors are in the $200 range.

I have a Dylos DC1100 dust monitor (considered very accurate) and it usually correlates with my Shinyei readings. But I'm pretty sure I introduced some "magic numbers" into my code to make the Shinyei readings match more closely with the Dylos. The entire process wasn't easy for me, and it took me weeks to get everything to behave the way I wanted.


DS18b20 Order of sensors on a cable I have a string of 10x DS18b20 sensors on a single two wire line (parasitic power). Below is a table of the sensors, Where they are located on the wire, and in what order where they discovered.

Serial              Order on wire*   Order discovered
286305560100002c    1                7
28a158610100006a    2                3
28ad48610100006b    3                6
2851ae60010000ad    4                4
289b426101000089    5                8
28cd1161010000ce    6                5
2864026101000030    7                1
280c766101000026    8                2

I read this document on how the OneWire discovers sensors on the bus. https://www.maximintegrated.com/en/app-notes/index.mvp/id/187

My question: Is there a way to detect the order of the sensors on a wire?

There is no way to detect position on the bus because all devices are connected in parallel. This is why a serial or "chain" wire, added to the newer devices, is required.

(To complicate matters, what is the "order of devices" - or even the meaning of "order" in a center-fed bus, or a circular, star, or other branched network? Order is just something we perceive when looking at an end-fed linear network. Electrons don't care. Think of a capacitor (unfortunately, the bus behaves like one but that's another story) with two plates, several centimeters square, and a dozen 1-wire devices connected from plate to plate. Now what is their order? Ow, my brain hurts! Let's go back to linear buses.)

The discovery order is a function of the set of binary device IDs on the bus. There are two ways I know of to come to know the physical ordering, both empirical (i.e., by observation):

Connect the set of devices one at a time, to a temporary bus such as a breadboard. With an Arduino, read the their IDs and tag them (human readable). With knowledge of the discovery alogrithm, or by running actual discovery on an Arduino with all devices connected, write down the IDs in the order they are discovered which is invariant for a given set of device IDs. Assemble your wired bus with the devices in this order.
(The reverse of 1 and quicker to build, and is what you've already shown in your question: Wire the bus. With a simple Arduino program, repeatedly sample all devices on the bus and report print their indices and temperatures (the indices will be in discovery order). One at a time, warm each device with your hand and notice which device index is affected. Write down the physical position (first, second, ...) and the index. This is the mapping table between position and index. Include it in your control algorithm.


Running Stepper motors (at least 2) at the same time Is there a way to run a Stepper motor with Arduino MEGA 2560 with A4988 driver component.

I am using this https://github.com/laurb9/StepperDriver library and with this code,

Serial.println("Starting motor ALL");
int steps = atoi(third.c_str());
int duration = atoi(fourth.c_str());

BasicStepperDriver stepper1(steps, DIR, STEP, ENBL);
stepper1.enable();
stepper1.setMicrostep(MICROSTEPS);
stepper1.setRPM(MAX_RPM);

BasicStepperDriver stepper2(steps, DIR_2, STEP_2, ENBL_2);
stepper2.enable();
stepper2.setMicrostep(MICROSTEPS);
stepper2.setRPM(MAX_RPM);

int starttime = millis();
int endtime = starttime;
while ((endtime - starttime) <= duration) // mS
{
     stepper1.rotate(90);
     stepper2.rotate(90);
     endtime = millis();
}
stepper1.disable();
stepper2.disable();
Serial.println("DONE");

The problem with this is that each stepper motor in this code waits for each other and not simultaneously like a DC motor. What could be done to make it work simultaneously?

Try the AccelStepper library. It can control both steppers at the same time. Also provides some useful examples

AccelStepper with more than one stepper also requires the Adafruit Motor library to be installed.


Roadblock using template functions As part of a larger project, I'm trying to create a simple template function that will take an array and a value, both of the same type, and fill the array with the value. I'm running into the error quoted below:

"specializing member '::Fill_With' requires 'template<>' syntax"

Below is the offending code fragment:

// Simple function to fill an array with a specified value.
template <class T> void Fill_With(T target_array, T value){
    int Array_Size = sizeof(target_array) / sizeof(T);
    for(int l = 0; l < Array_Size; ++l){
        target_array[l] = value;
    }
}

int array1[4] = {1,2,3,4}, k = 0;
Fill_With<int>(array1, k);

I've read numerous other forum posts on the error message, but haven't quite been able to figure out what I'm missing. I've read that I need to include a blank "template<>" header before the function declaration but that didn't seem to solve the issue.
What am I doing wrong? Thanks!

Let's start by getting rid of the templates, as they make things more confusing. In the following, I replaced T with int.

void Fill_With(int target_array, int value){
    int Array_Size = sizeof(target_array) / sizeof(int);
    for(int l = 0; l < Array_Size; ++l){
        target_array[l] = value;
    }
}

Let's try it out! I pasted this into the Arduino IDE and compiled it. Here is the output:

sketch_aug01a/sketch_aug01a.ino: In function 'void Fill_With(int, int)':
sketch_aug01a:4: error: invalid types 'int[int]' for array subscript
         target_array[l] = value;
                       ^
exit status 1
invalid types 'int[int]' for array subscript

This is telling us that we're trying to subscript (that's the term for the [] syntax) a variable of type int with a variable of type int. In C++, a pointer to the start of an array has type int *, not int. Let's fix the type of target_array in the function signature:

void Fill_With(int *target_array, int value){

It compiles, but if you ran it you would quickly run into a bug:

When given an expression, the sizeof operator will return the number of bytes in the type of the expression. The type of the expression target_array is int *, so sizeof(target_array) == sizeof(int *). On 32-bit systems, sizeof(int *) == 32/8 == 4.
When given a type, the sizeof operator returns the number of bytes in the type. So sizeof(int) gives the number of bytes in an int, which is guaranteed to be at least 2 bytes (16 bits), but is usually 4 or 8 (it depends on the system).

Together, this means that Array_Size ends up being some small number like 0 or 1, regardless of the contents of target_array. To fix this, you can instead pass in the length of the array as a parameter:

void Fill_With(int *target_array, int array_size, int value){
    for(int l = 0; l < array_size; ++l){
        target_array[l] = value;
    }
}

int array1[4] = {1,2,3,4}, k = 0;
Fill_With(array1, 4, k);

Now you can put the templates back in:

template <class T> void Fill_With(T *target_array, int array_size, T value){
    for(int l = 0; l < array_size; ++l){
        target_array[l] = value;
    }
}

int array1[4] = {1,2,3,4}, k = 0;
Fill_With<int>(array1, 4, k);

By the way, C++ already has this function built in. It's called std::fill. Here's how to use it:

#include <algorithm>

int array1[4] = {1,2,3,4}, k = 0;
std::fill(array1, array1 + 4, k);


Programming "Arduino" code to AT90S8515? I found (from a previous life) an STK500 and a couple AT90S8515's in the recesses of my basement..  that I would like to put to use.

Is there a way in which I can write "arduino code" for the 8515?  I know that it's basically C/C++.

I also know that the 8515 doesn't have, or support, a bootloader like the Mega series of ICs do..  so I expect that I will need to program it using the STK500.

I downloaded AVR Studio, but I will admit, I became very lost, very quickly.

Thanks for any direction!

Theoretically yes, once you write a core (1.5.x/1.6.x) for it. I'm not sure if the IDE has a configuration for the STK500, but it should be easy enough to add (since avrdude already supports it).


String to char array conversion In my project I need to convert a string to a char array. From various examples I concluded that toCharArray() will convert a string to a char array. But I failed to do so. The error is:

  'a' does not name a type

The code I am using is:

String a = "45317";
char b[6];
a.toCharArray(b,6);

Resources are https://www.arduino.cc/en/Reference/StringToCharArray and http://forum.arduino.cc/index.php?topic=199362.0

If you're trying to use a method of a in the global scope, that's doomed to failure. You can only call methods within functions.

If all you want is a char array with "45317" in it then just use:

char *b = "45317";

If you want to convert a string that is built at runtime into a char array, then your current method is correct - you just have to do it in the right place.


I2C communication between Arduino Due and Nano I'm trying to communicate between two Arduino Due and Nano. Nano as Master and Due as a slave. As given in the library description Wire Lib

When the master request for data from the slave, first it goes to Request ISR. Wire.onRequest(requestEvent)    But when compile the program for Arduino Due I get following errors.

In file included from C:\Users\\Slave_Test3.ino:14:0:

C:\Users\..\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\libraries\Wire\src/Wire.h:59:7: error:   initializing argument 1 of 'void TwoWire::onRequest(void (*)())' [-fpermissive]

 void onRequest(void(*)(void));

       ^

But If I change from Arduino Due to any other board this error does not come.

Thank you

Dead easy !!
(Well only because I had a -fpermissive yesterday :) )

You are trying to implicitly cast, and you can't do that with modern GCC versions (quite rightly).

So you need to explicitly cast the first parameter to void*.

Because this is in a "core" library for the Due I would get the latest version of the board package and see if it goes away.  You can turn the check off, but you will need to google on how to do that.


Individual control of multiple RGB leds I'm trying to control several RGB leds individually. So far I've been able to control multiple RGB leds using only 3 PWM outputs using NPN transistors as shown here (pic below).

I would like to control each led individually in order to display different colors in each led. If I used the Arduino Mega, which has 12 PWM pins I could only control 4 different groups of leds using the approach mentioned above. It would be nice to be able to control them using the Arduino Uno or other boards with less PWM pins.

What would be a good solution for this? I've been taking a look to shift registers using ShiftPWM and solutions like the TLC5940 but I haven't got enough experience to tell which way would work better.

Here is a 1/2 software 1/2 hardware solution:

You actually have 6 pwm pins (from the silk screen notation in your picture).  So you can control 2 RGB LEDs independently.  If you added 4 more transistors that are used to gate the common 5v going to each of the 4 RGB LEDs you could control them in pairs.  That is, you could turn on 2 independently controlled RGB LEDs and let the 6 PWM outputs control the brightness and color of each of the 2 for, say, 100ms.  Then you could turn those off and turn on the other 2 independently controlled RGB LEDs for 100ms.  During the switch, you would change the PWMs for the 2nd set of RGB LEDs.  The draw back to this approach?  You may start noticing the LEDs flickering.  You may have to adjust the rate which you switch between the two pairs of LEDs.  And, of course, it may not work as you expect it to.

Totally different approach:

You can use programmable RGB LEDs:

And use this Arduino software library. These types of RGB LEDs have the PWM build in.  The Arduino sends out serial data to the first LED which strips off its RGB data.  Then sends the data to the next RGB LED which does the same.  So you can control many RGB LEDs using a single pin on your Arduino.


Purpose of extra pin slots on Pololu DRV8835 I have a Pololu DRV8835 motor controller. I managed to properly solder and connect it and it actually works, however I've been wondering about the purpose of the extra pin slots - especially the ones without pins headers soldered to them on the right side of the picture below, but also the ones marked A and B (I assume these ones are an alternative way to connect to motors, though). I wasn't able to find anything about them, so I assumed that it may be obvious to someone who is not a complete beginner (like me). What, if anything, could I use them for if I soldered pin headers there?

A and B are the same as the A and B screw terminals.

The pins on the right, if you use your eyes and follow the traces, are the same as the pins that plug into the Arduino. I guess they are intended to be used to isolate the existing pin assignments (cut tracks on the underside between adjacent holes with a knife) and solder wires to other pins so you aren't limited to just using the pins they have assigned.


how to ignore a sensor being tripped the first time and start recording millis on the 2nd time it is tripped I am building a timing system that has a start, split and finish beams with this I am using a start gate that will drop when the race starts. when it drops it will trip the 1st sensor starting to count the millis which I am using to calculate the time. I am using IR sensors to that give me the 3 times based on the millis and then I do a calculation in excel that will give me the split and finish time.
Where I am running into issues is that after the person goes through the 3 timer sensors I have to close the start gate which trips the first sensor which messes up my times for the next person.
So I need to adjust my sketch so it takes this into consideration when it starts counting the millis. Basically I am thinking it needs a line of code to have the 1st sensor == LOW once and do nothing and then on the 2nd time that same sensor is == LOW it records the millis from that point.
Below is the sketch I am working on.
//timer
unsigned long start, reaction, push, elapsed;

void setup()
{
  Serial.begin(115200);
  pinMode(2, INPUT); // start switch
  pinMode(3, INPUT); // split sensor
  pinMode(4, INPUT); // finish sensor
}

void loop(){

if (digitalRead(2) == LOW)
  {

    start = millis();

  }

  if (digitalRead(3) == HIGH)
  {

    reaction = millis();
 //   delay(200); // for debounce

  }

     if (digitalRead(4)==HIGH)
      {

       push=millis();
       delay(500); // for debounce

    Serial.print(start);
    Serial.print(",");
    Serial.print(reaction);
    Serial.print(",");
    Serial.print(push);
    Serial.println();

  }

}

The start time will default to zero, so you could change it to:
if (digitalRead(2) == LOW && start == 0)
  {

    start = millis();

  }


Can I work with larger numbers than an unsigned long long in Arduino? I would like to use larger numbers than an unsigned long long in Arduino. Is that possible?

There are many ways to use numbers bigger than an unsigned long on Arduino. The right one depends on the application.

Floats and Doubles
floats and doubles types on Arduino can hold exact integers up  2^53. That is a very large number. They are built into the Arduino compiler.

uint64_t
The uint64_t type can hold exact integers up to 2^64. That is a very large number. This type is built into the Arduino compiler, but note that some Arduino library functions do not have versions for this type so may need to down-convert for printing and serializing and stuff like that.

BigNumber (or bc)
The BigNumber type can represent exact numbers (integer or otherwise) limited only by available memory- but certainly hundreds of digits long on Arduino. These are extremely big numbers. This type is not built into the Arduino, but there is a nice Arduino library version available...

https://github.com/nickgammon/BigNumber

Again, this type is not supprted by the Arduino built-in library functions so  you will need to either down-convert or find BigNumber compatible functions for things like printing and serializing.


What is the theory behind the Arduino UNO being able to create AM waves at 800 kHz I am doing a school project and saw someone use an Arduino and a piece of wire as an antenna here: https://forum.arduino.cc/index.php?topic=88422.0

I've tested this experiment and it works, but I have searched the internet for some time now for some background knowledge or theory on why this works, and how does it?

If anyone knows anything about the arduino creating simple AM waves, could you please let me know about it or redirect me to another source.

For some context, in this school project I've got to explain the theory behind creating basic AM waves and amplitude modulation in general, then prove the theory by conducting this experiment which I prove it correct.

Strictly speaking it's not AM, it's OOK (On-Off Keying) which just turns a carrier frequency (800kHz PWM, 50% duty cycle) on and off.

Many cheap 443MHz (eBay) modules do the same thing - turn the carrier frequency on and off.

The presence of the carrier frequency is seen as a logic 1 and the absence as a logic 0.

The fact that it's using PWM to generate a square wave means that the "cleanliness" of the signal will be incredibly horrible. You really want to get the carrier frequency as close to a pure sine wave as possible. A square wave has lots of harmonics at 3x, 5x, 7x, 9x etc the frequency. So your 800kHz signal will also have a 2.4MHz signal, a 4MHz signal, a 5.6MHz signal and so on, each at a lower level. That causes interference in other signals.

To understand more about why it works you first have to understand radio transmission theory, and that's not something we can cover on an Arduino site (it's an entire college course all by itself).


How to count the voltage pulses of a digital temperature sensor using Arduino Mega Atmega2560? I have a digital temperature sensor which gives digital output in the form of current pulses. The number of pulses corresponds to a particular temperature.

I have converted the current pulses to voltage pulses using transistor as a level shifter. I want to count the number of pulses for a time interval of 50ms each time.

Please help me with the algo and the code.

There are function called pulseIn which probably need exactly what you want.

Just set a variable with the current 'time' (millis, start counting until the current time reaches 50 ms later.

So something like (not checked):

unsigned long timer = millis();
unsigned pulses = 0;
while (timer + 50 < millis())
{
  pulseIn(PIN, LOW);
  pulses++;
}

PIN is a constant or variable that defines the pin number to check, LOW is to check low pulses, you also can use high, and optionally you can add a timeout. For example, you can use the timeout to check the last timeout is within the 50 ms region. Or to be more precise, check if the pulse was within the same 50 ms:

unsigned long timer = millis();
unsigned pulses = 0;
while (timer + 50 < millis())
{
  pulseIn(PIN, LOW);
  if (timer + 50 < millis())
  {
    pulses++;
  }
}


Arduino: how can I stop while() when bluetooth send a data? I have learned Arduino for a month, and I want to bulid a car with 2 modes,
Remote and Auto. Auto mode needs to have while() loop, so it can receive data from sensors. When I choose Auto mode via bluetooth, it keeps looping and it won't stop when I choose the Remote mode. Here's the part code:

char mode;

void loop()
{
    while(serial1.available())
    {
        char control = serial.read();
        if(control == 'r') mode = 'r';     // r stand for Remote Mode
        if(control == 'a') mode = 'a';     // a stand for Auto Mode

        if(mode == 'r') remoteMode(control);

        while(mode = 'a')
        {
            int IR = analogRead(A10);
            float U1cmMsec,U2cmMsec;
            long U1microsec = u1.timing();
            long U2microsec = u2.timing();
            U1cmMsec = u1.convert(U1microsec, Ultrasonic::CM);
            U2cmMsec = u2.convert(U2microsec, Ultrasonic::CM);

            robot(U1cmMsec, U2cmMsec,IR);

            /*
            Here is the code to stop while() that I don't know how
            to program.
            I have tried:

            if(serial1.read() != 'a') break;

            But it will stop while(), because it will waits for
            bluetooth send data to arduino board.
            And if I take this line off, it will keeps while() and
            nothing can stop it.
            So, what am I supposed to do?
            */
        }
    }
}

Your problem is with this line:

while(mode = 'a') {

What you are saying there is not what you think you are saying.  You are confusing = (assignment) with == (comparison).

You are basically saying "While I assign 'a' to the variable 'mode' and 'a' is not 0 ...", which of course will always be true.

Instead you want:

while (mode == 'a') {

or, "While the variable 'mode' contains the letter 'a' ..."

Now you just need to program in some way of changing the value of mode within your while loop.

You can read more on while loops here:

http://hacking.majenko.co.uk/the-while-loop


7 segment with arduino I am getting error with this. It is displaying those segments which are not to be displayed, i.e., 3.141 is dark and other segments are red. And I have checked that the seven segment module I am having is common anode type only.

#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {2, 3, 4, 5};
    byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
    sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(1000);
}

void loop() {
    sevseg.setNumber(3141, 3);
    sevseg.refreshDisplay(); // Must run repeatedly
}

If you use this library, then use

sevseg.begin(P_TRANSISTORS, numDigits, digitPins, segmentPins);


Any chance of repairing Mega 2560? So I decided it would be a good idea to flash a firmware onto my mega 2560 for a project. I ended up flashing the wrong side of the ICSP header (one near the usb plug/ M16U2) and killed my arduino for the most part. I'm a newb for the most part when it comes to this. I plug it in and the 'L' light is on with the 'ON' light as well. Wont show up in device manager, can't load sketches and can't get into DFU mode.(REV3 has DFU right?)

I have both a usbasp and USBtinyisp programmer and have tried 5 - 10 firmwares on both sides of the headers in hopes I can get it to work again.Literally almost tried everything I could find to get it to flash back. One guide I did find that got me somewhere was this though:

http://forum.arduino.cc/index.php?topic=96706.0

It appears to flash correctly with whatever firmware I use, but cannot pull the firmware off it to check or do the rest of what it says.My guess is that 1 or 2 of the firmware's are gone. Have erased the firmware/relfashed and tried to flash in the IDE with no luck in it working.

I did use this command to read the firmware(or lack of) on both sides of the header to get a better idea of what might be going on:

M16U2/M2560

I don't know if I'm supposed to flash one side first then the other or flashing one will be able to do both at the same time. Here is an example of how I would flash from avrdude:

avrdude -C avrdude.conf -P usb -p m16u2 -b 1200 -c usbasp flash:w:Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m -U efuse:w:0xF4:m -U lock:w:0x0F:m

With each side I would set the correct the fuses from what that file pulled up. So if anyone knows what I'm doing wrong for why it is not working I'd appreciate the help. Just don't know if I can save this or it's gonna end up in the garbage.Thanks

http://altlab.org/d/m/jpralves/recover_atmega2560/

Change fuses/firmware depending on which side you are flashing (M2560/M16U2)

Firmwares: Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex / stk500boot_v2_mega2560.hex

1st command:

avrdude -C avrdude.conf -P usb -p m16U2 -b 57600 -c usbtiny -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m -U efuse:w:0xF4:m -U lock:w:0x0F:m

2nd command:

avrdude -c usbtiny -p m16U2 -P usb -b 115200 -V -U flash:w:Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex

3rd command:

avrdude -c usbtiny -p m16U2 -P usb -b 115200 -U lock:w:0x0F:m

http://pastebin.ca/3178420


Can I connect a NEO-6M GPS Module and ESP8266 to the same Arduino? Can I connect a NEO-6M GPS Module and ESP8266 to the same Arduino? I think both modules require the use of the RX and TX pins.

You can use Software serial for this.

and assign pins like
SoftwareSerial mySerial(2, 3); // RX, TX

This is a link for better understanding https://www.arduino.cc/en/Tutorial/SoftwareSerialExample


Wrong analog reading I am making a simple Li-Ion battery Tester. Basically its two 5R1 resistor in series and a relay (used to cut off the battery when it reaches cutoff voltage). Arduino is connected with ground to the battery and with A3 to the end of the resistors. But when I try to read the analog value, I receive something like 870, which is about 4.24V. BUT the real voltage is about 3.90V (according to my multimeter). How is that possible? Thanks for any suggestions.

I have found the answer. I am not an arduino-newbie, but I was thinking that probably I am making a stupid mistake somewhere. But the problem is in my arduino. I tried setting pin D13 (and then all other pins) to HIGH, and I only measured 4.60V! I measured my USB port and it outputs 5.00V exactly, so there must be a problem in the arduino. So the solution - the ADC takes 4.60V as 1023, and therefore if you calculate it you get that the real voltage is 3.90V, which is exactly the same as my DMM said. Thanks Majenko, you were pointing the right way :) By the way, I was using a cheap Arduino Nano from China, I bought it only for 2.2 USD from Ebay. When I used original Arduino, the code and circuit perfectly works. Do you think that this can limit the functionality of my board?


force the state of the output i have one input and buzzeer output and reset pushbutton if the input is high the buzzer will be on and i want to turn off the buzzer by the pushbutton even if the input still high
any suggestions to do this
in my code the buzzer is not working at all
int in1 =     2; //input
int in26 =   8;// for buzzer reset
int BUZZER_PIN = 52   ; // output for buzzer out 25
int buttonState1 =  0;  //state for input1
int buttonState26 =  0; //for buzzer reset
bool buzzer_is_on;  // state variable
void setup() {
  pinMode(in1 , INPUT);
  pinMode(in26 , INPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  digitalWrite(BUZZER_PIN, LOW); // buzzer LOW

}

void loop() {

  buttonState1 = digitalRead(in1);
  buttonState26 = digitalRead(in26);

  bool input_rises = (buttonState1 == HIGH);
  bool reset_pressed = (buttonState26 == HIGH);

  if (buzzer_is_on) {
    if (reset_pressed) {
      digitalWrite(BUZZER_PIN, LOW);
      buzzer_is_on = false;
    }

  }
  else {  // buzzer is off
    if (input_rises) {
      digitalWrite(BUZZER_PIN, HIGH);
      buzzer_is_on = true;
    }
  }
}

I may have a personal bias for the concept of finite state
machine. I find that some many problems become so easy when ween
approached from this perspective...
Let me rephrase your requirements, just to make sure I understood
correctly:

If the buzzer is OFF:

it should turn ON if the input rises (goes from LOW to HIGH)

If the buzzer is ON:

it should turn OFF if the input falls (goes from HIGH to LOW)
it should also turn OFF if the reset button is pressed

Or, as a state diagram:

Or, as code:
bool buzzer_is_on;  // state variable

void loop() {
    bool input_rises = ...:
    bool input_falls = ...;
    bool reset_pressed = ...;
    if (buzzer_is_on) {
        if (input_falls || reset_pressed) {
            digitalWrite(BUZZER_PIN, LOW);
            buzzer_is_on = false;
        }
    } else {  // buzzer is off
        if (input_rises) {
            digitalWrite(BUZZER_PIN, HIGH);
            buzzer_is_on = true;
        }
    }
}

Now, the trick (which I leave as an exercise), is to properly detect
when the input rises. This is not the same as the input being HIGH: if
the user presses reset, the buzzer should turn OFF, but it should also
stay OFF, even though the input remains HIGH. Hint: you not only have
to read the input, you also have to remember the state you saw the
previous time you read it. Or you can search “edge detection”.
Note that you do not need edge detection for the other transitions: you
can turn the buzzer OFF when the input goes LOW, but you can also turn
it OFF when the input is LOW. It should not make a difference.


Arduino serial port implementation It might be an obvious answer to this, but I can't find it via a quick google search. To give my question a bit of more context, I'm writing an application which simulates a communication with Arduino via serial port, therefore I need to know how it is implemented internally.

From my previous experience with micro-controllers, the serial port is normally presented in micro-controller as two separate queues, one for TX and another for RX. For transmit out of MC, my software writes a byte to the end of transmit queue, and MC hardware reads byte from the beginning of the queue, converts it to bits, and toggles the pin to transmit data/parity/stop bits. And it keep doing that until queue is exhausted. The opposite happens for receive queue.

Am I right in assuming that Arduino has similar implementation with two separate queues? In particular, I want to read and write to serial port simultaneously.

Yes. Arduino has two buffers. See the HardwareSerial.h and HardwareSerial.cpp


How to measure water turbidity with arduino I would like to measure water turbidity in the sea. The sensor does not need to measure it in an accurate way, I just need to know if water is clear or very turbided. I know that there could be used a light scatter but I do not know what kind of sensor should I use. Could anyone help how to measure turbidity?

http://uk.farnell.com/ams/tsl257-lf/sensor-light-voltage-converter/dp/1226886
is a good one according to http://forum.arduino.cc/index.php?topic=299993.0

But it might be easier to buy a COTS sensor, its a bit more expensive but much easier.  http://www.aliexpress.com/item/Turbidity-Testing-Sensor-Module-Suite/1903197650.html?spm=2114.01010208.3.17.OSVwdj&ws_ab_test=searchweb201556_9,searchweb201602_2_10017_9868_10005_10006_10034_10021_507_10022_10020_1000020_10018_10019,searchweb201603_8&btsid=6dbcca61-3e0a-4e34-9359-a6c26b268509

BTW for everyone else Turbidity is the amount of muck in the water, so it would be no good looking at the crystal clear waters off the UK coast :)


Arduino: Record value of the encoder only once at the instant the PS2 joystick reads 128 (when at rest) I'm working on a project where I need my arduino to detect the value of encoder at the instant the reading of the joystick change to 128.  When the joystick is at rest, the reading is 128 which also means, my robot will hold its position/brake. Values above or below 128 correspond to the motor moving forward or backward.

I actually want to record the encoder value exactly at the first instant my arduino reads 128, so that I can apply PID position control so that my robot can brake or hold its position against gravity. The first instant when the joystick reads 128, that is the encoder value that I'd like to set as the Setpoint.

Here's some explanations for implementing PID in Arduino.
http://playground.arduino.cc/Code/PIDLibraryConstructor

For instance the joystick readings go from 140, 137, 131, [128], 128, 128, 133, 139, 131, [128], 128 and at the same time, the encoder gives out corresponding values. I need the encoder values at the Joystick value of 128 in the square bracket, [] in the example above.

If I use the code below, it will just run the statements in {} whenever it sees 128, which is not what I want. FYI, the motor sometimes tend to backdrive, and this gives different encoder value also at 128. What I only need is the first encoder value at the first reading of 128 whenever I encounter it.

void loop()
{

  int pwmSpeed;

  int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

  Input = encoder0Pos;

  if (Y_axis == 128)
  {

    Setpoint = encoder0Pos;
    myPID.Compute();
    analogWrite(pwm, Output);

  }

  else if (Y_axis > 128)
  {
    pwmSpeed = Y_axis;
    digitalWrite(dir,HIGH);           // set DIR pin HIGH or LOW
    analogWrite(pwm, pwmSpeed);            //analogWrite(pin, value)
  }
  else
  {
    pwmSpeed = abs(Y_axis-255);
    digitalWrite(dir, LOW);
    analogWrite(pwm, pwmSpeed);

  }

}

Thanks.

//New edited code is shown below:

What do you think of the code? Did I do it correctly? I will test it once I get back to the lab.

If 128 is detected, encoder value is stored in Setpoint and then Pid.compute() is executed for as long as 128 is detected. For this duration, Pid.compute() will compute the error = Setpoint - Input and use Pid formula to calculate the Output that can be found in the analogWrite(pwm, Output). Motor will work to maintain its position at Setpoint.

However if other than 128 is encountered, it will just execute the 'else if' and 'else' statement to move the robot forward or backward.

global g_detect128 = false;

void setup()
    {
//any code here
    }

void loop()
{

  int pwmSpeed;
  int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

  Input = encoder0Pos;

 if (!g_detect128 && Y_axis == 128)
    {
    Setpoint = encoder0Pos;
    g_detect128 = true;
    }

  if (Y_axis == 128)
  {

    myPID.Compute();
    analogWrite(pwm, Output);

  }

  else if (Y_axis > 128)
  {
    pwmSpeed = Y_axis;
    digitalWrite(dir,HIGH);           // set DIR pin HIGH or LOW
    analogWrite(pwm, pwmSpeed);            //analogWrite(pin, value)
  }
  else
  {
    pwmSpeed = abs(Y_axis-255);
    digitalWrite(dir, LOW);
    analogWrite(pwm, pwmSpeed);

  }

 if(Y_axis != 128)
    {
    g_detect128 = false;
    }

}

If you only want to catch this event once - when it first hits 128, you just need a global variable to flag when you've seen it:

boolean g_bSeen128 = false;

void setup()
{
    // ... whatever
}

void loop()
{
    // ... your existing code

    // catch first time we see 128
    if (!g_bSeen128 && Y_axis == 128)
    {
        // ... do whatever you need here. e.g.
        Setpoint = encoder0Pos;
        myPID.Compute();
        analogWrite(pwm, Output);

        // stop the event being caught next time
        g_bSeen128 = true;
    }

    // from comments below - to just ignore consecutive 128's, add this:
    if (Y_axis != 128) g_bSeen128 = false;

    // ... your existing code

}

If you only want to do something if the input changes, no matter what it is, you can keep track of the last input:

int g_nLastInput = -1;

void setup()
{
    // ... whatever
}

void loop()
{
    // get input
    int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

    // if input has changed ...
    if (Y_axis != g_nLastInput)
    {
        // ... save latest input
        g_nLastInput = Y_axis;

        // now process the change, e.g.
        if (Y_axis == 128)
        {
            // ... do something special for 128
        }
        else
        {
            // ... do something else for other inputs
        }
    }
}

I'm not sure what you're trying to do with the PWM when you get inputs either side of 128, it seems to me that you might want to go in one direction if the input is less than 128 and go in the other direction if it's greater than 128. In either case, the magnitude of your PWM speed should just reflect how far you are from 128 in either direction. So subtracting 128 from your input will give a delta that is +/- 128 and we can scale its absolute value to 0..255 for the PWM setting.

If that's correct, an alternative way of coding your original logic might be like this:

void loop()
{
    // get input
    int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

    Input = encoder0Pos;

    // if input has changed ...
    if (Y_axis != g_nLastInput)
    {
        // ... save latest input
        g_nLastInput = Y_axis;

        // now process the change
        int nDelta = Y_axis - 128;

        if (nDelta == 0)
        {
            // i.e. Y_axis is 128
            Setpoint = encoder0Pos;
            myPID.Compute();
            analogWrite(pwm, Output);
        }
        else
        {
            // choose direction
            digitalWrite(dir, (nDelta > 0) ? HIGH : LOW);

            // set PWM speed scaled to 0..255
            analogWrite(pwm, abs(nDelta) * 2);
        }
    }
}


Burn bootloader into Arduino UNO from Arduino Duemilanove I have been working with my Arduino UNO for 2-3 hours and after that it was not possible to load sketchs into the board since it returns a

  "avrdude: stk500_recv(): programmer is not responding" error.

The internal led "L" of the board is permanently on.

After a little research I guess that the bootloader was corrupted at some point (I still don't understand when and how).

Q: Apart from this board I have an Arduino Duemilanove board and I would like to know if it is possible to use this Duemilanove board to burn the bootloader in the broken board, is this possible? in afirmative case, how?

Since all the examples over there shows how to do it with the same board and not with a different one.

Yes, Nick Gammon has a page on doing that here  https://www.gammon.com.au/bootloader


MAX30100 not working I am unable to get the MAX30100 sensor to work
It keeps throwing the following error:
16:06:32.936 -> Initializing...
16:06:32.936 -> MAX30105 was not found. Please check wiring/power.

I am using the Sparkfun library Example sketch "Example5_HeartRate"
As far as I understand the breakout board for the MAX30100 is a bit buggy -
By which I mean the internal pullup resistors are connected to 1.8V for some reason instead of 5V
I have used MAX30100 before and had faced the same issue. However, after scouring the internet for hours  I found this helpful article: https://reedpaper.wordpress.com/2018/08/22/pulse-oximeter-max30100-max30102-how-to-fix-wrong-board/
I want to use another MAX30100 sensor and have followed the above article again and have done the said changes to my sensor which resulted in the board being detected at address 0x57 when I run the i2c scanner. However, unlike the previous time, the Example sketch did not run as expected.
I even tried this solution:
https://github.com/oxullo/Arduino-MAX30100/issues/51#issuecomment-391193292
But kept receiving the same error message.
The pin connections are:
ARDUINO -> MAX30100/MAX300102
3V3     ->    VIN
SDA (A4)->    SDA\
SCL (A5)->    SCL
GND     ->    GND
I need help asap.
Thank you in advance!
I hope the links mentioned are helpful for someone else.

Check out this link. I guess it will work I had the same MAX30100 module what i did was removed those 4.7k resistors mounted through hole resistors on breadboard and pull-uped them using 5V and it was working fine for me


Powering Motor shield and Arduino Mega Separately I'm trying to build a fire fighting robot, that uses 2 BO DC motors, 2 Servos - MG996R and SG90. For them I'm using Motor Shield v1 of Adafruit's make that uses 2 L293D IC's and a 74HC595 shift registers.

Now, I'm placing the motor shield over Arduino Mega and trying to connect other components such as Flame Sensor, Ultrasonic Sensor and submersible DC Water Pump.
As soon as I try to power up ultrasonic sensor, the power indicating LED's on both the shield and Mega goes off.

I've been testing this with simple USB connected power supply and to my understanding the power being supplied is insufficient.
Since it would be a moving cart, I would like to know whether there is any way to power up Shield and Mega separately by a 9v Battery?

On the side of the DC Motor Shield v1, there is an external power - +  2 pin terminal.

This can be used to supplement the shield with power.

Adafruit: "The motor controllers on this shield are designed to run from 4.5V to 25V.
MOST 1.5-3V MOTORS WILL NOT WORK"

If you are lucky to have the motor specs and ratings on hand, you will be able to account for how much power your motor(s) will need in your application.

Adafruit: "The motor driver chips that come with the kit are designed to provide up to 600 mA per motor, with 1.2A peak current. Note that once you head towards 1A you'll probably want to put a heatsink on the motor driver, otherwise you will get thermal failure, possibly burning out the chip."

Here is an important tid-bit for your scenario... (So no 9v Batteries for the motors!):

Adafruit: "You can't run motors off of a 9V battery so don't even waste your time/batteries! Use a big Lead Acid or NiMH battery pack. Its also very much suggested that you set up two power supplies (split supply) one for the Arduino and one for the motors. 99% of 'weird motor problems' are due to noise on the power line from sharing power supplies and/or not having a powerful enough supply!"

...

So makes sense,  get the Arduino powered, by itself, then get another power source for your motor shield.

Your sensors might be able to hop on the Arduino power supply if it's providing enough power.  I'd keep them separate from the motor power line, due to noise interference as suggested.

Try this, and see if the Arduino stays powered.

There is a lot of helpful info here, some new things I've learned just now.
https://learn.adafruit.com/adafruit-motor-shield/power-requirements


Bluetooth transfer problem with big files I want to send some data from an Arduino Mega to an android device via bluetooth (HC-06). I have installed some sensors whose values are frequently written in an SD card. Every time a new string line is added in a text file of the SD card. This is the format of the line

27/5/2015,11:55:00,34.00,27.00,42.50,26.80,47.80,26.00,24.62,24.12,26,0,0,708,1023,1023,1023,1023,10.5,10.5,10.5,10.5

and this is part of the code. I send from a bluetooth terminal the string "download" and after that the text file is opened and every line is readed and sent to the android device via bluetooth.

void loop(void){
    while(Serial1.available()) {
       character = Serial1.read();
       content.concat(character);
     }

if (content == "download") {
    Serial.println(content);
    content = "";
    read_from_SD_Card();
    }
    ........................
    ........................
    ........................
}

void read_from_SD_Card(){
    myFile = SD.open("test.txt");
    if (myFile) {
        Serial1.println("test.txt:");

        while (myFile.available()) {
            Serial1.write(myFile.read());
      }
      myFile.close();
    }
else {
  Serial1.println("error opening test.txt");
  }
}

The problems are:

the data are downloaded only after an upload of the sketch has been done. (I can't upload the sketch once and download the data from time to time)
No more than 10-20 lines can be downloaded. With bigger files the downloading seems to slow down and finally stops after a few lines.

Any thoughts would be appreciated.

I suspect that this is a String class heap-fragementation issue (again). To test this you could sending a fixed string buffer (vector of characters, "Hello world" :). Do not use String and SD/FAT in the test. Just send a large number of lines with dummy data.

If this works replace the String usage with a character buffer. Fill it from the SD file (buffer size at a time) and write to Serial.

Cheers!


Post Data To a Web Service From Arduino If you want to submit sensor data such as temperature to a remote server/database somewhere you need to use some kind of call to a web server since it isn't possible to connect directly to a database from the Arduino.

How do you post data to a JSON web service from an Arduino that's connected to the Internet?

There is the aJson library that allows you to work with JSON objects in Arduino.

However, depending on the complexity of your program, I would just do it manually to save memory. You may be able to just copy the functions you want out of the library.

Then check out the WebClient library which has an example for making a POST request at the bottom.


Hardware serial not working, SoftwareSerial is On my Uno-equivalent Arduino, a SoftwareSerial connection (on RX, TX = 8, 9) is working*, while a hardware serial connection to the same device, set up in the same way (but on pins RX, TX = 0, 1) is not working. Why is the hardware serial setup not working?

*By working I mean receiving a byte from the external device

Edit: as a simple example:

void setup() {
  Serial.begin(38000);
  pinMode(7, OUTPUT);
}

void draw() {
  if (Serial.available() > 0) {
    Serial.read();
    tone(7, 440, 1000);
  }
}

The above, using Serial, doesn't work, whereas

#include <SoftwareSerial.h>

SoftwareSerial serial(8, 9);

void setup() {
  serial.begin(38000);
  pinMode(7, OUTPUT);
}

void draw() {
  if (serial.available() > 0) {
    serial.read();
    tone(7, 440, 1000);
  }
}

does work.

I don't know if this helps, but connecting RX/TX through an LED to ground gave me the following, using Serial on (0, 1) and SoftwareSerial on (8, 9):

Serial
RX: bright
TX: bright
SoftwareSerial
RX: dim (but still lit)
TX: bright

Is the fact that RX is dim using SoftwareSerial significant?

There may be several reasons

Be sure uC pin connect pin header
In setup part, you write Serial.begin(xxxx);
After serial begin, don't change this pins IO features(Input, output)

Please check that after if not solve, please share code


Problem in SIM900 GPRS connection I make simple code to read web page by ITEAD Gboard. Here is my code:

  Serial.write("\nStarting..........\n");
  mySerial.print("AT+CSQ");
  delay(1000);

  while(mySerial.available()!=0)
    Serial.write(mySerial.read());

  Serial.write("\n-----1-----\n");

  mySerial.println("AT+CGATT=1");
  delay(1000);

  while(mySerial.available()!=0)
    Serial.write(mySerial.read());

  Serial.write("\n-----2-----\n");

  mySerial.println("AT+CGATT?");
  delay(1000);

  while(mySerial.available()!=0)
    Serial.write(mySerial.read());

  Serial.write("\n-----3-----\n");

  mySerial.print("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
  delay(1000);

  while(mySerial.available()!=0)
    Serial.write(mySerial.read());

  Serial.write("\n-----4-----\n");

  mySerial.print("AT+SAPBR=3,1,\"APN\",\"internet\"");
  delay(2000);

  while(mySerial.available()!=0)
    Serial.write(mySerial.read());

  Serial.write("\n-----5-----\n");

  mySerial.print("AT+SAPBR=1,1");
  delay(1000);

  while(mySerial.available()!=0)
    Serial.write(mySerial.read());

  Serial.write("\n-----6-----\n");

  mySerial.print("AT+HTTPINIT");
  delay(1000);

  while(mySerial.available()!=0)
    Serial.write(mySerial.read());

  Serial.write("\n-----7-----\n");

  mySerial.print("AT+HTTPPARA=\"URL\",\"xx.xx.xx.xx/my/web/site\"");
  delay(1000);

  while(mySerial.available()!=0)
    Serial.write(mySerial.read());

  Serial.write("\n-----8-----\n");

  mySerial.print("AT+HTTPDATA=100,1000");
  delay(10000);

  while(mySerial.available()!=0)
    Serial.write(mySerial.read());

  Serial.write("\n-----9-----\n");

  mySerial.println("AT+HTTPREAD");
  delay(1000);

  while(mySerial.available()!=0)
    Serial.write(mySerial.read());

  Serial.write("\nend.\n");

Which i get the following output:

Starting..........
AT+CSQ
-----1-----
AT+CGATT=1

ERROR

-----2-----
AT+CGATT?

+CGATT: 1

OK

-----3-----
AT+SAPBR=3,1,"CONTYPE","GPRS"
-----4-----
AT+SAPBR=3,1,"APN","internet"
-----5-----
AT+SAPBR=1,1
-----6-----
AT+HTTPINIT
-----7-----
AT+HTTPPARA="URL","xx.xx.xx.xx/my/web/site"
-----8-----
AT+HTTPDATA=100,1000
-----9-----
AT+HTTPREAD

ERROR

end.

AT+HTTPREAD return error. What wrong with me?

Note

xx.xx.xx.xx/my/web/site is my web page. The error is still there for all web page.

The problem (I believe) is that half way through your program you switched from using println() to using print(), thus the commands from that point on aren't being executed until right at the end where you switch back to println(), so the whole of the text you send from point 3 onwards is being run as one single command - which of course is in the wrong format:

  AT+SAPBR=3,1,"CONTYPE","GPRS"AT+SAPBR=3,1,"APN","internet"AT+SAPBR=1,1AT+HTTPINITAT+HTTPPARA="URL","xx.xx.xx.xx/my/web/site"AT+HTTPDATA=100,1000AT+HTTPREAD


How can I upload a sketch remotely from a distant location onto an arduino that is power by a battery Of course after developing a success full embedded product the next step would be making upgrades to compete favorably with new products in the market. Well making upgrades would require making adjustments in the sketch and Uploading it onto already made prototypes to cub the costs involved in by the hardware of a remotely located prototype. How can one upload a sketch from his location on to the prototype without going there psychically to upload through the port?

Battery powered devices need a system where the device checks over Internet connection (WiFi, mobile) if a new firmware bin file is available on a specific location on a server. If the bin file is available the device can download it and apply.

One option how to apply the new bin is to use SD card and SD bootloader (Zevero avr_boot) The sketch saves the downloaded file on SD card and resets the MCU. The SD bootloader then loads the binary from the SD card to flash.

Other option if enough free flash memory is available is to use the InternalStorage object from ArduinoOTA library. It uses the upper half of the flash memory to store the uploaded bin and then activates a modified Optiboot to copy the bin to run location and reset the MCU.


DC Motor doesn't turn and a beep sound is made, also there is a burning smell I was trying to drive a single dc motor with L293D Shield and Arduino Uno

#include <AFMotor.h>
#include <SoftwareSerial.h>

AF_DCMotor motorLeft(3);
AF_DCMotor motorRight(2);

unsigned char opMode = 0;

void setup()
{

}

void loop()
{
motorLeft.setSpeed(30);
motorLeft.run(FORWARD);
delay(5000);
motorLeft.setSpeed(0);
motorLeft.run(RELEASE);
delay(5000);
}

When I turned the power on, a beep sound was made continously. As I was trying to figure out where the sound comes from, I smelled something burning and turned the power off.

I am giving 6V (Four 1.5V  batteries in series) as external power. Burning smell doesn't come from batteries, that's for sure.

The smell comes from arduino or shield or both. But I think it is the the left LM293D driver.

What did I do wrong? Any idea?

Alright, I finally realized that RPM value was too low. It has to be at least 150 for my case.


Do I need a resistor to control a servo with a PWM signal? I working with Arduino Nano Every that has several analog PWM pins. I want to use one to control a small servo.
Do I need to put a resistor between PWM pin and the servo signal?

No, you don't.
Resistors are used to limit and control current (amongst other things) and you don't need to do that when sending a signal from one digital device to another.


How to copy files from Yun to local computer? I would like to copy a file that is in the root folder of my Yun, to my Macbook. They are connected with an ethernet cable and I am logged into the Yun through ssh.
The Yun's IP is 192.168.2.16 while the Mac's is 192.168.2.1.

How can I copy a file from the Yun?

Once I tried to copy a file from the Macbook to the Yun using "scp" and it worked, but now I don't know how to do for the other direction

You simply reverse the arguments.  Whatever you used to copy a file to the Yun you just do the opposite to copy from the Yun.

For instance, if you copied to the Yun using:

scp /my/local/file root@192.168.2.16:/where/you/want/it

Then you would change it around to copy from the Yun thus:

scp root@192.168.2.16:/path/to/file /where/you/want/it/to/go


ESP8266 disconnects after few hours My system looks like this:

ESP8266 is connected to Arduino Uno (2, 3 pins) and a relay's data input to Arduino's pin 12 and power for relay is provided from another source.

Arduino gets data from server and switches on/off relay according to that signal. This system works perfectly for few hours and then suddenly crashes. In my WiFi console I have:

  wlan0: STA 2c:3a:e8:4e:bf:70 WPA: pairwise key handshake completed
  (RSN) wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated wlan0:
  AP-STA-DISCONNECTED 2c:3a:e8:4e:bf:70 wlan0: STA 2c:3a:e8:4e:bf:70
  IEEE 802.11: disassociated wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11:
  associated wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated
  wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated wlan0: STA
  2c:3a:e8:4e:bf:70 IEEE 802.11: associated wlan0: AP-STA-CONNECTED
  2c:3a:e8:4e:bf:70

I have read this Arduino question, but circuit diagram similar to that one. I get power from my PC to run Arduino.

This is my Arduino code :

#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2, 3); // RX, TX
#endif

char ssid[] = "RPi";            // your network SSID (name)
char pass[] = "raspberry";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "192.168.50.1";

unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10000L; // delay between updates, in milliseconds
int testLED = 12;
// Initialize the Ethernet client object
WiFiEspClient client;

void setup()
{
  pinMode(testLED, OUTPUT);
  // initialize serial for debugging
  Serial.begin(9600);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

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

  //printWifiStatus();
}

void loop()
{
  // if there's incoming data from the net connection send it out the serial port
  // this is for debugging purposes only
  while (client.available()) {
    char c = client.read();
    //code to run relay
    if (c == '#')
    {
      while (client.available() == 0) { } // Do nothing while we wait for the next value

      // reading the second charactor
      c = client.read();
      if (c == '1') {
        Serial.println("On");
        digitalWrite(testLED, HIGH);
        delay(600000);
      }
      else if (c == '0') {
        Serial.println("Off");
        digitalWrite(testLED, LOW);
        delay(600000);
      } //end of C cheking if-else
    }  //end of first charactor # if
    //end of replay code
  }
  // if 10 seconds have passed since your last connection,
  // then connect again and send data
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server
void httpRequest()
{
  Serial.println();

  // close any connection before send a new request
  // this will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");

    // send the HTTP PUT request
    client.println(F("GET /simple.txt HTTP/1.1"));
    client.println(F("Host: localhost"));
    client.println("Connection: close");
    client.println();
    // note the time that the connection was made
    lastConnectionTime = millis();
  }
  else {
    WiFi.begin(ssid, pass);
    Serial.println("Reconnecting again");
  }
}

As long as I know you need at least 170mA to power the esp8266 also you need 100-200mA for the arduino and 100mA for the relay so I recommend to use a 1A power supply and solder some capacitors on the 5V and 3.3V rails. Also if your Wi-Fi is giving a ip address that is limited for certain time for example 1-2 hours you need to expand that time for your needs.If it disconnects the esp will lose its IP address and try to recover for example on my NODE MCU it works well for weeks. It also depends on your library (I am using ESP8266WiFi.h). Anyway I recommend to try the WebServer example for testing if the issue is in your code.


MQ135 output on Arduino Uno I bought an FC-22 (MQ135) gas sensor module which I plugged into my Arduino Uno. I connected it to the A0 analog port. Then created a code that reads the raw data from A0 (code below).

When I run the code on my Arduino Uno in my house I get values of about 30. If I blow over the sensor I get values until about 160. My question is now how I have to read / interpret these values.

According to the MQ135 specifications the sensor has a sesitivity for air quality, measuring benzene, alcohol and smoke.

How can I interpret the values I get? What is a good value and what isn't? Do I have to calculate something out of these values?

My code looks like this:

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop() {
  int sensorValue = analogRead(0);
  Serial.print(sensorValue, DEC);
  delay(100);
  if (sensorValue > 50) {
    digitalWrite(13, HIGH);
  }
  else {
    digitalWrite(13, LOW);
  }
}

According to the datasheet you have to calibrate it.


where to syphon off voltage from a 25 pin serial? I have a mircocontroller that's looking to be powered by a 5v source.

I am trying to 'cypher off' some of this power from a 25 pin serial port, which is being powered by a constant power source.

Are there any pins that could give me that sort of voltage, or enough to power the board?

Please note, I'm not an electrical person at all, and so hope this is actually possible (otherwise my 3 months + program's work doesn't really add to anything).

I've tried a 9v battery, but it didn't seem to hold its charge?

I'm reading these labels going "what the ..." so you can probably tell coding the board wasn't the easiest, either.

Edit History

I would like to clarify this is an existing serial lead
I understand this may be deemed verging off topic, but due to the need to 'power' a microcontroller, I thought this could be answered here
If this isn't possible, (as an alternative, possibly) would a 9V/battery be able to power this board reliably for around 2-3 weeks?

You should be able to use pin 7 for negative, 9 as positive, this gives you 12 volts.

YOU MUST NOT HOOK THIS UP DIRECTLY to the arduino, connect it to a plug for the power jack (right of the USB connection).

If you are using a USB -> serial adapter, then the voltage may be 5v, but don't count on it.

Of course, USB is always going to be better!

PS - if you draw more power than the serial port is rated for, you will probably destroy the card. In most cases, this will be the motherboard. You are unlikely to be able to find out what it is rated for (look for Amps or A, or milliAmps  mA, or microAmps uA). The Arduino (with NO inputs or outputs, and idle) running from a 9v battery will draw about 50 milliAmps.


Why is AREF connected to a capacitor in the Arduino Pro Mini Schematic? I'm currently looking at the Arduino Pro Mini schematic and have noticed that the pin AREF (analogue reference) is connected to a 0.1uF capacitor as shown below:

I have done some research and read this great explanation into AREF and now understand its purpose as a voltage reference. What I do not understand however is the purpose of the capacitor. Is it as a means of stabilising the pin when an external voltage is applied, or something else?

A full schematic of the Arduino Pro Mini can be sourced from here.

On the datasheet for the Atmega328P, in the Analog-to-Digital Converter section, is the sentence:

  The voltage reference may be externally decoupled at the AREF pin by a capacitor for better noise performance.

Also:

  The internal voltage reference may thus be decoupled by an external capacitor at the AREF pin to improve noise immunity.

Thus the capacitor is there to reduce noise on the AREF pin.


Computer to Arduino to hardware, controlling on / off state of hardware via user input on computer First time coding for Arduino. I'm working on code to operate an electronic valve switch. We have a laptop connected to an Arduino Mega, and that Arduino is hooked up to the valve (hardware) on Pin 53.

I was trying to work off of the "blink" example originally, but that gives no basis for user prompted control. Basically I want to have the computer ask me if I should turn it on or off, type in my response (I was using "HIGH" for on and "LOW" for off, as in voltage control), and have that activate or deactivate the hardware.

My main problem right now stems from how best to ask for that input. I've been trying to work with the Messenger.h library thus far. I'm definitely getting hung up on how to define the pin, or what the simplest method for user input would be. (HIGH or LOW? 0 or 1? Something else?)

Code is below. Thanks!

#include <Messenger.h>

Messenger message = Messenger();

// Variable definitions. Switchinput is what the user commands, current state is whether the air is flowing or not.
boolean currentstate;
boolean switchinput;
String pin53; // Something is up on this line?? How to define this pin??

// FUNCTION DEFINITIONS
// Startup fxn
void start()
{
  Serial.print("LOW = off, HIGH = on. Switch is ");
  Serial.println(currentstate);
  Serial.print("Enter LOW to turn on or HIGH to turn off: ");
  switchinput = Serial.read();
}

// Go off to on
void offtoon()
{
    digitalWrite(pin53,HIGH);
    currentstate = switchinput;
}

// Go on to off
void ontooff()
{
    digitalWrite(pin53,LOW);
    currentstate = switchinput;
}

// Stay same -- already off
void staysameoff()
{
  if ((currentstate = switchinput) && (switchinput = LOW))
  {
      void start();
  }
}

// Stay same -- already on
void staysameon()
{
  if ((currentstate = switchinput) && (switchinput = HIGH))
  {
    void start();
  }
}

// Running actual code
void setup()
{
  // initialize digital pin 53 as an output.
  pinMode(pin53, OUTPUT);

  // Sets default state to switch being off (Off = LOW, On = HIGH)
  String currentstate = LOW;
}

void loop()
{
   if ((currentstate != switchinput) && (switchinput = HIGH))
  {
      void offtoon();
  }

  if ((currentstate != switchinput) && (switchinput = LOW))
  {
      void ontooff();
  }

  if ((currentstate = switchinput) && (switchinput = LOW))
  {
      void staysameoff();
  }

  if ((currentstate = switchinput) && (switchinput = HIGH))
  {
      void samestayon();
  }
}

This seems way too complex for your purpose:

you really do not need to do anything to stay in the same state
if you want to switch the valve ON, no need to check whether it's OFF:
there is no harm in switching ON a valve that is already ON.

Here is a simplified version of the program:

void setup()
{
    Serial.begin(9600);
    Serial.println("Type '0' to turn OFF, '1' to turn ON");
}

void loop()
{
    int command = Serial.read();
    if (command == '0') digitalWrite(53, LOW);
    if (command == '1') digitalWrite(53, HIGH);
}

Notice that Serial.read() returns -1 if there is nothing in the input
buffer, and since -1 is neither '0' nor '1', this will not change the
output.

If you want to use more elaborate commands (not single characters), you
may want to take a look at this simple command-line
interpreter. It is intended to be easy to adapt to
different purposes.


Good book/reference for AVR coding in pure C/C++? Can someone recommend a good book/reference for going vanilla (i.e. not using arduino simplified language) on e.g. ATtiny85? I will need to use the equivalents of analogRead() and digitalRead() quite a bit. And is softwareserial the best method for debug output? I have less than 8KB of flash, so any advice on that (and reduction of binary for upload) would also be greatly appreciated.

First, let's make this clear: The Arduino environment does not provide a
“simplified language”: it provides a simple hardware abstraction layer
through its core library. The language is plain C++.

Like Talk2, I don't have good book recommendations. The basics of
low-level programming are covered in the Arduino tutorial on port
manipulation[]. Past this you will have to dig into the datasheet of
your MCU. Look also at the doc of the avr-libc and the tutorials in
Nick Gammon's microprocessors pages.

I would suggest you try to develop your program like this:

Do the initial prototype of your idea on an Arduino Uno (or similar)
using the Arduino libraries. It just makes things easier, and you are
more likely to get a working prototype pretty fast.
Once the initial idea works, optimize it for the limited resources of
the ATtiny85. This may involve replacing some call to the Arduino
libs with avr-libc and/or direct port access.
You may then want to remove all references to Arduino core, but you
don't have to: there are some ATtiny cores available that you can use
if you want.
If it now fits in less than 8 K, port to the ATtiny.

The thing I love about the Arduino environment is that you can very
easily mix and match abstraction levels: you can have, in the same
program, calls to Arduino core, to avr-libc, direct port access, and
even inline assembly if want to. You don't even need to stick to the
setup() and loop() method: you can write your own main() if you
prefer, just remember to call init() to initialize the Arduino core if
you are going to use it. Oh, and you don't have to use the Arduino IDE
either if you don't like it (I don't).

As for the optimization tips, I would recommend :

Use direct port access instead of digitalRead(), because that
function is pretty big and slow.
analogRead() may not be that bad, size wise, but it has a serious
shortcoming: it's a blocking function which spends 104 µs in a
spin loop, just waiting for the ADC result. If your CPU has better
things to do, you may want to implement a non-blocking read instead.
For debugging output, the most efficient option is likely to be the
USI port. You will have to search for a driver or implement your own
based on the Atmel application note AVR307: Half Duplex UART Using
the USI Module. Alternatively, you could use something like
AltSoftSerial. Do not use SoftwareSerial: it blocks interrupts for
insanely long amounts of time.
Use the command avr-nm --size-sort -Crtd my_program.elf to get a
listing of the functions of your program sorted by flash usage. This
will help you choose good targets for size optimization.


Problem with DHT11 and DS18B20 temperature sensors I am trying to connect to my Arduino Uno board two temperature sensors: DHT11 and DS18B20. The problem is with the DHT11 sensor: apparently there's an error with reading the temperature every two measurements.

Here's what I get on the serial monitor (temperature 1 is from the DHT sensor):

As I am new to this, I was wondering what the problem may be. I have read about the one wire interface used by the DS18B20, but I noticed that the DHT is not using the same protocol.

If I use the DHT11 alone, it works perfectly fine.

Also, I am using 4k7 pull-up resistors for both sensors.

Here's the code:

#include <DallasTemperature.h>
#include <OneWire.h>
#include <dht.h>

dht DHT;

#define ONE_WIRE_BUS 8
#define DHT11_PIN 7

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(void) {
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");
  sensors.begin();
}

void loop(void) {
  int chk = DHT.read11(DHT11_PIN);
  sensors.requestTemperatures();
  Serial.print("Temperature1: ");
  Serial.print(DHT.temperature);
  Serial.print(" Temperature 2 : ");
  Serial.println(sensors.getTempCByIndex(0));
}

There appears to be several DHT sensor Arduino libraries available:

niesteszeck/idDHT11
adafruit/TinyDHT
adafruit/DHT-sensor-library

You might try an alternate library to see if that solves your current problem.  Note, some if not all of these libraries need to know which DHT model you are using.

Before going through the DHT and OneWire source code line by line looking for conflicts, try to narrow down what is causing the problem:

Try only instantiating the OneWire class and skip calling the read method within the class.

If this works, then the conflict likely resides in the OneWire read method and not in the OneWire initialization code (that is, the OneWire's Constructor).

Calling the DHT read method multiple times consecutively to see if the problem resolves it self.

Actually, you have done this and exposed a curious patter of good-bad-bad-good-bad-bad... which is worth looking into.  The point here is that if only the 1st call to the DHT read method after a call the the OneWire read method was bad, then there might be a setup problem in the DHT read method.

Call the DHT Destructor, the DHT Constuctor then make the call to the DHT read method every time you read the DHT sensor.

This is a test case only and an extreme measure.  What you are doing here is re-initializing the DHT library (driver) every time you use it.  If this works it points to an initialization problem where the DHT library is initialization something which should probably be re-initialized again inside the DHT read method.  As the OneWire library is using the same "something" (resource).

One last thing, the OneWire example I looked at here:
PaulStoffregen/OneWire
...did not use the DallasTemperature library.  I doubt this will make a difference, but it is usually best to keep your code simple and avoid unnecessary complexities.

Added later...

As pointed out in the comments, it turns out the DHT11 only takes new readings every few seconds.  Guessing, the DHT11 library you are using either knowingly returns an unreasonable value of -999.0 until this time passes.  Or is returning exactly what the DHT11 reports which, again, is an unreasonable value of -999.0.

In this DHT11 library, there is code:

boolean DHT::read(bool force) {
  // Check if sensor was read less than two seconds ago and return early
  // to use last reading.
  uint32_t currenttime = millis();
  if (!force && ((currenttime - _lastreadtime) < 2000)) {
    return _lastresult; // return last correct measurement
}

...which returns the last good value for 2 seconds after a DHT11 "real reading" should the library user call upon it faster then the DHT11 can respond.


Hex to binary, LED blinking I need to write a program that takes a user inputted HEX value and converts it to binary, then an LED blinks according to the number of 1's in the binary. For instance, if the value is 0xABC then there are number of 1's are 7 so LED will blink 7 times.

I only just started Arduino so not sure how to let user input a value nor do I know how to convert HEX to BIN but I'm assuming that once I convert the HEX to BIN I can just use a loop to count the number of 1's yet I'm unsure as to actually how to do that. This is what I've written so far.

  byte val=0xABC;
int ledPin=13;

int countSetBits(unsigned int n)
{
    unsigned int c;
    for (c=0;n>0;n=n&(n-1))
        c++;
    return c;
}

void blink(int n)
{
    for (int i = 0; i < n; i++)
    {
        digitalWrite(ledPin,HIGH);
        delay(500);
        digitalWrite(ledPin, LOW);
        delay(500);
    }
}

void setup()
{
    Serial.begin(9600);
    pinMode(ledPin,OUTPUT);
    blink(countSetBits(val));
}

void loop()
{   }

Any help would be appreciated.
EDIT: If I want to take a number from a user and then make the LED blink according to the number of 1's in its binary form, how would I implement that?

You are almost there. Now you just have to read and parse the hex
numbers supplied by the user.

The simplest way to accept numeric user input is with
Serial.parseInt(). This is not always ideal since it involves blocking
the program until it either receives an invalid character or the reading
times out. It is also not applicable to your situation because it only
works with decimal numbers.

The better standard way to get the input is to put the incoming bytes
into a buffer until you catch a specific character designated as an end
of message marker. This is typically a CR ('\r' in C++) or an LF
('\n'). This technique is more involved than just calling parseInt()
but it is often preferred because it can be done in a non-blocking way.
See for example this simple command line interpreter.

In your case, however, you do not need to buffer the incoming bytes. You
can instead parse the hex number while you read it, like this:

void loop()
{
    if (Serial.available()) {
        static unsigned int val;
        int c = Serial.read();
        if (c >= '0' && c <= '9') {
            val = 16 * val + (c - '0');
        } else if (c >= 'a' && c <= 'f') {
            val = 16 * val + (c - 'a' + 10);
        } else if (c >= 'A' && c <= 'F') {
            val = 16 * val + (c - 'A' + 10);
        } else {  // End of number.
            blink(countSetBits(val));
            val = 0;  // reset for next round
        }
    }
}


Scheduler comparison for Arduino Uno I understand that the official Arduino Scheduler doesn't support Uno, and there are several third-party schedulers to fill the gap, notably, Scheduler, Arduino-Scheduler and TaskScheduler. There are probably many more, though I see that many so-called "task schedulers" are actually just periodic function callers which don't handle context (i.e. they don't support yield()).
I need to make a choice of a scheduler to use in a project (a real one, with yield, not a periodic function caller). Is there any comparison of Arduino task schedulers? I'm specifically interested in the following aspects:

context switching time (the most important one)
RAM/ROM consumption estimation
list of supported boards

I have just tested vbextreme/Scheduler and Arduino-Scheduler using the following code:
#include <Scheduler.h>

void setup() {
  pinMode(3, OUTPUT);
  Scheduler.startLoop(loop2);
}

void loop() {
  digitalWrite(3, LOW);
  yield();
  digitalWrite(3, HIGH);
  yield();
}

void loop2() {
  yield();
}

Without any Scheduler lines, the code occupies 734 bytes of ROM, 9 bytes of RAM, and the pin toggles with a period of 8.5 us (117 kHz). The numbers below represent the additional ROM/RAM/execution time:

vbextreme/Scheduler occupies additional 1676 bytes of ROM, 70 bytes of RAM, and the context switch takes 15.5 us (toggle frequency 14.18 kHz). It seems to only support AVR/SAMD boards.

vbextreme/Scheduler with CONFIG_AVR_OPTIMIZE_COOPERATIVE set to 1 occupies additional 1568 bytes of ROM, 70 bytes of RAM, and the context switch takes 11 us (toggle frequency 19.07 kHz).

Arduino-Scheduler occupies additional 578 bytes of ROM, 44 bytes of RAM, and the context switch takes 10.6 us (toggle frequency 19.59 kHz). It supports AVR/SAMD and some of the Teensy/STM32 boards. It seems that this scheduler is not compatible with tasks which use malloc().

CopyThreads occupies an additional 2148 bytes of ROM, 41 bytes of RAM, and the context switch takes 54.5 us (toggle frequency 4.417 kHz). This scheduler claims to have the advantage of using a single stack, so as long as tasks do not yield during peak stack usage, each task has essentially the complete stack at its disposal.

I couldn't get the equivalent code for TaskScheduler to run, I'll be grateful if someone posts an answer featuring schedulers I didn't test.


I'm pretty sure I fried my Arduino Uno. Given my setup, what caused it to be fried? (I can't identify the short) I was trying to drive a Nema 17 stepper motor using an arduino uno and an A4988 driver. I had it wired up according to this instructable (http://www.instructables.com/id/Drive-a-Stepper-Motor-with-an-Arduino-and-a-A4988-/) at step 2 without the motor power supply wired to the bread board yet. ALSO, I hadn't wired the sleep to reset yet (I just didn't read directions carefully). The board was connected to my computer via USB and I had uploaded the sketch on the instructable to it.

Then, because I misunderstood the directions, I plugged my 12V 8A power supply into the power input on the arduino. All of the sudden, my computer turned off. My computer is fine after restarting, but now the arduino isn't recognized at all by the computer when I plug it in.

Given this information, I am pretty sure that my arduino is fried. However, I can't understand why plugging in the power supply to the power input, which has a voltage regulator, would cause the board to fry.

The Uno is not one "thing" that fails. It has various components, some of which may have failed. I wrote a lengthy page about how to test various parts:

Have I bricked my Arduino Uno? Problems with uploading to board

  I plugged my 12V 8A power supply into the power input on the arduino.

Perhaps you reversed the leads, and shorted the USB power to ground, thus causing the PC to turn off? This would probably also blow most of the components on the Uno because they would have had -12V applied to them, assuming it got past the voltage regulator.

However there is a reverse polarity protection diode on the power input jack. Did you use that or the Vin pin? (or the Vcc pin?)

Note that the reverse polarity protection does not protect you if you use the Vin pin.


What is the difference between Arduino board and Genuino Board? I've got an Arduino UNO REV3 SMD EDITION.

In the Arduino Editor, I've selected Arduino/Genuino Uno.

In a tutorial, I saw Hardware required : Arduino or Genuino Board

What is the difference between Arduino board and Genuino Board?

The name Genuino grew out of the split between Massimo and Gianluca (aided in part by Microsoft of course, and a trademark wrangle that went wrong). Each side wanted to appear to be more "genuine" than the other. That lead to the "Genuino" name (a genuine Arduino), and a version number war with the IDE.

Both sides started making their own variants of boards, with some only available from the USA (Arduino) and others only outside the USA (Genuino).

Since they have patched up their differences now the two boards are one and the same. A Genuino Uno and an Arduino Uno are the exact same board. They always have been, there has just been arguments over the name.


Homemade soil moisture analog value reading jumping from 0 to max I made a soil moisture sensor out of two metal poles, adjustable resistor, for a project I am making. The first run with the project the sensor worked amazing and gave clear and concise readings, 0-800 depending on water. I then unhooked the sensor and left it in the soil while I fine tuned the code (added warnings to the areas that would read to low), and while testing the code without the sensor being hooked up my arduino uno (Sparkfun Pro Mini) would read a value of 330(area). I thought this strange but didnt worry about it.

Well I hooked up my sensor (just power, ground, and to the A1 pin) and now my readout for the readings jump from 0 to 800, 0 to 512, 0 to another random number. I commented out everything in the code BUT the part that sets up the pin and displays the analog reading and its still the same issue. I also checked all my wires, changed the resistor setting, changed to a 10k single resistor, nothing changed.

Does anyone have any idea on what could be wrong?

You are constantly running .5mA through 2 nails in wet earth. What are they made of, that won't undergo some electrolysis in 1/2 hour? Gerben appears to have hit the, er, nail on the head in one, above.

You can avoid this to an extent by using a.c. drive to the probes, which reverses the effect so they only tarnish at about the normal rate for metal X in soil.


What happens if I don't use a relay for 5V pump I am trying to build an automatic watering system by following some examples. However, I don't have all the components for the entire system, therefore I have built it in Fritzing using only the components that I have (see scheme below):

I didn't build the physical version yet, because I am not sure that such a system would work without burning anything. In many examples, people connect the pump to a Relay Module, but since I don't have it yet, I would like to build it like this until I set up the watering system.

Can anyone help me understand why a relay would make it better or worse?

P.S. I have a JPC-3F relay, but I can see that the Relay Module contains multiple components. Is it possible to add the JPC relay to the pump without having the entire Relay Module? Would I need extra components for that?

Thank you!

EDIT: Thanks to the answer from ratchet freak, I have added resistances and a transistor. It works fine, but the same question stands. Do I still need a relay in this case?

You should put a resistor in series with the led to limit the current.

The IO pins cannot source enough current to run the pump without damaging themselves. That's why you need a buffer of some kind.

The extra components in the relay module are a transistor to do the actual switching and a reverse-biased flyback schottky diode in parallel with the relay coil. The flyback diode is required to absorb the voltage spike generated by the coil getting switched off and acting like an inductor.

You can use a transistor to switch the motor directly assuming you can find one that can handle the current draw. If you do then you absolutely will need a flyback diode on the motor to avoid damage to the transistor.


global volatile variable not being updated in ISR Running on atmega168p, I've got an interesting behavior I can't explain. A global volatile var that's called pos over here is not updated as it should. Once I add some code below the assignment, it starts working.

#define ENCODER_DO_NOT_USE_INTERRUPTS
#include <Encoder.h>

Encoder myEnc(A2, A3);

void setup() {
  Serial.begin(115200);
  while (!Serial); Serial.println("Started.");
  PCMSK1 |= bit(PCINT10) | bit(PCINT11) | bit(PCINT12);
  PCIFR  |= bit (PCIF1);   // clear any outstanding interrupts
  PCICR |= bit(PCIE1);
}

volatile int pos  = 0;
int oldpos = 0;

void loop() {
  if (oldpos != pos) {
    oldpos = pos;
    Serial.println(pos);
  }
  delay(100);
}

// PCINT10, PCINT11
ISR(PCINT1_vect) {
  pos = myEnc.read();
  //  adding digitalRead(A0)
  // or even Serial.println(pos) updates the var correctly
}

Switching from int to byte doesn't change anything. Encoder library is https://github.com/PaulStoffregen/Encoder. Any clues?

You are using pos outside of the interrupt without turning the interrupt off.  pos is two bytes, so it takes the Arduino more than one cycle to read in that variable no matter how it is handled.  If an interrupt occurs during that time, you get a corrupted value.

You need to have a cli() and then make a copy of pos to another variable and then a sei() and then use that copy in your calculations in loop.


Power Arduino Over 9V automatically after being disconnected from USB 5V Am wondering if there is some way the Arduino can automatically power itself using through the 9v port in case the USB is disconnected, and afterwards if the USB is connected again it stop feeding from the 9v Input.

there is one way you can make it.
you can use a temporary capacitor(with a voltage output near to 9v)(or a lipo battery) connected to arduino's voltage input pin and 9v battery connected to arduino with a transistor.
whatever program you are uploading to arduino, you can add a code that reads the serial port, and if serial port is not available then it opens the transistor's gate so as the capacitor gets discharged very quickly the 9v battery takes the job.when it gets the serial port again it closes the transistor's gate and arduino stops feeding upon battery and takes power from USB port.


How to read the raw data from GY-85 module? This module has 3 sensors. Gyroscope, Accelerometer and Magnetometer.

I think I'm reading the raw data in the wrong way.

For example, for the magnetometer HMC5883L, I'm using this code which I copied from a library and it gives the correct values, but when I use the same code for reading the raw data from the accelerometer ADXL345 then it's not what it should be according to different sources I've read.

The magnetometer HMC5883L:

void HMC5883L_print_Serial(void)
{
  int16_t x,z,y;
  uint8_t data[6];
  float heading,heading_in_degrees,declination_angle_YANBU;

  data_read(data);

  // This one doesn't
  x = data[1] << 8 | data[0];
  z = data[3] << 8 | data[2];
  y = data[5] << 8 | data[4];

  // This one works OK
  /*x = data[0] << 8 | data[1];
  z = data[2] << 8 | data[3];
  y = data[4] << 8 | data[5];*/

  heading = atan2(y,x);
  declination_angle_YANBU = ((3.0 + (52.0 / 60.0)) / (180 / M_PI));  // in yanbu city it's
  heading += declination_angle_YANBU;

  // Correct for heading < 0deg and heading > 360deg
  if (heading < 0){
    heading += 2 * PI;
  }

  if (heading > 2 * PI){
    heading -= 2 * PI;
  }

  heading_in_degrees = heading * 180 / M_PI;
  Serial.println(heading_in_degrees);
  _delay_ms(20);

}

The accelerometer ADXL345

void ADXL345_print_Serial(void){
  int16_t x,z,y;
  uint8_t data[6];

  ADXL345_read_raw(data);

  // This one gives values from -255 to +255
  x = data[1] << 8 | data[0];
  z = data[3] << 8 | data[2];
  y = data[5] << 8 | data[4];

  // This one give values from -32768 to +32768
  /*x = data[0] << 8 | data[1];
  z = data[2] << 8 | data[3];
  y = data[4] << 8 | data[5];*/
    Serial.print(x);Serial.print("\t");
    Serial.print(y);Serial.print("\t");
    Serial.println(z);
    _delay_ms(100);
}

So basically I want to learn how to work with these sensors and also I want to know the principles about each one, because I'm confused between then I feel they are the same and each one provides similar functions; like, tilt sensing.

One of the places where the datasheets for the sensors of the GY-85 module can be found is here: https://www.hotmcu.com/gy85-9dof-imu-sensor-module-p-298.html
The following information comes from these datasheets:

Both the HMC5883L and the ADXL345 have internal registers which are numbered consecutively. When reading more than one register they are most efficiently read in the order they are numbered. For each of the three axes both sensors use two 8-bit registers to hold the measured value.

In the HMC5883L the register with the lower number holds the most significant byte (MSB) and the register with the higher number holds the least significant byte (LSB). This means that in a consecutive read the MSB is read first followed bij the LSB. When you combine these two bytes into one 16 bit number (datatype int) you have to shift the MSB-holding byte (the first byte received) 8 places to the left and "OR-in" the LSB-holding byte (the second byte received).
In the ADXL345 the internal numbering is the other way around: the register with the lower number holds the LSB and the register with the higher nummer holds the MSB. When reading, the LSB is red first followed by the MSB. So this time you have to shift the second byte received and "OR-in" the first byte received.

Both sensors give the measured value as a 16-bit 2-complement number, corresponding to datatype int (Arduino Uno). An 16-bit int can hold values from -32,768 to +32,767 but the sensors don't (can't) use this full range:
The ADXL345 has an adjustable range with a maximum of 13 bits (-4096 to +4095).
The HMC5883L has a range of 12 bits (-2048 to +2047).


MCU Recommendations for Audio Pitch Shifting I'm looking to use a MCU for audio sampling. I want to sample incoming audio and pitch shift it (without speeding it up/slowing it down). A bit about the build. I'm planning to make a circuit board that can take in a single audio source and output three or four different pitch-shifted sounds in real time, with each output being its own pitch-shifted sound. If possible, I would like to have a potentiometer for each output that could in effect change how pitch shifted each output is, sort've of like a tuning knob. These outputs will eventually get summed together to produce a chord-like sound.
I'm not quite sure what exact requirements are needed for this, just that the sampling rate should be around 44KHz (standard audio sampling rate). Of course, I would like the outputs to replicate the original sound as much as possible, just pitch-shifted. I am assuming as well that the way I pitch-shift and sample could affect the requirements. Also, I would like to avoid SMT if I can.
Given these requirements, what do you suggest the best MCU to use is? I would like to use Arduino to program the MCU. I really only need the chip itself (I think?), as I plan to create a separate circuit board for this (although would I need an Arduino board to initially program the chip?)
I'm fairly new to the Arduino world, so apologies in advance if I miss something obvious or mess up terminology. I do come from a background in analog circuitry and programming though. Just looking for as much help as I can get from people who know more than me but am eager to learn about this all.
Thanks!

I get the impression that you haven't done this sort of thing before, on any scale. Pitch shifting is a totally non-trivial process.  I suggest you start out on a regular computer and try to get a single channel working to your satisfaction.  Then, if you are still determined to do this on a smaller system, you will at least know what you are up against and will be able to decide what systems are appropriate.  Sorry if it sounds like I'm trying to throw cold water on your idea, because I'm sure it would be a fun instrument to play.  But I think you would be getting in way over your head if this isn't already your field of expertise.


User configuration file does not exist or is not a regular file, skipping I am facing issues while uploading sketch to Adafruit Feature 32u4 Bluefruit LE devices. When i try to upload Blink demo it was working fine and my device also blinking, But bellow error i am getting every time when i upload sketch.

   System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
     User configuration file is "/Users/myMacmnin/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

I am using Adafruit Feature 32u4 Bluefruit Le device,Arduion 1.8.3 version, MacMini with macOs Sierra(10.12.3).

Finally i found answer for my question, It happen because of uploading sketch in selected pin.

// Neopixel
//#define PIN            6   /* Pin used to drive the NeoPixels */
#define PIN            13   /* Pin used to drive the NeoPixels */

I Changed Pin 6 to 13 , it's worked for me.


Computer to multiple arduino bluetooth modules Im going to take part in a competition called IEEE Very Small Soccer and I need to set up a communication between my computer, that will run visual and strategy algorithms, and send some commands to 3 Arduinos, which will be the players. Most people use the Xbee module to send data to the Arduinos, so I was wondering why not use the Bluetooth module instead, once it is so much cheaper and the difference in power consumption isn't so big, the only drawback would be the working range, which is 10m, if Im correct... However, if the distance is really 10m, not 5m It will be ok, because the computer is always close to the robots.
Summing up, my questions are:

Can I use a computer to send data to 3 Arduinos at the same time?
What is the real working range of the Bluetooth module?
Any suggestions or tips? =D

?

yes, you can, this is what happens normally in a crowded area where multiple people use their phones with bluetooth headsets, for example.
if you believe the claims typical 10m max 100m but in practice there are a number of factors:

Quality of the HW design of the antennas
Signal to noise ratio due to other radios operating in the same area
Obstacles in the path
Responsiveness and throughput required by your application
etc.

you could consider other options, like this module, which is basically the same, from the perspective of transferring data. Also wifi could work, if you are allowed to setup your own access point.


How to calculate the RZERO value in MQ135 sensor, I have already burned it for 24 hours? I've already burned it for 24 hours and it is now giving the constant value of 932.36,pls tell me how to calculate the RZERO value.

From the datasheet here --->MQ135 datasheet, It is the value of Sensing resistor at 100 PPM of Ammonia(NH3) or from the graph in Fig. 3, you can use gases that has y intercept as 1 and appropriate concentration, i.e you need atleast some known parameter to get it. The legend in the graph is also not clear (as far as getting the values from the Log - Log graph, there are tutorials in youtube).

I'm also in need of solution to this, so far this is what I read on the internet... You need a chemistry lab to do it !!!


I just bought a TFT screen is it still possible to use the serial port 1 and 0? so I have a question regarding the TFT touch screen... I would like to use the serial ports 1 and 0 (on my UNO) to transmit data to my mega... however it take up those ports. on the back of it, it shows what each prong should occupy. However, nothing is noted to be required for those ports. is it possible to clip those prongs off and still have the screen be usable or are they important to keep?

Yes, you can use those pins. Just because there are physical pins on the shield doesn't mean they are actually used. If nothing is written next to them then yes you can use them.

Be warned though that those pins are used for communication with your PC - and that includes uploading sketches - so you may experience problems doing things like that while your Mega is connected to those pins.


Using Two Arduino to Lower Power Consumption I am planning to build a water quality sensor with ph, temperature, and dissolved oxygen, conductivity. The power consumption looks like it will be very high especially due to the signal isolator, I'm estimating about 250mA. I'm going to place it in a remote area so I need it to be as power-efficient as possible.
I was thinking would this work?
What if I use two Arduino to control the power? The first Arduino will control the power supply to second Arduino, which has the sensor installed, using a timer(RTC) to turn off the power for 30 minutes and on for 30 seconds for it to read the sensor data.
Can this work? What would the circuit look like?
For the isolator, I was thinking to use Tentacle Shield and in the documentation, it says that the isolator itself uses about 150mA plus the sensor circuit.
https://www.whiteboxes.ch/docs/tentacle/t1/#/
Thanks for the help.

I would do as follows:
Software:

Arduino is in sleep mode

every x seconds (x depending on your needs), wake up then switch on and read one sensor after the other and transmit the results or whatever you want to do.

then go back to sleep

Hardware:

as you have 4 sensors, you can connect their outputs to the arduino analog inputs (or digital...)
you will need 4 electronic switches, preferably Mosfets, connected to 4 digital outputs to switch the power of each sensor independently

This should reduce the consumption to the minimum.
Once your system is running, you may also think about using only the AVR microchip, not the complete Arduino, e.g. If you don't need the USB connection. In addition, you can further reduce consumption by clocking the AVR chip to a lower clock, if not using Arduino.