body: I have to switch 2 MOSFET IRF640 at a duty ratio of .6 and the frequency of  switching is  50khz how can I generate it with a single aurdino

title: how can i generate square pulse at 50khz frequency to drive two mosfets at a duty ratio .6

Answers: 2

body:
Lots of ways.

1. Use a timer interrupt.

2. Use a pwm module.

3. Use the output compare module.

4. Use the SPI module.

5. Use a timer.

6. Use a pwm generator.

.......

Literally endless ways of doing it.

body:
This could be achieved either with software (with a timer interrupt or
by polling `micros()`) or with hardware. The software methods, however,
are prone to a high level of jitter. If you want to have a steady
signal, you should use a hardware solution.

The most straightforward hardware option is to use a timer in PWM mode.
I would avoid fiddling with timer 0, as it is used by the Arduino
timekeeping functions. You are left with either timer 1 or timer 2. The
following program configures timer 2 to output the desired signal:

* period = 20 µs = 5 × 64 CPU cycles
* signal HIGH for 12 µs = 3 × 64 CPU cycles.

The output goes to pin 3, which is one of the two PWM pins controlled by
timer 2.

    void setup()
    {
        DDRD |= _BV(PD3);     // OC2B = PD3 = digital 3 as output
        OCR2A  = 5 - 1;       // period = 5 * 64 CPU cycles
        OCR2B  = 3 - 1;       // HIGH for 3 * 64 CPU cycles
        TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
               | _BV(WGM20)   // fast PWM, TOP = OCR2A
               | _BV(WGM21);  // ...ditto
        TCCR2B = _BV(WGM22)   // ...ditto
               | _BV(CS22);   // clock at F_CPU / 64
    }

    void loop(){}

