body:
    #include <LiquidCrystal.h>

    #include <SoftwareSerial.h>

    float pulse = 0;

    float temp = 0;

    SoftwareSerial ser(9,10);

    String apiKey = "U5AGYVQT5JRJPSDR";

    //  Variables

    int pulsePin = A0;                 // Pulse Sensor purple wire connected to analog pin 0

    int blinkPin = 7           ;                // pin to blink led at each beat

    int fadePin = 8;                  // pin to do fancy classy fading blink at each beat

    int fadeRate = 0;                 // used to fade LED on with PWM on fadePin

    LiquidCrystal lcd(13, 12, 6, 5, 4, 3);

    // Volatile Variables, used in the interrupt service routine!

    volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS

    volatile int Signal;                // holds the incoming raw data

    volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!

    volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not
     a "live beat".

    volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

    // Regards Serial OutPut  -- Set This Up to your needs

    static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino
    Serial Monitor ASCII Visual Pulse

    volatile int rate[10];                      // array to hold last ten IBI values

    volatile unsigned long sampleCounter = 0;          // used to determine pulse timing

    volatile unsigned long lastBeatTime = 0;           // used to find IBI

    volatile int P = 512;                      // used to find peak in pulse wave, seeded

    volatile int T = 512;                     // used to find trough in pulse wave, seeded

    volatile int thresh = 525;                // used to find instant moment of heart beat, seeded

    volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded

    volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM

    volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

    void setup()

    {

      lcd.begin(16, 2);

      pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!

      pinMode(fadePin,OUTPUT);          // pin that will fade to your heartbeat!

      Serial.begin(115200);             // we agree to talk fast!

      interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS

                                        // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,

                                        // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN

                                        //   analogReference(EXTERNAL);

      lcd.clear();

      lcd.setCursor(0,0);

      lcd.print("Engineers Garage");

      ser.begin(9600);

      ser.println("AT");

      delay(1000);

      ser.println("AT+GMR");

      delay(1000);

      ser.println("AT+CWMODE=3");

      delay(1000);

      ser.println("AT+RST");

      delay(5000);

      ser.println("AT+CIPMUX=1");

      delay(1000);

      String cmd="AT+CWJAP="EngineersGarage","egP@$$w0rd?"";

      ser.println(cmd);

      delay(1000);

      ser.println("AT+CIFSR");

      delay(1000);

    }

    //  Where the Magic Happens

    void loop()

    {

       serialOutput();

      if (QS == true) // A Heartbeat Was Found

        {

          // BPM and IBI have been Determined

          // Quantified Self "QS" true when arduino finds a heartbeat

          fadeRate = 255; // Makes the LED Fade Effect Happen, Set 'fadeRate' Variable to 255 to fade LED
     with pulse

          serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.

          QS = false; // reset the Quantified Self flag for next time

        }

      ledFadeToBeat(); // Makes the LED Fade Effect Happen

      delay(20); //  take a break

      read_temp();

      esp_8266();

    }

    void ledFadeToBeat()

    {

       fadeRate -= 15;                         //  set LED fade value

       fadeRate = constrain(fadeRate,0,255);   //  keep LED fade value from going into negative numbers!

       analogWrite(fadePin,fadeRate);          //  fade LED

    }

    void interruptSetup()

    {

      // Initializes Timer2 to throw an interrupt every 2mS.

      TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE

      TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER

      OCR2A  = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE

      TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A

      sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED

    }

    void serialOutput()

    {   // Decide How To Output Serial.

     if (serialVisual == true)

      {

         arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer

      }

     else

      {

          sendDataToSerial('S', Signal);     // goes to sendDataToSerial function

       }

    }

    void serialOutputWhenBeatHappens()

    {

     if (serialVisual == true) //  Code to Make the Serial Monitor Visualizer Work

       {

         Serial.print("*** Heart-Beat Happened *** ");  //ASCII Art Madness

         Serial.print("BPM: ");

         Serial.println(BPM);

         lcd.clear();

         lcd.print("BPM: ");

         lcd.print(BPM);

       }

     else

       {

         sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix

         sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix

       }

    }

    void arduinoSerialMonitorVisual(char symbol, int data )

    {

      const int sensorMin = 0;      // sensor minimum, discovered through experiment

      const int sensorMax = 1024;    // sensor maximum, discovered through experiment

      int sensorReading = data; // map the sensor range to a range of 12 options:

      int range = map(sensorReading, sensorMin, sensorMax, 0, 11);

      // do something different depending on the

      // range value:

      switch (range)

      {

        case 0:

          Serial.println("");     /////ASCII Art Madness

          break;

        case 1:

          Serial.println("---");

          break;

        case 2:

          Serial.println("------");

          break;

        case 3:

          Serial.println("---------");

          break;

        case 4:

          Serial.println("------------");

          break;

        case 5:

          Serial.println("--------------|-");

          break;

        case 6:

          Serial.println("--------------|---");

          break;

        case 7:

          Serial.println("--------------|-------");

          break;

        case 8:

          Serial.println("--------------|----------");

          break;

        case 9:

          Serial.println("--------------|----------------");

          break;

        case 10:

          Serial.println("--------------|-------------------");

          break;

        case 11:

          Serial.println("--------------|-----------------------");

          break;

      }

    }

    void sendDataToSerial(char symbol, int data )

    {

       Serial.print(symbol);

       Serial.println(data);

    }

    ISR(TIMER2_COMPA_vect) //triggered when Timer2 counts to 124

    {

      cli();                                      // disable interrupts while we do this

      Signal = analogRead(pulsePin);              // read the Pulse Sensor

      sampleCounter += 2;                         // keep track of the time in mS with this variable

      int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise

                                                  //  find the peak and trough of the pulse wave

      if(Signal < thresh && N > (IBI/5)*3) // avoid dichrotic noise by waiting 3/5 of last IBI

        {

          if (Signal < T) // T is the trough

          {

            T = Signal; // keep track of lowest point in pulse wave

          }

        }

      if(Signal > thresh && Signal > P)

        {          // thresh condition helps avoid noise

          P = Signal;                             // P is the peak

        }                                        // keep track of highest point in pulse wave

      //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT

      // signal surges up in value every time there is a pulse

      if (N > 250)

      {                                   // avoid high frequency noise

        if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) )

          {

            Pulse = true;                               // set the Pulse flag when we think there is a pulse

            digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED

            IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS

            lastBeatTime = sampleCounter;               // keep track of time for next pulse

            if(secondBeat)

            {                        // if this is the second beat, if secondBeat == TRUE

              secondBeat = false;                  // clear secondBeat flag

              for(int i=0; i<=9; i++) // seed the running total to get a realisitic BPM at startup

              {

                rate[i] = IBI;

              }

            }

            if(firstBeat) // if it's the first time we found a beat, if firstBeat == TRUE

            {

              firstBeat = false;                   // clear firstBeat flag

              secondBeat = true;                   // set the second beat flag

              sei();                               // enable interrupts again

              return;                              // IBI value is unreliable so discard it

            }

          // keep a running total of the last 10 IBI values

          word runningTotal = 0;                  // clear the runningTotal variable

          for(int i=0; i<=8; i++)

            {                // shift data in the rate array

              rate[i] = rate[i+1];                  // and drop the oldest IBI value

              runningTotal += rate[i];              // add up the 9 oldest IBI values

            }

          rate[9] = IBI;                          // add the latest IBI to the rate array

          runningTotal += rate[9];                // add the latest IBI to runningTotal

          runningTotal /= 10;                     // average the last 10 IBI values

          BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!

          QS = true;                              // set Quantified Self flag

          // QS FLAG IS NOT CLEARED INSIDE THIS ISR

          pulse = BPM;

        }

      }

      if (Signal < thresh && Pulse == true)

        {   // when the values are going down, the beat is over

          digitalWrite(blinkPin,LOW);            // turn off pin 13 LED

          Pulse = false;                         // reset the Pulse flag so we can do it again

          amp = P - T;                           // get amplitude of the pulse wave

          thresh = amp/2 + T;                    // set thresh at 50% of the amplitude

          P = thresh;                            // reset these for next time

          T = thresh;

        }

      if (N > 2500)

        {                           // if 2.5 seconds go by without a beat

          thresh = 512;                          // set thresh default

          P = 512;                               // set P default

          T = 512;                               // set T default

          lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date

          firstBeat = true;                      // set these to avoid noise

          secondBeat = false;                    // when we get the heartbeat back

        }

      sei();                                   // enable interrupts when youre done!

    }// end isr

    void esp_8266()

    {

       // TCP connection AT+CIPSTART=4,"TCP","184.106.153.149",80

        String cmd = "AT+CIPSTART=4,"TCP","";

        cmd += "184.106.153.149"; // api.thingspeak.com

        cmd += "",80";

        ser.println(cmd);

        Serial.println(cmd);

        if(ser.find("Error"))

        {

          Serial.println("AT+CIPSTART error");

          return;

        }

      // prepare GET string GET https://api.thingspeak.com/update?api_key=LHAG4NSIYJ5UWS6U&field1=0rnrn

      String getStr = "GET /update?api_key=";

      getStr += apiKey;

      getStr +="&field1=";

      getStr +=String(temp);

      getStr +="&field2=";

      getStr +=String(pulse);

      getStr += "rnrn";

      // send data length

      cmd = "AT+CIPSEND=4,";

      cmd += String(getStr.length());

      ser.println(cmd);

      Serial.println(cmd);

      delay(1000);

      ser.print(getStr);

      Serial.println(getStr);

     //thingspeak needs 15 sec delay between updates

      delay(3000);

    }

    void read_temp()

    {

      int temp_val =  analogRead(A1);

      float mv = (temp_val/1024.0)*5000;

      float cel = mv/10;

      temp = (cel*9)/5 + 32;

    }

title: no matching function to call for SoftwareSerial::SoftwareSerial(int&,int&)? How to rectify this problem

Answers: 1

body:
The sketch in the question is not for NodeMCU. It is for Arduino with esp8266 wired on pins 9 and 10. But the error in title is a current error for esp8266 Arduino boards package 2.6.0. The EspSoftwareSerial bundled with the esp8266 Arduino boards package version 2.6.0 has a compatibility breaking change.

The problem was immediately [reported][1] and the EspSoftwareSerial maintainer added the legacy API back to EspSoftwareSerial. The fixed version will be available with esp8266 boards package 2.6.1, which will be available soon because of multiple problems with 2.6.0.

  [1]: https://github.com/esp8266/Arduino/issues/6737


body:
I've been trying to create a sine wave using the pwm function of the Arduino DUE.
The sine wave has te be at higher rates than the analogWrite() function can handle, so I've been using the native capabilties of the SAM3X8E.

