message:
Bizarre transistor behavior and voltage with DC motor in simple circuit

I started a new motor related project recently with a new Arduino Uno, beginning with several tutorial circuits included in the Vilros Arduino guide. The circuit in question is #10, a simple DC motor circuit with a transistor switch (https://i.stack.imgur.com/KLC0K.jpg). The Arduino is being powered for the moment via USB.

The circuit, completed according to the diagram/common sense, does not work. The voltage across the transistor base is clearly not sufficient to activate the switch with the motor in the circuit. 5V (more like 4.6V) from Pin 13 is running across a 330 ohm resistor to the transistor base, but there is no current between the collector and the base. Bypassing the collector/base gap with a piece of metal will complete the circuit and activate the motor.

For some reason, the transistor *will* switch properly when the motor is replaced by a simple LED. *AND*, switching the cable from Pin 13 to the +5V out is enough to activate the transistor switch. I was under the impression that the transistor should only require .7V above the common grounded element.

But, even more bizarrely, with a cable running from +5V to the transistor base (through a resistor), a voltmeter across the DC motor is reading a potential difference of anywhere from 9V to 1702V (see https://i.stack.imgur.com/mwFKp.jpg, yes, with 4 digits). The multimeter is otherwise working normally, so I don't see a good explanation. Is the Arduino pin just incapable of providing sufficient current/voltage to activate the transistor, or am I missing something obvious. And does anyone have some idea why the voltmeter is reading so high and fluctuating so wildly? It is curious that the Arduino disconnects from the PC whenever the circuit is completed with the motor in it, so the Arduino likely is overdrawing from the USB.

The transistor included was not the one listed, but a common MPS2222A.

Thanks

body:
According to second image transistor seems to be connected in oposite direction (switched Collector with Emitter). It means common collector configuration is used instead common emitter and it's usually not enough to drive motor. And C-E can handle only about 10V Max (more or less, depends on transistor) even if it could handle much more in oposite direction.

See [link][1] for more details:
>
   * Common Base Configuration   –   has Voltage Gain but no Current Gain.
   * Common Emitter Configuration   –   has both Current and Voltage Gain.
   * Common Collector Configuration   –   has Current Gain but no Voltage Gain.

I've just tested this circuit an it must be powered by power jack. USB is not strong enough.

  [1]: http://www.electronics-tutorials.ws/transistor/tran_1.html


sender: user

sender: assistant

body:
There is nothing wrong with the circuit (although drawn in a bizarre method). Your understanding of how a transistor works is mistaken - forget voltage - transistors are controlled by current.

Most likely you have connected the transistor incorrectly.

The voltage reading is due to back EMF. If you used an analog meter it would give the reading you expect.

In all likelihood you have damaged the transistor.


message:
Difficulty with shifting data

Im trying to shift LEDs using 595 register. Using SN74HC595N registers. Im using 4 of the registers as i got alots of LEDs to shift. My code for shifting doesn't seem working.. i can shift some with 2 registers but not 4 registers

    // include the library code:
    #include <LiquidCrystal.h>
    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS1307 RTC;

    // initialize the library with the numbers of the interface pins
    // RS-12, E-13, D4-8, D5-9, D6-10, D7-11
    LiquidCrystal lcd(12, 13, 8, 9, 10, 11);

    int row[]={8,9,10,11};// Digital output connect directly to all rows
    int col[] = {A0,A1,A2}; // Analog input with 10K pull-up to 5V.
    int i,j; // Two counter variables to count inside for loop
    int col_scan; // Variable to hold value of scanned columns

    //Pin connected to ST_CP of 74HC595
    int latchPin = 3;
    //Pin connected to SH_CP of 74HC595
    int clockPin = 4;
    ////Pin connected to DS of 74HC595
    int dataPin = 5;

    //holder for infromation you're going to pass to shifting function
    byte data = 0;
    byte data1 = 0x55;
    byte data2 = 0xAA;

    void setup()
    {
      Wire.begin();
      RTC.begin();
      Serial.begin(9600);
      for(i=0;i<=3;i++)
      {
        pinMode(row[i],OUTPUT);
        //pinMode(col[i],INPUT);
        //digitalWrite(col[i],HIGH);
      }

      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print("Medicine Box");

      //set pins to output because they are addressed in the main loop
      pinMode(latchPin, OUTPUT);

      if (! RTC.isrunning())
      {
        Serial.println("RTC is NOT running!");
        // following line sets the RTC to the date & time this sketch was compiled
        RTC.adjust(DateTime(__DATE__, __TIME__));
      }

      for (i=0;i<=4; i++)
      {
        digitalWrite(latchPin, 0);
        shiftOut(dataPin, clockPin, data1);
        shiftOut(dataPin, clockPin, data1);
        digitalWrite(latchPin, 1);
        delay(500);
        digitalWrite(latchPin, 0);
        shiftOut(dataPin, clockPin, data2);
        shiftOut(dataPin, clockPin, data2);
        digitalWrite(latchPin, 1);
        delay(500);
      }
    }

    void loop()
    {

      DateTime now = RTC.now();
      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      //lcd.print(millis() / 1000);
      //Serial.println(now);
      //Serial.print("    ");
       /*   Serial.print(now.day(), DEC);
          Serial.print('/');
          Serial.print(now.month(), DEC);
          Serial.print('/');
          Serial.print(now.year(), DEC);
          Serial.print(' ');
          Serial.print(now.hour(), DEC);
          Serial.print(':');
          Serial.print(now.minute(), DEC);
          Serial.print(':');
          Serial.print(now.second(), DEC);
          Serial.println(" ");*/

          lcd.print(now.day(), DEC);
          lcd.print('/');
          lcd.print(now.month(), DEC);
          lcd.print('/');
          lcd.print(now.year()-2000, DEC);
          lcd.print(' ');
          if (now.hour()<10)
            lcd.print('0');
          lcd.print(now.hour(), DEC);
          lcd.print(':');
          if (now.minute()<10)
            lcd.print('0');
          lcd.print(now.minute(), DEC);
          lcd.print(':');
          if (now.second()<10)
            lcd.print('0');
          lcd.print(now.second(), DEC);
          //lcd.println(" ");

      for(i=0; i<=3; i++)
      {
        digitalWrite(row[0],HIGH);
        digitalWrite(row[1],HIGH);
        digitalWrite(row[2],HIGH);
        digitalWrite(row[3],HIGH);
        digitalWrite(row[i],LOW);

        for(j=0; j<=2; j++)
        {
          col_scan=analogRead(col[j]);
          if(col_scan < 1000)
          {
            while(analogRead(col[j])< 1000);
            keypress(i,j);
          }
        }
      }
      digitalWrite(latchPin, 0);
      shiftOut(dataPin, clockPin, data1);
      shiftOut(dataPin, clockPin, data1);
      digitalWrite(latchPin, 1);
    }

    void keypress(int i, int j)
    {
      if(i==0&&j==0)
        Serial.println("1");
      else if(i==0&&j==1)
        Serial.println("2");
      else if(i==0&&j==2)
        Serial.println("3");
      else if(i==0&&j==3)
        Serial.println("A");
      else if(i==1&&j==0)
        Serial.println("4");
      else if(i==1&&j==1)
        Serial.println("5");
      else if(i==1&&j==2)
        Serial.println("6");
      else if(i==1&&j==3)
        Serial.println("B");
      else if(i==2&&j==0)
        Serial.println("7");
      else if(i==2&&j==1)
        Serial.println("8");
      else if(i==2&&j==2)
        Serial.println("9");
      else if(i==2&&j==3)
        Serial.println("C");
      else if(i==3&&j==0)
        Serial.println("*");
      else if(i==3&&j==1)
        Serial.println("0");
      else if(i==3&&j==2)
        Serial.println("#");
      else if(i==3&&j==3)
        Serial.println("D");
    }

    // the heart of the program
    void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
      // This shifts 8 bits out MSB first,
      //on the rising edge of the clock,
      //clock idles low

      //internal function setup
      int i=0;
      int pinState;
      pinMode(myClockPin, OUTPUT);
      pinMode(myDataPin, OUTPUT);

      //clear everything out just in case to
      //prepare shift register for bit shifting
      digitalWrite(myDataPin, 0);
      digitalWrite(myClockPin, 0);

      //for each bit in the byte myDataOut�
      //NOTICE THAT WE ARE COUNTING DOWN in our for loop
      //This means that 000001 or "1" will go through such
      //that it will be pin Q0 that lights.
      for (i=7; i>=0; i--)  {
        digitalWrite(myClockPin, 0);

        //if the value passed to myDataOut and a bitmask result
        // true then... so if we are at i=6 and our value is
        // 010100 it would the code compares it to 000000
        // and proceeds to set pinState to 1.
        if ( myDataOut & (1<<i) ) {
          pinState= 1;
        }
        else {
          pinState= 0;
        }

        //Sets the pin to HIGH or LOW depending on pinState
        digitalWrite(myDataPin, pinState);
        //register shifts bits on upstroke of clock pin
        digitalWrite(myClockPin, 1);
        //zero the data pin after shift to prevent bleed through
        digitalWrite(myDataPin, 0);
      }

      //stop shifting
      digitalWrite(myClockPin, 0);
    }

body:
Your code looks unnecessarily convoluted for merely sending data to a shift register. You can use the SPI hardware for that.

For example:

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

    #include <SPI.h>

    const byte LATCH = 10;

    void setup ()
    {
      SPI.begin ();
    }  // end of setup

    void loop ()
    {
      digitalWrite (LATCH, LOW);
      SPI.transfer (0xAB);
      SPI.transfer (0xCD);
      SPI.transfer (0xEF);
      SPI.transfer (0x42);
      digitalWrite (LATCH, HIGH);
      delay (20);
    }  // end of loop

You have to use the SPI hardware pins for this to work. On a Uno these are:

* Chip pin 14 (DS) goes to MOSI  (D11)
* Chip pin 11 (SH) goes to SCK   (D13)
* Chip pin 12 (ST) goes to SS    (D10)  (or any other pin by changing LATCH)

Example wiring:

[![595 wiring schematic][1]][1]