For some in depth information on how timers work, see
[Nick Gammon's tutorial on timers](http://www.gammon.com.au/timers).


body:
I'm trying to create a linked list for use on the Arduino, in the Eclipse IDE with the Arduino/Sloeber plugin. The linked list is written in a `.h` and `.cpp` file, and included locally in the project.

[![enter image description here][1]][1]

However, when building, I get the error `undefined reference to Structures::LinkedList<int>::LinkedList()`.

And despite the fact that I've added the local folder to the list of includes (and it can find the top level file containing `setup()` and `loop()`), the problem persists;

[![enter image description here][2]][2]

My relevant file listings are below. Any ideas of what settings I can add to Eclipse in order to solve this? Potentially, could it be something to do with the use of `template<typename T>` in the header file?

Thanks very much,

David

FYI: This problem does not occur with the core libraries i.e. I can run examples like Serial and Blink.

My top level `.cpp` is pretty simple:

    #include "LinkedList.h"
    #include "RAStarSearch.h"
    #include "Arduino.h"

    using namespace Structures;
    void setup() { }

    void loop() {
      LinkedList<int> list = LinkedList<int>();
      return;
    }

And the referenced `.h` is:

    #ifndef LINKEDLIST_H_
    #define LINKEDLIST_H_
    #include "Arduino.h"

    namespace Structures {
    template<typename T>
    class LinkedList {
      public:
        /// Struct inside the class LinkedList
        struct Link {
          T value;
          Link *next;
        };

        LinkedList<T>(); ///< Default constructor
        void addValue(T val); ///< prepends new value at beginning of list
        T popValue(); ///< returns first element and deletes Link.
        Link* peekLink(); ///< Looks at first value
      private:
        Link *head; // this is the private member variable. It is just a pointer to the first Node
    };
    const int ERRNUM = 0x8000000; ///<Error number used, as exceptions not supported
    }
    #endif /* LINKEDLIST_H_ */

__EDIT__

On request I have included my code for `LinkedList.cpp`

    #include "LinkedList.h"
    #include "Arduino.h"

    namespace Structures {
      template<typename T>
      LinkedList<T>::LinkedList() {
        head = NULL; // set head to NULL
      }
      template<typename T>
      void LinkedList<T>::addValue(T val) {
        Link *n = new Link();   // create new Node
        n->value = val;             // set value]

        if (head == NULL) { //i.e. if list is empty
          n->next = head;         // make the node point to the next node or NULL
          head = n;    // last but not least, make the head point at the new node.
        } else {
          Link *it = head;
          Link *oldIt = NULL;
          //TODO check edge cases i.e. insertion at beginning and end of list
          while (n->value > it->value){ //until place in list is found, needs T to have > operator
            oldIt = it;
            it = it->next;
          }
          oldIt->next = n; //Set pointer to n
          n->next = it; //Set n pointer to next
        }
      }
      template<typename T>
      T LinkedList<T>::popValue() {
        T retval = ERRNUM;
        if (head != NULL) {
          Link *n = head;
          retval = head->value;
          head = head->next;
          delete n;
        }
        return retval;
      }
      template<typename T>
      typename LinkedList<T>::Link* LinkedList<T>::peekLink() {
        return head;
      }
    }

  [1]: https://i.stack.imgur.com/DuqMAm.png
  [2]: https://i.stack.imgur.com/lwIxfm.png

title: Undefined reference in Eclipse of .h and .cpp files

Answers: 2

body:
Have you tried placing the H file in the same folder as you main cpp file.  This should prove beyond all doubt that there is nothing wrong with the code (I can't see anything wrong).

I suspect its a path issue.  You need to check that Eclipse is setup up properly to source the libraries from you custom location.  Also it needs to be passing this location on to the compiler.  I don't know how to do that in Eclipse but Google should point you in the right direction. Try this http://forum.arduino.cc/index.php?topic=39972.0 ?

Also you might find it easier to specify the include files in the order system, 3rd party libraries, local libraries and then local include files.  This means that duplicate definition faults are reported against the files nearest to the ones you have written.  If you define time_t using your ordering the fault will be reported against <time.h> rather than your header file.

Also a `using namespace foo` statement removes the benefits that namespaces provide, so its best not to do it.

EDIT
Doh - I should have spotted this sooner.  Template classes have to have the functions inline not in a CPP file.  This is because the CPP file can't change what T is at compile time, but because the H file is included in the file it is used in when it is preprocessed the object represented by T can change.
Basically inline your functions and it will work.

body:
The error you get is telling you that you have not implemented the method.

    LinkedList<T>()

which you use in loop()

In other words: the header file is found and the correct references are made but when the linker tries to pack everything together he finds that he doesn't have an implementation.

The implementation is in LinkedList.cpp in your project but with templates this is not enough.You need to somehow explain the "toolchain" that your project needs a "instantiation of the template" of type int.

The fact you need to specify this is a "limitation" of the toolchain processong of templates and is well documented here https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl.
The same link contains solutions.
The article states "This solution may (or may not!) cause significant code bloat" which is probably one of the reasons why template classes are not so popular in embedded development.
In your case I would simply include LinkedList.cpp in my .ino file and rename the .ino to .cpp.
As I do not have the source code I can not tell you whether this will work.

note that including the LinkedList.cpp in the .ino doesn work because the LinkedList.cpp is included 2 times and there are no include gards in the LinkedList.cpp file


body:
I am using arduino pro micro 5v 16Mhz. I have built a simple IR transmitter circuit as shown. [![Led is connected to pin 9 through 330ohm resistor][1]][1]

The code i am using is
https://github.com/z3t0/Arduino-IRremote/blob/master/examples/IRsendDemo/IRsendDemo.ino

Although this worked yesterday, it doesn't seem to work now. I was able to turn on and off my TV yesterday but the led is not even blinking now. I checked led, its working.

After hours of trying to make it work I tried different library.
https://github.com/cyborg5/IRLib2/blob/master/IRLib2/examples/send/send.ino

Surprisingly this seems to work but the code is a bit complicated for receiver.

I want to use the first library. Any help is appreciated. Thank you.

  [1]: https://i.stack.imgur.com/rAelb.jpg

title: Problem using IRremote library

Answers: 1

body: The problem was with timer timer settings in library. I checked different timer configurations with different pins and its working now. I found out that timer4 uses pin 13 which is not used in Pro Micro board so I am now using timer 3.


body:
On Arduino I can set digital pins by setting special variables PORTB and PORTD (or maybe they are not variables?). Where are those variables defined? I grepped /usr/share/arduino, but found nothing.

    grep -r 'PORTB' /usr/share/arduino/

title: Where is PORTB defined?

Answers: 2

body:
PORTB is defined by the "toolchain". It is not defined by Arduino.
For instance in my setup the Arduino Uno uses "toolchain" avr-gcc\4.9.2-amtel3.5.3-arduino2\avr.

If you grep that folder (location dependent on tool and installation options) you will find a file called `iom328p.h` that defines

    #define PORTB _SFR_IO8(0x05)

This is a mapping to a physical address of the cpu.

body:
>. Where are those variables defined?

In the device header file. Like other device specific macros.


body:
I'm trying to burn the arduino bootloader onto my ATmega328P so it uses the internal clock. I followed the tutorial in this [page][1] but I'm getting this error.

    avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Error while burning bootloader.
    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

    avrdude done.  Thank you.

I tried placing a cap from reset to ground but it doesn't wort either.
Any idea on what might be wrong with my procedure?

Thanks

**[EDIT]**

 - I followed the procedure described at the bottom of the page linked (Minimal Circuit (Eliminating the External Clock)).
 - I used the bootloader in "breadboard-1-6-x.zip"
 - I am using the Arduino IDE v1.8.1

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

title: Problem burning bootloader on ATmega328P using internal clock

Answers: 2

body: If your ATMEGA328P has already been used with a crystal or already has a bootloader on it, then the fuses will be set to expect a crystal oscillator. In this case, you must initially have a crystal & the associated 2 capacitors connected. Once you have succeeded in burning the bootloader (this process also sets the fuses) you can dispense with the crystal.

body:
As noted in 6v6gt's answer, if the ATmega328 has been set to use a crystal, thereafter a crystal (or an external oscillator) are required for programming, until the fuses have been set to use the internal RC oscillator.  Here are a few thoughts, unfortunately somewhat scattered, on the matter.

If you have a parallel programmer (that delivers high voltage to the Reset pin and uses 8-bit parallel data signalling) you can use it to reset the fuses, since with that programming mode the clock is irrelevant.

Also, [USBasp programmers](http://www.fischl.de/usbasp/) interact with Avrdude to generate a programming clock of some specified frequency,   100kHz by default, 8kHz with the “Slow Clock” jumper installed.  Also see § “Set the clock in software” within [USBasp ICSP programmer quickstart guide](http://www.freetronics.com.au/pages/usbasp-icsp-programmer-quickstart-guide) at freetronics.com.au.  Unlike the Avrdude man page, that reference says the default programming frequency is 375kHz and says “Avrdude’s -B option allows you to set the programming clock speed from software”, while the man page says -B specifies bit clock period (in microseconds) for the JTAG interface or the ISP clock of the JTAG ICE only.  Anyhow, a USBasp can reprogram fuses away from the crystal setting if a crystal or external oscillator is used, without depending on serial port data rates.  I don't know for certain whether it will work without a crystal or oscillator.

Note, rather than “sharing” a crystal via wires from one board to another – a practice that will broadcast lots of RF noise and might not get the signal across anyway – you could instead write a program on one Arduino to toggle a pin at high frequency, and use that output as an external oscillator to drive one of the crystal pins on another chip.  For example, the program below *should* generate a 2.67 MHz square wave on pin PB0 of an Uno or a Nano.

    void setup() {
      cli();    // Avoid timer interrupts
      pinMode (8, OUTPUT); // PB0 is pin 8 on Uno / Nano
      while (1) PINB = 1;
    }
    void loop() {}

In the ATmega328 data sheet, see §14.3.1, Alternate Functions of Port B, and Table 14-3, which lists PB7 as XTAL2 (Chip Clock Oscillator pin 2), and PB6 as XTAL1 (Chip Clock Oscillator pin 1 or External clock input), indicating external oscillator attaches to the PB6 pin.


body: I want to send commands to ESP8266 over WiFi from my phone(I'm working on building an App using PhoneGap). I'm new to this module and WiFi. What I'm doing right now is that I communicate with the module by sending GET (or POST) commands. I'm sure there should be a better way but I can't seem to find how. What is the correct way to talk to ESP8266 over WiFi?

title: Send commands to ESP8266 over WiFi

Answers: 1

body:
Depending on what best suits your needs, you could use:

 - http GET/POST commands
 - Websockets over http
 - MQTT protocol
 - Your own TCP or UDP socket protocol
 - etc.

In all cases, what you code into the ESP8266 processor/flash will need to receive and process the commands. The possibilities are near endless, since you are writing the App and the code for the module and can make those design decisions.


body:
I tried to implement the [`autoCalibrateAccelerometerOffset()`][1] function, through the code below on Arduino Genuino 101.

In a static test, without any stress or noise, I read the three axis value.

When I see the data on the serial monitor or on my file created with processing, the Z acceleration values changes from 1~0,99 to 0,00 g.

[![][2]][2]

I think there is an error in my code.

<!-- language: lang-cpp -->

    #include "SoftwareSerial.h"
    #include "CurieIMU.h"

    float sensorVals[] = {0,0,0};

    void setup() {

        Serial.begin(9600);
        while (!Serial);

        Serial.println("Inizializzazione del device...");
        CurieIMU.begin();

        CurieIMU.setAccelerometerRange(2);
        CurieIMU.autoCalibrateAccelerometerOffset(X_AXIS,0);
        CurieIMU.autoCalibrateAccelerometerOffset(Y_AXIS,0);
        CurieIMU.autoCalibrateAccelerometerOffset(Z_AXIS,1);
    }

    void loop() {

        sensorVals[0] = CurieIMU.readAccelerometerScaled(0);
        sensorVals[1] = CurieIMU.readAccelerometerScaled(1);
        sensorVals[2] = CurieIMU.readAccelerometerScaled(2);

        Serial.print(sensorVals[0]);
        Serial.print(",");
        Serial.print(sensorVals[1]);
        Serial.print(",");
        Serial.println(sensorVals[2]);
        delay(100);
    }

  [1]: https://www.arduino.cc/en/Reference/CurieIMUautoCalibrateAccelerometerOffset
  [2]: https://i.stack.imgur.com/MtB97.png

title: autoCalibrateAccelerometerOffset() Why does my Z values swing from 0 to 1g in static condition?

Answers: 1

body:
Assuming you aren't jumping up and down while this is happening then it could be:

 - A loose wire
 - A dodgy power supply
 - A bad earth connection
 - A fault sensor
 - A weird magnetic field/flux thing

Check you wiring, make sure all the connections are secure, etc.  I bet you have done that already.

I have no idea how to check a power supply, but if you have a different one you could switch that in.  Also look into smoothing the power supply with decoupling capacitors (?)

A bad earth, all sorts of weird [stuff] happens when you haven't earthed things properly.  Different power supplies need to share earths, but I suspect that doesn't apply here.

A faulty sensor - again, unless you have a duplicate you might not know.

Weird flux.  I think the sensor is a magnetic sensor and so it could be the natural eddies and flows of magnetic flux have conspired against you.  Move the sensor away from power supplies, electrical things and specifically anything you are hacking.  Also rotate the sensor through 90 degrees and see if it still happens (With RF it will polarise the fields in a different way, and school was a long time ago and I can't remember if that works with magnetic fields too)


body:
I am building a robot for a school project. I use an Arduino Uno, 2 dc motor's and an Ultra Sonic range measurement module. I want the robot to be autonomous, he has to be able to move around on his own using the Ultra Sonic sensor. Important to mention is that I don't use a MotorShield to control my dc motors. This is my latest version of coding:

----------

    #include <Servo.h> //include Servo library
    #include <AFMotor.h> //include DC motor Library
    #define trigPin 12// define the pins of your sensor
    #define echoPin 13
    AF_DCMotor motor2(7); // set up motors.
    AF_DCMotor motor1(6);

    void setup() {
      Serial.begin(9600); // begin serial communitication
      Serial.println("Motor test!");
       pinMode(trigPin, OUTPUT);// set the trig pin to output (Send sound waves)
      pinMode(echoPin, INPUT);// set the echo pin to input (recieve sound waves)
      motor1.setSpeed(105); //set the speed of the motors, between 0-255
        motor2.setSpeed (105);
    }

    void loop() {

       long duration, distance; // start the scan
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2); // delays are required for a succesful sensor operation.
      digitalWrite(trigPin, HIGH);

      delayMicroseconds(10); //this delay is required as well!
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;// convert the distance to centimeters.
      if (distance < 25)/*if there's an obstacle 25 centimers, ahead, do the following: */ {
       Serial.println ("Close Obstacle detected!" );
    Serial.println ("Obstacle Details:");
    Serial.print ("Distance From Robot is " );
    Serial.print ( distance);
    Serial.print ( " CM!");// print out the distance in centimeters.

    Serial.println (" The obstacle is declared a threat due to close distance. ");
    Serial.println (" Turning !");
        motor1.run(FORWARD);  // Turn as long as there's an obstacle ahead.
          motor2.run (BACKWARD);

    }
      else {
       Serial.println ("No obstacle detected. going forward");
       delay (15);
       motor1.run(FORWARD); //if there's no obstacle ahead, Go Forward!
        motor2.run(FORWARD);
      }

    }

[![enter image description here][1]][1]
Now I added an ARDUINO MOTOR SHIELD REV3 to control my dc motors. Now the wheels are actually spinning, but after a few turns they stop. I think it is software related, but I am not 100% sure. Also I think I am connecting my motors correct to my motorshield, but don't adress them properly in my code.
And I don't have any clue how to solve this problem.
Can anybody help me with this?

  [1]: https://i.stack.imgur.com/8LRu9.jpg

title: Arduino Robot won't move

Answers: 1

body: I think your problem is that you connected the positive wire to the 5v pin when it said 5v and not 9v. Also, I am assuming the 6 double AA is in series creating 9v. The thing is, double AA has a lot of amps. I tested it with my multimeter and it has 7 Amps, way to much. What I would do it connect a 9v battery to the voltage in pin-Vin. That pin can take a 9v but not 7 Amps produced by your 6 AA in series. You have 2 dc motors you said.Each is running I am assuming for each of them I notice draw about 1 Amp. 9v will supply enough and be safe. Try connecting a 9v to the Vin pin. I don't think your issue is software related.


body: This question has been asked many times in many sites but I am unable to find answer for my problem. I wanted to measure the speed of Vehicle using Ultrasonic sensors. Two sensors are placed along the side of the road and when a vehicle passes in front of first sensor(i.e echo1 is HIGH) then it should start counting until when the vehicle crosses the second sensor(i.e echo2=HIGH). So I will get the time. But I don't know how to set time counter. I searched in Internet a lot and I learnt about millis(). So I wrote code using millis(). But the problem is,it starts counting as the program runs. I also tried using array to save the values and subtract final reading from initial one but I'm unable to do that too. I cannot create large size of arrays. Please help me how do I set timer for it?

title: How to set counter for two ultrasonic sensors?

Answers: 1

body:
Just get the time when the first pin goes high, and get it again when the second pin goes high, and subtract them to find the difference.

This is an example of how you could do that. It doesn't contain anything about the ultrasonic sensors, just how to measure an elapsed time between two pins going high.

    #define echo1 3 // Set your echo pins here
    #define echo2 4

    unsigned long startTime = 0;
    unsigned long endTime = 0;

    void setup() {
    }

    void loop() {
        // You can do stuff here

        // If the first sensor goes off
        if (digitalRead(echo1) && (0==startTime))
        {
            // Remember the time this happened
            startTime = millis();
        }
        // If the second sensor goes off
        if (digitalRead(echo2) && (0==endTime))
        {
            // Remember the time this happened
            endTime = millis();
        }

        // If we have both start and end times
        if (0 != startTime && 0 != endTime)
        {
            unsigned long duration = endTime - startTime;
            // Do what you want with "duration"
        }

    }


body:
I'm using the following 'compiler' to program my ESP8266-01 direct with Arduino IDE:

https://github.com/esp8266/Arduino

and I'm trying to read the temperature and humidity with the following library:

https://github.com/adafruit/DHT-sensor-library

since the DHT library was developed to be used on an Arduino board, should I be able to run it on the ESP8266?

title: Is the DHT.h library compatible with ESP8266 Arduino IDE compiler?

Answers: 2

body: As far as I see, the DHT sensor library does bit-banging, which is kind of expected given the ad-hoc nature of the protocol that DHT type of sensors utilize. It should be compatible, as the library doesn't use any Atmel-specific features of the MCU.

body: Yes, it does work. You may have a look at http://esp8266.github.io/Arduino/versions/2.3.0/doc/libraries.html where a list of libraries running with ESP8266 can be found. Furthermore, @anrieff's remarks regarding hardware-specific features are a good hint.


body:
I've made use of the cap sense library in Arduino to make a touch less piano. I went according to my design and tried it out. Even after using a 10M ohm resistor, my program is only responding when I'm touching the electrodes. I want it to start detecting my finger from at least a few inches away.

I've posted the schematic and code for Arduino and Processing below.

[![enter image description here][1]][1]

[1]: https://i.stack.imgur.com/P5Bg9.png

Code for processing:

    import ddf.minim.*;
    import processing.serial.*;

    Minim minim;
    AudioPlayer song40;
    AudioPlayer song41;
    AudioPlayer song42;
    AudioPlayer song43;
    AudioPlayer song44;
    AudioPlayer song45;
    AudioPlayer song46;
    AudioPlayer song47;
    AudioPlayer song48;
    AudioPlayer song49;

    Serial myPort;  // Create object from Serial class
    String val;     // Data received from the serial port

    int r=0;
    int m=1;
    void setup()
    {
      minim = new Minim(this);
      song40 = minim.loadFile("40.wav");
      song41 = minim.loadFile("41.wav");
      song42 = minim.loadFile("42.wav");
      song43 = minim.loadFile("43.wav");
      song44 = minim.loadFile("44.wav");
      song45 = minim.loadFile("45.wav");
      song46 = minim.loadFile("46.wav");
      song47 = minim.loadFile("47.wav");
      song48 = minim.loadFile("48.wav");
      song49 = minim.loadFile("49.wav");

      String portName = "/dev/cu.usbmodem1411";                             //Change COM48 to the port number that your Arduino is connected, you can check the port number from arduino program.
      myPort = new Serial(this, portName, 115200);

      size(160, 160);
      background(0);
    }

    void draw()
    {
      if ( myPort.available() > 0 )
      {  // If data is available,
        val = myPort.readStringUntil('\n');
        if(val!=null)
        {
          print(val);
          if(val.charAt(0)=='a')
          {
            song40.rewind();
            song40.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("DO", 80, 90);
          }
          if(val.charAt(0)=='b')
          {
            song41.rewind();
            song41.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("DO#", 80, 90);
          }
          if(val.charAt(0)=='c')
          {
            song42.rewind();
            song42.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("RE", 80, 90);
          }
          if(val.charAt(0)=='d')
          {
            song43.rewind();
            song43.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("RE#", 80, 90);
          }
          if(val.charAt(0)=='e')
          {
            song44.rewind();
            song44.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("MI", 80, 90);
          }
          if(val.charAt(0)=='f')
          {
            song45.rewind();
            song45.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("FA", 80, 90);
          }
          if(val.charAt(0)=='g')
          {
            song46.rewind();
            song46.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("FA#", 80, 90);
          }
          if(val.charAt(0)=='h')
          {
            song47.rewind();
            song47.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("SOL", 80, 90);
          }
          if(val.charAt(0)=='i')
          {
            song48.rewind();
            song48.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("SOL#", 80, 90);
          }
          if(val.charAt(0)=='j')
          {
            song49.rewind();
            song49.play();
            fill(0, 0, 0);
            rect(0, 0, 160, 160);
            fill(255, 255, 255);
            textAlign(CENTER);
            textSize(50);
            text("LA", 80, 90);
          }
        }
      }

      if (mousePressed == true)
      {
        if(r==1)
        {
          myPort.write(' ');
          background(0);
        }
        r=0;
        m=1;
      }
    }

    public void stop()
    {
      minim.stop();
    }

And here's the Arduino Code:

    #include <SD.h>
    #include <CapacitiveSensor.h>

    #define total 30                   //define sensitivity, high value for decreases sensitivity, low value increases
    #define sensor 1                  //define number of samples Arduino takes, high value will increase stability while increasing response time
    #define replay 40                 //define debouncing, high value will increase stability while increasing response time

    int led = 13;
    int state = HIGH;

    boolean yes12;
    boolean previous12 = false;

    boolean yes11;
    boolean previous11 = false;

    boolean yes10;
    boolean previous10 = false;

    boolean yes9;
    boolean previous9 = false;

    boolean yes8;
    boolean previous8 = false;

    boolean yes7;
    boolean previous7 = false;

    boolean yes6;
    boolean previous6 = false;

    boolean yes5;
    boolean previous5 = false;

    boolean yes4;
    boolean previous4 = false;

    boolean yes3;
    boolean previous3 = false;

    CapacitiveSensor   cs_2_12 = CapacitiveSensor(2,12);        // 2.2M resistor between pins 2 & 12, pin 2 is send pin, pin 12 is sensor pin
    CapacitiveSensor   cs_2_11 = CapacitiveSensor(2,11);        // 2.2M resistor between pins 2 & 11, pin 2 is send pin, pin 11 is sensor pin
    CapacitiveSensor   cs_2_10 = CapacitiveSensor(2,10);        // 2.2M resistor between pins 2 & 10, pin 2 is send pin, pin 10 is sensor pin
    CapacitiveSensor   cs_2_9 = CapacitiveSensor(2,9);
    CapacitiveSensor   cs_2_8 = CapacitiveSensor(2,8);
    CapacitiveSensor   cs_2_7 = CapacitiveSensor(2,7);
    CapacitiveSensor   cs_2_6 = CapacitiveSensor(2,6);
    CapacitiveSensor   cs_2_5 = CapacitiveSensor(2,5);
    CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4);
    CapacitiveSensor   cs_2_3 = CapacitiveSensor(2,3);

    void setup()
    {
      cs_2_12.set_CS_AutocaL_Millis(0xFFFFFFFF);  //Calibrate the sensor...
      cs_2_11.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_9.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_8.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_7.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_6.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_5.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_4.set_CS_AutocaL_Millis(0xFFFFFFFF);
      cs_2_3.set_CS_AutocaL_Millis(0xFFFFFFFF);
      pinMode(led, OUTPUT);
      Serial.begin(115200);
    }

    short int a=1,a1=0,b=1,b1=0,c=1,c1=0,d=1,d1=0,e=1,e1=0,f=1,f1=0,g=1,g1=0,h=1,h1=0,i=1,i1=0,j=1,j1=0;  //for debounce purpose

    void loop()
    {
      long total112 =  cs_2_12.capacitiveSensor(sensor);
      long total111 =  cs_2_11.capacitiveSensor(sensor);
      long total110 =  cs_2_10.capacitiveSensor(sensor);
      long total19 =  cs_2_9.capacitiveSensor(sensor);
      long total18 =  cs_2_8.capacitiveSensor(sensor);
      long total17 =  cs_2_7.capacitiveSensor(sensor);
      long total16 =  cs_2_6.capacitiveSensor(sensor);
      long total15 =  cs_2_5.capacitiveSensor(sensor);
      long total14 =  cs_2_4.capacitiveSensor(sensor);
      long total13 =  cs_2_3.capacitiveSensor(sensor);

      if (total112 > total){yes12 = true;}
      else {yes12 = false;}

      if (total111 > total){yes11 = true;}
      else {yes11 = false;}

      if (total110 > total){yes10 = true;}
      else {yes10 = false;}

      if (total19 > total){yes9 = true;}
      else {yes9 = false;}

      if (total18 > total){yes8 = true;}
      else {yes8 = false;}

      if (total17 > total){yes7 = true;}
      else {yes7 = false;}

      if (total16 > total){yes6 = true;}
      else {yes6 = false;}

      if (total15 > total){yes5 = true;}
      else {yes5 = false;}

      if (total14 > total){yes4 = true;}
      else {yes4 = false;}

      if (total13 > total){yes3 = true;}
      else {yes3 = false;}

      if(yes12 == true && previous12  == false && a)
      {
          if(state == LOW) {
            state = HIGH;
          }
          else
            state = LOW;
          a = 0;
          a1 = 0;
          Serial.println('a');
      }
      if(yes12 == false && previous12  == false)
        a1++;
      else
        a1=0;
      if(a1==replay)
      {
        a=1;
        a1=0;
      }
      if(yes11 == true && previous11  == false && b)
      {
        if(state == LOW) {
          state = HIGH;
        }
        else
          state = LOW;
        b = 0;
        b1 = 0;
        Serial.println('b');
      }
      if(yes11 == false && previous11  == false)
        b1++;
      else
        b1=0;
      if(b1==replay)
      {
        b=1;
        b1=0;
      }
      if(yes10 == true && previous10  == false && c)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
          state = LOW;
        c = 0;
        c1 = 0;
        Serial.println('c');
      }
      if(yes10== false && previous10  == false)
        c1++;
      else
        c1=0;
      if(c1==replay)
      {
        c=1;
        c1=0;
      }
      if(yes9 == true && previous9  == false && d)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        d = 0;
        d1 = 0;
        Serial.println('d');
      }
      if(yes9== false && previous9  == false)
        d1++;
      else
        d1=0;
      if(d1==replay)
      {
        d=1;
        d1=0;
      }
      if(yes8 == true && previous8  == false && e)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        e = 0;
        e1 = 0;
        Serial.println('e');
      }
      if(yes8== false && previous8  == false)
        e1++;
      else
        e1=0;
      if(e1==replay)
      {
        e=1;
        e1=0;
      }
      if(yes7 == true && previous7  == false && f)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        f = 0;
        f1 = 0;
        Serial.println('f');
      }
      if(yes7== false && previous7  == false)
        f1++;
      else
        f1=0;
      if(f1==replay)
      {
        f=1;
        f1=0;
      }
      if(yes6 == true && previous6  == false && g)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        g = 0;
        g1 = 0;
        Serial.println('g');
      }
      if(yes6== false && previous6  == false)
        g1++;
      else
        g1=0;
      if(g1==replay)
      {
        g=1;
        g1=0;
      }
      if(yes5 == true && previous5  == false && h)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        h = 0;
        h1 = 0;
        Serial.println('h');
      }
      if(yes5== false && previous5  == false)
        h1++;
      else
        h1=0;
      if(h1==replay)
      {
        h=1;
        h1=0;
      }
      if(yes4 == true && previous4  == false && i)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        i = 0;
        i1 = 0;
        Serial.println('i');
      }
      if(yes4== false && previous4  == false)
        i1++;
      else
        i1=0;
      if(i1==replay)
      {
        i=1;
        i1=0;
      }
      if(yes3 == true && previous3  == false && j)
      {
        if(state == LOW){
          state = HIGH;
        }
        else
        state = LOW;
        j = 0;
        j1 = 0;
        Serial.println('j');
      }
      if(yes3== false && previous3  == false)
      j1++;
      else
      j1=0;
      if(j1==replay)
      {
        j=1;
        j1=0;
      }

      digitalWrite(led, state);
      previous12 = yes12;
      previous11 = yes11;
      previous10 = yes10;
      previous9 = yes9;
      previous8 = yes8;
      previous7 = yes7;
      previous6 = yes6;
      previous5 = yes5;
      previous4 = yes4;
      previous3 = yes3;

      delay(2);
    }

