body:
This buzzer needs to generate an audible sound for one second.  The Buzzer is inside a function that is called by a loop that continues to run. It is possible to stop the loop for this one second.  PWM to a piezo disk is what I had in mind.  The coding has been simplified to: Stating the PWM     // #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
  // set timer_0 divisor to    64 for PWM frequency of   976.56 Hz (The DEFAULT)
  // The prescaler is a 3-bit value stored in the three least significant bits of the Timer/Counter register: CS02, CS01, and CS00.
        TCCR0B = TCCR0B & B11111000 | B00000011;  // 976.56 Hz  for PIN 5
        //  TCCR0B = _BV(CS00) | _BV(CS01)
        //Register first 5 bits   B11111000  logical 'OR' Divisor  = B00000011   and stop is with: TCCR0B = 0;  Is that all that I need?      #include <Arduino.h>
      #include <stdlib.h>
      #include <string.h>
      #include <inttypes.h>
      #include <Keypad.h>
      #include <TM1637.h>
      #include <TimerOne.h>
    class TimingISR
    {
    public:
        TimingISR();

      char lead_char, unit_sec, tens_sec, num_min;
      int int_unit_sec, int_tens_sec, int_num_min;
      int Count_Seconds, Remainder, brightness = 4, PowerLevel;   //BRIGHT_TYPICAL = 4, BRIGHT_DARKEST = 0, BRIGHTEST = 7
      bool Colon, PointFlag;
      char data_char;
    };

    // these are all Clobal Variables
      int pin_Clk = 2; //  or 3 for IC2
      int pin_DIO = 3; //  or 2 for IC2
      int PIN_RELAY = 4;  // controls power on/off to 'cook'
      int PIN_Beeper = 5; // PWM beeps when finished
    // Main() not included in this transmission, limit is 2 programs
    // in case you recognize the above, I now have functions instead of GOTO's in the MAIN()
    //*********************************************************************************
    // http://www.engblaze.com/microcontroller-tutorial-avr-and-arduino-timer-interrupts/
    // Arduino timer CTC interrupt example
    // www.engblaze.com

    // avr-libc library includes
    #include <avr/io.h>
    #include <avr/interrupt.h>

    //#define LEDPIN 2  will flash on & off once a second if a LED is used
    Timer()
    void setup()
    {
        //pinMode(LEDPIN, OUTPUT);

        // initialize Timer1
        cli();          // disable global interrupts
        TCCR1A = 0;     // set entire TCCR1A register to 0
        TCCR1B = 0;     // same for TCCR1B

        // set compare match register to desired timer count:
        OCR1A = 15624;
        // turn on CTC mode:
        TCCR1B |= (1 << WGM12);
        // Set CS10 and CS12 bits for 1024 prescaler:
        TCCR1B |= (1 << CS10);
        TCCR1B |= (1 << CS12);
        // enable timer compare interrupt:
        TIMSK1 |= (1 << OCIE1A);
        // enable global interrupts:
        sei();
    }

    //*********************************************************************************
    ISR(TIMER1_COMPA_vect)     // once a second code    Counting down,
       void){  // can only get here if lead_ char is a 'c' or a '1' i.e. 'cook' or 'def'

           If ( Colon = On ) Colon = OFF; else Colon = ON;  //blink
           // on TM1736 4 digit 7 second LED display
        {  if  ( Count_Seconds = 0 )  // Done cooking,  Beep On for one second
    // https://arduino-info.wikispaces.com/Arduino-PWM-Frequency
           // set timer 0 divisor to    64 for PWM frequency of   976.56 Hz (The DEFAULT)
            TCCR0B = TCCR0B & B11111000 | B00000011;  // 976.56 Hz  for PIN 5
    // https://electronics.stackexchange.com/questions/164834/stop-timer-set-new-value-and-start-again-avr-interrupt
            TCCR0B &= ~(0 << CS00);   // set the CS02, CS01, and CS00 bits in TCCR0B
            TCCR0B &= ~(0 << CS02);
            TCCR0B &= ~(0 << CS03);
            //Write 'DonE' to the TM1736
            lead_char = 'D';  num_min = 'o'; tens_sec =  'n'; unit_sec =  'E';
            Colon = OFF; brightness = 7;//  Full Brightness // for a few seconds
    DisplayAll()  // Main() has a character to number converter  // DisplayAll() has an extended Segment table
        }
         {
          if  ( Count_Seconds = -1 ) //  Beep OFF
               TCCR0B &= ~(1 << CS00);   // // clear the CS02, CS01, and CS00 bits in TCCR0B
               TCCR0B &= ~(1 << CS02);
               TCCR0B &= ~(1 << CS03);
         }
           if (  Count_Seconds < -11 )  cli();          // disable global interrupts //stop the interrupt timer
    return(0);
           else
              Count_Seconds = Count_Seconds - 1  // don't restart the timer
     { ( if   Count_Seconds < -10 || Count_Seconds > 0 )
              brightness = 4; counterValue = 0; resetCounter; Count_Seconds = Count_Seconds -1
     }
     }   End of Timer
    // ----------------------------------------------------

title: If this the way to generate a BEEP for a second

Answers: 1

body:
You have pasted this code together from a couple of samples, I even recognise some of it, but I think you really don't understand what its doing.

If I want to learn how to fly a plane I am not just going to jump in the pilots chair and push the throttles wide open.  Its the same with learning to code, and if you try and run this code it will do nothing.

To answer you question, no.

Try doing something really simple and annoying and wire a buzzer up to one of the pins and load this code:

    static const int BuzzerPin = 5;
    void setup()
    {
      pinMode(BuzzerPin, OUTPUT);
    }
    void loop ()
    {
      digitalWrite (BuzzerPin, HIGH);
      delay (500);
      digitalWrite (BuzzerPin, LOW);
      delay(500);
    }