To test it, instead of creating sinus I've been doing it linear. The code to do that is:
<!-- language-all: lang-cpp -->

      REG_PWM_ENA = REG_PWM_SR | B11111111; //enable output
      REG_PWM_CMR3 = 0x00000; //deadtime 0
      REG_PWM_CPRD3 = value;
      REG_PWM_CMR2 = 0x00000; //deadtime 0
      REG_PWM_CPRD2 = value;
      int i =0 ;
      waittime = 100;
      value = 30

      while (!Serial.available()) {
        REG_PWM_OS = 0x0000C;

    for (i = 0; i < value; i++) {
          pwmc_duty(i);
          pwmc_duty4(i);
          wait(waittime);
        }

    for (i = value; i > 0; i--) {
      pwmc_duty(i);
      pwmc_duty4(i);
      wait(waittime);
    }
    REG_PWM_OS = 0xC000C;
    wait(1);
    pwmc_duty(value);
    pwmc_duty4(value);
    REG_PWM_OS = 0xC0000;

    for (i = value; i > 0; i--) {
      pwmc_duty(i);
      pwmc_duty4(i);
      wait(waittime);
    }

    for (i = 0; i < value; i++) {
      pwmc_duty(i);
      pwmc_duty4(i);
      wait(waittime);
    }

    REG_PWM_OS = 0xC000C;
    wait(1);
    pwmc_duty(0);
    pwmc_duty4(0);
    }

    inline void pwmc_duty(unsigned short duty0) {
       // REG_PWM_CPRD3 = duty0;
        REG_PWM_CDTY3 = duty0;
    }
    inline void pwmc_duty4(unsigned short duty0) {
       // REG_PWM_CPRD3 = duty0;
        REG_PWM_CDTY2 = duty0;
    }

    void wait(int times){
      for (int i =0;  i < times; i++){
        __asm__("nop\n\t");
      }
    }

I expect the code to gradually increase the duty cycle of the signal and than slowly decrease. And that works!
The problem is that i do not get a normal PWM signal out of it.

I've attached one of the previous test signals to this post, with a bit different code, to show the problem.
[![The output signal][2]][2]

i've expected the pwm more clear like demonstrated in this paint picture:
[![Expected result][1]][1]

How do I get from these spikes to a more normal block signal?

  [1]: https://i.stack.imgur.com/WvAZG.png
  [2]: https://i.stack.imgur.com/SgoOw.png

title: Creating a sine with PWM Arduino DUE

Answers: 0


body:
I have made a code using involving HID control. But it seems that I messed up, but I can't upload a new sketch(nor edit the wrong code), because my Arduino is constantly doing things like Ctrl+Alt+Delete, Alt+F4... etc.
It seems that the only way is erasing the code in the memory, but how can I do so?

title: How can I clear the memory of my Arduino in this case?

Answers: 1

body:
1. Do the "button dance" - hold the Arduino in reset, releasing just you see the download start in the IDE. This may (will!) take a little practice to get just the right timing.

or

2. Use an external programmer connected to the ICSP connector. This could be a commercially made one, a DIY, or another Uno programmed and connected as an ICSP programmer. How-to's abound on the web.


body:
Currently I am working on an Arduino project. The project required to establish communication between Arduino Mega and NodeMCU ESP8266. Here are some details about the project:

- NodeMCU Rx Pin is connected to Arduino Mega Pin 14 (Tx3), while NodeMCU Tx Pin is connected to Arduino Mega Pin 15 (Rx3), Jumper Wires is used to connect NodeMCU and Arduino Mega
- Both Arduino Mega and NodeMCU are using baud rate 115200

Code for NodeMCU ESP8266 (Send The Data to Arduino Mega):

    void loop(){
           esp.println("0000");

           esp.flush();
    }

Code for Arduino Mega (Receive Data) :

     if(Serial3.available()){

      data = Serial3.readStringUntil('\n');

      Serial3.flush();

      Serial.println(data);

    }

The result :

[![enter image description here][1]][1]
  [1]: https://i.stack.imgur.com/cL5lv.png

The intented and expected result is "0000", however, the result shown in serial monitor is not accurate. Anyone could advise?

title: Bad Data : Arduino Mega & NodeMCU Serial Communication

Answers: 1

body: Sir mane ardunio mega 2560 my programing k hy jo k different sensor k value lake display karty hy aur sir ab my us value ko server jo k thingspeak hy aus p bajna chahta ho sir aus k leye mane esp8266 node-mcu use kar raha ho to sir ab my chahta ho k arduino value lake node-mcu ko send kary aur node mcu phr server p sir in k leye serial communication chahyae between two arduino sir is k leye koi refrence or any help


body:
**I am trying to make a battery capacity tester** (3.7v li-ion 18650 battery) using arduino uno. If possible i'd like to test 20 or more batteries at the same time. **I need to measure the voltage of each battery every 1 second.**

The uno has 6 anolog inputs iirc so too little for this application.
**I think using analog multiple extenders (connected using I2C) chained together to create enough analog inputs.**
**For example this one**: https://nl.aliexpress.com/item/32858973834.html?spm=a2g0o.productlist.0.0.57206143DNgWKp&algo_pvid=526d42f2-f7ee-4781-932b-947744ac631e&algo_expid=526d42f2-f7ee-4781-932b-947744ac631e-0&btsid=89c452fa-1d7c-4ae9-9dd5-ed8fc9bff128&ws_ab_test=searchweb0_0,searchweb201602_8,searchweb201603_52
**Do you think I'll be able to get relatively accurate voltage measurements using this approach?**

The purpose of the circuit is to measure the amount of mah (battery capacity) of the 18650 battery which is being discharged via the 10Ohm resistor. The battery will be discharged from 4.2volt (fully charged) to approx 2.5V using the 10ohm resistor, each second the voltage drop over the resistor will be measured and using it and the time passed the integral of time*current will be calculated to determine the capacity.