Thank you in Advance. :)

title: I'm facing a problem with cap sense proximity

Answers: 2

body:
Cap sensing is quite sensitive to the sense pad design. Generally you want thee pad to sufficiently big. I haven't seen a single wire design as you are using here.

I would play with one wire first and adjust your code to make it work before taking on more pads.

body:
## About your actual question

You have to realize that you are trying to measure **tiny**
capacitances, which is not completely trivial. Detecting your finger
“from at least a few inches away” is probably impossible with this
setup, as we are talking about fractions of a picofarad.

There are a few things you can do to increase the sensitivity though:

* make sure both you and the Arduino are properly grounded

* make the pads as big as practically possible

* increase the series resistance

* lower the detection threshold (your `total` constant) until you are at
  the verge of seeing spurious detections.

## About your Arduino code

This is not directly related to your question, but it addresses the
criticism you received for posting too large a program.

Looking at your code, it appears to be quite simple. It is too big only
because almost every statement is repeated ten times (once per piano
key). The simple thing you could have done is to remove all but one (or
maybe two) keys. This would have made the program easily digestible for
anyone trying to help you. What I strongly recommend is that you learn
about **using loops and arrays** in C++. This will allow you to avoid
repetition by instead looping through the arrays. Here is for example
how you could rewrite your `setup()` function based on an array of
sensors:

    const size_t SENSOR_COUNT = 10;

    CapacitiveSensor sensors[SENSOR_COUNT] = {
        CapacitiveSensor(2, 12),
        CapacitiveSensor(2, 11),
        CapacitiveSensor(2, 10),
        CapacitiveSensor(2, 9),
        CapacitiveSensor(2, 8),
        CapacitiveSensor(2, 7),
        CapacitiveSensor(2, 6),
        CapacitiveSensor(2, 5),
        CapacitiveSensor(2, 4),
        CapacitiveSensor(2, 3)
    };

    void setup()
    {
        for (size_t i = 0; i < SENSOR_COUNT; i++)
            sensors[i].set_CS_AutocaL_Millis(-1);
        pinMode(LED_BUILTIN, OUTPUT);
        Serial.begin(115200);
    }