Then once you work out how that works, move on to PWM to work out how that works and then finally try interrupts (if that's what you really want).

(Oh and yes the code is virtually blink.ino which you get with the IDE.)


body:
    class Pseudo_Interrupt {
      //only cummulative time is important, exact interval is not
      // Class Member Variables
      // These are initialized at startup
      long OffTime = 1000; // milliseconds of off-time
      // These maintain the current state
      unsigned long previousMillis; // will store last time updated

      void Update() {
        // check to see if it's time for an Interrupt
        unsigned long currentMillis = millis();
        if ((currentMillis - previousMillis >= OffTime) {
          //Time to execute the one second code
        }
      }
    }

title: Would this substitute for an Interrupt timer?

Answers: 5

body:
Yes, if you advance previous millis by 1000 once that comparison is true.

Setting previous millis to current millis is the wrong approach as it will accumulate timing errors.

edit:

here is a simple piece that hopefully will do what you are trying to do.

    //pseudo timer isr
    //return 1 if the timer overflows MYTMR_PR
    uint8_t mytmr_ovf(void) {
     static uint32_t last_time=0;  //previous time
     uint32_t current_time;

     current_time = millis();   //take current time
     if (current_time - last_time >= MYTMR_PR) {
      last_time += MYTMR_PR;   //update last time
      return 1;      //indicate overflow
     }
     return 0;       //indicate no overflow
    }

as I suggested earlier, the code is written so that the timer is long-term accurate.

Hope it helps.

edit 2: here is the above code running on a PIC24F, with MYTMR_PR set to 100 (=100ms)

    //user loop
    void loop(void) {
        //looping around
        if (mytmr_ovf()) digitalWrite(LED, !digitalRead(LED));   //flip the led
    }

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

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

body:
A function called by your program can do some, but not all, of what an interrupt function does. If you call it frequently enough, you can get timely execution of your "one second code". How frequently you must call it depends on how precisely an execution interval you need. That may require your mainline code to spend more time polling the timer than you can afford; it depends on your particular circumstances.

A true interrupt function will be called nearly immediately on the occurrence of whatever event is set to trigger it. Until then, no time will be taken from your mainline code.

Whether that is that is an effective substitute depends on your particular situation.

The code you supplied is not syntactically correct and does not compile. Nested functions are not include in C or C++, and in the 'if' statement, the parentheses are unbalanced.

body:
The whole idea is sound, but I would make a few changes:

* as explained by Jot in a comment, you have to update `previousMillis`
  inside the `if` statement. You have two choices:
  * set it to `currentMillis`, then `OffTime` will be the _minimum_ time
    between the pseudo-interrupts
  * increment it by a constant amount, which I would call `period`, then
    this will be the _average_ time between pseudo-interrupts; this is
    more similar to how real timer interrupts work
* add a constructor for:
  * making the period user-selectable
  * making the action of the timer user-selectable via a callback
  * initializing `previousMillis`

With those changes, the class will look like:

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

    class Pseudo_Interrupt {
        unsigned long period;
        unsigned long previousMillis;
        void (*callback)();

    public:
        Pseudo_Interrupt(void (*callback)(), unsigned long period)
            : period(period), previousMillis(millis()), callback(callback)
        { }

        void update()
        {
            if (millis() - previousMillis >= period)
            {
                callback();
                previousMillis += period;
            }
        }
    };

body:
I have since put the following in a continuous fast loop. When the program gets to it, it executes.   The one second is a little erratic, but the total cumulative is approximately correct.

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

    long OffTime = 1000;     // milliseconds of off-time

    // These maintain the current state of the timer
    long previousMillis;   // will store last time updated
    long lateMillis;       // how late was it

    //----------------------------------------------------------------------

    currentMillis = millis();     //correct for millis() overflow
    if (currentMillis - previousMillis < 0 )
        currentMillis = currentMillis + 32768;
    {
        if (currentMillis - previousMillis >= OffTime - lateMillis )

            // Assume the difference is longer than 1000 milliseconds
            // because the sample time will be late but not by much
            lateMillis = currentMillis - previousMillis - OffTime;

            // Thus, cumulative time is essentially correct
            //Time to execute the one second code here
            do some code
        else
            return;
        }
    // ----------------------------------------------------
    }  //  End Of Run Repeatedly

body:
Latest Version:  7/6/17

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

    //--------------------------------------------------------
    class Pseudo_Interrupt {

    {   // These maintain the current state of the timer
    public:
    volatile unsigned long previousMillis;   // will store last time updated
    volatile unsigned long lateMillis = 0;       // how late was it
    volatile bool CallOneMinute = false; //facilitates while loops,
    }
    // to prevent a callback set previousMillis = millis(); periodically within the 'period'
    // to start the callback set previousMillis = millis() - period; lateMillis = 0;
    volatile unsigned long currentMillis;
    static const unsigned long period = 1000;     // milliseconds of off-time delay
    volatile unsigned long delta;
        void (*callback)();
    public:
        Pseudo_Interrupt(void (*callback)(), unsigned long period)
            : period(period), previousMillis(millis()), callback(callback)
        { }

        void update()
        {       currentMillis = millis();
                CallOneMinute = false
                delta = currentMillis - previousMillis - period
            if (lateMillis + delta >= 0)
                lateMillis = delta;
                CallOneMinute = true
            {
                callback();   // with correction to keep net correct cumulative time
                previousMillis += ( period - lateMillis );
        }
    };
    //----------------------------------------------------------


body:
When I read articles/tutorials about the Arduino Uno, the potentiometer and button always get power from the 5 V pin instead of from digital pins.

May I know whether the two components above can be powered by digital pins?

What is the situation that the components must only get power from 5 V pin instead of digital pins?

title: Powering potientiometer/button with a digital pin

Answers: 1

body:
You can likely use an I/O pin as an output to "power" fairly high-impedance devices such as pullup resistors for buttons, or even potentiometers of moderate to high total resistance.

A reason you might wish to do so would to be able to stop the device from draining power while the entire system is in a low-power sleep mode, or to otherwise disable it beyond merely ignoring its input.

However, it's worth noting that powering an analog device such as a potentiometer from an I/O pin is likely to inject noise and full scale voltage uncertainty into the signal so derived, as the output voltage under load may be neither the same as the supply rail, not "quiet".

And, of course, you must not attempt to use an I/O pin to power lower-impedance (aka more "power hungry") loads via an output pin.  Generally, active devices should not be powered in this way - especially ones such as radio transmitters, other microcontrollers or complex logic functions, ultrasonic transmitters, and definitely not motors, relays, or solenoids.


body:
I'm looking for an **inexpensive** temperature sensor which is non reliant on the input voltage to return an analog reading back or some sort of digital signal. Accuracy is not very important, for instance +/- 4 C is fine. The lm35 I have been using jumps from 25 to 70 degrees regularly with changes in circuit load.

My other option is to add a separate voltage regulator, but I am trying to avoid that if possible! Thanks!

title: Stable temperature sensor under voltage fluctuations

Answers: 1

body:
The **DS18B20** is a temperature sensor with a digital interface (1-Wire). It works at 3.3 to 5V and the cable length can be a number of meters. It is accurate to 0.5°C.

The DS18B20 is probably the most used temperature sensor for Arduino projects. Its price starts at less than a dollar/euro. You only need the DS18B20, a pullup resistor of 10k and a digital pin.

In the Arduino IDE, go to the Library Manager and search for 'onewire'. Install the "OneWire by Jim Studt, Tom Pollard, ... Paul Stoffregen, ...".
Then search for 'dallas' and install "DallasTemperature by Miles Burton, ...".
The OneWire library on its own can read the temperature of the DS18B20, but the DallasTemperature makes it easier to use.
Look for the examples of the DallasTemperature in the Arduino IDE to start with the DS18B20.

The 1-Wire is a bus, you can add more DS18B20 sensors to the same wire. The DallasTemperature library has two options. Select either a sensor by index, or by its ID. Every DS18B20 has a unique ID inside the sensor.

Sometimes an analog temperature sensor has specific advantages, for example a ntc temperature sensor or a thermocouple sensor. For normal indoor or outdoor usage, the digital temperature sensors are far more easier to use.

Why measure only the temperature ? If you want the baromic pressure and humidity as well, the BME280 has it all. Its temperature accuracy is not very accurate, it is only ±1°C.


body:
I'm a big noob when it comes to writing a sketch and have set myself a task for an upcoming 4th July project, which has come to a halt.

I'm trying to set a strip of 30 LEDs to fade from red to white to blue through FastLED on a Wemos D1 mini. I also wanted it to flash each colour after the 3 colours have faded and continuously loop these.

I have searched many different forums and managed to get the fade to go from red to blue, but can't for love nor money add the white in-between.

Can someone point me in the right direction?

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

    #include "FastLED.h"
    #define NUM_LEDS 30
    #define DATA_PIN D4
    #define COLOUR_ORDER GRB

    CRGB leds[NUM_LEDS];

    void setup() {

        FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

    }
    void loop(){

        //start from red
        for( int colorStep=0; colorStep <= 255; colorStep++ ) {

            int r = 255;
            int g = 0;
            int b = colorStep;

            // Now loop though each of the LEDs and set each one to the current color
            for(int x = 0; x < LED_COUNT; x++){
                leds[x] = CRGB(r,g,b);
            }

            // Display the colors we just set on the actual LEDs
            delay(10);
            FastLED.show();
        }

        //into blue
        for( int colorStep=255; colorStep >= 0; colorStep-- ) {

            int r = colorStep;
            int g = 0;
            int b = 255;

            // Now loop though each of the LEDs and set each one to the current color
            for(int x = 0; x < LED_COUNT; x++){
                leds[x] = CRGB(r,g,b);
            }

            // Display the colors we just set on the actual LEDs
            delay(10);
            FastLED.show();
        }
    }

title: Fading red to white to blue continuous loop on ws2812 LED strip

Answers: 1

body:
Think of a color as a point in 3d as defined by its r g b attributes

Think of two points here, one is your starting color in that 3d space, and another your ending color.

Figure out the path you want to take from the starting color to the ending cokor.

Chop it up in a few steps and use your code to walk the path.

Done


body:
I have a SIM808 module like this: https://www.banggood.com/SIM808-Module-GPS-GSM-GPRS-Quad-band-Development-Board-For-Arduino-p-1063106.html

The output header has 5 pins: GND/RX/GND/TX/VCC and I connected them as:

GND/VCC to a LiPo battery, 7.4V@1000mAh

RX->pin 14 (written on it TX3)

GND->to arduino GND

TX->pin 15 (written on it RX3)

and uploaded this code

    #include <SoftwareSerial.h>

    SoftwareSerial GSMSerial(15,14);    // RX, TX

    void setup()
    {

      GSMSerial.begin(19200);
      Serial.begin(19200);
      Serial.println("START");
    }

    void loop()
    {
      if(Serial.available())
        GSMSerial.print((char)Serial.read());
      else  if(GSMSerial.available())
        Serial.print((char)GSMSerial.read());
    }

But I'm not getting anything on it (when sending "AT" or anything else).

Any help is appreciated.

Thank you!

title: Arduino Mega 2560 with SIM808 module

Answers: 1

body:
Don't use `SoftwareSerial` on the `HardwareSerial` pins.  Instead of this:

    #include <SoftwareSerial.h>
    SoftwareSerial GSMSerial(15,14);    // RX, TX

Just do this:

    #define GSMSerial Serial3


body:
Using ADS1115 (or any other external ADC), how its possible to read zero instead of random floating values while no any signal at the ADC's input pin?

The ADS1115 is driven by an op-amp buffer as follows.
[![enter image description here][1]][1]

The op-amp's `+` input is sometimes connected to a pH sensor, sometimes left unconnected.

  [1]: https://i.stack.imgur.com/8SfCt.gif

title: External ADC reading zero while input is zero

Answers: 1

body:
The behaviour you are seeing is what happens when you have high-impedance inputs.  Basically, if you don't drive them, you get random values.

Unfortunately in your case, where the sensor you are using has no output current to speak of, I don't think there's anything you can do about this electronically.

You'll have to solve the problem in some other way if you really need to be able to disconnect the sensor.  A mechanical solution would be a connector which shorts when disconnected.  Switched headphone connectors do this, for example - when you pull out the jack, they make a connection so that the speakers can be switched on.


body:
I am using a DIY colour sensor (RGB LED and LDR) and a servo to make a skittles sorter. I am testing out just the colour detection now and printing the RGB values to serial. It worked fine until I added servo code. Now it stops printing to serial after about 4 cycles. Not sure why this is happening. I have tried using other programs besides using the Arduino IDE but the same issue.

I am using a NodeMCU with Arduino code:
<!-- language-all: lang-cpp -->

 #define S0 4
 #define S1 0
 #define S2 2
 #include <Servo.h>
 Servo topServo;
 int frequency = 0;

 void setup() {
   pinMode(S0, OUTPUT);
   pinMode(S1, OUTPUT);
   pinMode(S2, OUTPUT);
   topServo.attach(14);
  Serial.begin(9600);
  Serial.print("Start");
 }

 void loop() {
   topServo.write(125);
   delay(500);

   for(int i = 150; i > 80; i--) {
  topServo.write(i);
  delay(5);
   }
   checkcolours();
   delay(500);
 }
 void checkcolours(){
  //RED
 digitalWrite(S1,LOW);
 digitalWrite(S2,LOW);
 digitalWrite(S0,HIGH);
 frequency = analogRead(17);
 int R = frequency;
 Serial.print("R= ");//printing name
 Serial.print(frequency);//printing RED color frequency
 Serial.print("  ");
 delay(100);

 //GREEN
 digitalWrite(S0,LOW);
 digitalWrite(S2,LOW);
 digitalWrite(S1,HIGH);
 frequency = analogRead(17);
 int G = frequency;
 Serial.print("G= ");//printing name
 Serial.print(frequency);//printing RED color frequency
 Serial.print("  ");
 delay(100);

 //BLUE
 digitalWrite(S0,LOW);
 digitalWrite(S1,LOW);
 digitalWrite(S2,HIGH);
 frequency = analogRead(17);
 int B = frequency;
 Serial.print("B= ");//printing name
 Serial.print(frequency);//printing RED color frequency
 Serial.println("  ");
 delay(100);
 returnservo();
   }
 void returnservo(){
   topServo.write(30);
 }

title: Serial Monitor Stops Working

Answers: 0


body:
I bought this [SIM800C development board][1] (vendor unknow):

[![Development board - front][2]][2]
[![Development board - back][3]][3]

I conected it to an Arduino and put a brand new SIM card in it. This is the model of SIM I'm using:

[![Nano SIM card][4]][4]

Problem is, development board doesn't detect SIM card:

    at+cfun=1,1
    OK
    at+cpin?
    +CME ERROR: SIM not inserted
    at+csmins?
    +CSMINS: 0,0

This is the scenario:

 - 6 pin SIM in a 6 pin SIM card holder.
 - SIM works fine in a cel phone. Send/receive voice call/sms.
 - Older, working SIM from various providers doesn't get detected either.
 - Every other non-SIM related aspect works.
 - No reboots, no flickering.
 - Board takes care of regulating voltages and signal levels.

I put an oscilloscope probe on the SIM_VDD pin (against board ground) and got this on every power-on:

[![Sim VCC on startup][5]][5]

Two 1.8v and two 3v pulses. That's all.

Please, note that I have no access to all SIM connexions (multi layer PCB).

How do I solve this problem?

  [1]: https://www.aliexpress.com/item/SIM800-Development-Board-Module-Support-GSM-GPRS-3-3-5V-TTL-Level-Control-DC-6-24V/32798811432.html?spm=2114.01010208.3.9.lbFC5h&ws_ab_test=searchweb0_0,searchweb201602_2_10152_10065_10151_10208_10068_10191_10136_10137_10060_10155_10062_437_10154_10056_10055_10054_10059_303_100031_10099_10103_10102_10096_10052_10053_10142_10107_10050_10051_10173_10084_10083_10080_10082_10081_10110_519_10111_10112_10113_10114_10182_10078_10079_10073_10123_10189_142,searchweb201603_16,ppcSwitch_5&btsid=0bed8485-be65-423d-8aab-4b16ac2eedc9&algo_expid=d79b8180-51bc-47bd-8e89-2267b6e579a3-1&algo_pvid=d79b8180-51bc-47bd-8e89-2267b6e579a3
  [2]: https://i.stack.imgur.com/JmENO.jpg
  [3]: https://i.stack.imgur.com/yA9gp.jpg
  [4]: https://i.stack.imgur.com/9qAIN.jpg
  [5]: https://i.stack.imgur.com/DT358.jpg

title: SIM800C developer board "SIM not inserted"

Answers: 3

body:
The print on the PCB and product description at sellers site states it is GSM/GPRS board. The  module on the board comes from [SIMCom](http://simcomm2m.com/En/). This particular [SIM800](http://simcomm2m.com/En/module/detail.aspx?id=138) module seems to have following capabilities as per SIMCom:

 - Compliant to GSM phase 2/2+
 - GPRS multi-slot class 12/10
 - Quad-band 850/900/1800/1900MHz

I think at the best you can only use a 2G SIM card on this board. Any 3G/4G SIM will not work.

Thanks for those images in the problem description, it gave me relevant keywords to search.

body:
**This is a hardware problem.**

We have experience the same issue in the company I'm working for and after a short discussion with a SimCOM Engineer we conclude it was a soldering issue. The problem may lies in the PCB or inside the SimCOM module. In both cases some part/parts are not soldered or the solder contact is broken. If the problem is outside you may fix it by inspecting the parts. If it is inside the SimCOM module there are very little you can do with the usual tools.

Just to be clear I quote a little bit of the discussion

Original question to SimCOM:
[![enter image description here][1]][1]

    A)We apply a zero pulse to PWR-key pin as you can see in the channel-1(yellow line)
    and immediately the SIM800c module wakes up, the net and status led pins
    become active (one led on the other blinks).

    B) After a short time <1.5sec the SIM800c deploy a signal to SIM_VDD pin
    (channel-2 - blue line)

    Now in some boards the SIM_VDD pin goes to 1.8V as it appears in the
    first of the 4 pulses and stay there. This situation is true if there is
    a SIM card in the slot and the SIM800c is working properly. In that case
    we can proceed and register to the network, send SMS etc...

    In some boards though, as you can see in the screenshots, the SIM800
    seams not to recognize the SIM card and tries again with 2 more pulses in
    3V and one last one in 1.8V. The behavior is like there is no SIM-card in
    the slot. Just to be clear. The SIM card is the same in all tests.
    VBAT=3.9V, SIMVDD produced fine at 2.8V etc... The boards are identical
    and no further code with AT commands is running.
Quite final answer from SimCOM:

    It must be a soldering issue then. Did they followed recommended Solder
    Reflow Profile?
    https://www.elecrow.com/download/SIM800C_Hardware_Design_V1.02.pdf page 46

    Please ask them where they measured signal from the scope pictures. From
    the SIM card pins? If no, can they repeat that on them and send pictures.

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

body:
This happened to me too with a SIM808 module on my own PCB. I would get those same 4 pulses on `SIM_VDD` and then nothing. I got the same `+CME ERROR: SIM not inserted` error with any AT command that had to do with the SIM card.

After futzing for wayyy too long, it turned out I had soldered the SIM slot on backwards! I am using the [SIM8051-6-0-14-01-A][1] holder and it has locating pins, but they're symmetrical. As a result, my SIM card was connected backwards and wasn't working.

Flipping it around fixed everything. Good luck!

  [1]: https://www.mouser.com/pdfDocs/SIM8055.pdf


body:
Using `Console.write()` to send data to my computer over network, which works when I use the serial monitor. However, I'm using PLX-DAQ to receive Serial communication and input it into an Excel document. The problem with that is that PLX-DAQ only has the option to listen over physical ports.

Is there a workaround to this?

If it helps, the computer is a Windows machine.

title: Trying to send serial data to computer over network from Arduino Yún

Answers: 0


body: They say that you must know what IC your board has before loading a new program from the Arduino IDE and that the information is available on the top of the IC, but where is it exactly and what is an IC?

title: What is actually an IC (Integrated Circuit)?

Answers: 2

body:
It's funny that you have a picture of one in your profile pic. :)

[![zoopcool's profile pic][1]][1]

The arrow points to the most obvious integrated circuit or chip in you pic, there is another square one to the left of the TX and RX markings.  There are lots of different types of ICs -- most are black and come in different shapes and sizes, different number of legs, but most have some form of writing on the back that Google can use to locate the data sheet, or general help.  Have a quick look on Wikipedia for a more authoritative description.

  [1]: https://i.stack.imgur.com/O8MrK.png "zoopcool's profile pic"

body:
IC stands for [*integrated circuit*](https://en.wikipedia.org/wiki/Integrated_circuit), which is a generic term encompassing any class of devices that has multiple electronic components (transistors, and possibly capacitors, resistors, diodes, and more) encased and interconnected within. The opposite of an integrated circuit is a discrete component, which is a single electronic component in its own package that relies on wiring (or a circuit board) to connect to other components.

Taking a look at the Arduino Uno R3 below (click for larger image), the long rectangular black thing is the primary IC. You can see the ATMEL logo on it, followed by a short series of numbers (a date code if I'm not mistaken). Below is the chip model itself; in this case, "ATMEGA328P-PU". With respect to the Arduino IDE, it's sufficient to know that the chip is an ATmega328P, which is sometimes incorrectly called ATmega328 in the Arduino world.

[![Arduino Uno R3][1]][1]

If you look closely, there are also several other ICs on the board. To the right of the ATmega328P is a small 5-pin package; if I'm not mistaken it's an [LP2985-33DBVR](http://www.smdmark.com/en-US/ic-367390.html), which is a low-dropout voltage regulator. On smaller packages like this they often have more cryptic legends printed on them, in this case if you squint at the full-size picture you can make out "LPFL". Fortunately for most Arduino development purposes, knowing the model of these auxiliary ICs is generally not necessary. Just below that, above the crystal (the metal oblong can marked SPK16.000G) is an 8-pin package marked 09TI R5R, which I believe is a [LMV358IDGKR](http://www.smdmark.com/en-US/ic-369055.html) dual op-amp.

Another IC of note on this board is the small square 32-pin package below the crystal; this is an ATmega16U2. In the case of the Arduino Uno R3, rather than being the primary microcontroller, this serves as the USB-to-serial converter.

Note that to the right of the crystal is a small three-pin package marked "340"; this is a [FDN340P](http://www.smdmark.com/en-US/ic-27432.html) MOSFET. While this model of MOSFET (as with many others) contains an integrated diode across its drain and source and could thus *technically* be classified as an integrated circuit, most would still consider it a discrete component.

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


body:
I am trying to build a frequency meter using Interrupts and Timer1, which works as if the system receives an Interrupt it would get the timer's data and would calculate

> Signal's Frequency = 1 / (Counter * Timer's Period) => F_s = F_t/TCNT

but the result is way off, and it does not even make sense. I have had altered my code to look that if the timer's data is not valid or sth, but the number that the timer counter has counted is sth that I expect.

Here is my code:

    int f=0;
    char msg[50];

    void setup()
    {
      Serial.begin(115200);
      noInterrupts();           // disable all interrupts
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
      TCCR1A = 0;
      TCCR1B = 0;
      OCR1A = 0;
      OCR1B = 0;
      TCCR1B |= (0<<CS12)|(1<<CS11)|(0<<CS10);    // Clock 2MHZ
      TCNT1  = 0;
      TIMSK1 = 0; // disable timer overflow interrupt
      interrupts();
      attachInterrupt(1,pin_ISR,RISING);
    }

    void pin_ISR(){
      //digitalWrite(13,!digitalRead(13));
      f = 2000000/TCNT1;
      TCNT1=0;
    }

    void loop()
    {
      sprintf(msg,"Humidity:%d \n",f);
      Serial.print(msg);
    }

title: Problem with the Frequency meter code

Answers: 4

body:
Did you find an example that works that way ? Is it, for example, allowed that the TCNT1 is cleared in an interrupt routine? The TCCR1A is cleared, but not set to a value ?
[**edit**] Clearing TCCR1A is okay. Clearing TCNT1 is also okay, but can be improved as @EdgarBonet shows.

The calculation uses a long of 2MHz, but the others are 16 bits. Could you force that calculation with long ? `f = int( 2000000L / long( TCNT1));`
[**edit**] It is not needed to force the compiler into a 'long' calculation, it already does so.

The 'f' variable is used in an interrupt and outside that interrupt. It must be made 'volatile': `volatile int f=0;`

The 'f' is used in the loop, but the interrupt could happen when 'f' is only half read or half written. The ATmega328P is a 8-bit microcontroller and 'f' is a 16-bits variable. I suggest to disable the interrupts and make a copy.

    noInterrupts();
    int fcopy = f;
    interrupts();
    sprintf(msg,"Humidity:%d \n",fcopy);

What is the range that you want to measure ?

Do you know that there are good libraries to measure a frequency ? They are the [FreqMeasure Library][1] and the [FreqCount Library][2].

[ADDED]
Try to slow down the loop with a delay. If you fill the transmit buffer of the Arduino Uno TX, then the Serial.println wait for each character if there is a place in the transmit buffer.

  [1]: https://www.pjrc.com/teensy/td_libs_FreqMeasure.html
  [2]: https://www.pjrc.com/teensy/td_libs_FreqCount.html

body:
Your approach is basically a reciprocal counter and it can work, if you start and stop the timer in the isr. The logic is essentially this:

If timer is on stop the timer and save the timer count.
Else initialize the timer and start counting.

For counting a wide range of frequencies, you may need to consider timer over flow.

Edit: any solution that reads a multi byte counter while it is running will produce the wrong results. Google atomicity to understand why.

body:
As stated in my comment, your code is _kind of_ fine. Id mostly works,
but it looses a few microseconds on each iteration. If you are looking
at multi-kHz frequencies, you probably want to avoid loosing
microseconds. The solution is simple: _never_ reset the counter. I
changed you ISR as follows:

    uint16_t previous_counter;

    void pin_ISR(){
        uint16_t counter = TCNT1;
        f = 2000000/(counter - previous_counter);
        previous_counter = counter;
    }

and now it gives the correct frequency... on average. There are some
variations though, dues mostly to delays caused by other interrupts.

**Edit 1**: If you want to avoid the fluctuations caused by other
interrupts, your best bet is probably to use the input capture feature
of Timer 1.

**Edit 2**: Here is why your measurement was somewhat off. Your original
ISR essentially does something like this:

    void pin_ISR() {
        uint16_t temporary_value = TCNT1;
        loose_some_time();
        TCNT1 = 0;
    }

The time you loose in the ISR is the part of the signal period you are
not measuring, which means you are underestimating the period by that
much. In the ISR you posted, this is mostly the time taken by a 32-bit
division, which is quite significant. A simple improvement would be to
clear `TCNT1` right after reading it:

    void pin_ISR() {
        uint16_t temporary_value = TCNT1;
        TCNT1 = 0;
        loose_some_time();
    }

and now the average period you measure is _almost_ right. It is not
perfect though, as the whole reading and writing of `TCNT1` takes
8 CPU cycles.

The alternative I am suggesting, where you _never_ clear the timer, is
the correct way of measuring a period with a timer interrupt: you don't
loose a single CPU cycle. The best way is to use input capture: you get
rid of the software-induced jitter.

**Note**: You should also take care of the very valid points raised in
Jot's answer, about making `f` volatile and reading it with interrupts
disabled.

body:
So I have had asked this question on the Arduino forum and some one has fixed my code which gives me the accuracy that I expect. The problem was that the division was better not to be in the ISR routine but in the main loop. Here's the link to that answer because that guy should be credited as he helped me big time.
https://forum.arduino.cc/index.php?topic=486573.0

Thanks to all who replied to me, I have learned many things about ISR's and their limitations.


body:
Hi I am very new to Arduino, with very little programming experience.

I am using mega 2560 and trying to understand how interrupt works.

I have a code written, it is very similar as the example code Memsic2125, so i am gonna use that in here.

For my case, I am reading from my hardware, 5x5 array of sensors.

What I would like to do is to have it --   *print out x and y using interrupts*   , **I want to print outputs the x and y every 10ms. Instead of printing it continuously right now.**

I will be sending it out in 16 bits. I tried some other example and read a lot of material. but still couldn't get it to work.

Any idea, suggestion, help, comment is appreciated.
<!-- language-all: lang-cpp -->

    const int xPin = 2;
    const int yPin = 3;

    void setup() {

      Serial.begin(9600);
      pinMode(xPin, INPUT);
      pinMode(yPin, INPUT);
    }

    void loop() {

      int pulseX, pulseY;

      int x, y;

      // read pulse from x- and y-axes:
      pulseX = pulseIn(xPin, HIGH);
      pulseY = pulseIn(yPin, HIGH);

      x= ((pulseX / 10) - 500) * 8;
      y= ((pulseY / 10) - 500) * 8;

      // print x,y
      Serial.print("x,y= ( ");

      Serial.print(x);   Serial.print(,);
      Serial.print(y);   Serial.println(")");

      delay(100);
    }

title: mega2560- Interrupts reading digital input

Answers: 2

body: There isn't any interrupt code in what you posted. What exactly is the problem?  One important note is that you shouldn't try to print to Serial line in the interrupt handler as serial is itself driven from interrupts which are switched off during your handler code.  If all you really want to do is to print something every 10ms then you don't need any interrupt.  Just use the "Blink Without Delay" style of timing and keep the other code from blocking.

body:
The simplest would-be to read the data and loop around for your desired time.

Alternatively, time stamp the events and onkybread the data if the desired time has elapsed.

Or to use a timer interrupt for that.


body:
I am using a JIC 139 UV Sensor ([datasheet](http://www.eoc-inc.com/ifw/JIC 137-138-139.pdf)) with an Arduino Mega 2560 and should be reading smooth curves as I bring a UV source to towards the sensor. Instead, my curves are increasing and oscillating. How can I remove the oscillations and what is the cause of these oscillations?

Code:

    float mapfloat(long x, long in_min, long in_max, long out_min, long out_max)
    {
        return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + out_min;
    }

    int averageAnalogRead(int pinToRead)
    {
        byte numberOfReadings = 8;
        unsigned int runningValue = 0;

        for(int x = 0 ; x < numberOfReadings ; x++)
            runningValue += analogRead(pinToRead);
        runningValue /= numberOfReadings;

        delay(100);

        return(runningValue);
    }

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

    void loop() {

       float pinRead0 = averageAnalogRead(0);
       float pVolt0 = pinRead0 / 1024.0 * 5.0;

       // In mW/m^2
       Serial.println(pVolt0);
       //  Serial.println(mapfloat(pVolt0, 0.0, 5.0, 0.0, 15.0));

       delay(100);
    }
`

Here is a sample screenshot from the Serial Plotter at 3 different distances from the UV Source:
[![enter image description here][1]][1]

Would post cicuit but don't have enough reputation. Will post as response.
  [1]: https://i.stack.imgur.com/4aXMI.png

**edit:** I added a very large capacitor(3300 uf) between the output pin and ground which seemed to smooth the values a little bit but the noise still exists

**edit:** The x-axis is number of readings and the y-axis is voltage(0-5v) calculated from analogRead()

title: Oscillating Analog Readings

Answers: 1

body:
Without seeing circuit and construction details and oscilloscope traces, it's difficult or impossible to say what the problem is.  It may be due to op amp instability due to a large capacitive load.  It may reflect a beat frequency between some sensor and MCU signals, or aliasing between 60-Hz noise and your data-conversion rate.

Regarding op amp instability, see for example the article [*Op Amps Driving Capacitive Loads*, by Grayson King](http://www.analog.com/en/analog-dialogue/articles/ask-the-applications-engineer-25.html).  Here is a quote from that article:
>Q. *How does capacitive loading affect op amp performance?*
A. To put it simply, it can turn your amplifier into an oscillator. Here's how: [...]

Rather than just connecting that big 3300 μF capacitor to the output pin, perhaps instead try attaching an [Active Low Pass Filter](http://www.electronics-tutorials.ws/filter/filter_5.html) to the output, or a unity-gain op amp followed by a [Passive Low Pass Filter](http://www.electronics-tutorials.ws/filter/filter_2.html); etc.  Put big capacitors across power into the UV source and power into the sensor, instead of on the sensor output.

Regarding beat frequencies and aliasing, low-frequency oscillation like that seen in the trace may occur as a difference of two higher-frequency signals, or as a sampling artifact.  To check this out, attach an oscilloscope to the UV source and see if its power consumption oscillates; and/or try a more-rational sampling scheme than that shown in your code.

For example, instead of taking 8 readings within one millisecond in `averageAnalogRead()` and then waiting 100 ms, perhaps add a `delay(1)` inside the loop so that readings are spread out slightly more.  Remove the `delay(100)` from within `averageAnalogRead()`.  Compensate by changing the other `delay(100)` in `loop()` to, for example, `delay(191)` or `delay(193)`.  Try various delay amounts to see if they have an effect on the waveform.


body:
I'd like to connect an M8N gps module to an Arduino Uno. From what I understand

 - the Arduino pins 0-RX/1-TX work on 5V
 - the M8N RX/TX work on 3.3v
 - the sensor-TX sending to the Arduino-RX should work (3.3v is “good enough” to drive the Arduino-RX-pin)
 - the Arduino-TX sending to the sensor-RX is problematic because of the 5v (could break the sensor)
 - During USB-programming, the Arduino-RX sensor can be at 5v (so suddenly the current flows in the "wrong direction"- which could break the sensor)
 - A level-converter could be used to “translate” the voltages in each direction.

Assuming we don’t use a level-convertor

- Could we use a schottky-diode (which as I understand blocks current in 1 direction) to block the 5V from the ArduinoRX going into the sensor?
- But then the 3.3V from the sensor-TX would pass (correct direction ), but the diode will drop the voltage "a bit more"… is this still enough to drive the arduino RX-pin?

- And it works, why not also use a schottky-diode to also protect the Arduino-TX to sensor-RX connection ( just to be safe, since some people were saying one some Arduino they needed to connect RX-RX and TX-TX to get the communication to work.. ? ).

As an alternative to the schottky ( or maybe in addition to it)
- Could we simply take 2 voltage dividers (for one for both RX-TX and TX-RX) ?

We can use a “resistive voltage divider” to lower the Arduino-TX 5v to 3.3 V
- I understand to get from 5V to 3.3V we need “x” and “2 * x” resistors-values, so e.g 1K Ohm and 2K Ohm… but how do I know which values would be appropriate ( I mean, we could also take 10K Ohm and 20K Ohm, would also lead to 5V to 3.3v) but at a different current (Amps)… ?

- And what about a voltage-divider with a resistor and a capacitor (see https://en.wikipedia.org/wiki/Voltage_divider, low-pass RC filter)?
- What would be appropriate values for that solution for the resistor and capacitor?

Please be patient, electronics-beginner here trying to make sense of this…

title: Connect Arduino Uno RX/TX to 3.3v NEO-M8N gps module

Answers: 2

body:
Buy some of these, it's a simple hardware solution to your problem then.

https://www.amazon.co.uk/gp/product/B0148BLZGE/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1

I know you said you don't want to use a level converter but it's the simplest way around the problem.
You stated that you're an electronics beginner AS AM I, which is exactly why when I came up against the same problem i just spent the money.
It was only £3.99 for 5 of them and as far as I'm aware you should be able to buy single ones off amazon too, haven't searched but i'd have thought you'd be able to.

Or if you need to do it with resistors you can use this calculator here

http://www.ohmslawcalculator.com/voltage-divider-calculator

body:
You can use something along the lines of this:

![schematic](https://i.stack.imgur.com/WMSnv.png)

When the 5V Rx is driven to 5V D1 protects the 3.3V Tx pin.

When the 5V Rx is driven to 0V R1 protects the 3.3V Tx pin from excessive current draw.

When the 5V Tx is driven to 5V D2 protects the 3.3V Rx pin and R2 pulls the pin to 3.3V.

When the 5V Tx is driven to 0V D2 pulls the 3.3V Rx pin to ~0.2 V

Resistor values are rough guidelines, lower values will put more strain on the parts and increase power draw but will also increase the maximum UART speed that will work reliably.


body:
I want to use a [wired OR connection][1] to connect some pins of the 74HC595 shift register to an Arduino Digital Input Pin. How do I choose proper diodes for this situation?

* Maximum rated forward current has to be higher than whatever current a single pin of the 74HC595 produces.
* The `V_F` forward voltage drop has to be as low as possible to make sure that a HIGH from the shift register has still a voltage high enough to result in a HIGH at the Arduino pin after passing through the diode.
* Switching time has to be low enough to match the shift register's frequency.

So far, so good? What did I miss?

By the way, I haven't decided on the voltage for `VCC`, yet. Most likely, either `5 V` or `3.3 V`.

[![schematic][2]][2]

  [1]: https://en.wikipedia.org/wiki/Wired_logic_connection#The_wired_OR_connection
  [2]: https://i.stack.imgur.com/Zx2El.png

title: How do I choose proper diodes for a 74HC595 shift register with a wired OR connection?

Answers: 1

body:
For this, almost any diode will work.  Searching, it turns out that the [1N4148][1] is a popular ubiquitous choice.  But don't go out of your way to obtain this particular diode.

> Maximum rated forward current has to be higher than whatever current a
> single pin of the 74HC595 produces.

You should turn your thinking around.  Consider the nominal high voltage of the 74HC595, subtract the forward bias diode voltage drop (usually  0.7V for a silicon diode) and divide that by the resistor you pick.  That will be the current passing out of the 74HC595, through the diode and resistor.  Only a small amount of current will pass into the Arduino.  It should be negligible for most applications.  You should pick a resistor high enough to only allow milliamps of current to pass through this circuit.

> The V_F forward voltage drop has to be as low as possible to make sure
> that a HIGH from the shift register has still a voltage high enough to
> result in a HIGH at the Arduino pin after passing through the diode.

Check the voltage margin allow for a logical high input to the Arduino (Atmel processor).  I think 3V - 0.7V = 2.3V is still considered a logical high.  However, if you think this is too close, then switch to the 5 volt Arduino where the 0.7 volt drop will make less difference.

> Switching time has to be low enough to match the shift register's
> frequency.

I doubt this will be a problem.  That is, I doubt the CMOS logic will surpass the speed at which the diode can turn on / off.

  [1]: https://en.wikipedia.org/wiki/1N4148_signal_diode


body:
I'm making a small IOT project using the ESP8266 in which I make 2 API calls:

 1. api.openweathermap.org for weather data
 2. api.timezonedb.com

The request logic is the same for both calls, the only difference being how I parse the response string. The first response is parsed fine, while the other isn't.

 1. I print the String responses to Serial, they look fine.
 2. Tried both Dynamic and Static buffers to no avail.
 3. Making the request only to the second API, still not being parsed.
 4. If I make a test and just make the response a String, char[] or char*, it parses fine.

Parsing logic [works]:

    StaticJsonBuffer<1000> jsonBuffer;
    JsonObject& root = jsonBuffer.parseObject(response);
    float raw = root[String("main")][String("temp")].as<float>();

Parsing logic: [does not work]

    StaticJsonBuffer<500> jsonBuffer;
    JsonObject& root = jsonBuffer.parseObject(response);

    String data = root[String("formatted")].as<String>();

The response object looks like this:

    {
      "status": "OK",
      "message": "",
      "formatted": "2017-06-30 11:34:13"
    }

Request logic:

    String RequestAPI::performRequest(String url, char* host){
    WiFiClient client;
    if (!client.connect(host, port)) {
        lcd -> clearScreen();
        lcd -> drawText("Failed to connect to API", 0, 0, this -> randomUint16());
        delay(5000);
        return "";
    }

    char endOfHeaders[] = "\r\n\r\n";
    client.print(
    String("GET ") + url + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n"
    );
    // Skiping HTTP headers from the response
    client.find(endOfHeaders);

    unsigned long startTime = millis();
    while(client.available() == 0){
        if(millis() - startTime > this -> timeout){
            lcd -> clearScreen();
            lcd -> drawText("API request failed", 0, 0, this -> randomUint16());
            delay(5000);
            return "";
        }
    }

    String response = "";
    while(client.available()){
        response += client.readStringUntil('\r');
    }
    Serial.println(response);

    return response;
    }

Now I'm thinking, could the empty message be causing a bug? Or am I doing something wrong?

title: Possible ArduinoJson bug on ESP8266?

Answers: 1

body:
The issue was caused because of: https://en.wikipedia.org/wiki/Chunked_transfer_encoding

Was not obvious as the data printed to the serial looked completely fine. Fixed with the below code:

    client.print(
      String("GET ") + url + " HTTP/1.0\r\n" +
      "Host: " + host + "\r\n" +
      "Connection: close\r\n\r\n"
    );

Dunno why it worked for one API but not the other though.


body:
Say I have 3 LEDs. I want LED1 to blink 5 times. At its third blink, LED2 should start blinking as well, also 5 times. While LED2 is at its 3rd blink, LED3 should start blinking. How do I do this in Arduino?
Here's what I have.

    int timeStep = 200; // delay time
    int myPins[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; // array with Pins
    int myPinsSize = sizeof(myPins) / sizeof(myPins[0]); // Length of my array
    int counter = 0;

    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      for (int i = 0; i < myPinsSize; i++) {
        pinMode(myPins[i], OUTPUT);
      }
    }

    // the loop function runs over and over again forever
    void loop() {
      LEDsequence();
      if(counter >= 9) {
        counter = 0;
      } else {
        counter++;
      }
    }

    void LEDsequence() {
      if(counter < 5) {
        switchOn(0);
      }
      if(counter >= 2 && counter < 7) {
        switchOn(1);
      }
      if(counter >=4 && counter < 9) {
        switchOn(2);
      }
      delay(timeStep);
      switchAllOff();
    }

    void switchOn(int index) {
      digitalWrite(myPins[index], HIGH);
    }

    void switchOff(int index) {
     digitalWrite(myPins[index], LOW);
    }

    void switchAllOff() {
      for (int i = 0; i < myPinsSize; i++) {
        digitalWrite(myPins[i], LOW);
      }
    }

title: Synchronising LEDs

Answers: 3

body:
Since you have 3 leds, make a 2 dimensional array, first index for the leds (3), second for the period in which you want to have the led on or off.

E.g.

    const uint8_t NR_LEDS      = 3;
    const uint8_t TIME_PERIODS = 20;

    uint8_t period[NR_LEDS][TIME_PERIODS] = [
    // Time  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17, 18, 19
            {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // Led 1
            {0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, // Led 2
            {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }}; // Led 3

This means over 18 time periods, each state shows which led is on and off.
You can use HIGH or LOW, but that makes the lines too wide.

Now you can easily create a loop:

    void loop()
    {
      for (int period = 0; period  < TIME_PERIODS; period ++) // Time
      {
        for (int led = 0; led < NR_LEDS; led++)
        {
          switch(led, states[led, period ]); // set the led on or off
        }
        delay(1000); // 1 s
      }
    }

    void switch(uint8_t led, uint8_t state)
    {
      digitalWrite(led, state == 0 ? LOW : HIGH);
    }

So instead of switchOn and switchOff, use the switch and set it on or off by a parameter.

Also, this way it is very easy to change the schema (you can always visually see it in code). If you want longer schemes you can change the array into strings, like:

    char* period[NR_LEDS] = [
     // Time 0         10
     // Time 012345678901234567890
            "10101010100000000000", // LED 1
            "00001010101010000000", // LED 2
            "00000000101010101010", // LED 3

And check the index within the correct string and check for '0' and '1' instead of 0 and 1.

Since blinking is done for all leds 'in sync' (meaning during blinking leds change at the same time), you can also define a '1' as blink and '0' as off.

Than change:

    char* period[NR_LEDS] = [
     // Time 0         10
     // Time 012345678901234567890
            "10101010100000000000", // LED 1
            "00001010101010000000", // LED 2
            "00000000101010101010", // LED 3

to

    char* period[NR_LEDS] = [
     // Time 0         10
     // Time 012345678901234567890
            "111110000", // LED 1
            "001111100", // LED 2
            "000011111", // LED 3

And change the loop in

    void loop()
    {
      for (int period = 0; period < TIME_PERIODS; period ++) // Time
      {
        for (int led = 0; led < NR_LEDS; led++)
        {
          switch(led, states[led, period]); // set the led on or off
        }
        delay(500); // 0.5 s

        for (int led = 0; led < NR_LEDS; led++)
        {
           switch(led, '0');
        }
        delay(500); // 0.5 s
      }
    }

(use a constant for 0.5 s delay) and optionally create a function for the two small for loops above)

body:
Building on Michel's answer (this is a bit long to put in a comment):

Rather than using a 2 dimensional array or an array of strings (which is also a 2d array) it would be far more efficient to use a bitmask system.

    const uint8_t TIME_PERIODS = 20;
    const uint8_t NR_LEDS = 3;
    const uint8_t ledStates[] = [1,0,1,0,3,0,3,0,7,0,6,0,6,0,4,0,4,0,4,0];

and then the loop becomes:

      for (int period = 0; period < TIME_PERIODS; period++)
      {
        for (int led = 0; led < NR_LEDS; led++)
        {
          switch(led, ledStates[period] & 1<<led ); // set the led on or off
        }
        delay(500); // 0.5 s
      }

How this works:

`1<<led` will be 0001 in binary for led=0, 0010 for led = 1, 0100 for led = 2.

So if `ledStates[period]` was 3 (0011 in binary) then `ledStates[period] & 1<<led` will be non-zero for leds 0 and 1 and zero for led 2. The way the switch function is written any non zero value turns the LED on, 0 turns it off.

Why do it this way? Mainly size. Memory is always important, this uses 1 byte per state rather than 3. It could even be expanded to up to 8 LEDs without increasing the amount of memory used.

body:
> How do I do this in Arduino? Here's what I have.

easy:

1) write a routine that blink a pattern on a given pin;

something like this would work

    void myblinking(uint8_t pin, uint8_t *ptrn, uint8_t steps) {
      uint8_t index;

      pinMode(pin, OUTPUT);  //set pin as output
      for (index=0; index<steps; index++) {
        digitalWrite(pin, !digitalRead(pin)); delay(ptrn[index]); //flip pin, waste sometime
      }
    }

2. then all you need is to call that routine, like this:

      myblink(LED_PIN0, led_ptrn0, 10); //blink led_pin0, per led_ptrn0, for 10 steps
      myblink(LED_PIN1, led_ptrn1, 20); //blink led_pin1, per led_ptrn1, for 20 steps
      ...


body:
I have this code to read a SMS:

    String read_SMS(int index)
    {
      Serial.println("--START READ SMS POSITION" + String(index) + "--");
      delay(400);
      sendATcommand("AT+CMGF=1", "OK", 1000);    // sets the SMS mode to text
      delay(2000);
      String tmp;
      tmp = readATcommand("AT+CMGR=1", 4000);
      Serial.println("Content: " + tmp);
      Serial.println("--END READ SMS POSITION" + String(index) + "--");
    }

    String readATcommand(String ATcommand, unsigned int timeout)
    {
      char response[800];
      unsigned long previous;
      memset(response, '\0', 800);    // Initialice the string

      int x = 0;

      GSMSerial.println(ATcommand);
      delay(3000);
      previous = millis();
      do {
        if (GSMSerial.available() > 0) {
          response[x] = GSMSerial.read();
          x++;
        }
      } while ((millis() - previous) < timeout);   // Waits for the asnwer with time out

      return (String) response;
    }

    // sending AT commands to the Sim808 module
    int8_t sendATcommand(String ATcommand, char* expected_answer, unsigned int timeout) {

      uint8_t x = 0, answer = 0;
      char response[200];
      unsigned long previous;

      memset(response, '\0', 200);    // Initialice the string

      delay(100);

      // Clean the input buffer
      while (GSMSerial.available() > 0 ) GSMSerial.read();

      if (ATcommand[0] != '\0') {
        // Send the AT command
        GSMSerial.println(ATcommand);
        //Serial.print(F("AT Command: "));
        //Serial.println(ATcommand);
      }

      // Waiting for the answer
      x = 0;
      previous = millis();

      do {

        // if there are data in the UART input buffer, reads it and checks for the asnwer
        if (GSMSerial.available() > 0) {

          response[x] = GSMSerial.read();
          x++;
          // check if the desired answer (OK) is in the response of the module
          if (strstr(response, expected_answer) != NULL) {
            answer = 1;
          }
        }

      } while ((answer == 0) && ((millis() - previous) < timeout));   // Waits for the asnwer with time out

      //Serial.println(F("START RESPONSE:"));
      //Serial.println(response);
      //Serial.println(F("END RESPONSE"));
      //if (answer == 0) {
      //  Serial.println("Could not get the expected answer!");
      //}
      //else {
      //  Serial.println("Found expected answer!");
      //}

      return answer;
    }

What can be wrong in the readATcommand function as it replies with an incomplete response:

    --START READ SMS POSITION1--
    Content:
    AT+CMGR=1

    +CMGR: "REC READ","+407245402XX","","17/06/29,10:
    --END READ SMS POSITION1--

But, when I run it from a terminal, the AT+CMGR=1 replies with:

    AT+CMGR=1

    +CMGR: "REC READ","+40724540234","","17/06/29,10:03:06+12"
    Salut

    OK

As you can see the message body is not there + the time of the SMS is also incomplete.

Thank you!

title: Arduino Mega 2560 with SIM808 module - Incomplete SMS response

Answers: 1

body:
Don't delay.

In the three seconds that you wait between sending the AT command and reading the response the entire response has arrived and been placed in the serial RX buffer - which has overflowed because there's more than 64 bytes in the response. So you lose data.

You should never use `delay()` when reading from serial, it's dangerous (as you see).

Instead you should be just immediately reading until you see the correct response from the command you sent - which will either be "OK" or "ERROR". Everything before that is the content of the response to your command.


body:
I'm working in an art project, is some kind of loop between contact microphones and walkie talkies. I want to create some kind of noisy feedback.

I'm putting one walkie-talkie inside of a bottle, and in front of the speaker/microphone from the walkie I want to put another contact microphone attached to an Arduino, and record the sounds of the walkie talkie and played with some delay in some buzzer in front of another contact microphone attached to an amp with three speakers. To sum up, I have like 3 parts linked between them, the first one the walkie, the second one with an Arduino and the third one a simple mic whith an amp and three speakers.

Only the second part will be working with the Arduino and I want it to record sound and play it simultaneously with some delay.
I worked with a friend with some servo motors and music shields and I've been doing some research. I found 3 very interesting projects one is this, that it's practically what I want to do [Space Replay][1]but there's so little information about it, and the other two are [Arduino Audio Input][2] and [Arduino Audio Output][3]
So, my questions are:

 - If I use a music shield I don't need a DAC or/and an amp? or only an amp if my speakers are too loud?
 - In the project Space Replay they only use [this music shield][4] so with only one music shield I can record and play music simultaneously? or I need two music shields?
 - That Adafruit Wave Shield is only for Arduino uno, but it will be better or easier to work with DUE or Arduino Mega and another music shields or making my own circuits like in the instructables Arduino Audio Input and Output?

I don't care too much about the quality of the audio, as I said the purpose is make some noise. The only thing is I want to create some kind of echo, or some kind of cannon, between the first sound of the walkie and the others pick up sounds.

Any other comment or advice will be much appreciated and welcomed.
Thanks

  [1]: https://arduino.stackexchange.com/questions/674/how-does-the-space-replay-record-audio
  [2]: http://www.instructables.com/id/Arduino-Audio-Input/
  [3]: http://www.instructables.com/id/Arduino-Audio-Output/
  [4]: https://www.adafruit.com/product/94

title: Recording and playback sound

Answers: 1

body:
Try using [this][1] shield from Adafruit. I believe it can record and play audio, and they have versions with and without amps.

I do not know about near-simultaneous playback, so read up a bit before buying.

  [1]: https://www.adafruit.com/product/1788


body:
I need to control a 10kOhm digital potentiometer in rheostat mode in 256 steps. I found an Arduino tutorial, which works with an MCP41010 (I added a viper resistance according to the datasheet). This works fine - I can send values from 0 to 255 to the CS pin an the resistance between output pin A and B changes from 0 to 10kOhm.
The problem is, that my application requires 16V to go through this resistance, which the MCP41010 can't handle.

I tried to go with a [MCP41HVX1][3] high voltage digital potentiometer (which I soldered on a TSSOP-to-DIP Breakout board) and assumed it would work the same way. Turns out it doesn't... My connections are:

Arduino nano -> MCP41HVX1

- 10 -> CS
- 11 -> SDI
- 13 -> SCK
- 5V -> VL
- GND -> DGND

With the MCP41010 I connect a 115Ohm viper resistor between output pin A and wiper terminal and measure resistance between output pin A and B (pink connectors). I noticed, that the MCP41HVX1 has a different description for the rheostat modus but I can't get that to work either.

This is my circuit that works with the MCP41010
[![Arduino MCP41010  circuit][4]][4]

And here is the respective code (which sets the MCP41010 to 255 i.e. 10kOhm)
<!-- language-all: lang-cpp -->

    #include <SPI.h>
    byte address = 0x11;
    int CS= 10;

    void setup()
    {
      pinMode (CS, OUTPUT);
      SPI.begin();
    }

    void loop()
    {
      digitalPotWrite(255, CS);

    }

    int digitalPotWrite(int value, char Port)
    {
      digitalWrite(Port, LOW);
      SPI.transfer(address);
      SPI.transfer(value);
      digitalWrite(Port, HIGH);
    }

Has anyone ever done this or has a clue what's going on?

  [1]: http://www.instructables.com/id/Digital-Potentiometer-MCP41100-and-Arduino/
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/11195c.pdf
  [3]: http://cdn-reichelt.de/documents/datenblatt/A200/DS_MCP41HVX1.pdf
  [4]: https://i.stack.imgur.com/jyDke.png

title: Controlling an MCP41HV31 Digital Potentiometer

Answers: 2

body:
One thing I discovered, after coming back to the internet multiple times for clues, is that that SHDN pin on the MCP41HVX1 has to be tied HIGH.

If not, you can try incrementing, decrementing, or writing values to your heart's content and the thing is not going to budge.

I tied SHDN to the VL level via a 10k resistor and I can write and increment without problems.

I think it should have been flagged in the datasheet though, in the Pinout Description table.

body:
I realize that this thread is old. I am providing an answer for anyone else who may end up here like I did a while back looking to solve this.

I have created an Arduino library on Github (https://github.com/gregsrabian/MCP41HVX1) which allows for control of this family of chips. The README.md within the github project documents all of the APIs and also provides the wiring diagram. There are also example sketches included.

I have created an article on Instructables (https://www.instructables.com/id/MCP41HVX1-Digital-Potentiometer-for-Arduino/) that provides a step by step on how to control this family of chips. There is also an explanation on how to solder the TSSOP chip.


body: What is an ICSP pin? I have read that it is an AVR and a tiny programming header for the Arduino, but what is an AVR and what does an ICSP pin do?

title: What is an ICSP pin?

Answers: 1

body:
ICSP stands for *In Circuit Serial Programming*, which represents one of the several methods available for programming Arduino boards.  Ordinarily, an Arduino bootloader program is used to program an Arduino board, but if the bootloader is missing or damaged, ICSP can be used instead.  ICSP can be used to restore a missing or damaged bootloader.

A typical [Arduino ICSP header](https://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=1199&bih=663&q=arduino+icsp+header&oq=Arduino+icsp&gs_l=img.1.1.0l7j0i8i30k1l3.1229.4003.0.6313.8.8.0.0.0.0.129.579.5j1.6.0....0...1.1.64.img..2.6.577.0.NxIOJx-ygj) has six pins, arranged 2x3.  The article [Connecting the Programmer:
In-Circuit Serial Programming (ICSP)](https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader/connecting-the-programmer) at Sparkfun describes some of the functions of ICSP pins, which include MISO, MOSI, SCK, V+, Ground, and Reset.

Each ICSP pin usually is cross-connected to another Arduino pin with the same name or function.  For example, MISO on an Uno or Nano's ICSP header is connected to MISO / digital pin 12; MOSI on the ISCP header is connected to MOSI / digital pin 11; and so forth.  Note, MISO, MOSI, and SCK pins taken together make up most of an SPI interface.

Several Arduinos, including the Uno, have two ICSP headers.  One of them is for use with the ATmega328 (or similar), and the other for use with the ATmega16U2 (or similar) chip that implements USB. When present, this  allows reprogramming the USB chip.

---

[AVR](https://en.wikipedia.org/wiki/Atmel_AVR) refers to the instruction set architecture used in a family of Atmel microcontrollers.  Several Arduinos  – Mega, Uno, Nano, Micro – use AVR chips.  Others, like the Zero and Due, instead use ATSAM3 chips, with an [ARM instruction set architecture](https://en.wikipedia.org/wiki/List_of_ARM_microarchitectures).


body:
I built a small PCB that has some LEDs (bare NeoPixel 5050) and an IR receiver on it. The microcontroller is an ATtiny85, and the PCB is powered by a LiPoly battery (3.7V). The circuit normally stays in ULP sleep mode until a pin change interrupt wakes the circuit. The pin change interrupt is tied to the IR receiver so when the receiver gets a signal from a remote (38kHz modulated IR burst) a lighting sequence is triggered. I have multiple of these PCBs running the exact same code (shown below). When the PCBs receive an IR signal they all start at the same time, but then after a few seconds they start to drift apart. The lighting needs to be synchronized. What is the reason for this drift and how can I eliminate it? Is it due to different battery voltages? That would be the only physical difference between any two PCBs. Thanks for your help.

    #define IR_PIN      4
    #define LIGHT_PIN   0
    #define DELAY_TIME  200

    #include <Adafruit_NeoPixel.h>
    #define NUM_PIXELS  2
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_PIXELS, LIGHT_PIN, NEO_GRB + NEO_KHZ800);

    #include "avr/interrupt.h"
    #include "avr/sleep.h"

    void setup() {
      pinMode(IR_PIN, INPUT);
      strip.begin();
      pixelsOff();
    }

    void loop() {
      sleep();

      for (int i = 0; i < 5; i++) {
       pixelsOnRed();
       delay(DELAY_TIME);
       pixelsOff();
        delay(DELAY_TIME);
       pixelsOnGreen();
       delay(DELAY_TIME);
       pixelsOff();
        delay(DELAY_TIME);
      }

      for (int i = 0; i < 5; i++) {
       pixelsOnBlue();
       delay(DELAY_TIME);
       pixelsOff();
        delay(DELAY_TIME);
       pixelsOnRed();
       delay(DELAY_TIME);
       pixelsOff();
        delay(DELAY_TIME);
      }

      for (int i = 0; i < 5; i++) {
       pixelsOnGreen();
       delay(DELAY_TIME);
       pixelsOff();
        delay(DELAY_TIME);
       pixelsOnRed();
       delay(DELAY_TIME);
       pixelsOff();
        delay(DELAY_TIME);
      }
    }

    void pixelsOff() {
      strip.setPixelColor(0, 0, 0, 0);
      strip.setPixelColor(1, 0, 0, 0);
      strip.show();
    }

    void pixelsOnRed() {
      strip.setPixelColor(0, 255, 0, 0);
      strip.setPixelColor(1, 255, 0, 0);
      strip.show();
    }

    void pixelsOnGreen() {
      strip.setPixelColor(0, 0, 255, 0);
      strip.setPixelColor(1, 0, 255, 0);
      strip.show();
    }

    void pixelsOnBlue() {
      strip.setPixelColor(0, 0, 0, 255);
      strip.setPixelColor(1, 0, 0, 255);
      strip.show();
    }

    ISR(PCINT0_vect)
    {
        //This is not needed for the current sketch
    }

    void sleep() {
        GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
        PCMSK |= _BV(PCINT4);                   // Use PB3 as interrupt pin
        ADCSRA &= ~_BV(ADEN);                   // ADC off
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

        sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
        sei();                                  // Enable interrupts
        sleep_cpu();                            // sleep

        cli();                                  // Disable interrupts
        PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
        sleep_disable();                        // Clear SE bit
        ADCSRA |= _BV(ADEN);                    // ADC on

        sei();                                  // Enable interrupts
    }

title: Two Arduinos get out of sync after a few seconds

Answers: 3

body:
> What is the reason for this drift and how can I eliminate it?

two solutions:

1) try using crystal oscillators;

2) try driving on arduino with the other arduino's clock output.

body:
*Assuming internal RC oscillator:*

In the datasheet:

> By default, the Internal RC Oscillator provides an approximate 8.0 MHz clock. **Though voltage and temperature
dependent,** this clock can be very accurately calibrated by the user. See “Calibrated Internal RC Oscillator Accuracy”
on page 164 and “Internal Oscillator Speed” on page 192 for more details. The device is shipped with the
CKDIV8 Fuse programmed. See “System Clock Prescaler” on page 31 for more details

And page 192 shows a graph of frequency vs voltage.

On 164 it says:

> It is possible to manually calibrate the internal oscillator to be more accurate than default factory calibration. **Please
note that the oscillator frequency depends on temperature and voltage. Voltage** and temperature characteristics
can be found in Figure 22-40 on page 193 and Figure 22-41 on page 193.

So yes, conclusive evidence there that the voltage will affect the frequency.

body:
Other answers have noted that the internal RC oscillator's frequency is voltage and temperature dependent.  If you have good control over voltage and temperature, consider manually or automatically calibrating the clocks of your several ATtiny85's.

Absent that control, consider adding crystals or ceramic resonators to your circuits, or set up a synchronization protocol using IR.  For example, if your IR transmitter is programmable, have it send a synchronization character as often as necessary to adequately synchronize the lights.  If your IR transmitter is not programmable, add an IR LED and driver to one or more of your ATtiny85's, and send synchronization characters at regular intervals.


body:
Is it possible to emit data from an arduino connected to a hc-05 Bluetooth module without pairing it to another device?
i.e. imagine that I want to send a Bluetooth signal as if it was a information spot. Then whoever who gets the signal can read it.

title: HC-05 emit data without pairing

Answers: 1

body: No. The HC-05 has to be paired. It runs on Bluetooth 2.x which requires pairing.  What you want is BLE (or Bluetooth 4.x) which has various "beacon" facilities.


body:
I am creating a server node that I want to be able to save the wifi SSID and the password into persistent memory so that when it starts ups it can connect to the network. I have looked for several hours and found just a few bits of information. One bit I found here http://playground.arduino.cc/Code/EEPROMWriteAnything

    #include <EEPROM.h>
    #include <Arduino.h>  // for type definitions

    template <class T> int EEPROM_writeAnything(int ee, const T& value) {
        const byte* p = (const byte*)(const void*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
              EEPROM.write(ee++, *p++);
        return i;
    }

    template <class T> int EEPROM_readAnything(int ee, T& value) {
        byte* p = (byte*)(void*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
              *p++ = EEPROM.read(ee++);
        return i;
    }

This code will not store String values to the EEPROM. So as I thought I would ask for advice from the Stack Exchange geniuses.

Thanks!

title: String to persistent memory (EEPROM?)

Answers: 1

body:
[EEPROM](https://www.arduino.cc/en/Reference/EEPROMPut) library has two functions `put` and `get` , which can help you store character array of any size, not exceeding the size of internal EEPROM size of Arduino. Please see the examples provided in the link above.

Here is a sample code to get you going.

    int address = 10;
    char arrayToStore[20];                    // Must be greater than the length of string.
    String testString = "hello there";

    testString.toCharArray(arrayToStore, testString.length()+1);  // Convert string to array.

    EEPROM.put(address, arrayToStore);                 // To store data
    EEPROM.get(address, arrayToStore);                 // To read data


body:
I want to send data from arduino to ESP8266. I have done all the RX and TX connections.
The problem is that data is not sent every second, it stops after a single byte. When I remove the arduino cable then data is read.

My Arduino Code :

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

    void loop() {

        Serial.write("50");
        delay(1000);
    }

My ESP8266 Code :

    void setup() {

    Serial.begin(9600);

      // connect to wifi.
      WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

      while (WiFi.status() != WL_CONNECTED) {

        delay(500);
      }
      Serial.println("Connected !");

    }

    void loop() {

     Serial.print(Serial.readString());

    }

title: Serial Communication between ESP8266 and Arduino Uno

Answers: 2

body:
Since you are  Arduino Uno, it has only one `Serial`. This Serial can be used to transmit data in USART mode to another Serial Device as well as see any Debug data in the Serial terminal.

However, both the functionality can not be used simultaneously. The Tx Rx pair of Arduino can be connected to one pair of other device i.e. either to the computer via the cable or to the Tx Rx of ESP8266.

But if you really need to plug in the Uno to the computer and send data to ESP8266 simultaneously, then you have to use [SoftwareSerial](https://www.arduino.cc/en/Reference/SoftwareSerial) library to convert any digital pin to Tx Rx pin, and connect them to ESP8266 for transmitting data.

body:
As explained by goddland_16. Using Software Serial library will solve the issue. Code is given below. By Initializing other digital pin as communication pin, Interupption between Tx and Rx and to ESP8266 is seperated.

**Arduino UNO / Nano Code :**

    /*
     * bismillah hir rahman nir raheem
     * UNO/Nano = Pin 7 & Pin 8
     * Note: Uno and ESP8266 cross connection
     */

    #include <SoftwareSerial.h>

    SoftwareSerial ArduinoUno(7,8);
    String f;

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

    void loop() {
        float i = (random(100) + 1);
        float j = (random(100) + 1);

        f = String('H') + String(i) + String('T') + String(j);
        ArduinoUno.println(f);
        delay(2000);
    }

**ESP8266 Code :**

    /*
     * bismillah hir rahman nir raheem
     * ESP8266 = Pin D7 & Pin D8
     * Note: Uno and ESP8266 cross connection
     */

    #include <SoftwareSerial.h>
    #include <ESP8266WiFi.h>

    SoftwareSerial NodeMCU(D7,D8);

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

     pinMode(D7,INPUT);
     pinMode(D8,OUTPUT);
    }

    void loop() {
        String content = "";
        char character;

        while (NodeMCU.available()) {
           character = NodeMCU.read();
           content.concat(character);
        }

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

        Serial.println("Temperature");
        Serial.println(content.substring(1, 6));
        Serial.println("Humidity");
        Serial.println(content.substring(7, 12));
        delay(2000);
    }


body:
I am working on a library to display custom text on a TFT screen and I came up with this error while making an example:

    EsploraHelloWorld:31: error: expected unqualified-id before '.' token
       TFTCharPlus.drawChar(chars[5, 0], chars[5, 1], chars[5, 2], chars[5, 3], chars[5, 3], 120, 0, 255, 255, 255, 4, EsploraTFT);
                   ^

Heres my code:

    #include <Esplora.h>
    #include <SPI.h>
    #include <TFT.h>
    #include <TFTCharPlus.h>

    // A table for all of the characters
    const char chars[6][5] = {
      {0xf8, 0x20, 0xf8, 0x1f, 0x15},
      {0xf8, 0x08, 0x08, 0x1f, 0x01},
      {0x70, 0x88, 0x70, 0x00, 0x00},
      {0xc0, 0x20, 0xc6, 0x29, 0xc6},
      {0xf0, 0x40, 0x80, 0x5f, 0x01},
      {0xf0, 0x90, 0x60, 0x00, 0x3d}
    };

    TFTCharPlus TFTCharPlus();

    void setup() {
      // initialize the screen
      EsploraTFT.begin();

      // make the background black
      EsploraTFT.background(0,0,0);

      // print the characters
      TFTCharPlus.drawChar(chars[0, 0], chars[0, 1], chars[0, 2], chars[0, 3], chars[0, 3], 0, 0, 255, 255, 255, 4, EsploraTFT);
      TFTCharPlus.drawChar(chars[1, 0], chars[1, 1], chars[1, 2], chars[1, 3], chars[1, 3], 24, 0, 255, 255, 255, 4, EsploraTFT);
      TFTCharPlus.drawChar(chars[2, 0], chars[2, 1], chars[2, 2], chars[2, 3], chars[2, 3], 48, 0, 255, 255, 255, 4, EsploraTFT);
      TFTCharPlus.drawChar(chars[3, 0], chars[3, 1], chars[3, 2], chars[3, 3], chars[3, 3], 72, 0, 255, 255, 255, 4, EsploraTFT);
      TFTCharPlus.drawChar(chars[4, 0], chars[4, 1], chars[4, 2], chars[4, 3], chars[4, 3], 96, 0, 255, 255, 255, 4, EsploraTFT);
      TFTCharPlus.drawChar(chars[5, 0], chars[5, 1], chars[5, 2], chars[5, 3], chars[5, 3], 120, 0, 255, 255, 255, 4, EsploraTFT);
    }

    void loop() {
      // not necessary
    }

And for reference, here is the `drawChar()` function:

    void TFTCharPlus::drawChar(byte data1, byte data2, byte data3, byte data4, byte data5, uint8_t xpos, uint8_t ypos, uint8_t colR, uint8_t colG, uint8_t colB, uint8_t size, TFT tft) {
      tft.stroke(colR, colG, colB);
      tft.fill(colR, colG, colB);
      byte data[5] = {data1, data2, data3, data4, data5};
      for (uint8_t x = 0; x < 5; x++) {
        for (uint8_t y = 0; y < 8; y++) {
          if (bitRead(data[x], 7 - y)) {
            tft.rect(x*size+xpos, y*size+ypos, size, size);
          }
        }
      }
    }

How can I fix the error?

**BTW**: The error is not in the library, everything is done correctly

**EDIT**: I realized that the error occurs on all six `drawChar()` lines, and After fixing a small error, I also got this:
`request for member 'drawChar' in 'TFTCharPlus', which is of non-class type 'TFTCharPlus()'`

Answers: 2

body:
It appears that you are calling the "description" of the library method (function).  What is necessary is to use the "description" to create a "working copy" of the library method.  Then call the "working copy".

In the above statement, the "description" is the Class, "to create" means to instantiate and "working copy" is referred to as the Object.

In the [Arduino Serial Port Example][1], you will find the following line:

    SoftwareSerial mySerial(10, 11); // RX, TX

Here, the Class "SoftwareSerial" is used to instantiate the Object "mySerial".  Later in the code calls are made to the "write" method with in that object:

    mySerial.write(Serial.read());

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

body:
In this line:

    TFTCharPlus TFTCharPlus();

you've given your TFT object the same name as its class, making that name ambiguous. If you change the name of the object to, e.g.:

    TFTCharPlus TFTobject();

 as well as changing all of your references to it (`TFTobject.drawChar(...)`), it should fix the issue.


body:
I would like to power my Raspberry Pi 3B using an Arduino Uno.

I have been able to do this by connecting the 5v on the Arduino to the 5 V on the Pi and connecting the GND to GND, and the Pi turns on. But I get a constant under voltage sign.

How can I get the Arduino to output the right amount of power (5 V and 2.5 A)?

title: Power a Raspberry Pi 3 from an Arduino Uno

Answers: 3

body:
If you are using PC USB, your total current cap is <500mA. Arduino + Pi + accesories is exceed this cap.

Use an adapter for Arduino. Ardiuno will suck up some current and rest can flow to Pi or whatever else is there.

Arduino has a linear voltage regulator. Try not to use >5v adapters. Voltage regulator will generate more heat as more current pass.

body:
You can't.

The on-board regulator of the Uno, the NCP1117, is only able to supply up to 1A before starting to dropout voltage (hence your undervoltage warning).

Even worse, because the NCP1117 lacks a proper heatsink, it will probably start dropping out voltage before reaching 1A, due to its internal thermal shutdown protection.

body:
If you reverse which board gets the power adapter you should be able successfully power them both from a single 5V 2.5A power supply.

Connect the power adapter to the Raspberry Pi3 and power the Arduino from the Pi's 5V pin.  The Uno should only draw about 200mA @ 5V from the Pi (depending on everything else you have connected).


body:
G'day guys, I'm trying to get an ESP8266 to work with an Arduino Uno.
Here is the wiring.

[![wiringPicture][1]][1]

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

When I go to the serial monitor (115200 baud) and type: AT, there is not response from the ESP8266.

Is there something that I am missing?

I also have a servo motor connected, it works fine.

    include "Arduino.h"
    include "ESP8266.h"
    include "dweet.h"
    include "Servo.h"

    define ESP8266_PIN_RX 10
    define ESP8266_PIN_TX 11
    define SERVO9G_PIN_SIG 2

    const int servo9gRestPosition   = 20;
    const int servo9gTargetPosition = 150;
    const char *SSID     = "Wireless Network";
    const char *PASSWORD = "wireless_password";

    ESP8266 wifi(ESP8266_PIN_RX,ESP8266_PIN_TX);
    Servo servo9g;

    const int timeout = 10000;
    char menuOption = 0;
    long time0;

    void setup()
    {
       Serial.begin(9600);
       while (!Serial); //await connection.
       Serial.println("start");

       wifi.init(SSID, PASSWORD);
       servo9g.attach(SERVO9G_PIN_SIG);
       servo9g.write(servo9gRestPosition);
       delay(100);
       servo9g.detach();

    }

    void loop()
    {
       servo9g.attach(SERVO9G_PIN_SIG);
       servo9g.write(servo9gTargetPosition);
       delay(500);
       servo9g.write(servo9gRestPosition);
       delay(500);
       servo9g.detach();
    }

I'm using the ESP8266 Library.
When trying to connect it just says `Initializing device...`

title: Trying to communicate with an ESP8266

Answers: 1

body:
Unless you have some project constraints which make it mandatory to use naked ESP8266, why not use a NodeMCU to communicate with the Arduino in a master/slave relation over I2C?

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

    #include <Wire.h>
    #define I2CAddressESPWifi 8

in `setup()`

    Wire.begin(D1,D2); // SCL D1 SDA D2

then call from anywhere inside your `loop()` call this function

 char readSlave(int x) { // send current time
   String xY = String(x);
   char c;
   int charArrayLength = xY.length()+1;
   char bufferChar[charArrayLength];
   Wire.beginTransmission(8);
   xY.toCharArray(bufferChar, charArrayLength);
   Wire.write(bufferChar);
   Wire.endTransmission();
   delay(10);
   Serial.print("wire sent: [");
   Serial.print(x);
   delay(50);//Wait for Slave to calculate response.
   int counter = 0;
   char buffMe[32];
   int bytesIn = Wire.requestFrom(8,32);
   while (Wire.available()) {
     delay(2);
     buffMe[counter] = Wire.read();
     /*
     c = Wire.read();
     Serial.print(c);
     */
     counter++;
   }
   delay(10);
   Wire.endTransmission();
   delay(500);
   Serial.print("] bytesIn: [");
   Serial.print(bytesIn);
   Serial.print("] buffMe: [");
   Serial.print(buffMe);
   Serial.print("]");
      return buffMe;
    }

and your arduino will be waiting (`setup`)

 Serial.begin(9600);
 // slave listens for call from master NodeMCU
 Wire.begin(I2CAddressESPWifi);  // predefined as `8` or whatever address you choose
 Wire.onReceive(receiveEvent);
 Wire.onRequest(requestEvent);

and at the end of your code

 void receiveEvent(int howMany) {
   if (howMany) {
     Serial.print("bytes[");
     Serial.print(howMany);
     Serial.print("] Received[");
     char charIn[howMany];
     int counter = 0;
     while (Wire.available()) {
       char c = Wire.read();
       charIn[counter] = c;
       //Serial.print(c);
       counter++;
     }
     delay(10);
     //do something with command from master
   }
 }
 void requestEvent() {
   char bufferChar[20] = "slave answer string";  // automatically null terminated extra character at end
   Serial.println(bufferChar);
   Wire.write(bufferChar);
 }

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


body:
This code is part of a long code for a robot that is both obstacle-avoiding and remote control. I am trying to get the code to check both "if" statements when the code number FF807F is received from an IR remote. When the code number is received
the program checks both "if" statements and carries out the one that is true. I want the program, once it has finished carrying out the true "if statement, to check both "if" statements again.

    void loop () {
    if (My_Decoder.value==0xFF807F){
     if (cm<6)
     {
      motor_stop();
      digitalWrite(backlights, HIGH);
      delay(2000);
      motor_backward();
      digitalWrite(backlights, HIGH);
      Serial.println("backward");
      delay(2000);
      motor_stop();
      digitalWrite(backlights, HIGH);
      delay(900);
      motor_right();
      digitalWrite(backlights, LOW);
      Serial.println("right");
      delay(1000);
    }
    if (cm>6)
     {
      motor_forward();
      digitalWrite(backlights, LOW);
      Serial.println("forward");
    }
    }
    }

title: Repeatedly checking multiple "if" statements

Answers: 4

body:
Your are missing the case when "cm == 6".

You don't need to do two "if"; one "if-else" is enough because is either one or the other.

You don't have/need to check twice; "cm" doesn't change inside the "if". But i you want, use functions:

    void loop () {
      if (My_Decoder.value == 0xFF807F) {
        doSomething();
        doSomething();
      }
    }

    void doSomething() {
      if (cm < 6) {
        motor_stop();
        digitalWrite(backlights, HIGH);
        // ...
        delay(1000);
      } else {
        motor_forward();
        digitalWrite(backlights, LOW);
        Serial.println("forward");
      }
    }

body:
I am going to assume you don't want to include `cm == 6` which is why you have both cases. I would consider using a while loop instead of a singular 'if' statement in order to continuously check if those buttons are being pressed or not (`while (cm<6){do this stuff}`). Otherwise, it will check once and never check again.

Instead it will jump down to the next 'if' statement, it will fail and then jump to the top of the loop where it will check for the code 0xFF807F. Let me know how it goes!

body:
    if (My_Decoder.value == 0xFF807F) {
    if (cm<6)

Are you wanting both "ifs" to occur? Maybe a bitwise operator like logical AND (`&`)?

body:
This looks like a good use for a State Machine.

It would look something like this:

```c++
typedef enum State
{
  STATE_IDLE,
  STATE_THIS,
  STATE_THAT,
  STATE_OTHER
} State;

State state;

const int IR_BUTTON_1    = 0xFF807F;
const int IR_BUTTON_2    = 0x112233;
const int IR_BUTTON_3    = 0X445566;
const int IR_BUTTON_STOP = 0x778899;

void setup()
{
  Serial.begin(115200);
  Serial.println(F("setup()"));
  state = STATE_IDLE;
}

void loop()
{
  Serial.println(F("loop()"));

  switch(my_decoder.value)
  {
    case IR_BUTTON_1:
      state = STATE_THIS;
      Serial.println(F("Entered STATE_THIS"));
      break;
    case IR_BUTTON_2:
      state = STATE_THAT;
      Serial.println(F("Entered STATE_THAT"));
      break;
    case IR_BUTTON_3:
      state = STATE_OTHER;
      Serial.println(F("Entered STATE_OTHER"));
      break;
    case IR_BUTTON_STOP:
      state = STATE_IDLE;
      Serial.println(F("Entered STATE_IDLE"));
      break;
  }

  switch(state)
  {
    case STATE_THIS:
      DoThis();
      break;
    case STATE_THAT:
      DoThat();
      break;
    case STATE_OTHER:
      DoOther();
      break;
  }
}

void DoThis()
{
  Serial.println(F("DoThis()"));
}

void DoThat()
{
  Serial.println(F("DoThat()"));
}

void DoOther()
{
  Serial.println(F("DoOther()"));
}
```
This locks the state machine into an active state as per the [OP's comment][1]:
 >  I want it to repeat the "void doSomething();" function until another button is pressed.

However, as Dave Newton pointed out in the comments, locking a machine into a particular active state can be dangerous, so I've edited the code to add a STOP button to transition back to the IDLE state. But this still relies on the operator pressing the STOP button to return to idle; there is no automatic return to idle which could be a hazard depending on the application.

  [1]: https://arduino.stackexchange.com/questions/40128/repeatedly-checking-multiple-if-statements/84361?noredirect=1#comment81907_40131


body:
This is my very first arduino sketch and it's causing me a bit of a headache.
Sounds so simple really all I want the sketch to do is digitalread from one of 4 digital input pins and then digitalwrite to one of 4 output pins in essence.
So that when button 1 is pressed LED 1 lights up, button 2 pressed led 2 lights up and so on.
I've added a serial write so I could check that the buttons are actually working when pressed.

The code I've written:

<pre>const int buttonPin1 = 7;     // number of pushbutton 1 pin
int buttonState1 = LOW;       // set the default variable value for pushbutton1 status
const int ledPin1 =  6;       // number of the LED 1 pin
const int buttonPin2 = 8;     // number of pushbutton 2 pin
int buttonState2 = LOW;       // set the default variable value for pushbutton2 status
const int ledPin2 =  9;       // number of the LED 2 pin
const int buttonPin3 = 4;     // number of pushbutton 3 pin
int buttonState3 = LOW;       // set the default variable value for pushbutton3 status
const int ledPin3 =  5;       // number of the LED 3 pin
const int buttonPin4 = 2;     // number of pushbutton 4 pin
int buttonState4 = LOW;       // set the default variable value for pushbutton4 status
const int ledPin4 =  3;       // number of the LED 4 pin

void setup() {                  // Set Pins to Outputs Or Inputs
  pinMode(buttonPin1, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin1, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin2, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin2, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin3, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin3, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin4, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin4, OUTPUT);     // initialize the LED pins as an outputs:
  Serial.begin(9600);           // initialize serial communication at 9600 baud
}

void loop() {

  buttonState1 = digitalRead(buttonPin1);  // read current states of the pushbutton value:
  buttonState2 = digitalRead(buttonPin2);  // read current states of the pushbutton value:
  buttonState3 = digitalRead(buttonPin3);  // read current states of the pushbutton value:
  buttonState4 = digitalRead(buttonPin4);  // read current states of the pushbutton value:

  // check if the pushbutton is pressed buttonState# == HIGH/LOW
  // if pressed change buttonState == HIGH to turn on ledPin#
  // else if buttonState == LOW then digitalWrite(ledPin#, LOW) Keeps Led off.

    if (buttonState1 == HIGH) {    //check buttonState
    digitalWrite(ledPin1, HIGH);  //if HIGH turn LED on:
    } else {
    digitalWrite(ledPin1, LOW);   // turn LED off:
    }
    Serial.println(buttonState1); //Print buttonState to serial
    if (buttonState2 == HIGH) {   //check buttonState
    digitalWrite(ledPin2, HIGH);  //if HIGH turn LED on:
    } else {
    digitalWrite(ledPin2, LOW);   // turn LED off:
    delay(10);
    }
    Serial.println(buttonState2); //Print buttonState to serial
    if (buttonState3 == HIGH) {   //check buttonState
    digitalWrite(ledPin3, HIGH);  //if HIGH turn LED on:
    } else {
    digitalWrite(ledPin3, LOW);   // turn LED off:
    delay(10);
    Serial.println(buttonState3); //Print buttonState to serial
    }
    if (buttonState4 == HIGH) {   //check buttonState
    digitalWrite(ledPin4, HIGH);  //if HIGH turn LED on:
    } else {
    digitalWrite(ledPin4, LOW);   // turn LED off:
    delay(10);
    Serial.println(buttonState4); //Print buttonState to serial
    }

The Leds all have a common GND and the buttons all have a common GND.
Buttons are connected to +5V & Input pin# so one terminal has got two wires,
Led's are connected to digital output pins then resistor and straight to GND.
What happens is that ALL of the LED's come on when any one of the 4 buttons in pressed.

I've attempted to edit some of the code in the example sketches to get this to work.

Can anyone suggest anything that I'm doing wrong?
Or ammend the code sp that I can see where I'm going wrong.

title: Arduino code to control 4 led's from 4 buttons

Answers: 3

body:
It is likely you have connected the switches incorrectly.  Normally, people use [single poll single throw (SPST) switches][1] connected to 5 volts and the input pin of the Arduino.  This will pull the input pin to 5 volts when the switch is closed.  Then, to pull the input pin to ground when the switch is open, people add a large resistor between ground and the same processor pin.

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

Almost any large resistor will work here.  Consider using 10K ohms (10,000 ohms) or there abouts.

Of course, if you are using a 3 volt Arduino, do not connect the switch to a 5 volt source.  Instead connect it to a 3 volt source.

Alternatively, a pull up resistor inside the processor, if available, can be activated.  Look at [this arduino.cc web page][3]. There this sample code shows how to activate the processor's pull up on pin number 2:

    pinMode(2,INPUT_PULLUP);

Because not all processors have a "pull up" feature on all input pins & because the range of internal to the processor pull up resistances can vary (for example 50,000 ohms to 150,000 ohms), it may be more useful and universal to use an external pull up resistor.

  [1]: https://en.wikipedia.org/wiki/Switch#Contact_terminology
  [2]: https://i.stack.imgur.com/VpRNc.png
  [3]: https://www.arduino.cc/en/Tutorial/InputPullupSerial

body:
Get rid of the external resistors, use the internal pullup resistor.

In setup():

pinMode (pinX, INPUT_PULLUP);

Wire the button between input pin pinX and Gnd, then test for a LOW to see if the button is pressed in loop():

if (digitalRead (pinX) == LOW){ // button is pressed

// do something

}

else { // button is not pressed

// do something else

}

body: I would suggest taking the resistor/s off the switches, so the button connects to digital inputs to the 3v/5v line. Then use 470ohm resistors for the leds(to limit the current) on the digital outputs.