**This is the basic circuit used to connect each 18650 battery**, the ANALOG1 pin will be connected to the input of the analog extenders:
[![enter image description here][1]][1]
(I based it off of the circuit from this video: https://www.youtube.com/watch?v=WScPyfQz_f8)
The idea is to measure the voltage drop over the 10Ohm10W power resistor and calculate the current using the known resistance value, calculate the integral of current*time to get a capacity value for the battery.

**Is this a good approach? Would you recommend using analog extenders for this? If not what would be a better solution? Thank you very much!**

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

title: How to Measure many voltages (Uno) - Analog extenders a good option?

Answers: 1

body: Actually it is two separate questions and I answer your first question of reading multiple analog values using one ADC and the answer is Yes you can use this approach but  you should give enough time for each channel to charge internal ADC capacitor when you change channel .so if you use more independent ADC you get more time for each channel and result is better


body:
I want to measure a 9 V battery via one of the analog input ports of my Arduino Nano. From all the schemes of [this great answer](https://electronics.stackexchange.com/a/127538/234609), I choose the simplest one, the voltage divider. Assuming the maximum input voltage to be 12 V (just to be safe) and maximum divider's output voltage to be 5 V, I've solved it against R₂:R₁ proportion. It turns out that R₂:R₁ = 5:7.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

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

<!-- End schematic -->

With the values above, the input of A0 pin will be exactly 5 V.

The problem is that it could be any values. 5 Ω and 7 Ω or 5 MΩ and 7 MΩ!

I understand, that there should be another equation to take into account that will give me the values of those two resistors. [Another brilliant answer](https://electronics.stackexchange.com/a/28903/234609) demonstrates, that the values depend on the current I want to flow through the branches:

>So the point is when determining the resistance of the resistors, we should take into account the input resistance of the load and the two voltage divider resistors should be as small as possible.
>
>On the other hand, let's compare the current going through the divider in the circuit with large resistors on the divider and the circuit with small resistors on the divider. As you can see, the large resistors have current of just 2.5 μA going through them and the small resistors have current of 25 mA. The point here is that the current is wasted by the voltage divider and if this was for example part of a battery operated device, it would have a negative impact on the battery life. So the resistors should be as large as possible in order to lower the wasted current.

9 V batteries are known to have a little of energy canned inside, with the most popular 6LR61 having only about 550 mA·h. I do not want to waste it on heating the resistors, so, probably, I need to use large resistors. But how large? Too large R₁ will let only a little current to flow to the A0 pin and I've read somewhere that small currents may lead to `analogRead` measurement errors (underestimations?) due to ADC's internal capacitor.

Trying to find the right answer, I've [read on the Arduino's forum](https://forum.arduino.cc/index.php?topic=65134.msg475890#msg475890) that:

>The ATmega328P datasheet has this info way in the back: Table 28-16 (page 328). The analog input resistance is claimed to be 100 Mohms.
>
>During an actual sample, the input resistance is temporarily a lot lower as the sampling capacitor is charged up so **it is recommended that whatever you connect to the A/D have an output impedance of 10k or less for best accuracy**.

And here, I am stuck. I understand that **I am connecting a voltage divider to the A/D, but what is it's "output impedance"?** It should depend on R₁ and R₂ somehow, and solving that equation (`F(R₁, R₂) == 10 000`) will give me the exact value…

P.S. I saw some cunning schemes in the Internet with capacitors, diodes and op-amps (everybody say it's super easy and safe to use them for this task), but, please:

 - I am just trying to understand the basics and making my first steps with electronics.
 - The device I'm making should be lightweight and compact (although I should be able to compose it without any PCB magic). Two resistors seems to be fine.
 - I'm going to read the voltage only once when the device is turned on, so I don't actually need super-fast op-amp's speed.
 - I'll try not to plug negative voltage, so I do not need a protection. Yet.

title: Measuring 12 V via voltage divider: choosing the right resistors

Answers: 1

body:
What you are looking for is called the [Thévenin equivalent][] source.
For the schematic you are showing, and assuming you can neglect the
output resistance of the battery itself, the output resistance of the
voltage divider is the same as the two resistors in parallel. If you
want the maximum allowed resistance (minimum current) you have then to
solve:

1/R1 + 1/R2 = 1/(10 kΩ)
R2 / (R1 + R2) = 5/12

which gives:

R1 = 12/5 × 10 kΩ = 24 kΩ
R2 = 12/7 × 10 kΩ ≈ 17.1 kΩ

You can then round the values down to the closest standard values,
taking care that the rounding does not impose more than 5 V on the
analog pin. For example, if you restrict yourself to the E6 series, you
could choose

R1 = 22 kΩ
R2 = 15 kΩ

which would give you a Thévenin equivalent output resistance of
8.9 kΩ, and a maximum output voltage of 4.86 V.

[Thévenin equivalent]: https://en.wikipedia.org/wiki/Thévenin's_theorem


body:
I have an Arduino code for logging sensor data, time and date. Then I store all the data in the SD card and then I will send the sensor value to another node by using Lora. but I can't write the data in the SD card. Please help me to solve this problem. The code is also attached.

    #include <RHReliableDatagram.h>
    #include <RH_RF95.h>
    #include "RTClib.h"
    #include <SPI.h>
    #include <SD.h>

    RTC_DS1307 rtc;
    File myFile;

    #define node_address 12
    uint8_t gateway_address = 11;
    const int sensor_pin = A1;
    float level;

    /* Chip selection */
    const int CS1 = 8;/*SD Card*/
    const int CS2 = 10;/*LoRa*/

    /* Configure LoRa driver */
    RH_RF95 driver(10,2);
    RHReliableDatagram manager(driver,node_address);

    void setup () {
      pinMode(sensor_pin, INPUT);
      pinMode(CS1,OUTPUT);
      pinMode(CS2,OUTPUT);
    //  SPI.begin();`
      /*--------Serial port connection setup--------*/
      Serial.begin(9600);

      /*----------RTC Initialization----------*/
      Serial.println(F("Initializing RTC...!"));
      if (! rtc.begin()) {
        Serial.println(F("Couldn't find RTC"));
      }
      if (! rtc.isrunning()) {
        Serial.println(F("RTC is NOT running!"));
    //    rtc.adjust(DateTime(2019, 11, 12, 12, 32, 0)); // (Year,Month,Date,Hour,Min,Sec)
      }

      /*----------SD CARD Initialization----------*/
      digitalWrite(CS2,HIGH);
      delay(500);
      digitalWrite(CS1,LOW);
      Serial.println(F("Initializing SD card..."));
      if (!SD.begin(CS1)) {
        Serial.println(F("initialization of SD Card is failed!"));
        return;
      }
      Serial.println(F("Initialization of SD Card is done."));
      /*----------LoRa Initialization----------*/
      digitalWrite(CS1,HIGH);
      delay(500);
      digitalWrite(CS2,LOW);
      if (manager.init())
      {
        Serial.println(F("LoRa Successfully Initialised "));
      } else {
        Serial.println(F("LoRa initialization failed"));
      }
      driver.setFrequency(433.0);
      driver.setTxPower(14,false);
      Serial.println();
    }

    void loop () {
      DateTime now = rtc.now();
      /*----------Date----------*/
      Serial.print(now.year(), DEC);
      Serial.print('/');
      Serial.print(now.month(), DEC);
      Serial.print('/');
      Serial.print(now.day(), DEC);
      Serial.print(',');
      /*----------Time----------*/
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println();

      /*----------SD card----------*/
      digitalWrite(CS2,HIGH);
      delay(500);
      digitalWrite(CS1,LOW);
      delay(100);
      myFile = SD.open("test.txt", FILE_WRITE);
      if (myFile) {
        /*----------Saving Date----------*/
        myFile.print(now.year(), DEC);
        myFile.print('/');
        myFile.print(now.month(), DEC);
        myFile.print('/');
        myFile.print(now.day(), DEC);
        myFile.print(',');
        /*----------Saving Time----------*/
        myFile.print(now.hour(), DEC);
        myFile.print(':');
        myFile.print(now.minute(), DEC);
        myFile.print(':');
        myFile.print(now.second(), DEC);
        myFile.println(',');
        level = analogRead(sensor_pin);
        myFile.print(level);
        myFile.println();
        myFile.close();
      } else {
        Serial.println("Error opening test.txt");
      }
      delay(500);
      digitalWrite(CS1,HIGH);
      delay(500);
      digitalWrite(CS2,LOW);
      char data[RH_RF95_MAX_MESSAGE_LEN];
      sprintf(data,"$%d#%d",node_address,level);
      Serial.print("Level transferred is ");
      Serial.println(data);
      Serial.println(sizeof(data));
      if(!manager.sendtoWait((uint8_t*)data,sizeof(data),gateway_address))
      {
        Serial.println("Gateway offline");
      }
      delay(500);
    }

title: SD writing problem

Answers: 1

body:
You should not manually control the SD card's CS pin.  By doing so you are confusing both the library and the SD card.

There is a special operation with SD cards in "SPI" mode that isn't part of the SPI standard as part of the initialization routine whereby the master (the Arduino) must send at least 72 clock pulses to the card *with the CS pin held HIGH*.

By manually setting the CS pin LOW you are breaking that.

There is no call for you to ever do anything for the CS pin other than tell the library what it is - the library does everything else for you. So remove all references to `digitalWrite(CS1, ...)` from your code.


body:
Excuse my naivete in this as I am very new to Arduino and the programming of. I am trying to put together a project for stair lighting triggered by a ultrasonic sensor at the bottom of the stairs and turned off by an ultrasonic sensor at the top of the stairs and vise versa. I am using an WS2812 LED strip and have the lights travel up the stairs when going up and down when going down. I'm sure this is a project many of you have seen. I have searched the net and youtube and have found many examples of this project, none that I can find using the HC-SR04 sensor. I have managed to cobble together a code which works fine in both direction but it is intermittent in working. I'm sure it is something to do with timings as sometimes it will work fine first time but then others the sensor needs to be blocked for a couple of seconds.
I would also like to add an LDR to the project so it is only active at night. If any of you can point me in the right direction I would be really grateful. I have attached the code so you can see where I am at.
This is just a test code and the final project will have around 200 LEDS.
Thanks

~~~~~~~~

#include <FastLED.h>
#define trigPin_up 2
#define echoPin_up 3
#define trigPin_down 4
#define echoPin_down 5
#define LED_PIN     7
#define NUM_LEDS    13
CRGB leds[NUM_LEDS];

void setup() {

    //Set Serial
  Serial.begin(9600);

  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);

  pinMode(trigPin_up, OUTPUT);
  pinMode(echoPin_up, INPUT);
  pinMode(trigPin_down, OUTPUT);
  pinMode(echoPin_down, INPUT);

}
 void loop(){
 if (trigPin_up, HIGH && trigPin_down, LOW);
 {
   short duration, distance;
  digitalWrite(trigPin_up, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin_up, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin_up, LOW);
  duration = pulseIn(echoPin_up, HIGH);
  distance = (duration/2) / 29.1;

  if (distance <= 50) {
  leds[0] = CRGB(255, 225, 255);
  FastLED.show();
  delay(100);
  leds[1] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[2] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[3] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[4] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[5] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[6] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[7] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[8] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[9] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[10] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[11] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[12] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[13] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  }

{    short duration, distance;
  digitalWrite(trigPin_down, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin_down, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin_down, LOW);
  duration = pulseIn(echoPin_down, HIGH);
  distance = (duration/2) / 29.1;

  if (distance <= 50) {
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[6] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[7] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[8] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[9] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[10] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[11] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[12] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[13] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  }

else
if (trigPin_up, LOW && trigPin_down, HIGH);
  {

     short duration, distance;
  digitalWrite(trigPin_down, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin_down, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin_down, LOW);
  duration = pulseIn(echoPin_down, HIGH);
  distance = (duration/2) / 29.1;

  if (distance <= 50) {
  leds[13] = CRGB(255, 225, 255);
  FastLED.show();
  delay(100);
  leds[12] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[11] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[10] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[9] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[8] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[7] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[6] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[5] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[4] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[3] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[2] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[1] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[0] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  }
{
  short duration, distance;
  digitalWrite(trigPin_up, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin_up, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin_up, LOW);
  duration = pulseIn(echoPin_up, HIGH);
  distance = (duration/2) / 29.1;

    if (distance <= 50) {
  leds[13] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[12] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[11] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[10] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[9] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[8] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[7] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[6] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[5] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[4] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[3] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[2] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[1] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[0] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  }
}

  }
}
 }
 }
~~~~~~~~~

title: Help with Stair Lighting using HC-SR04 sensor and WS2812 LED Strip

Answers: 2

body:
There are a couple things with your code which you might need to look into.
Note: I'm doing this ontop of my head, so please correct me if I say something incorrect. ]

**First**, to check if values are equal, with an if-statement you'd have to use:

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

    //if (trigPin_up, HIGH && trigPin_down, LOW); not like this.
    if (trigPin_up== HIGH && trigPin_down== LOW) {.....} //But like this

Do not use the ';' because that would be then end of the statement.

**Second**, there seems to be a random '{' without any statement beforehand, at line 88.

**Extra tip**
[You can use for loops!][1]
So:

    leds[0] = CRGB(255, 225, 255);
      FastLED.show();
      delay(100);
      ....
      leds[13] = CRGB(255, 255, 255);
      FastLED.show();
      delay(100);
becomes:

    for (int i = 0; i <14; i++){
        leds[i] = CRGB(255, 225, 255);
      FastLED.show();
      delay(100);
      }

As a good exercise, could you try to clean up your code, edit it in the OP, and try if it works then?

  [1]: https://www.arduino.cc/reference/en/language/structure/control-structure/for/

body:
Calvin Bootsman is right with the errors, that he described, but there are more problems in your code.

1. Look at these two lines, that I got from your sketch. I already corrected, what Calvin had to say about the if statement.

        #define trigPin_up 2
        if (trigPin_up == HIGH && trigPin_down == LOW){

    You define `trigPin_up` as the number two. A define is read by the preprocessor. It will replace all occurances of `trigPin_up` with the number 2. `HIGH` and `LOW` are also defines (defined in the Arduino core) with the values 1 and 0. They also get replaced. After that the code goes to the actual compiler. So the compiler sees this if statement:

        if( 2 == 1 && 4 == 0)

    2 isn't equal 1 and 4 isn't equal 0, so the result is always false. That corrupts your complete logic. I'm sure you want to read the state of the pin. `trigPin_up` and siblings are only the pin numbers. For getting the real electrical state of the pin you need to actually read it via `digitalRead()`:

        if(digitalRead(trigPin_up) == HIGH && digitalRead(trigPin_down) == LOW){

    You can simplify this even more, when you know, that zero is treated as `false` and every other value as `true`:

        if(digitalRead(trigPin_up) && !digitalRead(trigPin_down)){

    The `!` before the second `digitalRead()` does a negation, so that the part after the `&&` will become true, if `digitalRead(trigPin_down)` evaluates to false.

2. Now look at these lines:

        #define NUM_LEDS    13
        CRGB leds[NUM_LEDS];
        leds[13] = CRGB(0, 0, 0);

    You create an array named `leds` with `NUM_LEDS` (13) elements. The first index is 0 (as we start to count from zero in most programming languages). But that means, that the last index in the array is 12, not 13. When doing `leds[13]=...` you actually write to a memory address outside of your array. It could be everything, what is saved there. And you overwrite it. This often is a hard to diagnose problem, since it can have very weird consequences. Calvin Bootsman also did this wrong in his answer. For the for loop you only should count to 12, meaning using `i < 13` or `i < NUM_LEDS` in the for loop.

3. Then I guess you don't really understand how the logic of interfacing the HC-SR04 works. The trigger pins, that you define, are outputs. Their state will only change, if you yourself change it via `digitalWrite()`. But that cannot happen, as you enclosed the statements doing it into the if statement. It does not make sense to read these pins either. Instead you should write if statements with the calculated distance. You could go with the following flow in you `loop()` function: Trigger first HC-SR04, read the echo back, trigger second HC-SR04, read the echo back, if statement to compare the calculated distances to a trigger value, in there if statements to decide, which one was triggered, execute the corresponding code in it.

---

Honestly I'm suprised, that your code even compiled. You should look into some basic C/C++ tutorials, so that you get the programming syntax right. Also you should carefully think about the logic of your program. Often it is better to first write down short notes, what the logic of the program should be, without really writing the code. That helps with focussing on the logic instead of the syntax. That can be done afterwards.


body:
I'm using arduino uno and nrf24l01. to monitor sensor data.
But this is the message that master receives:

> ⸮

this is my slave code.

    void monitoring() {
        delay(10);
        radio.stopListening();
        int soilMoisture = analogRead(A5);
        int light = analogRead(A4);
        float temp = analogRead(A3);
        temp = temp * 0.48828125;
        int ltemp = int(temp);
        String message = String(soilMoisture) + "," + String(light) + "," +    String(ltemp);
        Serial.println(message);
        delay(200);
        radio.write(&message, sizeof(message));
        delay(50);
        radio.startListening();
        delay(10);
    }
and here is my master code.

    while (1) {
        if (radio.available()) {
          char message[32] = "";
          radio.read(&message, sizeof(message));
          delay(500);
          Serial.println(message);
    }

title: I can't receive string that I have sent through nrf correctly

Answers: 1

body:
Remove the & in the master code line, change

     radio.read(message, sizeof(message));

to

    radio.read(message, sizeof(message));

`message` is an array, so either you should pass the address of the first character (`&message[0]`), or simply pass `message`.

Another problem is sending a String in the slave code (using type `String `). It's better not to use this type anyway, but you probably have to convert it to a character array of the same type as in the master code.

You can use the function `StringToCharArray` for that, see [StringToCharArray][1].

  [1]: https://www.arduino.cc/en/Reference.StringToCharArray


body:
evrything worked for a bit and changed to much to get it working again. dont really understand the error.

[![C:\Users\bavob\AppData\Local\Temp\ccyfrkaL.ltrans0.ltrans.o: In function `loop':

C:\Users\bavob\Documents\Arduino\counte_up/counte_up.ino:96: undefined reference to `num_Write(int)'

collect2.exe: error: ld returned 1 exit status

exit status 1
Fout bij het compileren voor board Arduino/Genuino Uno][1]][1]

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

```int num_array[10][7] = {
  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }  // 9
};

int pin = 2;
int buttonState = 0;
const int button = 12;
int led = 13;
int randVal;
bool pressVal;
void num_Write(int);
void setup() {
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  pinMode(button, INPUT);
}

void loop() {
  buttonState = digitalRead(button);
  if (buttonState == LOW) {
    turnOff();
    pressVal = false;
  }
  else
  {
    if (pressVal == false)
    {
      randVal = rand() % 10;
      pressVal = true;
    }
    Serial.println(randVal);
    if (randVal == 0)
    {
      void zero(int number);
      num_Write(0);
    }
    else if (randVal == 1)
    {
      void one(int number);
      num_Write(1);
    }
    else if (randVal == 2)
    {
      void two(int number);
      num_Write(2);
    }
    else if (randVal == 3)
    {
      void three(int number);
      num_Write(3);
    }
    else if (randVal == 4)
    {
      void four(int number);
      num_Write(4);
    }
    else if (randVal == 5)
    {
      void five(int number);
      num_Write(5);
    }
    else if (randVal == 6)
    {
      void six(int number);
      num_Write(6);
    }
    else if (randVal == 7)
    {
      void seven(int number);
      num_Write(7);
    }
    else if (randVal == 8)
    {
      void eight(int number);
      num_Write(8);
    }
    else
    {
      void nine(int number);
      num_Write(9);
    }
  }
}

void zero(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}

void one(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}

void two(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void three(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void four(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void five(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void six(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void seven(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void eight(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void nine(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void turnOff()
{

}
```

title: cant figure out how to fix this compile error

Answers: 1

body:
You call function `num_Write` a lot, you create a forward declaration:

   void num_Write(int);

But you forgot to create the implementation.

If you would have forgot the forward declaration the function would not be known at all (and you would get a compiler error). But with the forward declaration you let the compiler know the signature of `num_write` (so the return value and argument types).

When the linker wants to link all object (.o) files together it cannot find an implementation of the function `num_write` and you get this error. Hence `ld` is the linker.


body:
I want to transmit and receive data with the help of NRF24l01 modules. I tried to deliver joystick values from UNO to UNO but I have trouble about it.

In receiver side I have only zeros. I have been connect pins according to pin out orders.
```
ce--9
csn----10
sck----13
mosi----11
miso-----12
```
on both side. I am using module adapter to provide constant current and feeding with 3.3 volt and 5 volt another one. Both did not work. I bought new modules and adapters and connected 3.3 volt but nothing changed. I could not understand the problem help me please. Here is are my sketches:

**RECEIVER**
<!-- language-all: lang-cpp -->

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    #define CE_PIN   9
    #define CSN_PIN 10
    const uint64_t pipe = 0xE8E8F0F0E1LL;
    RF24 radio(CE_PIN, CSN_PIN);
    int data[3];
    void setup()
    {
      Serial.begin(9600);
      SPI.begin();
      radio.begin();
      radio.openReadingPipe(1, pipe);
      radio.startListening();
      radio.setPALevel(RF24_PA_MAX);
    }

    void loop() {
      if ( radio.available() ) //Eğer sinyal algılarsan...
      {

        radio.read( &data, sizeof(data) );

        Serial.print("data[0]=");
        Serial.println(data[0]);
        Serial.print("data[1]=");
        Serial.println(data[1]);
        delay(300);
        radio.stopListening();

      }
      else {
        Serial.println("no signal");
      }
    }

**TRANSMITTER**

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    #define PIN_ANALOG_X 0
    #define PIN_ANALOG_Y 1
    #define CE_PIN   9
    #define CSN_PIN 10
    const uint64_t pipe = 0xE8E8F0F0E1LL;
    RF24 radio(CE_PIN, CSN_PIN);
    int data[2];

    void setup() {

      // Start serial because we will observe values at serial monitor
    SPI.begin();
      Serial.begin(9600);
      radio.begin();
      radio.openWritingPipe(pipe);
      radio.setPALevel(RF24_PA_MAX);
    }

    void loop() {

      // Print x axis values

      Serial.print("x: ");

      Serial.println(analogRead(PIN_ANALOG_X));

      // Print y axis values

      Serial.print("y: ");

      Serial.println(analogRead(PIN_ANALOG_Y));
      data [0] =map( analogRead(PIN_ANALOG_X),0,676,0,255);
      data [1] = map(analogRead(PIN_ANALOG_Y),0,676,0,255);

     radio.write( &data, sizeof(data) );
      Serial.println("data0");
      Serial.println(analogRead(PIN_ANALOG_X));
      Serial.println("data1");
      Serial.println(analogRead(PIN_ANALOG_Y));

    Serial.println(data [0]);
    Serial.println(data [1]);
      // Some delay to clearly observe your values on serial monitor.

      delay(300);

    }

title: NRF24l01 receiving only zeros

Answers: 0


body:
I am currently working on an autonomous firetruck project. Its already doing obstacle avoidance however, I still don't know the proper code for fire detection. It already detects fire but what I want to happen is the motor will stop for a second when it detects fire then it will go forward directly to the fire and put it off using a water pump. I already made a code but it is not working. Secondly, where I will insert the GND and VCC of the water pump? I don't know its connection.

Materials:
Arduino UNO
Ultrasonic Sensor
Flame Sensor
Servo Motor
Button
Mini Breadboard
L298n
2wd Robot Kit

Here is the code:

```
#include <Servo.h>
#include "Ultrasonic.h"

const int button = 2;
const int led    = 3;
const int pump = 4;
const int motorA1= 6;
const int motorA2= 9;
const int motorB1=10;
const int motorB2=11;
const int flame=12;
const int buzzer=13;

Ultrasonic ultrasonic(A4 ,A5);
Servo myservo;

int distance;
int checkRight;
int checkLeft;
int function=0;
int buttonState=0;
int pos=90;
int flag=0;
int flame_detected=0;

void setup(){
 Serial.begin(9600);
 myservo.attach(5);
 myservo.write(pos);
 pinMode(button, INPUT_PULLUP);
 pinMode(led,  OUTPUT);
 pinMode(buzzer, OUTPUT);
 pinMode(motorA1,OUTPUT);
 pinMode(motorA2,OUTPUT);
 pinMode(motorB1,OUTPUT);
 pinMode(motorB2,OUTPUT);
 pinMode(flame,INPUT);
 pinMode(pump,OUTPUT);
}

void loop(){
 flame_detected = digitalRead(flame);
  if (flame_detected == 1)
  {
    Serial.println("No flame detected. stay cool");

    //Check button state
    buttonState = digitalRead(button);
    unsigned long currentMillis = millis();

    if (buttonState == LOW) {
      delay(500);
      if ( flag == 0){
       function = 1;
       flag=1;
      }
      else if ( flag == 1){
       function = 0;
       flag=0;
     }
   }

   if (function == 0){
    myservo.write(90);
    stop();
    digitalWrite(led, HIGH);
    }
   else if (function == 1){
    //Read distance...
    distance = ultrasonic.Ranging(CM);

   if (distance > 20){
    forward();

    digitalWrite(led,LOW);
   }
    else if (distance <=20){
    stop();

    digitalWrite(led,HIGH);

    for(pos = 0; pos < 180; pos += 1){
     myservo.write(pos);
     delay(10);
     //myservo.write(90);
    }

    checkLeft = ultrasonic.Ranging(CM);
    //myservo.write(90);

    for(pos = 180; pos>=0; pos-=1){
    myservo.write(pos);
    delay(10);
    //myservo.write(90);
    }

    checkRight= ultrasonic.Ranging(CM);

          myservo.write(90);

           if (checkLeft < checkRight){
             left();
             delay(400);
             }
           else if (checkLeft > checkRight){
             right();
             delay(400);
           }
           else if (checkLeft <=10 && checkRight <=10){
             backward();
             left();
           }
   }
 }

}

else if (flame_detected == 0) {
  Serial.println("Flame detected...! take action immediately.");
  buzzerwarning ();

  stop();

  if(distance > 25){
  forward();
  }
  else if (distance <= 25){
  stop();
  digitalWrite (pump, HIGH);
  }

  digitalWrite (pump,LOW);
  flame_detected == 1;
  }
}
void backward(){
 digitalWrite(motorA1, HIGH);
 digitalWrite(motorA2, LOW);
 digitalWrite(motorB1, HIGH);
 digitalWrite(motorB2, LOW);
}

void forward(){
 digitalWrite(motorA1, LOW);
 digitalWrite(motorA2, HIGH);
 digitalWrite(motorB1, LOW);
 digitalWrite(motorB2, HIGH);
}

void left(){
 digitalWrite(motorA1, HIGH);
 digitalWrite(motorA2, LOW);
 digitalWrite(motorB1, LOW);
 digitalWrite(motorB2, HIGH);
}

void right(){
 digitalWrite(motorA1, LOW);
 digitalWrite(motorA2, HIGH);
 digitalWrite(motorB1, HIGH);
 digitalWrite(motorB2, LOW);
}

void stop(){
 digitalWrite(motorA1, LOW);
 digitalWrite(motorA2, LOW);
 digitalWrite(motorB1, LOW);
 digitalWrite(motorB2, LOW);
}

void buzzerwarning () {
int i=0;

  do {
    i++;
    tone(buzzer, 7500);
    delay (700);
    tone(buzzer, 5500);
    delay (700);
    noTone (buzzer);
    delay (0);

  }
  while(i<2);

delay(0);
}
```

Thanks.

title: Arduino UNO: Autonomous Firetruck Coding (Fire Detection) and Connection (Water Pump) Problem

Answers: 0


body:
I am trying to interface SIM900 GSM Module with Arduino Mega. When I send AT command on COM port in carriage mode then its not sending 'ok' back so I think the interface is not successful. Here is the resource which I referred to - [Link][1].

Have a look below:-

Code:-

    #include <SoftwareSerial.h>     //please put less than and greater than sign respectively in place of  =

    SoftwareSerial SIM900(10, 11); // (RX, TX). please zoom image above to see exactly what is going where.

    void setup()
    {
      SIM900.begin(19200);               // the SIM900 baud rate
      Serial.begin(19200);

    }

    void loop()
    {

      if (SIM900.available())              // if date is comming from softwareserial port ==> data is comming from gprs shield
      Serial.write(SIM900.read());
      if (Serial.available())                // if data is available on hardwareserial port ==> data is comming from PC or notebook
      SIM900.write(Serial.read());

    }

Electric Connection:-

[![circuit][4]][4]

How to interface it correctly?

Update:- I added a 5v 2A power supply and changed Arduino Rx/Tx pin to 10/11. Added micro sim at the back but still the same result

  [1]: http://hotresistor.blogspot.com/2015/02/interfacing-simcom-sim900-with-arduino.html
  [2]: https://i.stack.imgur.com/dhFVl.jpg
  [3]: https://i.stack.imgur.com/qt4IK.jpg\
  [4]: https://i.stack.imgur.com/rr0gR.jpg

title: can't interface SIM900 GSM Module with Arduino Mega

Answers: 0


body:
It gives the right value on the monitor but it doesnt display the value on my display.
```
int pinNumb[7] = {2, 3, 4, 5, 6, 7, 8};
int num_array[11][7] = {
  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }, // 9
  { 0, 0, 0, 0, 0, 0, 0 }  //nothing
};

int pin = 2;
int button = 12;
int buttonVal;
int randVal;
bool pressVal;
void setup() {
  Serial.begin(9600);

  for (int i = 0; i < 7 ; i++)
  {
    pinMode(pinNumb[i], OUTPUT);
  }
  pressVal = false;
  pinMode(button, INPUT);
}

void loop() {
  buttonVal = digitalRead(button);
  if (buttonVal == 0)
  {
    //zero();
    turnOff();
    pressVal = false;
  }
  else
  {
    //zero();
    if (pressVal == false)
    {
      randVal = rand() % 10;
      pressVal = true;
      delay(100);
    }
    Serial.println(randVal);
    if (randVal == 0)
    {
      zero();

    }
    else if (randVal == 1)
    {
      one();

    }
    else if (randVal == 2)
    {
      two();

    }
    else if (randVal == 3)
    {
      three();

    }
    else if (randVal == 4)
    {
      four();

    }
    else if (randVal == 5)
    {
      five();

    }
    else if (randVal == 6)
    {
      six();

    }
    else if (randVal == 7)
    {
      seven();

    }
    else if (randVal == 8)
    {
      eight();

    }
    else
    {
      nine();

    }
  }
}

void zero()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[0][j]);
    pin++;
  }
}

void one()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[1][j]);
    pin++;
  }
}

void two()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[2][j]);
    pin++;
  }
}
void three()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[3][j]);
    pin++;
  }
}
void four()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[4][j]);
    pin++;
  }
}
void five()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[5][j]);
    pin++;
  }
}
void six()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[6][j]);
    pin++;
  }
}
void seven()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[7][j]);
    pin++;
  }
}
void eight()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[8][j]);
    pin++;
  }
}
void nine()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[9][j]);
    pin++;
  }
}
void turnOff()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }

}
````

title: It gives some glitching on 7 segment display

Answers: 2

body:
These can all be byte instead of int to save on memory:

    int pinNumb[7] = {2, 3, 4, 5, 6, 7, 8};
    int num_array[11][7] = {
      { 1, 1, 1, 1, 1, 0, 1 }, // 0
      { 0, 1, 1, 0, 0, 0, 0 }, // 1
      { 1, 1, 0, 1, 1, 1, 0 }, // 2
      { 1, 1, 1, 1, 0, 1, 0 }, // 3
      { 0, 1, 1, 0, 0, 1, 1 }, // 4
      { 1, 0, 1, 1, 0, 1, 1 }, // 5
      { 1, 0, 1, 1, 1, 1, 1 }, // 6
      { 1, 1, 1, 0, 0, 0, 0 }, // 7
      { 1, 1, 1, 1, 1, 1, 1 }, // 8
      { 1, 1, 1, 0, 0, 1, 1 }, // 9
      { 0, 0, 0, 0, 0, 0, 0 }  //nothing
    };

    int pin = 2;
    int button = 12;
    int buttonVal;
    int randVal;

In addition, the array can be reduced to 11 bytes:

    0bFD, // 0
    0bC0, // 1
    0bDE, // 2
    etc.

Then your functions can do direct port manipulation to send bits 0-5 to the Port for D2 to D7, and bit to D8.

As written, these functions probably need some hold time so they don't just flash the LED and disappear:

    void one()
    {
      for(int i = 0; i < 7 ; i++)
      {
        digitalWrite(pinNumb[i],LOW);
      }
      for (int j = 0; j < 7; j++) {
        digitalWrite(pin, num_array[1][j]);
        pin++;
      }
    }

body:
You are continually incrementing the pin variable via pin++, but you are never resetting it to the start (2?) when a new number is to be written.  So it might work the first time but never after that.

Also, you clear the display with digitalWrite(pinNumb[i],LOW);
But you turn segments on with digitalWRite(pin,....); pin++.
Shouldn't you turn the segments on with digitalWrite(pinNumb[i] . . ?


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

    #define trigPin 13
    #define echoPin 14
    #define e1 10  // Enable Pin for motor 1
    #define t1 8   // Control pin 1 for motor 1
    #define t2 9   // Control pin 2 for motor 1
    #define led 3
    #define led2 5
    #define buzzer 4

    float duration,distance;
    #include<SoftwareSerial.h>

    void setup() {
     Serial.begin(9600);
     pinMode(trigPin,OUTPUT);
     pinMode(echoPin,INPUT);
     pinMode(e1, OUTPUT);
     pinMode(t1, OUTPUT);
     pinMode(t2, OUTPUT);

    }

    void loop() {
      digitalWrite(e1, HIGH);
      digitalWrite(t1, HIGH);
      digitalWrite(t2, LOW);

      digitalWrite(trigPin,LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin,HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin,LOW);

    duration=pulseIn(echoPin,HIGH);
    distance=(duration/2)*0.0343;
    Serial.print("Distance= ");
    if(distance>=400||distance<=2)
    {
      Serial.println("out of range");
    }
    else if(distance<=100&&distance<=50)

    {
      digitalWrite(led,HIGH);
      delay(1000);
      analogWrite(e1,157);
      digitalWrite(t1,HIGH);
      digitalWrite(t2,LOW);
      delay(500);
    }
    else if(distance<=50&&distance>=25)
    {
      digitalWrite(buzzer,HIGH);
      delay(100);
      analogWrite(e1,56);
      digitalWrite(t1,HIGH);
      digitalWrite(t2,LOW);
    }
    else if(distance<=25&&distance>=10)
    {
      digitalWrite(led2,HIGH);
      delay(100);
      analogWrite(e1,0);

    }
    else if(distance<=390&&distance>=100)
    {  digitalWrite(e1, HIGH);
      digitalWrite(t1, HIGH);
      digitalWrite(t2, LOW);

    }

    delay(500);
    }

title: Will this code for braking of dc motor using sensor work?

Answers: 0


body:
I am trying to write a code where photoresistors (a or b) sense blinking of the light, and lights LED (k and d) simultaneosly with that blinking. And I want that when both photoresistors sense dark for more than 3 secs, the LEDs would light up and stay until one of them again gets lighting. But I cannot understand in which part should I put millis time count?
<!-- language-all: lang-cpp -->

    int k = 2;
    int d = 3;
    int fk = A0;
    int fd = A1;
    int a = 0;
    int b = 0;

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

    void loop()
    {
      a = analogRead (fk);
      b = analogRead (fd);
      while (a < 1000 && b < 1000)
      {
        digitalWrite(2, HIGH);
        digitalWrite(3, HIGH);
        a = analogRead (fk);
        b = analogRead (fd);
      }
      if (a > 1000)
        digitalWrite(2, HIGH);
      else
        digitalWrite(2, LOW);
      if (b > 1000)
        digitalWrite(3, HIGH);
      else
        digitalWrite(3, LOW);
    }

title: Time counting using millis

Answers: 3

body:
Millis gives you a measure of time.  You can store that measure and compare to it later.  I don't know what in your code represents a sense of dark/light in your code (resistors can be used to raise or lower the measured input depending on your circuit) so you will have to work the following in by replacing stuff in <>

    unsigned long lastlight;
    void loop()
    {
        if (<isLitSensorA>) lastlight = millis();
        if (<isLitSensorB>) lastlight = millis();
        if(millis() - lastlight > 3000){ //3 sec since lastlight
            <LightsAlwaysOn>
        }
        else{
            <BlinkWithLights>
        }
    }

body:
This is one of those cases where the solution is simply to implement a
[finite state machine][FSM]. Consider a state machine with these three
states:

* `LIGH`: light has been detected by at least one of the sensors, the
  LEDs follow the light sensors
* `SHORT_DARK`: neither sensor sees light, both LEDs are off
* `LONG_DARK`: it has been at least three seconds since neither sensor
  saw light, both LEDs are on.

The transitions between those states can be depicted by the following
state diagram:

[![state transitions][1]][1]

where “darkness detected” means that no sensor sees light, and “light
detected” means that at least one sensor sees light.

As a general rule, it is a good practice to always draw a state diagram
before you start writing code. Once you are sure your diagram describes
the desired behavior, it is almost trivial to translate it into code.
Here is how I would code it:

```c++
void loop()
{
    bool light_k = analogRead(IN_K) >= 1000;
    bool light_d = analogRead(IN_D) >= 1000;

    static enum { LIGHT, SHORT_DARK, LONG_DARK } state;
    static uint32_t darkness_start;
    switch (state) {
    case LIGHT:
        digitalWrite(OUT_K, light_k ? HIGH : LOW);
        digitalWrite(OUT_D, light_d ? HIGH : LOW);
        if (!light_k && !light_d) {
            darkness_start = millis();
            state = SHORT_DARK;
        }
        break;
    case SHORT_DARK:
        if (light_k || light_d) {
            state = LIGHT;
        } else if (millis() - darkness_start >= 3000) {
            digitalWrite(OUT_K, HIGH);
            digitalWrite(OUT_D, HIGH);
            state = LONG_DARK;
        }
        break;
    case LONG_DARK:
        if (light_k || light_d) {
            state = LIGHT;
        }
        break;
    }
}
```

[FSM]: https://majenko.co.uk/blog/finite-state-machine
[1]: https://i.stack.imgur.com/HMnez.png

body:
Here is a more elegant way to do this. This program doesn't require you to actually count it has been dark, instead it just remembers the time it has last seen the light (how poetic ;). I also added some commentary alongside the code.
```c++
// All the variables
int k = 2;        // LED 1
int d = 3;        // LED 2
int fk = A0;      // photoresistor 1
int fd = A1;      // photoresistor 2
int lastLight = 0;

// Set up the LEDs
void setup() {
  pinMode(k, OUTPUT);
  pinMode(d, OUTPUT);
}

void loop()
{
  // Check the photoresitors
  int a = analogRead (fk);
  int b = analogRead (fd);
  if (a > 1000 || b > 1000)
  {
    // Turn LEDs on if one photoresitor senses light
    digitalWrite(k, HIGH);
    digitalWrite(d, HIGH);
    // Also set the last time it was bright to the current time
    lastLight = millis();
  }
  else if (abs(millis() - lastLight) > 3000)
  {
    // Turn LEDs on if it has been dark for more than 3 seconds (that is 3000 milliseconds)
    digitalWrite(k, HIGH);
    digitalWrite(d, HIGH);
  }
  else
  {
    // Turn LEDs off
    digitalWrite(k, LOW);
    digitalWrite(d, LOW);
  }
}
```


body:
I'm simply trying to use timer 2 for tone generation and what I get is a very faint and strange tone (almost like its modulated somehow as there is a "pulsing" to it). Here's my simple code:

    #include <Arduino.h>

    #define SPEAKER_PORT PORTC
    #define SPEAKER_BIT 2

    void setup()
    {
      pinMode(A2, OUTPUT);

      TCCR2A = _BV(WGM21);  // CTC mode
      TCCR2B = _BV(CS20);   // clk/1

      OCR2A = 200;  // 8-bit timer, so keep less than 256
      bitSet(TIMSK2, OCIE2A);  // enable OCR2A interrupt
    }

    void loop()
    {
      // NOP
    }

    ISR(TIMER2_COMPA_vect)
    {
      SPEAKER_PORT ^= _BV(SPEAKER_BIT);
    }

Any obvious mistakes? Thanks for your help!

title: ATmega328P - Problem using timer 2 for tone generation

Answers: 3

body:
I tried the code on an Uno and as you say, it does sound odd.

By my calculations, the frequency is 40kHz (16MHz/(200 x 2)), which is above the threshold of hearing. The sound we are actually hearing is probably the 3rd or 5th harmonic, at a reduced intensity and perhaps subject to jitter.

I tried changing

`TCCR2B = _BV(CS20);   // clk/1`

to

`TCCR2B = _BV(CS21);   // clk/8`

which should mean that the frequency is now 5kHz (16MHz/8/(200 x 2)).

It sounds cleaner.

body:
Looks like my tone frequency was possibly just too high for the buzzer I was using, causing strange output.

Adjusting the clock divider fixed the issue. That is, I changed the following:

    TCCR2B = _BV(CS20);   // clk/1

to

    TCCR2B = _BV(CS22) | _BV(CS20);  // clk/128

and now I get reasonable-sounding tones.

Note that the clock divider you choose is ultimately driven by what frequency range you want to support, and the bit width of the timer. The formula is something like:

    freq = 16000000 / d / n / 2

where `d` is the clock divider value (like 128), and `n` is the counter value at which to interrupt (what goes in `OCR2A` for instance). `n` must fit into the bit width of the specific timer (on ATmega328P timer 1 is 16-bits wide, and timer 2 is 8-bits wide).

Hope this is helpful for anyone else running into these issues. Thanks so much to [Kartman over at AVRFreaks.net for pointing me in the right direction](https://www.avrfreaks.net/comment/2795731#comment-2795731).

body:
If you drive the speaker pin from an interrupt, you will inevitably have
some jitter, as the interrupt request will sometimes fire while the CPU
is processing another ISR. This can lead to one of the levels being held
for longer than expected, which in turn leads to spurious frequencies in
the output. Note that these are not really _harmonics_ (harmonics always
have frequencies higher than the fundamental), but rather _beating_
between different interrupt sources. That's why you are able to hear
something even though the fundamental is well above the hearing range.

If you want to have a clean PWM signal, you should instead generate it
in hardware. Timer 2 for example can drive pins 11 (OC2A) and 3 (OC2B).
See the bits COM2{A1,A0,B1,B0} in TCCR2A.


body:
I wonder if a laptop USB port is enough or I have to use an external power supply if the NodeMCU under heavy load. Here is my list of sensors and port used.

````
3.3V
3.3V
D1 to D7
A0
GND

````

Sensors: Turbidity sensor, Flow sensor, Temperature sensor, 4 led

title: Can I use laptop USB port to power Nodemcu if every port used

Answers: 2

body: Sensors don't usually require that much current and a usb port should be able to handle 4 leds and the MCU without a problem.  If you are using an Apple laptop it will disable the usb port temporarily if you draw too much current from it.  Some PC laptops probably do the same.

body:
standard current you can draw from a usb port is 500 mili ampere with 5 volt(you may get even more but it is not recommended) . so if you want to calculate

sensors are very low current about 1~2 mA(but you must check out datasheet)

[turbidity][1] for example draws 30 mA

temperature ds1820 is 1 mA

flow is up 2 mA

the LEDs based on resistors series with them you normally up to 3 mA for
each(1k series to 3.3 volt)

if you sum up all of them

30+1+2+4*3=45mA

but you should consider other consumers for example if you need 3.3 V you need a regulator such as ams1117 and it may waste some mili Ampere (not too much) and you certainly have a microprocessor and you should check data sheet but consider 100mA for that in worst case.

to count all of them the answer is YES

  [1]: http://www.farnell.com/datasheets/1770074.pdf


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

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

Hello guys. I'm working on a little lightshow that has 3 extra feature's when i press the button. depending on the variable counter the lights should do something and it should message you that you found a feature. But my project does'nt work. it compiles fine on the tinkercad site but not everything works. The lights itself work but the button feature's dont. I don't know if my code is wrong or the wiring since its able to compile.

I expected that if i press the countbutton it counts up and when it reaches 6 it does the code in the if statement. However when i press the count up and or count down button according to the variable it needs to reach it doesn't do anything.

the code:

    int time = 250;
    int ledpins[] = {3, 6, 7, 4, 2, 5};
    int amount = 6;
    int countup = 11;
    int countdown = 12;
    int counter;
    int timepressed = 4000;
    float timerpressed = 0;

    void setup()
    {
      for (int pin = 0; pin < aantal; pin++)
        {pinMode(ledpins[pin], OUTPUT);}
       //alle leds worden door middel van de loop gedefinieerd als output
       //pin is eerst 0 dat is element 3 in de array. de counter heeft einde
       //nog niet en gaat verder tot de conditie bereikt is
       pinMode(countdown, INPUT_PULLUP);
      pinMode(countup, INPUT);
       Serial.begin(9600);
    }

    void loop()
    {
      bool plus = digitalRead(countup);
      bool minus = digitalRead(countdown);
      delay(20);

      if (plus == LOW){
        counter++;
       if (counter > 10) counter = 0;
      }

      if (minus == LOW){
        counter--;
      }

    //Easter egg nummer 1. 2 lights on.
    if (counter == -2){
        digitalWrite(ledpins[1], HIGH);
        digitalWrite(ledpins[4], HIGH);
        Serial.print("Gefeliciteerd je hebt (1/3) easter egg gevonden!");
    }
    //Easter egg nummer 2. all lights off.
    else if (counter == 6){
      digitalWrite(ledpins[0], LOW);
      digitalWrite(ledpins[1], LOW);
      digitalWrite(ledpins[2], LOW);
      digitalWrite(ledpins[3], LOW);
      digitalWrite(ledpins[4], LOW);
      digitalWrite(ledpins[5], LOW);
      Serial.print("Gefeliciteerd je hebt (2/3) easter egg gevonden!");
    }
    //Easter egg nummer 3. blink alternately after keeping the button pressed for 4 seconds.
    else if (timerpressed >= timepressed){
      digitalWrite(ledpins[0], HIGH);
      digitalWrite(ledpins[1], HIGH);
      digitalWrite(ledpins[4], HIGH);
      digitalWrite(ledpins[5], HIGH);
      Serial.print("Gefeliciteerd je hebt (3/3) easter egg gevonden!");
     }

---

Okay an update on this post is a was able to make a couple of fixes. My code was keep getting stuck in the array loop for the leds. I've made it that it now only goes trough it once. Another thing i fixed was the wiring of the buttons since this wasnt correct. The only feature that isnt working right now is the keep the button pressed feature.
[![enter image description here][1]][1]

    int tijd = 250;
    int ledpins[] = {3, 6, 7, 4, 2, 5};
    int aantal = 6;
    int knopplus = 11;
    int knopmin = 12;
    int teller;
    int indruktijd = 4000;
    float timerdruktijd = 0;
    int pin = 0;
    int pin1 = 0;

    void setup()
    {
      for (int pin = 0; pin < aantal; pin++)
        {pinMode(ledpins[pin], OUTPUT);}
       //alle leds worden door middel van de loop gedefinieerd als output
       //pin is eerst 0 dat is element 3 in de array. de counter heeft einde
       //nog niet en gaat verder tot de conditie bereikt is
       pinMode(knopmin, INPUT_PULLUP);
      pinMode(knopplus, INPUT);
       Serial.begin(9600);
    }

    void loop()
    {
      bool plus = digitalRead(knopplus);
      bool minus = digitalRead(knopmin);
      delay(20);

      if (plus == LOW){
        teller++;
       if (teller > 10) teller = 0;
      }

      if (minus == LOW){
        teller--;
      }

    //Easter egg nummer 1. twee lichten aan.
    if (teller == -2){
        digitalWrite(ledpins[1], HIGH);
        digitalWrite(ledpins[4], HIGH);
        Serial.print("Gefeliciteerd je hebt (1/3) easter egg gevonden!");
    }
    //Easter egg nummer 2. alle lichten uit.
    else if (teller == 6){
      digitalWrite(ledpins[0], LOW);
      digitalWrite(ledpins[1], LOW);
      digitalWrite(ledpins[2], LOW);
      digitalWrite(ledpins[3], LOW);
      digitalWrite(ledpins[4], LOW);
      digitalWrite(ledpins[5], LOW);
      Serial.print("Gefeliciteerd je hebt (2/3) easter egg gevonden!");
    }
    //Easter egg nummer 3. knipper om en om na 4 seconden lang de -knop ingedrukt te houden
    else if (timerdruktijd >= indruktijd){
      digitalWrite(ledpins[0], HIGH);
      digitalWrite(ledpins[1], HIGH);
      digitalWrite(ledpins[4], HIGH);
      digitalWrite(ledpins[5], HIGH);
      Serial.print("Gefeliciteerd je hebt (3/3) easter egg gevonden!");
     }

      for (pin; pin < 6; pin++)
      {digitalWrite(ledpins[pin], HIGH);
       delay(tijd);
       digitalWrite(ledpins[pin], LOW);}
      //loop voor volgorde heen.

      for (pin1; pin1 < 6; pin1++)
      {digitalWrite(ledpins[pin], HIGH);
       delay(tijd);
       digitalWrite(ledpins[pin], LOW);}
      //loop zelfde volgorde terug
    }

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

title: lightshow project

Answers: 0


body:
I created a program to show a random number on a 7 segment display. It shows a random number in the serial monitor but always shows the same segments 'a c d and g'. anyone know hopw to fix this without changing the base of the coding its for and exercise so i need to have most of the code like I wrote it.

```
int num_array[11][7] = {
  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }, // 9
  { 0, 0, 0, 0, 0, 0, 0 }
};  //OFF

int buttonState = 0;
const int button = 12;
int randVal;
bool pressVal;
void num_Write(int);
void setup() {
  Serial.begin(9600);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(button, INPUT);
}

void loop() {
  buttonState = digitalRead(button);
  if (buttonState == LOW) {
    turnOff();
    pressVal = false;

  }
  else
  {
    if (pressVal == false)
    {
      int pin = 2;
      for (int i = 0; i < 7 ; i++)
      {
        digitalWrite(pin++, num_array[11][i]);
      }
      randVal = rand() % 10;
      pressVal = true;
    }
    Serial.println(randVal);
    if (randVal == 0)
    {
      void zero();

    }
    else if (randVal == 1)
    {
      void one();

    }
    else if (randVal == 2)
    {
      void two();

    }
    else if (randVal == 3)
    {
      void three();

    }
    else if (randVal == 4)
    {
      void four();

    }
    else if (randVal == 5)
    {
      void five();

    }
    else if (randVal == 6)
    {
      void six();

    }
    else if (randVal == 7)
    {
      void seven();

    }
    else if (randVal == 8)
    {
      void eight();

    }
    else
    {
      void nine();

    }
  }
}

void zero()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[0][j]);

  }
  delay(250);
}

void one()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[1][j]);

  }
  delay(250);
}

void two()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[2][j]);

  }
  delay(250);
}
void three()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[3][j]);
  }
  delay(250);
}
void four()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[4][j]);

  }
  delay(250);
}
void five()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[5][j]);

  }
  delay(250);
}
void six()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[6][j]);

  }
  delay(250);
}
void seven()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[7][j]);

  }
  delay(250);
}
void eight()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[8][j]);

  }
  delay(250);
}
void nine()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[9][j]);

  }
  delay(250);
}
void turnOff()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[10][j]);
  }
  delay(250);
}
```

title: number generator show wrong segments on 7 segment display

Answers: 1

body:
Note, this is not an answer to your question, but I like to show some programming improvements, making your sketch  much shorter and easier to maintain.

Instead of having all functions `one`, `two`, etcetera, use a parameter to pass the number. So you get this: (I couldn't test it as I don't have an Arduino IDE at hand). Also you can use a `for` loop in the `loop` function to set the output pins.

    int num_array[11][7] = {
      { 1, 1, 1, 1, 1, 0, 1 }, // 0
      { 0, 1, 1, 0, 0, 0, 0 }, // 1
      { 1, 1, 0, 1, 1, 1, 0 }, // 2
      { 1, 1, 1, 1, 0, 1, 0 }, // 3
      { 0, 1, 1, 0, 0, 1, 1 }, // 4
      { 1, 0, 1, 1, 0, 1, 1 }, // 5
      { 1, 0, 1, 1, 1, 1, 1 }, // 6
      { 1, 1, 1, 0, 0, 0, 0 }, // 7
      { 1, 1, 1, 1, 1, 1, 1 }, // 8
      { 1, 1, 1, 0, 0, 1, 1 }, // 9
      { 0, 0, 0, 0, 0, 0, 0 }
    };  //OFF

    int buttonState = 0;
    const int button = 12;
    int randVal;
    bool pressVal;

    void num_Write(int);
    void digit(int value);

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

      for (int pin = 2; pin <= 8; pin++)
      {
        pinMode(pin, OUTPUT);
      }

      pinMode(button, INPUT);
    }

    void loop() {
      buttonState = digitalRead(button);
      if (buttonState == LOW) {
        turnOff();
        pressVal = false;

      }
      else
      {
        if (pressVal == false)
        {
          int pin = 2;
          for (int i = 0; i < 7 ; i++)
          {
            digitalWrite(pin++, num_array[11][i]);
          }
          randVal = rand() % 10;
          pressVal = true;
        }
        Serial.println(randVal);
        if ((randVal >= 0) && (randVal <= 9))
        {
          digit(randVal);
        }
      }
    }

    void digit(int value)
    {
      int pin = 2;
      for (int j = 0; j < 7; j++) {
        digitalWrite(pin++, num_array[value][j]);
      }
      delay(250);
    }

    void turnOff()
    {
      int pin = 2;
      for (int j = 0; j < 7; j++) {
        digitalWrite(pin++, num_array[10][j]);
      }
      delay(250);
    }

You can also remove `turnOff` if you treat it like digit 10 but that is not so clear (or put the implementation of `digit` to another function and call it from `digit` and `turnoff`.

To solve your problem, print the values of each pin to the serial monitor. If they are correct, there is a problem in your circuit. If they are incorrect, there is a problem in your sketch. In the latter case, add more print statements until you found the exact problem.

**Update**

- Fixed void forward declaration to function call (see comment of chrisl)

If the `digit` function is never called, it means:

1. `((randVal >= 0) && (randVal <= 9))` is false, however, that is not possible since it is initialized to 0 and with the rand function it gets always values between 0 to 9.
2. pressVal is always TRUE.

So check the value of pressVal, also add (lots of) `print` statements, especiallya after each `if` and `else` so you know exactly the flow of your sketch. You will see it's very easy to find the error. If you pinpoint the problem to a `digitalRead` that is not the expected value, THAN there is high likely a problem with your circuit (a button that is never going to be LOW or HIGH). In that case, you probably forgot a pullup/pulldown resistor.


body:
I have an infrared sensor(OTI 301) which in order to display the desired temperature I need to apply a formula that depends on 3 binary numbers extracted from the sensor itself. I have tried different approaches but no success yet to extract these binary numbers. Please see link for the data sheet of the sensor where you can see useful information regarding the formula and the binary numbers. https://drive.google.com/file/d/1XMRDCNzY3fn0q6lkGejs5D-pqksfRuZ8/view also here is the code I have tried in the Arduino IDE. Also, attached picture are the needed commands to extract the data from the second data sheet, https://drive.google.com/file/d/1mmdkHkNbwC5VgQxGMrq07XolajNvgBkN/view. [![enter image description here][1]][1]

    #include <Wire.h>
    byte val[2] = {0x20,0x80};
    void setup() {
    Wire.begin(0x20);        // join i2c bus (address optional for master)
    Serial.begin(9600);  // start serial for output
    }

    void loop() {

      //master writter
      Wire.beginTransmission(0x20); // transmit to device
      Wire.write(val,2);
      //Wire.write(x);              // sends one byte
      Wire.endTransmission();    // stop transmitting

      //master reader
      Wire.requestFrom(0x20, 6);    // request 6 bytes from slave device

      while (Wire.available()) { // slave may send less than requested
      Serial.println("H");
      char c = Wire.read(); // receive a byte as character
    }

    delay(500);
    }

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

title: Extract binary numbers from infrared sensor that uses I2C bus

Answers: 1

body:
There are likley two problems:

 - An invalid device address is used. The device address is 0x10 and the Arduino Wire library expects it that way (and not in the shifted version with read/write bit).
 - Your code uses two separate transactions, however the datasheet specifies a single transaction with a repeated START condition for separating the write and read part.

So an improved version looks like so:

    #define DEVICE_ADDRESS 0x10

    void loop() {
        Wire.beginTransmission(DEVICE_ADDRESS);
        Wire.write(0x80);  // readout command
        Wire.endTransmission(false); // stop sending without ending transaction (repeated START)
        Wire.requestFrom(DEVICE_ADDRESS, 6); // request 6 bytes
        uint8_t data[6];
        for (int i = 0; i < 6; i++) {
            data[i] = Wire.read();
        }
    }


body:
How to program an ATtiny45 to use the pins 1, 5, 6, 7 (i.e. PB5, PB0, PB1, PB2) as input or output?

    pinMode(5, OUTPUT);
    pinMode(0, OUTPUT);
    pinMode(1, INPUT);
    pinMode(2, INPUT);
    digitalWrite(5, HIGH);
    ...

These pins are usually used **to program the ATtiny itself**, so how to avoid a conflict?

Of course, I could just avoid these 4 pins, but then as there are also pins for VCC and GND, **there would be only 2 pins left: PB3, PB4!**

Question: how to use the pins as input/output that are usually used for ATtiny programming?

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

Linked question:

* Should I connect pins 1, 5, 6, 7 of the ATtiny to the programmer

* Or should I connect pins 1, 5, 6, 7, **as well as 8 and 4 (VCC and GND)** of the ATtiny to the programmer?

If the second bullet is correct, when connecting VCC and GND, won't it make the ATtiny run the previously uploaded code?

title: How to use ATtiny pins that are usually 'reserved' for chip programming?

Answers: 2

body:
You can just normally use all pins except for the reset pin (pin 0). When you want to program the Attiny, you just connect the programmer. It will reset the Attiny through the reset pin and put it into ISP programming mode. At that point your code hasn't run.

Note: If you want to program the Attiny while it still sits in its circuit, you have to be careful, that the connected circuit does not disturb the ISP communication. The safest way is to disconnect the Attiny from its circuit and then program it.

body:
The ATTiny chips commonly used in Arduino-like boards, such as the Adafruit Trinket or the Digispark USB will usually have a bootloader which runs before your own code. The bootloader checks for a certain state on the USB port of the board, to see if something is waiting to write a new program to the chip.

The bootloader accepts new code from the host computer, if present, and writes it to a certain location in flash memory. If the bootloader does not find anything connected to the USB connector trying to load a new program, then it (the bootloader) starts executing from flash at the location where your program has been stored.

But, what if you want to write a new bootloader, or not have a bootloader? In that case, you can write new software using the MOSI, MISO, and SCK (clock) pins if the RESET pin is pulled to ground.

See:
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf#page=151

In order to make use of all 6 non-power pins as I/O for the Trinket or Digispark, a "fuse" is set in the ATTiny chip which disables the RESET pin's normal purpose of holding the chip in reset. This means you cannot pull RESET to ground and load a program the normal way.

If the RESET pin is disabled, and the bootloader is not present, then there is another method for loading software, called "High Voltage Serial Programming". Not to worry, the "high" voltage is is about 12V.

See:
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf#page=155

You can find schematics, or purchase kits/products that allow you to program an ATTiny chip in HV mode online. Many use the small 12V "A23" or "A27" batteries commonly found in RF remote control transmitters to get the 12V signal to put the chip in high-voltage programming mode.


body:
Regardless of whatever voltage at A0, the software is always returning high (1023)

    volatile unsigned char* ADmux = (unsigned char*) 0x7C;
    volatile unsigned char* ADCSRa = (unsigned char*) 0x7A;
    volatile unsigned char* ADCSRb = (unsigned char*) 0x7B;
    volatile unsigned char* ADCh = (unsigned char*) 0x79;
    volatile unsigned char* ADCl = (unsigned char*) 0x78;
    int Voltage;

    void adc_init()
    {
      *ADmux = 0x00; // setting entire register to 0's notably setting Refs1 and refs0 to 0's meaning reference voltage is AREF
      *ADCSRa = 0b10000111; //Sets most significant bit to 1, which is the ADC enable bit, and the 3 least signifcant bits are the prescalar, which is 128

    }

    unsigned int adc_read( unsigned char adc_channel)
    {
      *ADmux = *ADmux | 0b00000000;// set mux bits to 0 to test A0 regardless of whatever adc_channel is
      *ADCSRa = *ADCSRa | 0b01000000; // set ADSC bit high to start conversion

      while(*ADCSRa & 0b01000000);//wait until ADSC goes low, indicated conversion is complete

      return ADC; //return bits in the adc registers
    }

    void setup() {
       // put your setup code here, to run once:
       Serial.begin(9600);
       adc_init(); // initializes the adc
    }

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

      Voltage = adc_read(0b00000); // calls on adc_read

      Serial.print(Voltage); // prints voltage reading
      Serial.write("\n");

    }

And here is a schematic of the circuit:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

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

<!-- End schematic -->

I have combed over chapter 26 of the atmega2560 document and the descriptions of each register, but I am at a loss. Why is the contents of the adc registers always filled with 1's regardless of the voltage at a0?

title: ADC register always returning high

Answers: 2

body:
First, let me give a couple of suggestions on the programming style.
There is no point in defining your own variables for accessing the
hardware registers: the avr-libc does that for you, you just have to
`#include <avr/io.h>`. Actually, you don't have to \#include anything:
the Arduino IDE automatically \#includes Arduino.h, which in turn
\#includes avr/io.h.

Next, the same avr-libc also defines macros for the bit names, so you
don't have to explicitly write binary numbers in your own code (which is
error-prone). And a couple of utility macros that you can use to make
the code a little bit more readable. For example:

```c++
void adc_init()
{
    ADMUX  = _BV(REFS0);  // ADC reference = AVCC
    ADCSRA = _BV(ADEN)    // enable the ADC
           | _BV(ADPS2)   // set prescaler to 128
           | _BV(ADPS1)   // ditto
           | _BV(ADPS0);  // ditto
}

unsigned int adc_read(unsigned char adc_channel)
{
    ADMUX   = _BV(REFS0) | (adc_channel & 7);  // select channel
    ADCSRA |= _BV(ADSC);  // start conversion

    // Conversion is complete when ADSC goes low.
    loop_until_bit_is_clear(ADCSRA, ADSC);

    return ADC;  // return the adc data register
}
```

Now, let's answer your actual question. When you set both `REFS0` and
`REFS1` to 0, the voltage reference is stated to be “AREF, internal V
REF turned off”. The implication is that you are supposed to bring your
own voltage reference and connect it to the AREF pin. Otherwise AREF is
left as a floating input. This is illustrated in the schematic of the
ADC. Here is the relevant part:

[![AREF input MOSFET][1]][1]

As you see here, `REFS0` is used to connect AREF to one of the other
possible references: either AVCC or the internal bandgap. If `REFS0` is
zero, the transistor depicted above is off, and AREF is left floating.

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

body:
What are the resistance values for R1 and LDR1? Their ratio will determine the voltage at A0. If the ratio of their resistances is too high (for example, 100:1) then any light measured by LDR1 would only result in a small change in the voltage being measured. If the difference is extreme enough, the voltage could also appear to be constantly low or high. If you have a multimeter available, checking the voltage of that divider circuit could help determine what's going on.

https://learn.sparkfun.com/tutorials/voltage-dividers/all


body:
I'm developing a bridge, or man in the middle for touch controller and a system board connected with I2C.  The connection is: <br/>

Touch Controller(slave)---I2C---(master)STM32(slave)---I2C---(master)ARM Board

The original i2c cable is cut in half and STM32 is sitting in the middle.

The point it letting common communication through and just sometimes after an external trigger injecting a click event. (It's for automated testing.) The TC is the only I2C device on the bus.

Have someone done something similar?

The protocol is simple. The ARM board writes two bytes address.Then reads several(3-259) bytes.

I'm trying to request data from TC after receiveEvent() from master, but I don't know how many bytes shall I request. It also takes time for the answer.

Any ideas?

title: i2c man in the middle

Answers: 0


body:
I have been trying to push the data of temp, humidity, and pressure from a sensor to MQTT using ESP 32Cam, and was able to do using the following code:

    pressure = bme.readPressure();

    //Convert the value to a char array
    char preString[16];
    dtostrf(pressure, 1, 2, preString);
    Serial.print("Pressure: ");
    Serial.println(preString);
    client.publish("esp32/pressure", preString);

When I started off with the following code for getting the mac address:

    chipid=ESP.getEfuseMac();//The chip ID is essentially its MAC address(length: 6 bytes).
    Serial.printf("ESP32 Chip ID = X",(uint16_t)(chipid>>32));//print High 2 bytes
    Serial.printf("X\n",(uint32_t)chipid);//print Low 4bytes.

But when I tried to publish the Chip id, that I was getting on the serial monitor, to the MQTT, an error came up with this:

`call of overloaded 'String(uint64_t)' is ambiguous`

Here's my code that I tried:

    char macValue[16];
    String(ESP.getEfuseMac()).toCharArray(macValue,16);
    client.publish("esp32/ChipID", macValue);

title: Publish chipid to mqtt using ESP32-CAM

Answers: 1

body:
You would be better off formatting it nicely instead of relying on String...

    char macValue[17]; // Don't forget one byte for the terminating NULL...
    uint64_t mac = ESP.getEFuseMac();
    sprintf(macValue, "6x", mac);
    client.publish("esp32/ChipID", macValue);

However, I'm not certain that sprintf can cope with a 64 bit value like that directly. If not, you can split it:

    char macValue[17]; // Don't forget one byte for the terminating NULL...
    uint64_t mac = ESP.getEFuseMac();
    uint32_t hi = mac >> 32;
    uint32_t lo = mac;
    sprintf(macValue, "xx", hi, lo);
    client.publish("esp32/ChipID", macValue);


body:
I am trying to get the value of a key pressed and set it to return a value to use in a loop.  In the code below the Print(t) does not show anything

    #include <Keypad.h>

    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    char hexaKeys[ROWS][COLS] = {
        {'1', '2', '3', 'A'},
        {'4', '5', '6', 'B'},
        {'7', '8', '9', 'C'},
        {'*', '0', '#', 'D'}
    };
    byte rowPins[ROWS] = {9, 8, 7, 6};
    byte colPins[ROWS] = {5, 4, 3, 2};
    Keypad customKeypad = Keypad(makeKeymap(hexaKeys),rowPins,colPins,ROWS,COLS;

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

    void loop()
    {
        int t;
        switch (customKeypad.getKey())
        {
        case 'A':
            t = 8;
            break;
        case '2':
            t = 9;
            break;
        }
        return t;
        Serial.print(t);
    }

title: Switch Case Return , Return not printing

Answers: 1

body:
You misunderstand the use of return.  The loop function is declared void.  That means it doesn't return anything.  If you simply remove that return statement completely then your code will do what you want.

The return stops the loop.  It throws away the value since the loop is defined as returning void, and code execution never reaches the print statement.  Writing anything in a function after a return statement is useless.


body:
For example what would be the process of converting the integer 1023 into ascii characters of

0x31 (1)
0x30 (0)
0x32 (2)
0x33 (3)

Not looking for any library functions (I know of Serial.print() and what not). I am trying to serially communicate an integer to the serial monitor, and I'd like to know what the process would be for an algorithm to take an integer and make each digit its corresponding ascii character

title: Converting each digit in an integer to its respective ASCII characters

Answers: 1

body:
To convert a whole number to a char array in one go use the itoa function. That sounds like what you actually need.

To convert one digit from decimal to ascii just add '0', the ascii value for a 0. If you just want to try to understand what's going on, it's something like this.

    char result[4] = {0};
    int num = 345;

    int digit = num % 10;  // get the 5 off the end
    result[2] = digit + '0';  // convert to ascii and store
    num /= 10;   // get rid of the 5
    digit = num % 10;   // get the 4 off the end
    result[1] = digit + '0';  // convert to ascii and store
    num /= 10;   // get rid of the 4
    digit = num % 10;   // get the 3 off the end
    result[0] = digit + '0';  // convert to ascii and store

    Serial.print(result);  // prints "345"