As you can see here, the sensor initialization
(`set_CS_AutocaL_Millis()`) is only written once, and the Arduino is
instructed by the `for` loop to repeat the same thing on every sensor,
one after the other. If you then do the same for `loop()`, you will end
up with a program that is almost ten times shorter, and a _whole lot_
easier to read, modify and debug. For that, you would need to also
replace your `yesXX`, `previousXX`, `a`, `a1`, `b`, `b1`, `c`, `c1`...
variables with arrays.

At this point you have a collection of arrays. The next level in
modularization is to replace the collection of arrays by an array of
collections: you put all the data relevant to one piano key inside an
object, and then you have just one array of such objects.

I tried rewriting your program with this approach, and I am posting the
result here. Beware that I did not test it. I realize this may be a
little bit above your current level, but I hope it will at least give
you an idea of how the language allows you to abstract things: the whole
logic about detecting whether a key was hit lives in the
`PianoKey::hit()` method, and then the `loop()` becomes short and
simple.

    #include <CapacitiveSensor.h>

    class PianoKey : private CapacitiveSensor
    {
        public:
            PianoKey(byte sendPin, byte receivePin, char _note)
                : CapacitiveSensor(sendPin, receivePin), note(_note),
                  last_state(false), last_toggle(0)
                { set_CS_AutocaL_Millis(-1); }
            bool hit();
            char note;
        private:
            static const byte SAMPLES = 1;     // number of samples to average
            static const long THRESHOLD = 30;  // detection threshold
            static const short DEBOUNCE = 50;  // debounce time (ms)
            bool last_state;
            uint32_t last_toggle;
    };

    // Returns true once per hit on the key.
    bool PianoKey::hit()
    {
        uint32_t now = millis();
        if (now - last_toggle < DEBOUNCE)
            return false;
        bool state = capacitiveSensor(SAMPLES) > THRESHOLD;
        bool was_hit = state && !last_state;
        if (state != last_state) {
            last_state = state;
            last_toggle = now;
        }
        return was_hit;
    }

    const size_t KEY_COUNT = 10;

    PianoKey keys[KEY_COUNT] = {
        PianoKey(2, 12, 'a'),
        PianoKey(2, 11, 'b'),
        PianoKey(2, 10, 'c'),
        PianoKey(2,  9, 'd'),
        PianoKey(2,  8, 'e'),
        PianoKey(2,  7, 'f'),
        PianoKey(2,  6, 'g'),
        PianoKey(2,  5, 'h'),
        PianoKey(2,  4, 'i'),
        PianoKey(2,  3, 'j'),
    };

    void setup()
    {
        pinMode(LED_BUILTIN, OUTPUT);
        Serial.begin(115200);
    }

    void loop()
    {
        static int led_state = HIGH;
        for (size_t i = 0; i < KEY_COUNT; i++) {
            if (keys[i].hit()) {
                led_state = !led_state;  // toggle LED
                Serial.println(keys[i].note);
            }
        }
        digitalWrite(LED_BUILTIN, led_state);
    }

A couple of final notes:

* The line `class PianoKey : private CapacitiveSensor` says a piano key
  _is_ a capacitive sensor with some extra functionality. Another valid
  option would be to say that the key _has_ a sensor, i.e. to store a
  `CapacitiveSensor` inside the object.

* <s>I do not know whether it's safe to call `set_CS_AutocaL_Millis()`
  before the low-level initialization of the Arduino. That's why it's
  done in a `begin()` method to be called by `setup()`.</s> I checked
  the source code of the CapacitiveSensor library, and it appears that
  `set_CS_AutocaL_Millis()` does nothing but set a private member of the
  object. This means it is safe to call it from a global constructor,
  before the hardware initialization of the Arduino.
  Had this not been the case, one would need to defer this call until
  `setup()`, as done in [a previous version of this
  answer](https://arduino.stackexchange.com/revisions/34677/2).

* The `PianoKey::hit()` method uses time-based rather than
  loop-count-based debouncing. This should be more consistent if you
  change the program in a manner that changes the time it takes to loop.
  It does pure debouncing: you may want to change that to an algorithm
  that combines debouncing with deglitching.


body:
As I should expect(?), the PIR on pin#2 should trigger the trigsensor state at any time the board is running. However, I may get one trigger then nothing else. I have a GSM shield on top of a UNO. I know that I still have some tweaking to do, but I'm trying to solve one issue at a time. Thanks for any insight. The other functions seem to perform correctly. When I enter an incorrect code, the alarms operates properly. When the interrupt is triggered, the alarm response should be the same.

    ///////////////////////// initialize & includes //////////////////////////
    #include "SIM900.h"
    #include "sms.h"
    #include "Keypad.h"
    #include <GSM.h>
    SMSGSM sms;

    boolean started = true;
    int PIR_SensorPin = 2;
    int Alarm_OutPin = 11; //green
    int Light_OutPin = 12; //red
    int alarm_count;
    boolean volatile trigsensor = false;
    const byte interruptPin = 2;
    int z = 0;
    int i = 0;

    //////////////////////////// setup keyPad //////////////////////////
    const byte ROWS = 4; // four rows
    const byte COLS = 4; // four columns
    char keys[ROWS][COLS] =
    {
      {
        '1', '2', '3', 'A'
      }
      ,
      {
        '4', '5', '6', 'B'
      }
      ,
      {
        '7', '8', '9', 'C'
      }
      ,
      {
        '*', '0', '#', 'D'
      }
    };
    byte rowPins[ROWS] = {
      6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
    }; // connect to the row pinouts of the keypad
    byte colPins[COLS] = {
      3, A0, A1, A4
    }; // connect to the column pinouts of the keypad
    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
    const char PIN[5] = {
      '9', '6', '7', '9', '#'
    }; // PIN number
    char key_input[5] = {
      0, 0, 0, 0, 0
    }; // used for comparison

    //////////////////////////////// setup ///////////////////////////////////
    void setup() {
      Serial.begin (9600);  // Establish Serial connection.
      pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
      pinMode (Light_OutPin, OUTPUT);   // Set pinMode.
      pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
      digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (Light_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (PIR_SensorPin, LOW);
      Serial.println ("GSM Shield testing."); // Serial message that GSM shield is starting up
      if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
        Serial.println ("Status = READY");
        digitalWrite (Alarm_OutPin, HIGH);
        // PIR as interrupt
        attachInterrupt (digitalPinToInterrupt (2), trigger, RISING);
        //attachInterrupt ((0), trigger, RISING);
      }
      //  started = false; //////////////////////////////////////////////////////////////
      Serial.println ("System Ready, at the keypad loop!");
    }

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

    ////////////////////////////// void trigger ///////////////////////////////////
    void trigger() {
      trigsensor = true;
      started = true;
    }

    //////////////////////////////// void alarm ///////////////////////////////////
    void alarm() {
      Serial.println (started); Serial.println (trigsensor);
      //  digitalWrite (trigsensor, LOW);
      Serial.println("at Alarm");
      // while ((timedelay - time) > 0); Serial.println (time);  time++;
      if ((started == true) && (trigsensor == true)) {
        // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
        Serial.println ("MOTION detected: SMS Sent");
        for (alarm_count = 0; alarm_count < 5; alarm_count++) { // Cycle outputs if triggered
          digitalWrite (Alarm_OutPin, HIGH); delay (2000); // On/Off/On/Off/Off
          digitalWrite (Alarm_OutPin, LOW);
          digitalWrite (Light_OutPin, HIGH); delay (2000);
          digitalWrite (Light_OutPin, LOW); // End by turning off light
        }
        digitalWrite (Alarm_OutPin, HIGH);
      }
      else { }
      readKeypad();
    }

    //////////////////////////////// read Keypad ///////////////////////////////////
    void readKeypad() {
      char key = keypad.getKey();
      if (key != NO_KEY) { // if a keypad input
        key_input[z] = key;
        Serial.print("Key_input["); Serial.print(z); Serial.print("] = "); Serial.println(key);
        z++;
        if (z >= sizeof(key_input)) {
          z = 0;
        }
        switch (key) {
          case '*': // resets key_inputs to "0"
            z = 0;
            break;
          case '#': // pressed to "enter"
            z = 0;
            for ( i = 0;   i < 4 ;  i++ ) {
              Serial.print(key_input[i]);
            }
            Serial.println ("-------");
            delay(100); // for extra de-bounce
            checkPIN();
            break;
        }
      }
    }

    //////////////////////////////// check PIN ///////////////////////////////////
    void checkPIN() {
      Serial.println ("@ checkPIN ");
      int correct = 0;
      int i;
      for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
        if (key_input[i] == PIN[i]) {
          correct++;
        }
      }
      if (correct >= sizeof(PIN) - 1) {
        Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
        correctPIN();
      }
      else {
        incorrectPIN();
      }
    }

    //////////////////////////////// correct PIN ///////////////////////////////////
    void correctPIN() {              // do this if correct PIN entered
      Serial.println ("@ correct PIN ");
      started = false;
      digitalWrite (Alarm_OutPin, HIGH);
      readKeypad();
    }

    ///////////////////////////// incorrect PIN ///////////////////////////////////
    void incorrectPIN() {           // do this if incorrect PIN entered
      Serial.println ("@ incorrect PIN ");
      started = true;
      // add time delay before alarm, via keypad??
      alarm();
    }