More details on my [page about the 595 chip](http://www.gammon.com.au/forum/?id=11518).

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


message:
Should I control each of the four robot wheel separately or wire two from each side together?

I am making a remote controlled Arduino robot. I has 4 DC motors for wheels. I have 2 motor drivers available that control two dc motors each. I was wondering what the downsides are of wiring 2 dc motors together. The DC motors are 6v and the maximum current per channel of my motor driver is 1.2A which should be plenty for the motors. The motor driver that I am using can be found [here.][1] Each motor is getting controlled using a PWM signal. The DC motors are controlled separately.

  [1]: https://www.sparkfun.com/products/9457

body:
it looks like you have two channels on each controller, so you have some options here. but first I'm going to talk a bit about your motors. If you have a spec sheet for them you can gather most of this info through that, but it doesn't hurt to do some experimentation. A motor will draw max current when it is stalled (is trying to drive but it can't), and you can determine this "stall current" with a multimeter or from the spec sheet. when you're driving the robot, this can occur when you drive up to a wall and try to push through the wall (hint, no robot this size will damage a well built wall) but likely the driver will reach a wall and stop driving (unless she can't see the robot while driving, idk). the lowest current it will draw (aside from zero when it can't...) is it's "free speed" current, this is when it's spinning as fast as it can with no load on it. while you're driving the robot you can expect the current to be between these numbers, if you want to get super fancy (and you want to equip your robot to do this) you could log the instantaneous current every 10ms or however often (this can be useful if you want to diagnose faults, but again its a small robot)... so if you have two motors in parallel (which you want to do because in series one will drive harder than the other), then the current drawn by each will add, so you can double it for two motors.

anyways, here's a few options for the motor configuration:

if two of your motors in parallel draw less than continuous 1.2 amps, you could use a single controller for one robot, controlling left wheels on channel 0 and right on channel 1.

if your motors draw more than that in parallel, you will have to use two channels per side, however you could Y the PWM lines between the motor controller and the arduino

if you are using something like omni wheels and want control over every single wheel, obviously you will want one channel per wheel...


message:
Send button press over RF

I'm trying to send a button press over RF (performing a closed circuit operation on the receiving end).

I have a controller with an UP and DOWN button. Unfortunately I am limited to the cable length, and would like to extend it with radio frequency. The controller has one cable for GND and one each for the corresponding UP and DOWN buttons.

The RF units is the typical 433mhz bought online (ebay).

Can I in someway send the signal over RF (directly on the data pin of the transmitter) without hooking it up to a microcontroller (Arduino)?

body:
No. You need a micro-controller at both the sending, and receiving sides.

eBay does set RF remotes with a few buttons. This might be easier and cheaper than making your own.


message:
Adding Date and Time to existing sketch

I am currently **trying to add a clock functionality to my current sketch** for a peristaltic pump [run by NEMA 23].

*The current sketch waits for a button on my breadboard to be pressed, it then runs the motor for a specified amount of steps and then stops and waits for the next press of the button*. It also displays the amount of steps to the Serial Monitor. I have a working sketch for a clock using an RTC DS3231 module and have unsuccessfuly attempted to fit it into my motor sketch. **The problem is, the clock seems to be taking precedent over the rest of my sketch, so pressing the button no longer works and the time is simply consistently output onto the Serial Monitor.**

***The ideal functionality would be the time and date displayed on LCD constantly (or at least blinking so rapidly that one could not tell the difference) with the number of button presses displayed under it, changing in value only when a button is pressed.***

Attatched find my code, it is really quite simple, and thank you so much for the time and help.

    #include <Bounce2.h>
    #include <LiquidCrystal.h>
    #include <SoftwareSerial.h>
    #include <AccelStepper.h>
    #include <MultiStepper.h>
    #include <Wire.h>       //I2C Library
    #include <OneWire.h>
    #define DS3231_I2C_ADDRESS 0x68

    AccelStepper stepper(1, 9, 8); // initiate stepper motor

    LiquidCrystal lcd(6, 7, 5, 4, 3, 2);

    int pos = 0; // variable to store position
    int buttonPresses = 0;

    const byte ButtonPin = 10;
    const byte LedPin = 13; // for debugging and visualization

    unsigned long ledOnTimer = 0;

    const unsigned int ledPeriod = 3000;

    Bounce button;

    void setup() {
      Wire.begin();
      Serial.begin(9600);
      lcd.begin(16, 2);
      button.attach(ButtonPin);
      pinMode(LedPin, OUTPUT);
      stepper.setMaxSpeed(4000);
      stepper.setSpeed(2000);
      stepper.setCurrentPosition(0);
    }

    byte bcdToDec(byte val)  {
      // Convert binary coded decimal to normal decimal numbers
      return ( (val / 16 * 10) + (val % 16) );
    }

    void loop() {
      motor();
      printDate();
    }

    void motor() { // functioning motor sketch by itself

      //if led is on
      if (digitalRead(LedPin)) {
        stepper.runToNewPosition(21000); //about 420 steps per 10 mL
        digitalWrite(LedPin, LOW);
        // }
      }

      //if led is off
      else {
        button.update();
        if (button.fell()) { // if the button "fell" from a value from HIGH to LOW (so now it is off)
          stepper.setCurrentPosition(0);
          digitalWrite(LedPin, HIGH);
          buttonPresses++; // count presses of button and print to monitor
          lcd.clear();
          Serial.print("Number of Button ");
          lcd.setCursor(0, 1);
          Serial.print("Presses = ");
          Serial.println(buttonPresses);
        }
      }
    }

    void printDate() { //functioning time sketch by itself

      // Reset the register pointer
      Wire.beginTransmission(DS3231_I2C_ADDRESS);

      byte zero = 0x00;
      Wire.write(zero);
      Wire.endTransmission();

      Wire.requestFrom(DS3231_I2C_ADDRESS, 7);

      int second = bcdToDec(Wire.read());
      int minute = bcdToDec(Wire.read());
      int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
      int weekDay = bcdToDec(Wire.read()); //0-6 -> sunday - Saturday
      int monthDay = bcdToDec(Wire.read());
      int month = bcdToDec(Wire.read());
      int year = bcdToDec(Wire.read());

      //  print the date EG   3/1/11 23:59:59
      Serial.print(month);
      Serial.print("/");
      Serial.print(monthDay);
      Serial.print("/");
      Serial.print(year);
      Serial.print(" ");
      Serial.print(hour);
      Serial.print(":");
      Serial.print(minute);
      Serial.print(":");
      Serial.println(second);
    }

Last note: Everything compiles, and I will change "Serial" to "lcd" after I finish debugging the sketch, so that is why everything is currently beign sent to the Serial Monitor.

body:
I think you need to look at using interrupts.

The printDate function is quite processor intensive with all the Wire and Serial.print calls, it will be taking the majority of the time in each loop().
Whilst in printDate it won't be looking at the state of the button, so you have to press at just the right time.

If you place an interrupt on the button's pin I think you will get a more responsive system.  Another thing that you could look at it only reading the clock once a second, this could be done with a timer interrupt.


body:
Even if you want to display time with the seconds showing, you don't need to check the time on the RTC continiously. Once a second should be enough. You can use a timer interrupt that triggers an ISR(Interrupt Service Routine) every second to do that check for you. This will free a lot of time which your arduino can use to do other stuff.

Same goes for your button(s): you can use an External Interrupt (INT) or a Pin Change Interrupt (PCINT) for them. This way the arduino will only look at them when they are pushed (and/or released).

If you combine those two interrupts (for the clock and the button), your arduino will have a lot of spare time. This is especially handy if you later want to expand your project with more buttons and motors.


body: Attaching interrupt (PIN change or LEVEL change) to the push button would work fine. You can trigger a flag and the flag should access the controller to run motor() function.


message:
Can I use a PIR sensor to turn on an arduino?

I'd like to use a PIR sensor (HC-SR501) to control the power to an Arduino Uno. Note that I'm not talking about using a PIR sensor as input to the Arduino and sensing the output pin from the PIR, I'm talking about using the output pin from the PIR to turn the Arduino itself on and off.

Hooking it up directly doesn't seem to work as I'm guessing the PIR doesn't handle that much current output. Would I use a transistor of some kind to do this?

My reason for wanting to do this is simple, power preservation. The PIR uses so little current when it doesn't sense anything that I thought it would be nice for something like a mailbox sensor that doesn't need to run that often. Thanks.

body:
Yes you can.

It all depends on how you are turning the power on.  You sensor needs to flip a 'switch' rather than actually power the Arduino directly.  (I'm sure you know that but just in case).

So you need a normally open relay in between you power source and you Arduino.  Normally open because you don't want it powered unless you 'turn it on'.  Your relay might be able to be switched by your PIR sensor's data output, but if you need more current then you are going to have to use a transistor and draw more power from the power source.

You have the PIR sensor, so now find the relay capable of carrying the maximum current you need for the Arduino.


message:
Arduino Pro Mini interrupts timer not working

i am trying to make an arduino pro mini sd card serial logger.The arduino should log the data that comes over the uart and write it to an sd card and if it is no data on the serial for 25 seconds to save automatically the data into the file.Each file are named diffrent every time they are saved(for example datalog0.txt, datalog1.txt and so on).I am creating also at the start of the sketch an config(config.txt) file where the number of the file present of the sd are stored and if the file already exist than a new one will be created, this option works good.Now, after the 25 seconds past and it is no more  data over the serial the arduino dont close the datalog.txt file , so the next data will be saved in the same file, this is the problem i have, even in the config file the file number will be increased.I will attach the sketch and expect patient from you, ai am still newbie.I forgot to mention that it was working good for some time but not anymore, the only thing i did was to upload the bootloader from ide and since than is not working anymore.

Regards.

    //#include <Wire.h>
    #include <SPI.h>
    #include <SD.h>
    #include <string.h>
    #include <SoftwareSerial.h>

                int i;
                int incomingByte = 0;
    //int data[512];
                File myFile;
                unsigned char bytes,flag_again;
                unsigned int fileNo,timer_count;
                String s_fileNo,filename,filename_master;
                char comanda;

                void Timer1_InIt()
            {
                TCCR1A = 0;
                TCCR1B = 0;
                TCNT1  = 0;
                OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
                TCCR1B |= (1 << WGM12);
                    TCCR1B |= (1 << CS12) | (1 << CS10);
                    //TIMSK1 |= (1 << OCIE1A);
                }

    ISR(TIMER1_COMPA_vect)
    {
        timer_count++;
        if(timer_count > 25)
        {
            timer_count = 0;
            TIMSK1 &= ~(1 << OCIE1A);
            myFile.close();
            fileNo++;
            myFile = SD.open("config.txt",FILE_WRITE);
            myFile.seek(0);
            myFile.print(fileNo);
            myFile.close();
            //software_Reset() ;    //reset the sketch
        }
    }
    SoftwareSerial mySerial(4, 5); // RX, TX

    void setup()
    {
        cli();
        Timer1_InIt();
        sei();

        mySerial.begin(9600);
        Serial.begin(10752,SERIAL_8E2);
        //mySerial.print("Initializing SD card...");

        if (!SD.begin(10))
        {
            //mySerial.println("initialization failed!");
            return;
        }
        Serial.println("initialization done.");

        myFile = SD.open("config.txt",FILE_READ);
    // mySerial.println("Config file created");
        if(!myFile.available())
            bytes = 0;
        else
        {
            bytes = myFile.available();
            for(i = 0; i< bytes ; i++)
                s_fileNo += (char)myFile.read();
        }
        myFile.close();
        fileNo = s_fileNo.toInt();
    // mySerial.print("file no:");
        //mySerial.println(fileNo);

        filename = "datalog";
        filename += fileNo;
        filename += ".txt";

        myFile = SD.open(filename,FILE_WRITE);
        if (myFile)
        {
            //mySerial.print(filename);
            //mySerial.println(" File Open...");
        }
    }

    void loop()
    {

        if(!myFile)
            myFile = SD.open(filename, FILE_WRITE);

        while(Serial.available())
        {
            incomingByte = Serial.read();
            /*if(incomingByte == 0 || incomingByte < 15 )
            {
              Serial.print('0');
              myFile.print(0,HEX);
            }*/
            //mySerial.println(incomingByte,HEX);
            myFile.println(incomingByte,HEX);
            // myFile.println(incomingByte);
            timer_count = 0;
            flag_again = 1;
        }
        if(!Serial.available() && flag_again)
        {
            TIMSK1 |= (1 << OCIE1A);
            flag_again = 0;
        }

    }

body:
In untested (pseudo-)code

    unsigned long lastSerialInput = millis();

    void loop()
    {

        if(!myFile)
            myFile = SD.open(filename, FILE_WRITE);

        while(Serial.available())
        {
            incomingByte = Serial.read();
            myFile.println(incomingByte,HEX);

            lastSerialInput = millis();
        }

        // check for 25 seconds of inactivity
        if( myFile && (millis()-lastSerialInput > 25000 )
        {
            myFile.close();
            fileNo++;
            filename = "datalog";
            filename += fileNo;
            filename += ".txt";

            //save new fileNo to config.txt (though I'd personally find the file with the largest number in setup instead of relying on a config.txt file)
        }

    }


message:
Large values are changed by Arduino when viewing with `Serial.print()`

**Why are (big) values being changed?**

I tried out printing some values and noticed bigger values are changed more, they seem to be rounded to quarters and then to halves when the value gets bigger.

**MWE**

    void setup() {
      Serial.begin(9600);
      Serial.print("12457591.51 is changed into ");
      Serial.println(12457591.51);
      Serial.print("2457591.80 is changed into ");
      Serial.println(2457591.80);
      Serial.print("1234567.89 is changed into ");
      Serial.println(1234567.89);
    }

    void loop() {}
gives me

    12457591.51 is changed into 12457592.00
    2457591.80 is changed into 2457591.75
    1234567.89 is changed into 1234567.87

I'm working with an Arduino Nano ATMega328.

**Background**
I need the calculation `(2457591.33 + 0.5 - 2440588)  * 60 * 60 * 24` to be precise to within preferably a hundred, but currently it's off by about `7000`.

body:
Floating point numbers doesn't have infinite precision. But you can always change your equation to use smaller numbers (preferably integers or longs as floating point is extremely slow)

For example on [AVR Freaks][1] they mentioned precision about 6 or 7 digits. It makes sense as 24bits signed number range is from -8388608 to 8388607

  [1]: http://www.avrfreaks.net/forum/floating-point-range


message:
WDT & Software RESET in ESP8266 + Arduino IDE

I am working on ESP8266 in Arduino IDE. I want to know how to Software RESET the ESP8266. Any sketch/example would be useful. Moreover, how to initialise WDT in ESP8266.

Kindly help!

body:
Software reset in ESP8266 is achieved using `ESP.reset()`

as per WDT, the other answer has info on that, i.e. software WDT is cleared using `yield()` - hardware WDT is not accessible through software


message:
is the Arduino shield pinout a standard, so that any Arduino shield can work with any Arduino board

I'm new to Arduino and dying to delve in.

There are lots of Arduino base board vendors, and lots of shield vendors.

In general, should I be able to plug any shield into any Arduino board, even with existing shields?

body:
Most shields will fit most of the "regular sized" boards. the obvious exception is the boards like the nano which are tiny. Shields are going to have the best compatibility with the Uno, just because that one is the most common, so if you are going to get one arduino and a bunch of shields, get an uno. Some shields (the gen 1 ethernet and wifi shields in particular had an issue where they could not be used on Megas because the mega listens to SPI on pins 50+ which simply were not connected to the shield, however most of the newer shields will connect to the 6-pin block in the center now-adays to allow Mega usage.

The next thing you want to look at is if you are stacking shields, if they will collide on pin usage (SPI gets around this through multiplexing) and some of the 3.3 volt devices may have conflicts with 5-volt shields. Although the 3.3v devices do provide 5v power-out pins in the same locations as the Uno, it becomes more of an issue with trying to read a 5v on a 3.3v pin, which could damage the microchip.

the best thing to do is to check the documentation of the shields and check which pins they use, what voltages they need/supply, and comparing this with the particular arduino you are using.


body:
No, they are not standard - not entirely - although there have been some attempts to make them more standard.

Some things to watch out for:

* SPI
    * The Uno originally had SPI on pins 10-13
    * The Mega had it on another COMMS header instead

SPI has now been standardized to the 6-pin ICSP header, though not all shields honour that, and still use pins 10-13 instead, so they won't work on boards like the Mega

* I2C
    * The Uno has I2C on pins A4/A5
    * The Mega has it on the COMMS header instead

I2C has now been standardized on a special pair of pins added to the end of the digital IO header (pins 8-13 + GND + AREF) though many shields still look for it on pins A4/A5, so they won't work on boards like the Mega

Some other boards, like the Leonardo, also have these (and other) functions on other pins, so may not work with some shields that don't use the SPI / I2C headers.

The basic functions, though, i.e., digital IO and analog inputs and UART 1 are all in the same places on the majority of boards, and most have PWM in the same places too. But you can't rely on any thing more than that between any two boards.


message:
Who makes this cool Arduino display shield, and what model is it?

Anyone recognize Mfgr/model of this display that reads: "Wireless Internet Of Things".  The Arduino board is a WIOT.

I've been looking and looking for a source for Arduino display like this, but cannot find.

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

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

body:
That will be an SSD1306 based blue OLED display with SPI interface. There's lots of them around by lots of different people. Some are I2C interface, and some of those have a "broken" I2C interface that doesn't send ACKs (especially cheap ones on eBay) and need a special ACK-less Software I2C implementation.

The SPI ones, of course, won't suffer from that problem.

They are generally 0.96" diagonal, and that one, I think, is 96x39 pixels (or it may be 128x64).


message:
4 channel Remote Control

I'm trying to make a 4 channel RC using Arduino and nrf24L01 module.
I already know how to deal with this module, but the question is "What does 4 channel mean ?", and how to make it supports 4 channel ?

body:
4 channel means having the ability to send 4 individual values (maybe speeds?) at once.

Since the nRF24L01+ is a packet based system it is as simple as sending the different "channels" as different bytes (or groups of bytes if more than 0-255 or -128 to +127 is needed).

For instance, if you want 4 channels that can represent 0-255 then you need 4 bytes, and so you can set both sender and receiver to have a packet size of 4 bytes (for efficiency) and send a packet made up of the 4 channel values.

If you want to represent numbers bigger than that then you need to split the variable into bytes (two bytes for an int, 4 for a long) or create a `struct` to represent your packet of data. Of course you then need the sender and receiver to be set to a packet size *at least* big enough to contain the data, and both ends must agree on the packet size.


message:
Send sensor information to processing

I am currently working on an Arduino project where the Arduino will send data to a processing program via bluetooth and processing will draw the data. However, my code doesn't seem to work.

Here is my Arduino code:

    #include <SoftwareSerial.h>

    int bluetoothTx = 1;
    int bluetoothRx = 0;

    SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

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

    void loop() {
      Serial.println("Hello");
    }

And here is my Processing code:

    import processing.serial.*;
    Serial myPort;

    void setup() {
      myPort = new Serial(this, "COM42", 9600);
      myPort.bufferUntil('\n');
    }

    void serialEvent( Serial myPort) {
      String data = myPort.readStringUntil('\n');
      println(data);
    }

I identified that the incoming port from the HC-05 module is "COM42" from my Bluetooth settings. I am expecting to see several "Hello" lines being printed on the processing console but this does not happen

body:
Your whole sending program is a complete mess, sorry to say:

First you create a SoftwareSerial port using the HardwareSerial pins. (Why on earth would you do that?)

Then you "begin" that SoftwareSerial port.

Finally you try and print `Hello` through the **HardwareSerial** port!

Either use SoftwareSerial **OR** use the hardware UART. You can't mix and match both. And since you are using the hardware UART pins, why even consider using SoftwareSerial?

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

    void loop() {
        Serial.println("Hello");
    }

**OR, to use *other pins than 0 and 1*:**

    #include <SoftwareSerial.h>

    const int bluetoothTx = 2;
    const int bluetoothRx = 3;

    SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

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

    void loop() {
        bluetooth.println("Hello");
    }


message:
What's with the debug error messages, like VMDPE_1|1_VMDPE?

I'm using visual micro for visual studio, and I understand this kind of thing is caused by conflicting serial data when I try to read and print to the main serial at the same time, right?

Well, I need to read serial data from the main serial on my Mega 2560, and then I need to see it on my LCD screen, which is controlled by the board via SPI. I know I can use those two at the same time because I'm doing it with my transmitting arduino and I can see that it's transmitting correctly.

When I try to view my serial data in the serial port, I get nothing but a stream of these error codes, or whatever they are. They generally look like this: VMDPE_1|1_VMDPE. Usually there are some numbers in there too, like: MDPE_1|2571143_VMDPE. I sort of expected that, since you can't read and write at the same time on one serial. But that would be fine, because my project is not going to be plugged into a PC anyway.

So of course I try to pipe my data directly to the LCD screen so I can plug my recieving arduino into external power and not have to see the error messages, which I thought were coming from the debugger of my compiler. Here's my code:

    //on the receiver side

    #include <stdint.h>
    #include <TFTv2.h>
    #include <SPI.h>

    char incoming[3];

    void setup() {
     Serial.begin(9600);
     //TFT_BL_ON;      // turn on the background light
     //Tft.TFTinit();  // init TFT library
     //Tft.setDisplayDirect(DOWN2UP);
     //TFT_BL_ON;      // turn on the background light
     //Tft.drawString("INCOMING:", 20, 301, 3, RED);
     Serial.println(incoming);

    }

    void loop() {

     if (Serial.available()) {

      Serial.readBytesUntil(',', incoming, 3 ) ;

      //Tft.fillRectangle(64, 236, 45, 165, BLACK);

      //Tft.drawString(incoming, 65, 235, 4, WHITE);
      Serial.println(incoming);

     }
    }

But nope! I get the same error codes on my LCD screen! Even worse, now they seem to have screwed up my zigbee module! I took it off the board, plugged it into my computer, and now the XCTU utility is reading all sorts of messed up values that are total nonsense. Somehow, this seems to have overwritten the zigbee's actual SERIAL NUMBERS!!! What are they now? Take a guess!

Serial number high: E_1|2571092_VMDPE

Serial number low:  MDPE_1|2571143_VMDPE

body:
Your `incoming` buffer is not big enough to handle the data that you're giving it. Cutting away the comments from your code:

    char incoming[3];

This declares a buffer for **two** characters, allowing for the (required) `0` on the end. `println()` needs to know when to stop printing characters: it does this when it sees a `NUL` (`0`) character.

    Serial.readBytesUntil(',', incoming, 3 ) ;

You're passing in that you want to read `3` characters - but that completely fills `incoming`, leaving no room for the trailing `NUL` (`0`).

    Serial.println(incoming);

This then prints the first character, the second character, the third character... then the 4th, 5th, 6th, 7th etc. in memory until it _finally_ reaches a `NUL` and then quits.

What you call "debug messages" are actually printed gibberish in memory... To fix it, you need to make `incoming` larger.

Also, it's a good idea when using buffers like this to use the `sizeof()` function, as follows:

    Serial.readBytesUntil(',', incoming, sizeof(incoming)-1 ) ; // Note the -1!


body:
I have seen the same messages, using VS2017 and Arduino Unu and Visual Micro. Messages start with "DPV..." or "VMDPV...".

The solution is to upload the sketch to the Arduino using Release mode. Then the hidden debug serial prints that Visual Micro seems to put in are gone.
[![enter image description here][1]][1]

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


body:
I had the same problem. The problem seems to come from AVR Studio serial debugging. If you turn off the serial debugger the problem will go away. Remember to also turn of **"Automatic Software Debugging (Release/Debug)"**, as shown below.
[![enter image description here][1]][1]

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


message:
Help me restructure code for multitasking Neopixel + IR remote + arduino

First of all, I'm completely new to both arduino, and programing. Second, as for a good newbie, i'm trying to build a fairly complicated project. So, any help and suggestion is welcome. The goal is: light up a shelf, with 2x 1m led strip, with 2 different "fire" animation. And remote control the arduino to switch between effects and colors.

The state of the project so far https://circuits.io/circuits/2459366-arduino-ir-with-neopixel

I learned one arduino is not enough to decode IR signals and drive led strips. So, I'm using two. Successfully merged 2 sketches: one, that receives, decodes and sends the IR signal to another arduino.

And based on tutorial https://learn.adafruit.com/multi-tasking-the-arduino-part-3/put-it-all-together-dot-dot-dot

I managed to control the LEDs via IR remote control. Here is code currently using (a bit bloated since its contains all the effect from the tutorial.)

Here is code so far:

    #include <Adafruit_NeoPixel.h>
    #include <Wire.h>
    #define I2C_SLAVE_ADDRESS 8

    // Remote control button codes
    const unsigned int BUTTON_1 = 0xFD08F7;
    const unsigned int BUTTON_2 = 0xFD8877;
    const unsigned int BUTTON_3 = 0xFD48B7;
    const unsigned int BUTTON_4 = 0xFD28D7;
    const unsigned int BUTTON_5 = 0xFDA857;
    const unsigned int BUTTON_6 = 0xFD6897;
    const unsigned int BUTTON_7 = 0xFD18E7;
    const unsigned int BUTTON_8 = 0xFD9867;
    const unsigned int BUTTON_9 = 0xFD58A7;
    const unsigned int BUTTON_UP = 0xFD50AF;
    const unsigned int BUTTON_DOWN = 0xFD10EF;
    const unsigned int BUTTON_VOL = 0xFD906F;

    int t = 0; // variable for switching led rings with the remote
    int b = 255; // brigtness starting value
    // IR received code
    unsigned int irCode = 0;            //ir code ends here
    // Pattern types supported:
    enum  pattern { NONE, RAINBOW_CYCLE, THEATER_CHASE, COLOR_WIPE, SCANNER, FADE, FIRE };
    // Patern directions supported:
    enum  direction { FORWARD, REVERSE };

    // NeoPattern Class - derived from the Adafruit_NeoPixel class
    class NeoPatterns : public Adafruit_NeoPixel
    {
        public:

        // Member Variables:
        pattern  ActivePattern;  // which pattern is running
        direction Direction;     // direction to run the pattern

        unsigned long Interval;   // milliseconds between updates
        unsigned long lastUpdate; // last update of position

        uint32_t Color1, Color2;  // What colors are in use
        uint16_t TotalSteps;  // total number of steps in the pattern
        uint16_t Index;  // current step within the pattern

        void (*OnComplete)();  // Callback on completion of pattern

        // Constructor - calls base-class constructor to initialize strip
        NeoPatterns(uint16_t pixels, uint8_t pin, uint8_t type, void (*callback)())
        :Adafruit_NeoPixel(pixels, pin, type)
        {
            OnComplete = callback;
        }

        // Update the pattern
        void Update()
        {
            if((millis() - lastUpdate) > Interval) // time to update
            {
                lastUpdate = millis();
                switch(ActivePattern)
                {
                    case RAINBOW_CYCLE:
                        RainbowCycleUpdate();
                        break;
                    case THEATER_CHASE:
                        TheaterChaseUpdate();
                        break;
                    case COLOR_WIPE:
                        ColorWipeUpdate();
                        break;
                    case SCANNER:
                        ScannerUpdate();
                        break;
                    case FADE:
                        FadeUpdate();
                case FIRE:
                        RainbowCycleUpdate();
                        break;
                    default:
                        break;
                }
            }
        }

        // Increment the Index and reset at the end
        void Increment()
        {
            if (Direction == FORWARD)
            {
               Index++;
               if (Index >= TotalSteps)
                {
                    Index = 0;
                    if (OnComplete != NULL)
                    {
                        OnComplete(); // call the comlpetion callback
                    }
                }
            }
            else // Direction == REVERSE
            {
                --Index;
                if (Index <= 0)
                {
                    Index = TotalSteps-1;
                    if (OnComplete != NULL)
                    {
                        OnComplete(); // call the comlpetion callback
                    }
                }
            }
        }

        // Reverse pattern direction
        void Reverse()
        {
            if (Direction == FORWARD)
            {
                Direction = REVERSE;
                Index = TotalSteps-1;
            }
            else
            {
                Direction = FORWARD;
                Index = 0;
            }
        }

        // Initialize for a RainbowCycle
        void RainbowCycle(uint8_t interval, direction dir = FORWARD)
        {
            ActivePattern = RAINBOW_CYCLE;
            Interval = interval;
            TotalSteps = 255;
            Index = 0;
            Direction = dir;
        }

        // Update the Rainbow Cycle Pattern
        void RainbowCycleUpdate()
        {
            for(int i=0; i< numPixels(); i++)
            {
                setPixelColor(i, Wheel(((i * 256 / numPixels()) + Index) & 255));
            }
            show();
            Increment();
        }

        // Initialize for a Theater Chase
        void TheaterChase(uint32_t color1, uint32_t color2, uint8_t interval, direction dir = FORWARD)
        {
            ActivePattern = THEATER_CHASE;
            Interval = interval;
            TotalSteps = numPixels();
            Color1 = color1;
            Color2 = color2;
            Index = 0;
            Direction = dir;
       }

        // Update the Theater Chase Pattern
        void TheaterChaseUpdate()
        {
            for(int i=0; i< numPixels(); i++)
            {
                if ((i + Index) % 3 == 0)
                {
                    setPixelColor(i, Color1);
                }
                else
                {
                    setPixelColor(i, Color2);
                }
            }
            show();
            Increment();
        }

        // Initialize for a ColorWipe
        void ColorWipe(uint32_t color, uint8_t interval, direction dir = FORWARD)
        {
            ActivePattern = COLOR_WIPE;
            Interval = interval;
            TotalSteps = numPixels();
            Color1 = color;
            Index = 0;
            Direction = dir;
        }

        // Update the Color Wipe Pattern
        void ColorWipeUpdate()
        {
            setPixelColor(Index, Color1);
            show();
            Increment();
        }

        // Initialize for a SCANNNER
        void Scanner(uint32_t color1, uint8_t interval)
        {
            ActivePattern = SCANNER;
            Interval = interval;
            TotalSteps = (numPixels() - 1) * 2;
            Color1 = color1;
            Index = 0;
        }

        // Update the Scanner Pattern
        void ScannerUpdate()
        {
            for (int i = 0; i < numPixels(); i++)
            {
                if (i == Index)  // Scan Pixel to the right
                {
                     setPixelColor(i, Color1);
                }
                else if (i == TotalSteps - Index) // Scan Pixel to the left
                {
                     setPixelColor(i, Color1);
                }
                else // Fading tail
                {
                     setPixelColor(i, DimColor(getPixelColor(i)));
                }
            }
            show();
            Increment();
        }

        // Initialize for a Fade
        void Fade(uint32_t color1, uint32_t color2, uint16_t steps, uint8_t interval, direction dir = FORWARD)
        {
            ActivePattern = FADE;
            Interval = interval;
            TotalSteps = steps;
            Color1 = color1;
            Color2 = color2;
            Index = 0;
            Direction = dir;
        }

        // Update the Fade Pattern
        void FadeUpdate()
        {
            // Calculate linear interpolation between Color1 and Color2
            // Optimise order of operations to minimize truncation error
            uint8_t red = ((Red(Color1) * (TotalSteps - Index)) + (Red(Color2) * Index)) / TotalSteps;
            uint8_t green = ((Green(Color1) * (TotalSteps - Index)) + (Green(Color2) * Index)) / TotalSteps;
            uint8_t blue = ((Blue(Color1) * (TotalSteps - Index)) + (Blue(Color2) * Index)) / TotalSteps;

            ColorSet(Color(red, green, blue));
            show();
            Increment();
        }

        // Calculate 50% dimmed version of a color (used by ScannerUpdate)
        uint32_t DimColor(uint32_t color)
        {
            // Shift R, G and B components one bit to the right
            uint32_t dimColor = Color(Red(color) >> 1, Green(color) >> 1, Blue(color) >> 1);
            return dimColor;
        }

        // Set all pixels to a color (synchronously)
        void ColorSet(uint32_t color)
        {
            for (int i = 0; i < numPixels(); i++)
            {
                setPixelColor(i, color);
            }
            show();
        }

        // Returns the Red component of a 32-bit color
        uint8_t Red(uint32_t color)
        {
            return (color >> 16) & 0xFF;
        }

        // Returns the Green component of a 32-bit color
        uint8_t Green(uint32_t color)
        {
            return (color >> 8) & 0xFF;
        }

        // Returns the Blue component of a 32-bit color
        uint8_t Blue(uint32_t color)
        {
            return color & 0xFF;
        }

        // Input a value 0 to 255 to get a color value.
        // The colours are a transition r - g - b - back to r.
        uint32_t Wheel(byte WheelPos)
        {
            WheelPos = 255 - WheelPos;
            if(WheelPos < 85)
            {
                return Color(255 - WheelPos * 3, 0, WheelPos * 3);
            }
            else if(WheelPos < 170)
            {
                WheelPos -= 85;
                return Color(0, WheelPos * 3, 255 - WheelPos * 3);
            }
            else
            {
                WheelPos -= 170;
                return Color(WheelPos * 3, 255 - WheelPos * 3, 0);
            }
        }

       // brightness, need some improvements probably
       void incbrigtness() {
       if (b >= 255) {
          b = 255;
       setBrightness(b);}
       else {b = b + 10;
       setBrightness(b);}
       }

       void decbrigtness() {
       if (b <= 5) {
          b = 5;
       setBrightness(b);}
       else {b = b - 10;
       setBrightness(b);}
       }

    };

    void Ring1Complete();
    void Ring2Complete();

    void receiveEvent(int numBytes) {//decode the ir signal
      byte byte1 = Wire.read();
      byte byte2 = Wire.read();
      irCode = byte2;
      irCode = irCode << 8;
      irCode = irCode | byte1;
    }

    // Define some NeoPatterns for the two rings and the stick
    //  as well as some completion routines
    NeoPatterns Ring1(24, 6, NEO_GRB + NEO_KHZ800, &Ring1Complete); // led parameters
    NeoPatterns Ring2(24, 7, NEO_GRB + NEO_KHZ800, &Ring2Complete);

    // Initialize everything and prepare to start
    void setup()
    {
       Serial.begin(9600);
       Serial.println("my-main-program starting!");
       Wire.begin(I2C_SLAVE_ADDRESS);
       Wire.onReceive(receiveEvent);
       Serial.println("my-main-program successfully started!");
     }
    // Main loop
    void loop()
    {
        // Update the rings.
       if (irCode) {             //Reads the ir code
        handleButton(irCode);
        irCode = 0;
      }
     Ring1.Update();
     Ring2.Update();
     }

    void handleButton(unsigned int irCode) {
      switch (irCode) {
       case BUTTON_UP:      // button up  will control led stip 1, button 2 will control let strip 2, button 3 both.
          t = 1;
         Serial.println(t);
         break;
       case BUTTON_DOWN:
          t = 2;
         Serial.println(t);
          break;
       case BUTTON_VOL:
         t = 0;
          Serial.println(t);
         break;
       case BUTTON_1:
         if (t == 1) {    // this also needs some improvements
          Serial.println(t);
         Ring1.TheaterChase(Ring1.Color(0,255,0), Ring1.Color(0,0,50), 100);
          }
         else if (t == 2) {
         Serial.println(t);
         Ring2.TheaterChase(Ring1.Color(255,0,0), Ring1.Color(0,50,0), 100);
          }
         else {      // some random effects for testing
         Serial.println(t);
          Ring1.TheaterChase(Ring1.Color(0,0,255), Ring1.Color(50,0,0), 100);
         Ring2.TheaterChase(Ring1.Color(0,0,255), Ring1.Color(50,0,0), 100);
          }
       break;
        case BUTTON_2:
          Serial.println("2");
           Ring1.Scanner(Ring1.Color(255,0,0), 55);
         break;
        case BUTTON_3:
         Ring1.ColorWipe(Ring1.Color(0,255,255), 55);
         Serial.println("3");
          break;
        case BUTTON_4:
          Ring1.Scanner(Ring1.Color(0,255,255), 55);
         Serial.println("4");
          break;
        case BUTTON_5:
          Serial.println("5");
          break;
        case BUTTON_6:
          Serial.println("6");
          break;
        case BUTTON_7:
          Serial.println("7");
          break;
        case BUTTON_8:         //  test the brightness here.
       Ring1.incbrigtness();
       Serial.println(b);
         break;
        case BUTTON_9:
       Ring1.decbrigtness();
       Serial.println(b);
         break;
        default:
          Serial.print("Unrecognized code received: 0x");
          Serial.println(irCode, HEX);
          break;
      }
    }

    //------------------------------------------------------------
    //Completion Routines - get called on completion of a pattern
    //------------------------------------------------------------

    // Ring1 Completion Callback
    void Ring1Complete() //dont really need to do anything specific after loop ended so should go back to update.
    {Ring1.Update(); }

    void Ring2Complete()
    {Ring2.Update(); }

The problem:
What I need is help, how to restructure 2 different effects. to fit into the above code. Loops replaced wilth millis() and delay with an updater.

here is the first, fire code by danesparza:

    #include <Adafruit_NeoPixel.h>
    #define PIN 6

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(29, PIN, NEO_GRB + NEO_KHZ800);

    void setup() {
      strip.begin();
      strip.setBrightness(brightness);
      strip.show(); // Initialize all pixels to 'off'
    }

    void loop() {

      //  Uncomment one of these RGB (Red, Green, Blue) values to
      //  set the base color of the flame.  The color will flickr
      //  based on the initial base color

      //  Regular (orange) flame:
      //  int r = 226, g = 121, b = 35;

      //  Purple flame:
      //  int r = 158, g = 8, b = 148;

      //  Green flame:
      int r = 74, g = 150, b = 12;

      //  Flicker, based on our initial RGB values
      for(int i=0; i<strip.numPixels(); i++) {
        int flicker = random(0,55);
        int r1 = r-flicker;
        int g1 = g-flicker;
        int b1 = b-flicker;
        if(g1<0) g1=0;
        if(r1<0) r1=0;
        if(b1<0) b1=0;
        strip.setPixelColor(i,r1,g1, b1);
      }
      strip.show();

      //  Adjust the delay here, if you'd like.  Right now, it randomizes the
      //  color switch delay to give a sense of realism
      delay(random(10,113));
    }

And a ripple effect that needs a restructure by suhajdab

    #include <Adafruit_NeoPixel.h>
    #define PIN 2
    #define Pixels 24
    #define BG 1
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(Pixels, PIN, NEO_GRB + NEO_KHZ800);

    int color;
    int center = 0;
    int step = -1;
    int maxSteps = 16;
    float fadeRate = 0.6;
    int diff;

    //background color
    uint32_t currentBg = random(256);
    uint32_t nextBg = currentBg;

    void setup() {
      strip.begin();
      strip.show(); // Initialize all pixels to 'off'
    }

    void loop () {
      ripple();
    }

    void ripple() {
      if (BG){
        if (currentBg == nextBg) {
          nextBg = random(256);
        }
        else if (nextBg > currentBg) {
          currentBg++;
        } else {
          currentBg--;
        }
        for(uint16_t l = 0; l < Pixels; l++) {
          strip.setPixelColor(l, Wheel(currentBg, 0.1));
        }
      } else {
        for(uint16_t l = 0; l < Pixels; l++) {
          strip.setPixelColor(l, 0, 0, 0);
        }
      }

      if (step == -1) {
        center = random(Pixels);
        color = random(256);
        step = 0;
      }

      if (step == 0) {
        strip.setPixelColor(center, Wheel(color, 1));
        step ++;
      }
      else {
        if (step < maxSteps) {
          strip.setPixelColor(wrap(center + step), Wheel(color, pow(fadeRate, step)));
          strip.setPixelColor(wrap(center - step), Wheel(color, pow(fadeRate, step)));
          if (step > 3) {
            strip.setPixelColor(wrap(center + step - 3), Wheel(color, pow(fadeRate, step - 2)));
            strip.setPixelColor(wrap(center - step + 3), Wheel(color, pow(fadeRate, step - 2)));
          }
          step ++;
        }
        else {
          step = -1;
        }
      }

      strip.show();
      delay(50);
    }

    int wrap(int step) {
      if(step < 0) return Pixels + step;
      if(step > Pixels - 1) return step - Pixels;
      return step;
    }

    // Input a value 0 to 255 to get a color value.
    // The colours are a transition r - g - b - back to r.
    uint32_t Wheel(byte WheelPos, float opacity) {

      if(WheelPos < 85) {
        return strip.Color((WheelPos * 3) * opacity, (255 - WheelPos * 3) * opacity, 0);
      }
      else if(WheelPos < 170) {
        WheelPos -= 85;
        return strip.Color((255 - WheelPos * 3) * opacity, 0, (WheelPos * 3) * opacity);
      }
      else {
        WheelPos -= 170;
        return strip.Color(0, (WheelPos * 3) * opacity, (255 - WheelPos * 3) * opacity);
      }
    }

So, can someone help me how to include these 2 effects based on the tutorial (unfortunately not much help on my current skill level) to the first code? Much appreciated.

body:
You see in the second part is a `void ripple(){`, which is just like a `void loop(){` but only runs when it is called.

You can merge these codes by placing an if-statement after your `void loop(){` to check if it needs to run the loop or the ripple. You can simply use a boolean for this. For example:`

    void loop(){
      if(state == true){  //I've called the boolean state
        ripple();  //this calls the ripple function, and runs void ripple()
      }

      //here's the rest of the loop, this runs if state != true.
      //you can change state wherever you'd like.
    }

You could even create a new function based on what's currently in your loop. Example:

    void loop(){
      if(state == 1){
        originalLoop(); //what's originally in your loop, but now as a separate function
      }
      else if(state == 2){
        ripple();
      }

      //rest of the loop in which you can change state to 1 or 2 however you like
    }

Hope this helps a bit :)


message:
Stepper Motor Button Press

I am having difficulties programming what should be a simple sketch that gets my **stepper motor to run at one step per second indefinitely at the press of a button and then stops at the press of another button.** I am using the *Bounce2.h* and *accelstepper.h* libraries and have been unable to figure out how to do it. Any help would be greatly appreciated, and as for hardware I am using a ***NEMA 23 High Torque Stepper Motor*** connected through a ***M542T Motor Driver*** powered by a ***Switching Power Supply*** and running on an ***Arduino UNO.***

Attatched find my code, and thank you so much for the help!

    #include <Bounce2.h>
    #include <LiquidCrystal.h>
    #include <SoftwareSerial.h>
    #include <AccelStepper.h>

    AccelStepper stepper(1, 9, 8); // initiate stepper motor

    //int buttonPresses = 0;
    const byte ButtonPin = 10;
    const byte LedPin = 13; // for debugging and visualization

    Bounce button;

    void setup() {
      Serial.begin(9600);
      button.attach(ButtonPin);
      pinMode(LedPin, OUTPUT);
      stepper.setSpeed(1);
    }

    void loop() {
      if (button.rose()) {
        stepper.runSpeed();
        digitalWrite(LedPin, HIGH);
        //    buttonPresses++; // count presses of button and print to monitor
        //    Serial.print("Number of Button ");
        //    Serial.print("Presses = ");
        //    Serial.println(buttonPresses);
      }
      else {
        button.update();
        digitalWrite(LedPin, LOW);
        if (button.fell()) {
          stepper.stop();
        }
      }
    }

**As of now, a button press runs the motor at 1 step/second, but a second press or any subsequent presses thereafter do nothing to stop the motor. Thanks so much!**

***!!EDIT!!***

Upon adding a boolean buttonState and setting it to LOW in the setup and changing my void loop() code to look like:

    void loop() {
      button.update();
      if (button.rose() == true && buttonState == LOW) {
        stepper.runSpeed();
        digitalWrite(LedPin, HIGH);
        buttonState = HIGH;
      }
      else {
        if (button.fell() == true && buttonState == HIGH) {
          stepper.stop();
          buttonState = LOW;
        }
      }
    }

I know get a step every button press. Just thought it may help in answering.

**EDIT 2**

So I I tried pulling the runSpeed() out of the loop and adding                                                            `if (buttonState = HIGH){stepper.runSpeed();}`
but that now just runs the stepperMotor constantly and at variable speed and will not turn it off?

**EDIT 3 and Working Code**
Thank you Janw for the help. I realized my fault in calling the runSpeed function within the if statement. Further, I also needed to change button.fell() to button.rose() since button.fell() returns true when the button is released, so basically I was stopping the motor everytime I let go of the button. Here is the final, and working void loop() in case anyone runs into a similar problem in the future:

    void loop() {
      button.update();
      if (button.rose() == true && buttonState == LOW) {
        digitalWrite(LedPin, HIGH);
        buttonState = HIGH;
      }
      else {
        if (button.rose() == true && buttonState == HIGH) {
          stepper.stop();
          buttonState = LOW;
        }
      }
      if (buttonState == HIGH) {
        stepper.setSpeed(1);
        stepper.runSpeed();
      }
    }

body:
You will probably get only 1 step each button press because your *runSpeed()* is within the *if (button.rose() == true && buttonState == LOW)*-statement.

The *runSpeed()* needs to be called every loop to check if the motor needs to step.

A simple way to change this is to set a boolean to true or false if you check your button and add something like this pseudocode:

    if(motorRun == true) stepper.runSpeed();


message:
Data transfer using SPI

Sorry for my code is long and my English is not good.

I'm working with **8x8x8 LED cube** project using **Arduino nano**. I tried to understand code, but I don't understand how `cube[][]` data write on `pins`.

I just want to know, how write the data from `cube[8][8]` to hardware using **SPI**. code download using [this][1] link.

Thanks in advance.

My code is here :

    #define AXIS_X 1
    #define AXIS_Y 2
    #define AXIS_Z 3
    #define REFRESH_RATE 120

    int CUBE_SIZE = 8;
    int SPI_CS = 10;// This SPI Chip Select pin controls the MAX72xx
    byte value[8];

    volatile unsigned char cube[8][8];
    volatile int current_layer = 0;

    void setup()
    {
      Serial.begin (115200);
      Serial.println("jolliFactory 8x8x8 jolliCube Demo example 1.0");

      pinMode(SPI_CS, OUTPUT);

      SPI.begin();

      maxTransferAll(0x0F, 0x00);   // 00 - Turn off Test mode
      maxTransferAll(0x09, 0x00);   // Register 09 - BCD Decoding  // 0 = No decoding
      maxTransferAll(0x0B, 0x07);   // Register B - Scan limit 1-7  // 7 = All LEDS
      maxTransferAll(0x0C, 0x01);   // 01 = on 00 = Power saving mode or shutdown
      maxTransferAll(0x0A, 0x0F);   // Set Brightness Intensity

      setUpInterrupts();
    }

    // Get the current status of a voxel
    unsigned char getvoxel(int x, int y, int z)
    {
     if (inrange(x,y,z))
     {
      if (cube[z][y] & (1 << x))
      {
       return 0x01;
      } else
      {
       return 0x00;
      }
     } else
     {
      return 0x00;
     }
    }

    void maxTransferAll(uint8_t address, uint8_t value)
    {
      digitalWrite(SPI_CS, LOW);

        for ( int c=1; c<= CUBE_SIZE;c++) {
            SPI.transfer(address);
            SPI.transfer(value);
        }

      digitalWrite(SPI_CS, HIGH);
    }

    void maxTransferOne(uint8_t whichMax, uint8_t address, uint8_t value)
    {
      byte noop_reg = 0x00;    //max72xx No op register
      byte noop_value = 0x00;  //value

      digitalWrite(SPI_CS, LOW);

      for (int i=CUBE_SIZE; i>0; i--)   // Loop through our number of Max72xx ICs
      {
        if (i==whichMax)
        {
          SPI.transfer(address);
          SPI.transfer(value);
        }
        else
        {
          SPI.transfer(noop_reg);
          SPI.transfer(noop_value);
        }
      }

      digitalWrite(SPI_CS, HIGH);
    }

    void maxTransferLEDCube(uint8_t address)
    {
      digitalWrite(SPI_CS, LOW);

      for (int i=0; i<CUBE_SIZE; i++)   // Loop through our number of Max72xx ICs
      {
          SPI.transfer(address);
          SPI.transfer(value[CUBE_SIZE-i-1]);
      }

      digitalWrite(SPI_CS, HIGH);
    }

    void setUpInterrupts()
    {
      cli();//stop interrupts while we set them up
      //set up an interrupt with timer1
      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1  = 0;
      OCR1A = (16000000/REFRESH_RATE/1024/CUBE_SIZE -1);
      TCCR1B |= (1 << WGM12);
      // Set to CS10 and CS12 so we have the 1024
      TCCR1B |= (1 << CS12) | (1 << CS10);
      TIMSK1 |= (1 << OCIE1A);
      sei();//re-allow interrupts
    }

    ISR(TIMER1_COMPA_vect)
    {
      for(byte y = 0 ; y < CUBE_SIZE ; y++)
      {
        byte b = 0;

        for(byte x = 0 ; x < CUBE_SIZE ; x++)
        {
          //form data byte
          b = b << 1;

          if (getvoxel(x,y,current_layer)==1)
          {
            b |= 1;
          }
        }
            value[y] = b;
      }

      maxTransferLEDCube(CUBE_SIZE - current_layer);

      current_layer++;

      if (current_layer == 8)
        current_layer = 0;
    }

  [1]: http://www.instructables.com/id/JolliCube-an-8x8x8-LED-Cube-SPI/?ALLSTEPS

body:
First, you need to know how the LEDs are arranged. There are 8 layers, each with 8 rows, each with 8 LEDs.

Each LED is represented as a single _bit_ inside `unsigned char cube[8][8];` - the first `[8]` is the array of layers, the second `[8]` is the array of rows, and the `unsigned char` holds 8 bits to represent the state of the 8 LEDs in that row.

Each LED layer has one MAX7219 8x8 LED Matrix Controller. To tell it what to do you need to give it a Command byte and a Data byte. So to tell it to light up LEDs 1, 2, and 7 on the fourth row, you need to tell it `0x04 0x86`. You send this command by setting `CS` `LOW`, sending the 16 bits of the Command+Data, then setting `CS` `HIGH`.

Each MAX7219 is connected one after the other in an SPI string. To command all of them at once you need to set `CS` `LOW`, send 16 bits for each MAX7219 (128 bits in all), then set `CS` `HIGH`. If you only want to command one MAX7219, you need to send a `NOP` Command+Data (`0x00 0x00`) to all the others.

The way the program works is:

1. **`setup()`**

  a. Initialise the `Serial` port, and print a message.
  b. Set the `CS` pin as an `OUTPUT`, then initialise `SPI`.
  c. Initialise all the MAX7219 chips by sending a series of commands -
  the same Command+Data to each of them (`maxTransferAll()`).
  d. Initialise the Timer interrupt (`setUpInterrupts()`).

2. **`loop()`**
  This isn't shown in the code. Presumably it alters the `cube[8][8]` array to make the special effects.

3. **`TIMER1_COMPA_vect`** (the interrupt handler)
  Every time the timer ticks, the handler will command all of the MAX7219s to show the next row of LEDs.  This will last until the next timer tick, when the next row will be displayed. If this is done fast enough, the human eye's "persistence of vision" will not see the rows flickering.

        For each row (`y`) in the `cube` array
           Set `b` to 0
           For each bit ('x') in the `cube` data
              If the bit is set (`getvoxel(...)`) set a bit in `b`.
           Store `b` in the `value[y]` array

`value` now holds the bytes needed as Data for the next row for each of the MAX7219 chips.

        Send value over SPI using `maxTransferLEDCube(...)`

Since the cube displays the same row for each layer simultaneously, the Command doesn't have to change, only the Data does. That's what the `value` array holds: the Data to be sent to each MAX7219 chip.


message:
Exporting ADC data to excel

Do I need third party s/w to export to a spreadsheet? I have built a heat flux sensor meter and wish to log my data.

body:
You need some way of getting the data from the Arduino to the PC. There's a number of ways of doing it depending on what resources you have available.

* Through serial as CSV

This entails printing the data to the serial port in CSV format then using some software on the PC to capture that and save it to a file. That could be as simple as a good terminal emulator that provides "capture to file" or similar, or you could write your own program in your favourite programming language.  This method is essentially free.

* To an SD card

Writing the data as a CSV file onto an SD card directly attached to the Arduino can be quite convenient. It means you can then just take the SD card with the data on it and slip it into your computer to import the data as you would with any other file.  It needs an SD card shield or breakout board attaching to the Arduino

* Through the network

If your Arduino has a network connection of some form (WiFi shield, Ethernet shield, etc) you could POST the data to a web page running on your PC and store it in a CSV file for later importing. Probably the most expensive option but it does mean you can do things with the data "live" as it comes in.


body:
Use tabs to separate columns of data, and newlines between each row.
Then you can copy the serial output, and paste it into Excel.


message:
ESP8266 - AT Command for Network Requiring Username AND Password

I have been using my ESP8266 module with my Arduino on my university's Wi-Fi network, which only requires a password to log on to.

The university will soon terminate that Wi-Fi network and replace it with one that requires a username and password to log on.

What would that AT command be to connect to such a network?

Edit: I have since found out that the university has changed the network so that a user can "connect" to the network and then enter their university id/password in a captive portal to gain internet access (and perhaps other features of the network). Also, I have since learned how to overwrite the firmware on my esp-01 so that I no longer need to use the AT commands -- in fact, I can program it in the Arduino IDE just as I would with another esp8266-based device, such as the NodeMCU.

body:
We can't tell without more information but it sounds rather like you will need a [WiFi_SSID, WiFi_PASSWORD] pair for the ESP to connect to the WiFi, and a [Network_USERNAME, Network_USERPASSWORD] pair for their network to let you use the network (as if you were logging onto it by hand from a terminal).

If so, you'd provide the first pair as you do now, with the AT+CWJAP... command, to get your device connected to the WiFi. For the second pair, your Arduino will probably need to interact with a user logon screen to provide the second pair. You'll need to get those details from the school's IT department, and possibly mimic a terminal.

Update:
As above, you need to find out whether the network requires 2 sets of credentials - the SSID and WPA2 key and network username and password. If it requires the latter, then your ESP can get you onto the WiFi but your Arduino will then have to mimic a user sitting at a terminal - read the network ID and Password challenges and provide the appropriate responses. Without know that, you can't know how to write the login code, nor can we. It sounds as if there are people on site who have already done what you're trying to do. They and their experience can be far more helpful than we, who have no knowledge of the school network.


body:
If you are using Arduino+ESP8266 version 1(ESP-01)module. You can connect ESP module to the internet, using AT commands as follows:

Normally, AT+CWJAP="ssid","password"

If your Internet requires ssid, username and passowrd(usually in universities- eduroam) then

1) Connect to eduroam or university wifi using ssid, username and password from
   your laptop.

2) Install Connectify Hotspot software in your laptop.

3) Open "Connectify Hotspot" application and open settings tab, then create
   wifi-hotspot.

4) Give eduroam(or your wifi)-->"Internet to share" field , Give your own
   Hotspot name and password. Then click on "start Hotspot" button.

5) Now your esp01 module can detect this new hotspot using AT+CWLAP. Connect to
   it using AT+CWJAP="HOtspot ssid","HOtspot password".

This way you can overcome the problem of extra Authentication.

Hope it helped. Enjoy Programming.


message:
Listen for USB "TX signal received" response on RX

Is there a usb signal I can send on TX that will generate a response from the computer on the RX only if the computer is active/not a wall usb power supply? I'm trying to use the Remote library when a button is pressed and sometimes it won't work because the computer is off/asleep/etc and in those instances I would like the arduino to behave differently but because I have no way of knowing if the USB power is coming from the wall or passively from a computer that's off or actively from a computer that's on, I can't know what behavior to take.

To be clear about the application in mind: Right now I have a device that sends keyboard signals to my computer using a modified version of Stefan Jones' modified [USBAPI.h and HID.cpp files.](https://github.com/stefanjones/Arduino/tree/master/hardware/arduino/cores/arduino) It works fine but if you restart the computer you have to manually unplug and replug in the arduino to get it to work again. This is necessary every restart, is rather annoying, and adds unnecessary wear to the connector. This is also necessary if the arduino is connected before the OS has loaded. Additionally there are some LEDs on the device (not talking about the diagnostic lights on the arduino itself) that stay lit up at night even when the computer is off. If I could detect when the computer is off/unconnected it would be trivial to fix this.

body:
If an MCU which has a built in USB interface (such as the ATmega32u4 on a Leondardo) is properly configured and connected to an operating USB host, it will receive a "Start of Frame" packet every millisecond.  I'm not very familiar with the details of the USB engine on that particular chip, but generally you can detect this as an interrupt, or as a change in a peripheral status register bit.

Going a step further, in the Arduino API an `if (Serial)` test will determine if the board is connected to a host which is in an active CDC-ACM "serial" session with it, ie, one that has a serial terminal or other program talking to it.  Again, this only applies to those that implement USB within the chip on which the sketch is running.

**Chances are your problems can be fixed by enabling the AVR watchdog timer at one of its longer limits and resetting it in the USB ISR found in `USBCore.cpp`** Then if the the USB goes down (ie, the usual every millisecond SoF interrupt fails to happen for several seconds) your Arduino will reset.  In the simple case, it will keep resetting as long as it has power and the USB is down, but you can put some startup logic to wait for the USB while resetting the watchdog if that bothers you.  See for comparative example the implementation details behind the `if (serial)` and create something similar for your chosen USB mode.


body:
As I understand, you are trying to implement some peripheral device based on AtMega 8-bit micro-controller that uses USB1.1 interface (FS or LS) to connect to USB host. Your problem seems to be that your host computer (unspecified) puts the port into SUSPEND (sleep), and does not wake up when you try to activate your device (button or something).

First, the USB2.0/1.1 interface does not have any "Tx" or "Rx", it is a half-duplex bi-directional bus. It has D+ and D-, and VBUS. But it is true that a USB peripheral device can generate a bus event called RESUME.

You have two choices. (1) either you make your host computer to never sleep or put USB ports into SUSPEND, or (2) make your device to support RESUME (aka "remote wake-up") function in full compliance with USB specifications.

In case (2) the driver for your device (on host computer) must support remote wake-up function, and this function must be enabled. Then when the host computer is planning to go into one of various sleep modes and decides to SUSPEND your device, it must send special control command to your device which should arm it for wake-up, and the host will be expecting it. In this case the host will never remove VBUS ("passively from computer"), so the device will be able to wake the bus up.

Is this your question about?


body:
Upon having a clarification on what the problem essentially is, the answer is as follows:

(1) There is no way of knowing if the port is a wall charger or inactive computer port, initially. Therefore the initial device behavior must be identical in both cases – asserting pull-up on D+ (assuming it is USB 1.1 FS interface);

(2) However, if the port belongs to a computer, the connect event will awake the host, and the host will issue USB_reset, and perform device enumeration. There is no need to “send any Tx signal” or else, the host will perform this activity by itself. The Arduino software must remember this.

(3)  If the host decides to suspend the port (fell asleep), the device must transition into SUSPEND state, and Arduino software must remember this.

(4) If the port was initially in a state with USB totally disabled and does not wake up upon cable attach, see scenario (1);

(5) When/if the host computer is awaken, it will see USB attach status (D+ is up), and will start scenario (2).

In summary, the device (upstream facing port) must implement port functionality in full accord with port state machine described in USB2.0 specifications, Section 9 (Figure 9-1) and Appendix C.2 , Figures C-2 and C-3. As one can see, contrary to the assumption of OP, the port can be in more than two states, and Adruino software must have several different behaviors. Any half-baked implementation of the port state diagram is unacceptable and will cause some functional problem sooner or later.


message:
Is Sparkfun's MicroView OLED Arduino module a shield?

I'm getting confused by the Arduino terminologies:  shield, breakout, module.

Is this MicroView an Arduino compatible shield that will plug into Arduino's or Adafruit's Uno?

body: No, MicroView is not an Arduino shield, so you can't plug that into any Arduino. Arduino Uno and MicroView are developed based on Atmega328 controller. So it is 100% code compatible with Arduino Uno, means the code that runs on an Arduino Uno will also be able to run on the MicroView.


message:
Missing Libraries make no sense

I've never much issue importing a library to my master sketchbook location, restarting Arduino, then using the library examples. Today is a different story:

 1. I'm loading [RCLib][1] which is part of this [ArduinoLibraries][2] family
 2. RCLib requires [PinChangeInt][3]

So everything is in my sketchbook location right? `Arduino > Preferences > Sketchbook Location`

Still I'm getting compiler errors about missing libraries:

    /Users/Jackson/Documents/Arduino/ArduinoLibraries-master/RCLib/Examples/Maga6ChanelsA8_A13/Maga6ChanelsA8_A13.ino:7:86: fatal error: PinChangeInt.h: No such file or directory
     #include "PinChangeInt.h"

I've even tried `#include <PinChangeInt.h>` Which makes more sense since this is a system library.

**What is going on here?**

The sketch I'm trying to run:

    /**This is an example of using the RCLib with a mega and pinchangeint
     * This example isprovided as is by Jantje
     * Congratualtions, constructive feedback and I like it can be send to eclipse@baeyens.it
     **/

    #define NUM_RC_CHANNELS 6 //You need to specify how many pins you want to use
    #include "PinChangeInt.h"  //If you need pinchangeint you need to include this header
    const uint8_t RC_Channel_Pin[NUM_RC_CHANNELS]={
      A8,A9,A10,A11,A12,A13};//Here I specify I want to listen to pins A8 to A13 of my mega

    uint16_t RC_Channel_Value[NUM_RC_CHANNELS]; //This variable will contain the values read from the RC signal
    #include "RCLib.h" //This include needs all declarations above. Do not try to move it up or it won't compile

*Arduino v1.6.9 | OSX 10.11.4*

  [1]: https://github.com/jantje/ArduinoLibraries/tree/master/RCLib
  [2]: https://github.com/jantje/ArduinoLibraries
  [3]: https://github.com/GreyGnome/PinChangeInt

body:
I had downloaded PinChangeInterrupt through Arduino

Sketch > Include Library > Manage Libraries... > *Filter your search...* > PinChangeInterrupt > Install

I thought this is all I needed but I was wrong. This differs from the popular [PinChangeInt library][1]. Ultimately the file names where slightly different which is why my file was showing as missing. I found this out by manually looking at the file names in the library I was trying to used and comparing them against my includes.

  [1]: https://github.com/GreyGnome/PinChangeInt


message:
arduino ethernet run php from sd card

I am just interested, but I would like to run a webpage with php on my arduino ethernet. I would like to be able to store my webpage on the sd card as well.

does anyone know of a library that would let me do this?

body:
Thats not possible, only if you write yourself a PHP interpreter, which I suspect won't fit inside an Arduino.

You might be able to create your own interpreter for simple Get and POST requests, but bear in mind that HTTP, and even TCP are very sophisticated protocols to run on an AVR. You might want stick with simple things, preferentially with small messages as you also have very little RAM on those MCUs.


body:
Loading a file off an sdcard and displaying it on port 80 isn't hard. Just check out the 'Ethernet' library and the 'SD' library.

I don't want to discourage you too much about the PHP part, but you won't be able to load the official PHP interpreter onto the Arduino. Simply not enough memory available.

However, if you just want to have dynamic website such as display variables or output from sensors, then you could write your own code interpreter for dynamic web pages that would fit in the memory of an Arduino, just think a bit smaller in scope as far as what it can handle. Maybe you'll end up writing a new library for dynamic webpages for Arduino sensor data.

If you really need to run a PHP interpreter then you can try something like a Rapsberry Pi and hook it up to the Arduino for sensor input using the I2C protocol.


message:
How do I connect components to the Arduino with a motorshield?

How would I connect components to the Arduino with this motor shield?

[![Arduino motor shield][1]][1]

  [1]: https://i.stack.imgur.com/gABEh.jpg
Thanks :)

body:
If you are up for a little soldering, look into [stackable Arduino headers][1]. (Feel free to shop around for those, adafruit was just the first result.) You could then use [male jumpers][2] and a breadboard to connect anything that fits in a breadboard.

Just be careful to avoid pins that the shield is already using.

  [1]: https://www.adafruit.com/product/85
  [2]: https://www.google.com/search?q=male jumpers electronic&tbm=isch


message:
Getting "Undefined reference to vtable for {classname}

I have a large collection of libraries that compile correctly but won't link. I am using Visual Micro for Visual Studio 2015. Here is the complete collection of error messages:

    CommandPattern3.cpp.o:In function `DualMotorRomeo
    DualMotorRomeo.h:undefined reference to `vtable for DualMotorRomeo
    DualMotorRomeo.h:undefined reference to `vtable for DualMotorRomeo
    CommandPattern3.cpp.o:In function `__static_initialization_and_destruction_0
    CommandPattern3.ino:undefined reference to `DualMotorRomeo  ~DualMotorRomeo()
    collect2.exe*:error: ld returned 1 exit status

    Error compiling for board Arduino/Genuino Mega w/ ATmega2560 (Mega 2560)

I have been through the code with a fine toothed comb, but cannot see what references are undefined.

Is there some Windows 10 utility that can examine the vTables and help me find what is missing?

The code base is too large to post, but I can provide a ZIP file with all the code in it for anyone willing to help.

body:
I don't have the header file for `DualMotorRomeo`, but the linker is saying that a destructor has been declared (`~DualMotorRomeo()`) in the class header, but no destructor has been defined. If you didn't write `DualMotorRomeo` then the library needs to be updated.

Until then, simply add the following to one of your source files:

    DualMotorRomeo::~DualMotorRomeo() {
    } // DualMotorRomeo::~DualMotorRomeo()

That will also fix the `vtable` linker errors - the `vtable` will be included in the compiled file with this declared in it.


message:
Arduino wait for change in value

I am currently working on a project that involves steering wheels, and I would like a way for Arduino to wait for a change in value. A potentiometer is used and I would like a program to run (say, like lights blinking ) until there is a change in value of the potentiometer ( like an increase in 300).

Thanks in advance.

**EDIT**
I realized that I did not give enough information about what I want, so here is the actual task I am trying to achieve :

The lights goes on when :

Button is pressed

The lights goes off when :

The button is pressed again

*or*

Another button is pressed

*or*

Potentiometer increases **or** (only one of it) decreases by 300

Plus I didn't mention that the value of the potentiometer will be constantly changing so the old value for the potentiometer should be the one right after the button press.

Soooo sorry for the inconvenience caused. ( I am really bad at programming)

body:
    int oldValue;
    void setup()
    {
        oldValue = analogRead(A1);
    }

    void loop()
    {
        int value = analogRead(A1);
        while( abs(value-oldValue)<300 )
            delay(1);
        oldValue = value;

        // start blinking lights here, as the value has changed by at least 300

    }


body:
A change in value is nothing more than that.  A change between a value *then* and the value *now*.

All you need to do is remember what the value used to be, and compare it with what the value is now. If the two have changed, and the change is big enough, then you do something.

And of course you have to remember that "now" will be "then" "next time".


body:
Figured it out in the end. Although my solution doesn't exactly fit what I wanted but it works in this case. I used the FMS Majenko mentioned like this :
Wait for potentiometer value to go beyond a certain value, then wait for it to come back to the value. If that happens then the lights stop blinking. Thanks guys( this is quite different from what I initially wanted but it is enough for what it is meant to do)


message:
Custom ATMega 2560 board won't execute Arduino code

I have a custom PCB with an ATMega 2560 microcontroller on it. To test if the ATMega was working properly, I uploaded the following code:

    void setup() {
      Serial.begin(9600);
      Serial.println("Test setup");
      pinMode(6, OUTPUT);
      pinMode(30, OUTPUT);
      pinMode(31, OUTPUT);
      pinMode(32, OUTPUT);
    }

    void loop() {
      digitalWrite(6, HIGH);
      digitalWrite(30, HIGH);
      digitalWrite(31, LOW);
      digitalWrite(32, HIGH);
    }
The mentioned ports are connected to LEDs, 6 to an external LED and 30, 31 and 32 to LEDs on the PCB. Each connected in series with a 220 Ohm resistor.

The board is setup like this:

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

When uploading I am using a Arduino UNO as ISP and after uploading the Arduino IDE says 'Done uploading' without any errors, but the board is not showing any sign of executing the code. I have checked that VCC is 5V and RESET is HIGH after uploading. The text "Test setup" is also not shown on the serial monitor.

Does anybody have a clue why the board is not working?

Thanks on forehand.

  [1]: https://i.stack.imgur.com/BosL4.png
  [2]: https://i.stack.imgur.com/HsWlF.png
  [3]: https://i.stack.imgur.com/kzpkK.jpg

body:
When using an empty ATMega2560 you need to change the fuse settings, otherwise it will just upload your code but it won't execute.
This tutorial explains it very clearly:
[Programming ATMega 2560 with Arduino UNO][1]

  [1]: https://soc.ninja/documentation/programming-atmega2560-with-arduino-uno-or-mega/#comment-159


message:
Arduino due + mcp2551

I am currently using an atmega328 along with the mcp 2515 and the 2551 for CAN communication in my systems.

However, I've now decided to upgrade to the arduino due for my operations. Can anybody tell me if the arduino due along with it's inbuilt CAN controller be used with the mcp2551 transciever to operate CAN successfully.

If not, can somebody also tell me if there are other alternatives I should look into. Thanks :)

body:
The biggest trouble you are going to find is the voltage levels. The MCP2551 works at 5V and your MCU is 3.3V. I personally don't have experience with this MCUs, but some STM32 MCUs are 5V tolerant on some pins, including the CAN_TX and Can_RX and it's fine to use a 5V Transceiver like the MCP2551.

Anyway, you still can replace the CAN Transceiver with one that has a built in level shifter,  like one of the following:

- MCP2562
- ATA6561
- SN65HVD256
- NCV7351D13

I've used all the above, except the TI one, and they all talk nicely between each other. Some have different features, like silence or advanced sleeping modes.

Cheers


message:
Neopixel Painter - Need to change few lines. Not sure where to start

My name is Maria and I'm learning programing in high school.
I'm working on a birthday present for my mom, want to make a mood light. Using light painter, a neopixel strip, and an arduino.

https://github.com/adafruit/NeoPixel_Painter

I found the part, which reads the bmp line by line a very innovative way to make custom animations.

But some tweaks are needed. (I've tried to make them, believe me, oh I've tried.) So, i was wondering if i can ask someone a favor and teach me how to modify the code (like, comment on parts that been changed.)

Basically, what I want to be changed is, to loop the current bmp until 'next' button is pressed, rather than hold the trigger. Also, I'm not sure if the code try to save power, but it can be disabled since it will run from a power supply.

Here is the part that makes you hold the trigger button (i think)

      for(;;) {
        while(!(TIFR1 & _BV(TOV1)));               // Wait for Timer1 overflow
        TIFR1 |= _BV(TOV1);                        // Clear overflow bit

        show();                                    // Display current line
        if(stopFlag) break;                        // Break when done

        if(++block >= nBlocks) {                   // Past last block?
          if(digitalRead(TRIGGER) == HIGH) {       // Trigger released?
            memset(sdBuf, 0, N_LEDS * 3);          // LEDs off on next pass
            stopFlag = true;                       // Stop playback on next pass
            continue;
          }                                        // Else trigger still held
          block = 0;                               // Loop back to start
        }
        card.readBlock(block + firstBlock, sdBuf); // Load next pixel row
      }

And the complete code: https://github.com/adafruit/NeoPixel_Painter/blob/master/NeoPixel_Painter.ino

Anyway, Since I'm talking to an experts right now, I have this idea to remote control the code! from  another arduino!

My, probably retarded idea is, to run an IR remote code on a second arduion, than when it receives a signal, send a simulated button press to the first ardu playing the bmp! Is that even possible? Just wondering.

Cheers
Maria

body:
I think you need something like this.

      for(;;) {
        while(!(TIFR1 & _BV(TOV1)));               // Wait for Timer1 overflow
        TIFR1 |= _BV(TOV1);                        // Clear overflow bit

        show();                                    // Display current line

        if(++block >= nBlocks) {                   // Past last block?
          block = 0;                               // Loop back to start
        }

        if(digitalRead(NEXT_PIN_OR_SOMETHING) == LOW) {       // Next button pressed
          break; // Break out of for-loop
        }

        card.readBlock(block + firstBlock, sdBuf); // Load next pixel row
      }


message:
Do I need resistors or capacitors on this relay?

I'm using my Arduino to control a relay switch, which has an extension cord attached to it (see photo).

The relay is connected to the Arduino via pin 9, which is set to `pinMode(9, OUTPUT);`

Do I need any resistors or capacitors or diodes attached to this? Almost feels _too_ simple, given I'm running AC power through the relay. But maybe no?

It definitely _works_, but I want to make sure I'm not going to burn something out (or down).

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

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

body:
Yes, that is too simple.

The Arduino's IO pin is not designed to directly drive a relay. It needs to go through a transistor first, and you must include a diode to absorb the back-EMF generated by the collapsing magnetic field.

Google for "Arduino Relay" and you will find hundreds of thousands of examples.

In short, the circuit you need to create is this:

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

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


message:
How to detect cancelled download?

I have a server with files that may be downloaded.

How do I go about detecting when a download is cancelled by a client?

The function that handles reading files for download:

    void readFile()
    {

 EthernetClient client = server.available();

 // Open file for Reading.
 SdFile webFile;
 webFile.open(&root, &MyBuffer[1], O_READ);
 if (!webFile.isOpen()) error("readFile");

 do   // @ adafruit_support_rick's do-while loop
 {
  int count = 0;
  char buffers[BUFSIZE];
  bool done = false;

  while ((!done) && (count < BUFSIZE) && (webFile.available()))
  {
   char c = webFile.read();
   if (0 > c)
   done = true;
   else
   buffers[count++] = c;
   delayMicroseconds(1000);
  }

  if (count)
  client.write( buffers, count);

 } while (webFile.available());

 webFile.close();

 fileDownload = 0;  //File download has finished; allow logging since download has completed

 delay(500);

 MyBuffer[0] = '\0';

    }

body:
Well, assuming cancelling a download == incomplete download == client disconnected before server was done, you could create a flag like this at the top of the function:

    bool dload_cancel = false;

Change the `IF` block, below the innermost `WHILE` loop, to this:

    if (count){
      if (client.connected())
        client.write( buffers, count);
      else {
        dloadCancel = true;
        break;
      }
    }

The flag will be set once your server checks and discovers that the client has been disconnected. You can check the state of the flag outside the `DO-WHILE` block to know if the download was completed or not.

    if (dloadCancel){
      // client was disconnected; download did not complete
    }

`dloadCancel` is also a better indicator of a completed download than your `fileDownload` flag.

You should also know that this:

    if (0 > c)
        done = true;

is redundant. Its already taken care of by `webFile.available()`.


message:
How do you change the state of an image on a TFT display when the associated pin changes state?

I just recently resolved my problem on getting images to load on to my TFT display via the SD card. Thanks to UTFT_SdRaw!!! it's by far the easiest to use. For a novice like me, its been a real feat. Now translating the code, I am trying to turn on and off the image when the pin state changes:

Example:
When pin A2 on my MEGA goes high (+5vdc) I want my SD to spool up and load an image so here is my code snipit:

****myFiles.load(20, 55, 130, 130, "Power Medium.raw");****

So now when the pin state changes back to low (0vdc), how do I remove the image without clearing the entire screen? The image seems to stay frozen instead of disappearing when the pin voltage falls away.

Any ideas? I am stumped. Thanks in advance for any comments and suggestions that may help me over the hump.

body:
It's quite silmple: just draw a box over the image the same colour as the background.

Either that or draw a different image over the top of the existing image.


message:
Chinese CH340 Arduino Uno - Burning stand allone chip

I followed regular tutorial and I was able to burn boot-loader on my standalone ATM328 chip, but because I'm using this [CH340 UNO][1] and example is with regular UNO, I can't just remove the chip from there (CH340 UNO) and upload the code directly to my new standalone chip trough that board.

So what I tried was to use my [FTDI][2] cable, so I hooked up GND, RX, TX and VCC for my breadboard from there, but when I tried to upload a sketch I keep getting that message that programmer is not responding.

So I was wondering, is there a way to use this Chinese board to upload sketch to my new chip without de-soldering the chip from that board as option one.

As option two what I'm doing wrong with FTDI cable and why I'm not able to upload sketch directly like that? I saw some comments related to some auto-reset that needs to be implemented but I'm not following that part, not sure what I need to hookup extra for that...

UPDATE

Here's how my board look like:
[![enter image description here][3]][3]

**Update 2:**

**OK, everything works great now! I just needed one pull-up resistor for reset pin.**

Thanks everyone!

  [1]: http://g01.a.alicdn.com/kf/HTB1ALCYIFXXXXa_XXXXq6xXFXXXj/Hot-sales-NEW-UNO-R3-ATmega328P-CH340-Mini-USB-Board-for-Compatible-Arduino-free-shipping.jpg
  [2]: http://www.canadarobotix.com/serial-ttl/ftdi-cable-5v-vcc-3-3v-i-o
  [3]: https://i.stack.imgur.com/zSqAL.jpg

body:
You said:

It just need a pull-up resistor for the reset pin!


message:
VGAX library only allows 4 colors, library or hardware limitation?

I'm working with VGA DSUB-15 output, however [VGAX][1] only allows for 4 colors. I'm using an Arduino Nano that uses an 8-bit atmel chip, and I've seen many 8-bit computers of which have a _bit_ more than 4 colors.

  [1]: https://github.com/smaffer/vgax "VGAX"

body: Are you using the Arduino to directly drive the VGA, or are you using a shield. If you're directly driving the display, I think the limitation is on the Arduino because with only 2kb or RAM, you can't really store all the pixel data. And the duino is also generating the high frequency vsync and hsync signals.


body:
The VGA interface uses full analog signals for Red, Green an Blue video. There is no limit to the color levels in the VGA standard.

However, it is not unusual to find that minimalist implementations of VGA in microcontroller products use Digital to Analog Converter (DAC) techniques with a limited number of bits of resolution.  For example, using two bits of resolution for Red and Blue, and three bits of resolution for Green so that the pixel information will fit into an 8-bit byte, etc.


body: It's a memory limitation. The ATmega328 has 2 KB of RAM, and a 120x60 framebuffer at two bits per pixel (four colors) uses 1.8 KB. There's no room for more.