title: A coding problem or improper interrupt usage?

Answers: 1

body: None of the code you posted ever sets trigsensor to false, besides the initial value.


body:
i have a problem with my new  [2.8" TFT LCD Screen Module HY-280TFT][1].i connect it with an Arduino Uno board like this way:
 [Connect HY-TFT280 to Arduino UNO][2]

 - LEDA -> 5V
 - LEDK -> GND
 - VCC -> 5V
 - RD -> 3.3V
 - GND -> GND
 - DB0->DB5 to D8->D13
 - DB6->A0
 - DB7->A1
 - DB10->DB17 to D0->D7
 - RSET->A2
 - CS->A3
 - WR->A4
 - RS->A5

i downloaded and installed the new [UTFT library][3]. then i tested the example : *Arduino(AVR)->UTF_Demo_320x240* , but i always have a white screen.
In the code, i change

    UTFT myGLCD(ITDB32WD,38,39,40,41); by UTFT myGLCD(ITDB32WD,A5,A4,A3,A2);
 but i still have the white screen

please what can be the problem? thank you

  [1]: http://www.goodluckbuy.com/2-8-tft-lcd-screen-module-hy-280tft-w-sd-card-and-touch-screen.html
  [2]: http://www.geeetech.com/wiki/index.php/2.8"TFT_LCD
  [3]: http://www.rinkydinkelectronics.com/library.php?id=51

title: white screen : 2.8" TFT LCD Screen Module: HY-280TFT

Answers: 0


body:
Hi I am a newbie I am trying to test LCD but it always show me a fading boxes It was working before .
connection

LCD p1 - gnd

Lcd p2 - VCC

Lcd p3 - potentiometer middle (10k)

lcd p4 - pin 7 microcon

lcd pin 5 - gnd

lcd pin 6 - pin8 microcon

4 vacant lcd spaces

lcd pin 11- pin9 microcon

lcd pin 12 - pin10 mocrocon

lcd pin 13- pin 11 microcon

lcd pin14- pin 12 microcon

lcd pin 15- 5v

lcd pin 16- gnd![enter image description here](https://i.stack.imgur.com/QhqLJ.jpg)

title: LCD Display Issue

Answers: 0


body:
I have 4 single color LED strips which I would like to control individually with one remote controller - turn them on/off an dim them. So far I only have my LED strips (They are about 3.5 meters of length combined), an 80W power supply and an Arduino Uno. I'm new to this kind of stuff. Could you help me with the setup. What parts do I need?

EDIT:
So I decided to go with an Arduino Nano. First, I'll try to power up only one strip. My question now is, how to power up the Nano. All the setups I found, have an USB cable connected to the nano to power it up. Can I connect my 12V+ to the VIN?

EDIT2:
Take a look at my setup. Is that OK?
[![enter image description here][1]][1]

Thanks

  [1]: https://i.stack.imgur.com/XDUi1.png

title: Controlling 4 LED strips

Answers: 1

body:
You will need several things.

First I assume that the power supply is a 12V power supply. If it isn't, better to get one (3.5m of leds can be 4.2A, so even a 12V 5A supply is fine). Note: you didn't specify the led size, so the current can vary a lot. But a standard one is a 60 leds/m 5050 leds, which means 60mA/5cm, or 4.2A for a 3.5m strip.

Anyway you will need a 12V power supply to power both the strips and the arduino (through the Vin pin).

You will then need a way to control the leds from the arduino. Since the required current is too high for the arduino, you will need to put a transistor. I tend to prefer nMOS over NPN, but just because of the way I learned them. Anyway just get a low-side transistor (either an nMOS or an NPN) capable of handling the required amount of current (at least a couple amperes, better if they are >5A) and the proper circuit to turn them on. Usually you will just need one or two resistors. You will need to connect the +12V to the plus terminal of the leds, the drain (or collector) of the transistor to the ground pin of the led you want to control, the source (or emitter) of the transistor to ground and the gate (or base) of the transistor to the arduino through the proper circuit.

Then the remote controller. You did not specify what kind of remote controller you want to use, but usually you can cope with a IR receiver (e.g. the [TSOP382](https://www.sparkfun.com/products/10266) or any other) and the proper decoding. A lot of remote controllers are already mapped in the library [IRremote](https://github.com/z3t0/Arduino-IRremote); you just have to read the value it provides; inside the arduino you will need to save the codes for the commands (you will have to train it first) and then simply compare.

This is a generic answer, because you did not provide any details. If, implementing this, you encounter any problem open a specific question with what you did up to that point.


body:
I'am trying to apply USSD operation with variable codes, for example this piece of code return my account balance:

                 gsm.SimpleWriteln("AT+CUSD=1,\"*100#\"");
i want to change "*100#" to variable so gsm.SimpleWrite uses what the variable contains. I want to find how to make it work like this:

                 gsm.SimpleWriteln("AT+CUSD=1,\"Variable\"");

EDIT: here is my code to give you a better view. it return balance in serial monitor.

    #include "SIM900.h"

      void setup()
        {
       Serial.begin(9600);
        Serial.println("GSM Shield testing.");
           if (gsm.begin(9600))
                Serial.println("\nstatus=READY");
          else Serial.println("\nstatus=IDLE");

             gsm.SimpleWriteln("AT+CUSD=1,\"*100#\"");
          delay(10000);
                 char msg[200];
                 gsm.read(msg, 200);
                Serial.print("resp: ");
                Serial.println(msg);
     }
        void loop()
         {

        }

title: Insert Variables In AT commandes

Answers: 1

body:
I cannot find which "SIM900.h" library you are using - none of the ones I found have "SimpleWriteln" in them, so this is pure assumption about what functions and overloads may be available.

Just split your string into chunks, like you would with any serial device:

    gsm.SimpleWrite("AT+CUSD=1,\"");
    gsm.SimpleWrite(command);
    gsm.SimpleWriteln("\"");

Where `command` is a suitable container for your data - say `const char *`.


body:
In this arduino project we have 3 Leds that lights up according to the voltage of a battery but when we the voltage read is very close, it results into an uncontrolled switching between  Leds  can any one help me ?

    int Batpin = A0;
    int Led1  = 12;
    int Led2  = 11;
    int Led3 = 10;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin (9600);
      pinMode(Led1,OUTPUT);
      pinMode(Led2,OUTPUT);
      pinMode(Led3,OUTPUT);

    }

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

    void volt(){
    int sensorVal = analogRead(Batpin);
    float voltage = sensorVal * (5.0/1023.0);

     Serial.print(" volt: ");
     Serial.println(voltage);
     if (voltage < 3.80){
         digitalWrite(Led1,HIGH);
      }

       if (voltage > 3.80 && voltage <= 4)
       {
          digitalWrite(Led1,LOW);
          digitalWrite(Led2,HIGH);
       }

       if (voltage > 4)
       {
          digitalWrite(Led1,LOW);
          digitalWrite(Led2,LOW);
          digitalWrite(Led3,HIGH);
       }
       delay (1000);
    }

title: Battery level indicator

Answers: 1

body:
What you could do with for this is *[hysteresis](https://en.wikipedia.org/wiki/Hysteresis)*.

Instead of simple threshold ranges (0 < A < B < C < 5) you instead need to watch the voltage over time and decide what it is doing compared with what it has done in the past.

You need to keep a record of what state the voltage is in at any one time - That is, is it in band A, B or C in the thresholds above. You then need a second set of thresholds, A1, B1 and C1.

The two thresholds overlap:

[![enter image description here][1]][1]

If, for example, the voltage rises from between A and B to between B1 and C1 then you switch states to the BC state.

If it falls from between B1 and C1 to between A and B then you switch to the AB state.

Basically, if the voltage rises, it needs to transition between the lower set of thresholds to the upper set of thresholds to register as a change. If it drops it has to transition between the upper set of thresholds and the lower set of thresholds to register as a change.

So, in pseudocode,

    if (State == 0A && Voltage > A1 && Voltage < B1)
        State = AB
        Turn on LED 1

    if (State == AB && Voltage > B1 && Voltage < C1)
        State = BC
        Turn on LED 2

    if (State == BC && Voltage > C1)
        State = C5
        Turn on LED 3

    if (State == BC && Voltage < B && Voltage > A)
        State = AB
        Turn on LED 2

    if (State == AB && Voltage < A)
        State = 0A
        Turn on LED 1

    if (State == C5 && Voltage < C && Voltage > B)
        State = BC
        Turn off all LEDs

It's up to you to decide what a good level of separation is suitable for your system.

  [1]: https://i.stack.imgur.com/bM68p.png


body: I'm new at multiplexing with arduino (I use arduino from some years), and -as title says- I'd like to learn. I'm trying to build an expandible system with 3 sensors, and I'd like to use a 74hc595b1 to link them, leaving some pins free. My first question is: is It possible? And second, can you kindly link me a simple -but very simple- example about multiplexers in arduino? Thankyou!

title: Simple example multiplexer usage

Answers: 1

body:
For connecting 8 analog devices to an Arduino, using only 3 Arduino pins, look at say a 4051 multiplexer IC: [4051 example][1]

  [1]: https://electronics.stackexchange.com/questions/67004/how-do-i-extend-the-number-of-analog-input-pins-available-to-me


body:
I like to build a fluid(liquid) level detector using Arduino that can send 2 types of information:

 1. Status of the Fluid Container (Empty,Full or Below Required Level)

 2. Location of Fluid Container

Now I like to know how small and compact such a fluid detector can be so that it can be placed in vessels, containers, tanks, etc. without causing any contamination to the fluid.
In addition, how can I interface this fluid detector with external systems like a smartphone app or cloud based app, etc.

What Arduino would i be using for the said purpose and why?

title: How compact, small and smart a fluid detector need to be communicate with external systems?

Answers: 1

body:
Your question should be broken into a minimum of two parts.

The first, regarding the sensor, can be addressed with at least one specific product, although there may be others of this nature. It is a teflon coated pressure sensitive strip placed into the holding container or tank. Teflon is a non-reactive plastic and will not contaminate the substance in the tank, unless you are measuring extraordinarily reactive chemical liquids. One example is
[Chemical eTape][1] which is available in lengths from 130mm to 800mm.

[![enter image description here][2]][2]

This particular product is offered in three different interface types, all of which are acceptable to a properly configured Arduino.

The second portion of your question regarding the smartphone and type of Arduino is going to depend on how you plan to use the data you'll collect with the sensor. This aspect of the question is also extremely broad, as there are many solutions, including Blynk, SMS, WiFi and others.

You will want to "start small," and create a local Arduino-only interface, to ensure that you can properly code the sensor to present the results you require.

Once you have the data, you would then explore the many options available for distribution and dissemination.

  [1]: http://milonetech.com/products/chemical-etape-assembly
  [2]: https://i.stack.imgur.com/32L74.jpg


body:
I am new to Arduino, and am trying to understand the following code.  The question is: Is my understanding correct, or if not, what is happening here?

I have to reverse engineer an existing undocumented project, based on Marlin firmware for 3D Printers.  The relevant lines from the source are:

    #define DIO87_PIN               PINE2
    #define DIO87_RPORT             PINE
    #define DIO87_WPORT             PORTE
    #define DIO87_DDR               DDRE
    #define DIO87_PWM               NULL

    #define MASK(PIN)  (1 << PIN)
    #define _TOGGLE(IO)  do {DIO ##  IO ## _RPORT = MASK(DIO ## IO ## _PIN); } while (0)
    #define TOGGLE(IO)  _TOGGLE(IO)

    TOGGLE(87);

1) Reducing this code gives me:
``DI087_RPORT = 1 << DI087_PIN``

2) Which reduces further to:
``PINE = 1 << PINE2``
3) Which reduces further to:
``PINE = 00000100``

4) I understand this to mean that we are setting Pin 2 of the Inputs Register (of Port E) to "High". (and are setting the other 7 pins to low)

5) I understand this to mean, as we are writing to an "Input", that we are enabling the internal pull-up resistor on Port E Pin 2.
(EDIT: I have made a mistake here in point 5: to enable a pull-up resister, you write to a pins OUTPUT register, not it's INPUT register. (but you must write to it's output register when it is in "input mode")

**Questions:**

 1. Is my understanding and work-through above correct?
 2. If yes, does this also mean that we are **also** disabling the pull-up resistors to the other 7 Input Pins at the same time?

I am confused by the "TOGGLE" code given above - it seems that it is "destructive" in the sense that by "toggling" the input resistor on one pin, you also *disable* the resistors on all other pins?  Would it not make more sense to just toggle the one pin with a bitwise ``or``.
e.g:
``PINE = PINE | 1 << PINE2``

title: Understanding writing to input pins and pull up resistors

Answers: 3

body:
As noted in the *I/O-Ports – Introduction* section of the ATmega2560 datasheet,

>... writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register.  In addition, the Pull-up Disable –  PUD bit in MCUCR disables the pull-up function for all pins in all ports when set.

Bits masked with a zero won't be affected.  You can toggle several bits at once if the byte written to the PINx register has several 1's in it.

Pullups are on for an input bit when the data bit is high *and* the PUD bit in  MCUCR is low.  So as suggested in your comment, pullups for toggled bits would toggle too, if PUD is low.

Regarding the macro code, your reduction looks right.  But note that use of `_TOGGLE` as an identifier in that code violates section 17.4.3.1.2 of the C++ Standard.  Names beginning with an underscore followed by an uppercase letter are reserved for use by language-implementation software.  They are off-limits for user code.  See [What are the rules about using an underscore in a C++ identifier?](https://stackoverflow.com/q/228783) for discussion.

body:
The feature is well documented in the datasheetss.

Just be aware that it is not available on all across chips.
Atmega8 for example is a notable exception.

body:
Now that I have improved my understanding, I provide a full answer here for completeness.

 1. To enable (or disable) a pull up resister, you write a 1 (or 0) to
    the PORTxn (data) register.
 2. Writing a 1 to a PINxn (input)register, toggles (bitflips) whatever value is in the PORTxn data register.
 3. Writing a 0 to PINxn does nothing, ever.
 4. The structure of the Macro means it is hardcoded to **only** write to a PINxn register - it is impossible (with this code structure) to call "TOGGLE" on a PORTxn (Data) register.
 5. Thus, this TOGGLE macro will never cause any issues, as writing zero's to PINx causes no action.

Specifically the answer is in the following two lines of code:

    #define DIO87_RPORT             PINE
    #define _TOGGLE(IO)  do {DIO ##  IO ## _RPORT = MASK(DIO ## IO ## _PIN); } while (0)

(TOGGLE is hardcoded to use "DIO_XX_**RPORT**" which is **PINx**)


body: I'm using servo motor in my Arduino based project, I've tried to provide servo with external power supply, So I've used 9v battery with IC7805 to step down to 5v,  but the motor is not working, so what should I do? FYI: I used the same battery with IC7805 to power IR proximity sensor which works fine.

title: Servo motor with 9V battery

Answers: 1

body:
A 9v "transistor" battery is unsuited to powering servos - at best it might work very briefly.

Use 4 alkaline (or depending on the servo ratings, perhaps 5 rechargeable) AA or AAA cells to power the servo.

Either power your Arduino from something else, or get a 3.3V version that you can operate from a low dropout regulator on the 4 or 5 cell pack.

A 7805 has a high dropout voltage and is out of place in a battery powered system.


body:
I am trying to program an ESP8266-01 WiFi module using an Arduino Uno as a USB to TTL programmer.
I have removed the ATmega and grounded the RESET pin (quite useless without the uC though).
Then, using esptool.py I tried to upload a Bare minimum sketch with the Arduino IDE and later using the following:

    python esptool.py -b 57600 -p /dev/cu.usbport write_flash 0x000000 "nodemcu.bin"

However, both ways give me the same output:

    A fatal error occurred: Failed to connect to ESP8266: Invalid head of packet ('\x08')

I have tried sending AT commands to the ESP01 like "AT" or "AT+GMR" and everything works fine, but I cannot upload any sketch because of that error.

I also followed esp8266 [official forum][1] advice to edit the Python script according to the following, but without success.

    Line 43 ESP RAM BLOCK = 0x1800 //change this to 180
    Line 44 ESP RAM BLOCK = 0x400 //change this to 40

The level conversion from 5v TTL to 3.3v is done through simple resistor node (2k and 1k), while RST is kept at Vcc through 10k pull-up resistor and a push button to ground it.

[![Wiring][2]][2]

  [1]: http://www.esp8266.com/viewtopic.php?f=6&t=442&start=16
  [2]: https://i.stack.imgur.com/LIZJ0.png

title: ESP01 flashing error

Answers: 2

body:
Your wiring sounds wrong.

Tie CHPD to Vcc (3.3v) to enable the device.

Tie GPIO0 to ground as you power up, to put it into programming mode.

RST can be left floating, or PULL (not tie!) up to Vcc through a resistor, say 10k.

That diode level shifter arrangement is unusual. A potential divider on the ESP's RxD is all you need - say 1k and 2k.

body:
An addition to Mark's answer, from https://arduino.stackexchange.com/questions/17571/uploading-sketch-to-esp8266

> Before download, pull both GPIO0 and RST to ground. Release the pull
> down on RST, but keep GPIO0 low. When the IDE has finished uploading,
> release GPIO0 from low.


body:
I have USB charger battery pack with two output ports ([Fremo C510][1]).  One is marked as 5 volts 1 amp, and the other as 5 volts 2 amps.

I'm building a toy robot and would like to run the UNO off of one of those ports, and the motors off of the other.

Can I safely do that?  I have two main concerns:

 - Can I safely power the arduino with that current?
 - If I power both the motors and the arduino from that source (two usb ports connected to the same battery), will I still have to worry about spikes from switching the motors on and off?  I don't know how those ports are wired to the actual battery inside.

  [1]: https://www.newegg.ca/Product/Product.aspx?Item=N82E16875790001

title: Can I safely power my UNO and DC motors with the 5v1A and 5v2.1A ports on a USB charger?

Answers: 1

body:
You can power the Arduino from either side, since it will only draw what it needs, and most arduinos are powered from a .5 amp USB port. But you'll want to reserve the higher current side for the motors.

Make sure your motors' total draw (including starting current) doesn't exceed the 2 amps available.

Unless you can find out for sure that the two power ports are isolated from one another, you're better off to assume they are not and provide motor spike damping yourself.


body:
i'm currently trying to send a randomly generated number from Arduino via ESP8266 wifi module to a local mysql database estabilished with xampp, but having a problem with it. Here is my arduino and php receiving code. I should mention that i'm extremely unfamiliar with mysql, php, and the whole server & database things, so any help would be greatly appreciated.

Arduino Code:

    #include <ESP8266WiFi.h>

    const char* server = "192.168.1.106";
    const char* ssid = "DARUSALAM C8";
    const char* password = "asro4520";
    const char* SensorID = "ESP001";

    WiFiClient client;

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

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

      WiFi.begin(ssid, password);
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.print(ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi Connected");
    }

    void loop() {
    float n = random(300);

    Serial.print("Random Number: ");
    Serial.println(n);

      if (client.connect(server,80)) {
        Serial.print("Posting data...");
        digitalWrite(BUILTIN_LED, LOW);
        Serial.println("Random Number: " + String(n));
        client.println("GET /log.php?n=" + String(n));
        client.println("HOST: ");
        client.println(server);
        client.println("Connection: close");
        client.println();

        client.stop();
        Serial.println();

        digitalWrite(BUILTIN_LED, HIGH);
      }

      delay(5000);
    }

PHP code:

    <?php

    $db_amb = mysqli_connect("127.0.0.1", "root", "", "wemos");
    if (!$db_amb) die("Gagal terkoneksi ke DB Utama. Error : " . mysqli_connect_error());

    $n = $_REQUEST['n'];
    if (!empty($n) &&)
    {
      $s = "insert into data_random set value1='$n'";
      $r = mysqli_query($db_amb, $s);
      echo "OK";
    }
    else echo "ERR";
    ?>;

The database is named 'wemos', and the table where i intend to store the data is named 'data_random' with 4 columns named value1-value4. My intentions is to store the random number to the 'value1' field.

**EDIT** the problem i encountered is whenever i checked `http://localhost/log.php` this appears:

    Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\log.php on line 7

i have tried modifying the syntax in numerous ways but the problem presist. I suspect my code may have some underlying fundamental problem that is not syntax related, but i can't tell due to my lack of experience. Again, any help/clue is greatly appreciated. Thank you very much

title: Problem sending data from arduino with ESP8266 to a local mysql database

Answers: 2

body:
The `HOST` should not have a newline after it, so you should have

    client.print("HOST: ");
    client.println(server);

In addition your PHP looks dodgy to me.  I'm not very familiar with PHP at all, but I think the `&`s here are left over from something you have removed, and causing syntax errors - just remove them

    if (!empty($n) &&)

I believe your `n` parameter is going to be in `_GET` (not `_REQUEST`).  Also, you should check whether it's there, not just assume it is, so:

    if isset ( $_GET["n"] )
    {
        $n = $_GET["n"];
        // Do your database stuff here
    }

(You should find the PHP log (where depends on what OS your server is running on) and I think it would point you straight to this problem.  No point trying to debug it blind.)

body:
Change this:

    client.println("GET /log.php?n=" + String(n));
    client.println("HOST: ");
    client.println(server);

To this:

    client.print("GET /log.php?n=" + String(n));
    client.println( " HTTP/1.0" );
    client.print("Host: ");
    client.println(server);

This means you're sending the `Host:` header + value on one line, and you're correctly appending the ` HTTP/1.0\n` after your URL-request.


body:
I have a NodeMCU, which I program with the Arduino IDE. I have connected a VOC sensor to pins D1, D2, which are the SLC/SDA pins for NodeMCU. They have pull-up resistor at 4,3kohm to 3.3V.

First I used I2C scanner code, provided by Arduino, and got a response that I have the sensor connected at address 0x70, which is the correct address, indicated on the datasheet for the sensor.

After I tried to read values from the sensor with command 0b00001001 (provided in the datasheet also), I only get 0s as output! Probably something weird in the coding, perhaps someone could assist me in what I am doing wrong here?

In the code, I request 100 bytes just to make sure to get everything, but I receive only 32 back. The datasheet says it should be 6 bytes on address 0x9. And I have tried hex and dec form but that doesn't work. Binary is the proper way I assume.

My Output:

    Start
    Bytes Available: 32
    Data read: 00000000000000000000000000000000

Code:

    #include <Wire.h>

    int miscadr = 0b1110000;

    void setup() {
      Serial.begin(115200);
      Wire.begin();
      delay(100);
    }

    void loop() {
      Serial.println();
      Serial.print("Start");
      Serial.println();
      Wire.beginTransmission(miscadr); //Start bit
      Wire.write(0b00001001); //Asking for registry 9
      Wire.endTransmission();
      Wire.requestFrom(miscadr, 100);
      Serial.print("Bytes Available: ");
      while(Wire.available()==0);
      Serial.print(Wire.available());
      Serial.println();
      Serial.print("Data read: ");
      while(Wire.available()!=0) {
        Serial.print(Wire.read());
      }
      Serial.println();
      delay(2000);
    }

title: I2C Arduino ESP8266 Bad Reading

Answers: 2

body:
Which VOC sensor is it ? I like to see the datasheet myself. My crystal ball tells me it is a MiCS-VZ-86/89. When the i2c scanner finds address 0x7, then you should use 0x7. In your sketch the miscadr is now 0x70.

The read and write bit is taken care of by the Wire library. You could print the return value of Wire.endTransmission and Wire.requestFrom. The Wire.endTransmission  returns an error and the Wire.requestFrom returns the number of read bytes. Those return values can tell if the I2C transaction was wrong.

There is no need for a while-loop to wait for data after the Wire.requestFrom. You can remove that first while statement.

You can not request 100 bytes. The Wire library has a buffer of 32 bytes.

When you use the term "address", please use "i2c address" or "register address".

The Wire.requestFrom reads bytes from the Slave (the VOC sensor), but the sensor can not stop the I2C transaction after 6 bytes. The Master (the ESP8266) should set the number of bytes to read. If you need only 6 bytes, then you should read only 6 bytes.

body:
If your ESP8266 device NodeMCU is not using the Arduino ESP8266 Library standard pins for I2C ( SDA=2, SCL=14) then you must change the Wire.begin() statement to Wire.begin(SDA, SCL) inserting your values for the SDA and SCL pins. See this note for another ESP breakout (Sparkfun) [Arduino ESP8266 Wire][1]

  [1]: https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/using-the-arduino-addon


body:
Last night I had my arduino connected to pc and mc connected to 9 volts in the same time then today I tried to connect my arduino to pc and i removed any connection i just wanted to display a string it i used this code

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

       void loop() {

        Serial.print("NO FORMAT");
         }

its not showing anything in serial montor I tried to blink led no output still

And  i have another arduino i used the same code it showing the message in serial monitor is my previous board broken ? thank you for help when i tried to click the reset button in arduino the orang led built in is not blinking

title: Is my arduino board broken?

Answers: 1

body:
I assume that PWR LED is turned on?
If on USB connection PWR LED is off and on 9V connection it turns on you should check fuse. It is on the right side of USB connector and is protection only from USB voltage source.

If it works you should check level of voltages or try connect usbasp and then using avrdude check if it is connecting normally.

Few ideas for voltage levels:

 1. Voltage on "main" ATMega328 (You can check it through ISP header)
 2. Voltage on Arduino's chip which is ATmega16, or CH340 if you have chinese one (or something like that). It should be the same as on main Arduino, but to be sure...
 3. Voltage on reset

You need around 5 volts to be sure that it works properly because of construction of arduino's board.

If you still have no answers, no voltages you should check Arduino's schematic for more information: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

If there is electrically everything all right and you did not check with usbasp (or other AVR-compatible programmer) I believe that next step is to check bootloader on your board.


body:
I've uploaded a sketch from the Arduino IDE to my (Amica) esp8266-12e board with the sketch data upload tool (ESP8266FS). This goes without any errors or problems. However, the code is never executed, it's like that the code isn't even on the board, it does nothing. I've tried flashing the firmware several times but this does not help. Depending on the installed firmware I get different messages on the serial monitor such as

    NodeMCU 0.9.5 build 20150318  powered by Lua 5.1.4
    lua: cannot open init.lua

or

    Ai-Thinker Technology Co.,Ltd.
    invalid

So installing different kinds of firmware is not the problem here. What did I do wrong which causes the board to 'ignore' the uploaded data sketch?

title: esp8266-12e Nodemcu 1.0 board not starting uploaded data sketch from Arduino IDE

Answers: 1

body:
It appears that you have not uploaded the Arduino Core Software to your ESP8266 device because you are getting messages from the LUA interpreter which is overwritten when you install the Arduino Core Software.
The pre-requisites for using ESP8266FS to load sketches are here: [ESP8266FS][1]

  [1]: https://github.com/esp8266/arduino-esp8266fs-plugin


body:
I'm using a -12E with three light sensors and a sketch I've successfully used with an Uno.  I cannot get the -12E to print anything but 0 or 1023 for a light level (0 when I connect the grounds, 1023 without grounds).

I've successfully printed from a single light sensor but now I'd like to try three.

I'm curious to know what I'm missing.  Any guidance would be appreciated.

Code is as follows:

    const int photocellPin_0 = 16; // D0
    const int photocellPin_1 = 5; // D1
    const int photocellPin_2 = 4; // D2
    int photocellReading_0;
    int photocellReading_1;
    int photocellReading_2;

    void setup() {
      delay(4900);
      Serial.begin(115200);
      Serial.println("Startup");
      delay(100);
      pinMode(photocellPin_0, INPUT);
      pinMode(photocellPin_1, INPUT);
      pinMode(photocellPin_2, INPUT);
    }

    void loop() {
      delay(1000);
      photocellReading_0 = analogRead(photocellPin_0);
      photocellReading_1 = analogRead(photocellPin_1);
      photocellReading_2 = analogRead(photocellPin_2);
      Serial.println("-----NEW ON READING-----");
      Serial.print("Photo Sensor #1 = ");
      Serial.println(photocellReading_0); // the raw analog reading
      Serial.print("Photo Sensor #2 = ");
      Serial.println(photocellReading_1);
      Serial.print("Photo Sensor #3 = ");
      Serial.println(photocellReading_2);
      delay(5000);
    }

This is based on an adafruit sketch I pulled off of some website (modified for three photo sensors) and I'd credit it if I could recall exactly where I got it from.

title: NodeMCU Light Sensor

Answers: 1

body:
The ESP8266 ESP-12E has only one analog input, that is A0 (which tolerates a range 0-1 volt).

digitalRead() statements are not appropriate for a photocell within a potential divider since you will simply get a boolean result 0 or 1 from the connected pin.

You can read one photocell connected on A0 by analogRead( A0 ) assuming it is so connected within a potential divider that a maximum of 1 volt is presented to pin A0.

The Arduino Uno by contrast has 6 Analog inputs which tolerate up to 5 volts


body:
>I am able to send text from the Arduino wirelessly to RPi.  I am now trying to send the sensor data I'm measuring to the Pi.  This is what I have below:

    int moisture = A0;
    int temp = 3;

    //Skipping the setup and reading of the values

    radio.write(&moisture);
    radio.write(&temp);

    //the above couple lines is where I start having trouble.  The RPi will spit output a seemingly random selection of numbers

title: How to send sensor data from Arduino through NRF24L01 to Raspberry Pi

Answers: 4

body:
As you haven't said or shown which NRF24L01 library you are using, one can't say for sure what the problem is, but in some NRF24 implementations, the `write()` method accepts (or requires) a second parameter, `len`, giving the number of bytes to be sent.  If the library you're using doesn't require that parameter, it could be defaulting it to some value, or could be treating the buffer as a string, to be terminated with a null byte.

Either of those cases could produce erratic results.

Instead of leaving off the second parameter, specify it.  For example:

    radio.write(&moisture, 2);
    radio.write(&temp, 2);

body:
I recommend you to choose a platform for communication. You don't need to deal with the low level communication.
I suggest you to try https://www.mysensors.org/ It helps to wire your sensors, gives you example codes for the chosen sensors for data transfer in the direction to your Pi. There is a well documented API you can build your application on.
On the Pi you can use a serial gateway or/and a controller installed. These controllers are written to communicate with your sensors and other nodes. They give graphical web interface to visualize your data and their history. For a controller I recommend to start with https://www.domoticz.com/ or Openhab I think Domoticz is the better choice to start with on Pi.

body: most likely is that your nrf24l01 library only allow text or string communcaiton, not nuermical data.  when you send your measured data, nrf24l01 treats it as text.  so what you read is text (text's unicode numbers).  I encountered the same problem.

body: I will suggest you to provide valid size of data with write function for eg radio.write(&moisture,sizeof(moisture)). hope this will work for further explanation of this method www.robofever.in


body:
I am new to the Arduino platform so please bear with me. I have a program to display rolling text on a LED matrix which is for the Tinyduino platform

<!-- language: lang-c++ -->

    #include "Charliplexing.h"
    #include "Font.h"
    #include "Arduino.h"

    void setup()
    {
      LedSign::Init();
    }

    static char test[]="HELLO";

    void loop()
    {
      for (int8_t x=DISPLAY_COLS, i=0;; x--) {
        LedSign::Clear();
        for (int8_t x2=x, i2=i; x2<DISPLAY_COLS;) {
          int8_t w = Font::Draw(test[i2], x2, 0);
          x2 += w, i2 = (i2+1)%strlen(test);
          if (x2 <= 0)  // off the display completely?
            x = x2, i = i2;
        }
        delay(80);
      }
    }

Then I have some code to read temperature and humidity data for the same Tinyduino platform

<!-- language: lang-c++ -->

    #include <Wire.h>
    #include <SI7021.h>

    SI7021 sensor;

    void setup()
    {
      Serial.begin(115200);
      Wire.begin();
      Serial.print("Initializing sensor... ");
      if(!sensor.begin()){
        Serial.println("Sensor not found!");
        while(true);
      }
      Serial.println("Success!");
    }

    void loop()
    {
      int celcius=sensor.getCelsiusHundredths()/100;
      int relativeHumidity=sensor.getHumidityPercent();
      Serial.print(celcius);
      Serial.print(" deg Celsius\t");
      Serial.print(relativeHumidity);
      Serial.println("% relative humidity");

      delay(500);
    }

I am trying to integrate this together so that Arduino reads the temperature and humidity sensor data and then displays it on the LED matrix as text. I have some code that is integrated from the above two examples

<!-- language: lang-c++ -->

    #include "Charliplexing.h"
    #include "Font.h"
    #include "Arduino.h"
    #include <Wire.h>
    #include <SI7021.h>

    SI7021 sensor;

    void setup()
    {
      Serial.begin(115200);
      Wire.begin();
      Serial.print("Initializing sensor... ");
      if(!sensor.begin()){
        Serial.println("Sensor not found!");
        while(true);
      }
      Serial.println("Success!");
      LedSign::Init();
    }

    static char test[100]="";

    void loop()
    {
      int celcius=sensor.getCelsiusHundredths()/100;
      int relativeHumidity=sensor.getHumidityPercent();
      test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";

      for (int8_t x=DISPLAY_COLS, i=0;; x--) {
        LedSign::Clear();
        for (int8_t x2=x, i2=i; x2<DISPLAY_COLS;) {
          int8_t w = Font::Draw(test[i2], x2, 0);
          x2 += w, i2 = (i2+1)%strlen(test);
          if (x2 <= 0)  // off the display completely?
            x = x2, i = i2;
        }
        delay(80);
      }
      delay(500);
    }

Here is the error message that the IDE throws out

    test:28: error: invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

     test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";
                                 ^

    Using library LOL in folder: C:\Program Files (x86)\Arduino\libraries\LOL (legacy)
    Using library Wire at version 1.0 in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire
    Using library Temp in folder: C:\Program Files (x86)\Arduino\libraries\Temp (legacy)
    exit status 1
    invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

Any suggestions on how to resolve this error is welcome.

title: How to concatenate strings

Answers: 2

body:
You cannot "add" character arrays like that. You may try to use a
`String` object instead, as these do support the `+` operator as a way
to concatenate them:

<!-- language: lang-c++ -->

    String message = (String(celcius) + " deg Celcius, "
                   + relativeHumidity + " relative humidity");
    const char *c_message = message.c_str();

And then you use `c_message` in place of your `test` variable.
Note that only the first element (`celcius` here) needs to be explicitly
converted to a `String` object. The other conversions happen implicitly.

**Edit**: Updated the code to avoid using the internal state of a
(possibly destroyed) temporary object.

body:
You can use sprintf to format a string.

You have to change:

    test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";

for

    sprintf(test,"%d deg celsius %d relative humidity",celcius,relativeHumidity);


body:
I have a Raspberry Pi B+ running 7x24. I have to connect an Arduino Mega 2560 to its USB. The Arduino has only one nRF24L01-PA-LNA powered from its 3V3.
Can I power the Arduino from the Pi's USB?

title: Powering Arduino Mega 2560 from a Raspberry Pi Usb

Answers: 3

body:
If you are powering your RPi from power supply 5V/2A at least there should be no problem. USB hub on the RPi should not give more than 500mA to power Arduino. Also there is a fuse on Arduino's board to prevent any damage from USB power.

Check both Arduino and RPi schematics for more details about modules used there:

 - [Arduino]
 - [Raspberry]

[Arduino]: https://www.arduino.cc/en/uploads/Main/arduino-mega2560_R3-sch.pdf
[Raspberry]: https://datasheets.raspberrypi.com/rpi3/raspberry-pi-3-b-reduced-schematics.pdf

body: raspberry pi can power ur mega board normally,but the 3v3 in the mega board is not stable and has noise,so it is better to use 3v3 supply source for ur NRF the simplest to use is just hooking a piece of 1117 to 5v of ur mega board

body: Yeah, as the others have mentioned you can power the Arduino form the raspberry pi's power supply, but you cannot transit data from the raspberry to the Arduino without a third party software.


body: I'm interested in using an Arduino for a project for taking information and sending it through a phone application. I was wondering what the cheapest option there is for an arduino with internet capabilities. From what I see, a lot of articles list they use UNOs with shields for wifi/ethernet. After looking these up, I noticed that they can get a little pricey. Is there any alternative options I may be overlooking? Thanks.

title: Arduino for push notifications to phone

Answers: 1

body: You could look into buying an ESP8266 WiFi module (cca. 7$) and add it to your existing Arduino. If you're not constrained with money that much I would then recommend look up Arduino Industrial 101, which comes with WiFi out of the box. You could then use MQTT protocol to send messages to a broker and your phone. There are alot of nice tutorials online on MQTT.


body:
I am beginner at Arduino,i tried to read as much as i can but i am not sure if i am doing good.I would like to send a specific code for a (non PC) device through the TX pinout when i push the button which is wired to the Pin 2.I have writtem this small code to check it:

    int buttonUPpin = 2;
    int UpinStatus=LOW;

    void setup() {
      Serial.begin(9600);
      // put your setup code here, to run once:
    pinMode(buttonUPpin, INPUT_PULLUP);
    digitalWrite(buttonUPpin,HIGH);

    }

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

    UpinStatus=digitalRead(buttonUPpin);

    if(LOW==UpinStatus)
    {
    Serial.print('A');
    digitalWrite(1,LOW);

    }

    }

When i push the button i can see at serial monitor the 'A' character but i am not sure if this character was also sent out to the TX pinout since the TX led is not blinking only the RX led.

title: Does Arduino sent output to TX pinout?

Answers: 2

body:
You haven't set pinMode for pin 1 and using pin 1 will interfere with the serial monitor (never use 0 and 1).

    #define buttonUPpin = 2;
    #define LedPin = 3;
    int UpinStatus = LOW;

    void setup()
    {
        Serial.begin(9600);
        pinMode(buttonUPpin, INPUT_PULLUP);
        pinMode(LedPin, OUTPUT);
        // digitalWrite(buttonUPpin,HIGH);  // Don't think this is right

    }

    void loop()
    {
        UpinStatus=digitalRead(buttonUPpin);
        if(LOW==UpinStatus)
        {
           Serial.print('A');
           digitalWrite(LedPin, LOW);  // Not sure if High or Low depends on you circuit
        }
    }

body:
If you start the `Serial` it takes over the `TX` and `RX` pins and it ignores pin mode settings (and `digitalWrite` too).

Btw `TX` and `RX` LEDs are driven by USB to Serial interface chip so you don't have any control of it either.