body:
i have a problem with my code, i basically move a motor with the help of 3 relays, when a sensor does not detect the presence of an object part of a call, everything works perfectly, if it was after having called the function CHIAMATA() the arduino loop() stop unexplains, i certainly made a mistake, but i do not understand which.

thanks for your help
this is the code....

    #include <swRTC.h>
    #include <SoftwareSerial.h>
    #include <String.h>

    swRTC rtc; //create a new istance of the lib
    SoftwareSerial mySerial(3, 2);

    const int buttonPin = 19;
    const int sensorPin = 9;
    const int allarmPin =  13;

    int buttonState = 0;
    int sensorState = 0;
    int relay1 = 8;
    int relay2 = 7;
    int relay3 = 6;
    int var = 0;

    // initialize the stepper library on pins 8 through 11:

    void setup() {
     rtc.stopRTC(); //stop the RTC
     rtc.setTime(12,0,0); //set the time here
     rtc.setDate(4,6,2012); //set the date here
     rtc.startRTC(); //start the RTC
      Serial.begin(19200); //choose the serial speed here
      mySerial.begin(19200);
      pinMode(allarmPin, OUTPUT);
    }

    void loop() {

    while(mySerial.available()!=0);{}delay(10);

        Serial.print(rtc.getHours(), DEC);
        Serial.print(":");
        Serial.print(rtc.getMinutes(), DEC);
        Serial.print(":");
       Serial.print(rtc.getSeconds(), DEC);
        Serial.println(" ");

    //stato riserva croccantini
    sensorState = digitalRead(sensorPin);

    if (sensorState == HIGH) {
        // turn LED on:
        digitalWrite(allarmPin, HIGH);
        Serial.println("Croccantini esauriti");
        Serial.println("Spia allarme ACCESA");
        Serial.println("Tramoggia DISABILITATA");
        Serial.println("Imposto la chiamata");
        while(sensorState == HIGH) {CHIAMATA(); break;}
      } else {
        // turn LED off:
        digitalWrite(allarmPin, LOW);
        Serial.println("Croccantini OK");
      }
    if (sensorState == LOW && rtc.getHours()== 12 && rtc.getMinutes()== 00 && rtc.getSeconds()== 5) {startmotor();}
      //start manuale carico/scarico
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);
      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
        if (buttonState == 1) {
          Serial.print("Pulsante alimentazione manuale ATTIVO");
        // turn on:
      // singlestartmotor();
      }

          }

    void startmotor(){
    //numero di cicli di carico da eseguire (5)
     while(var < 5){
     pinMode(relay1, OUTPUT);
      pinMode(relay2, OUTPUT);
        pinMode(relay3, OUTPUT);

     digitalWrite(relay3, LOW); //ABILITA TUTTO
     //AVANTI
     digitalWrite(relay1, LOW);
     digitalWrite(relay2, LOW);
     Serial.print("AVANTI");
     delay(1000); // wait 2 seconds

     digitalWrite(relay3, HIGH);//STOP TUTTO
     digitalWrite(relay1, HIGH);
     digitalWrite(relay2, HIGH);
     delay(1000); //ATTESA PER INVERSIONE MARCIA

     //INDIETRO
     digitalWrite(relay3, LOW);//ABILITA TUTTO
     digitalWrite(relay1, HIGH);
     digitalWrite(relay2, HIGH);
     Serial.print("INDIETRO");
     delay(1000); // wait 2 seconds

      digitalWrite(relay3, HIGH);//STOP TUTTO
      delay(5000); // wait 2 seconds

      var++;
    }}

    void CHIAMATA() {
     mySerial.println("ATD329xxxxx135;");//dial the number, xxxx ix the phone number.
     delay(100);
     Serial.print("Chiamata in corso..."); return loop();}

title: Arduino stop the loop

Answers: 1

body:
Don't do `return loop();` With that you enter into a never ending recursion. No system can resist that.

See: `return loop();` means "evaluate loop() and return whatever it returns". Well, `loop` is `void`; it doesn't return anything.

Even worse is the recursion problem: you call `loop()`, which calls CHIAMATA, which calls `loop` ... never ending. You blow out the stack.

I don't look any further than that. Probably there are more errors.


body:
Situation: I was trying to make a simple Arduino program that mimics my TV-Remote ON-OFF button.

Diagnosis: It just won't work. So just to check I grabbed another Arduino (2) and added my IR-Sensor to that one and let it look for the signals sent by Arduino (1).

Conclusion: Even though I ran exactly the same program in a loop sending IR signals, Arduino (2) noticed each time another IR signal. The received signals didn't even look like the IR signal I sent.

[![The way I connected my IR-LED (By Adafruit)][1]][1]

The program I use to mimic my remote: [Link to the Github. It is an example of a Lib][2]

It could be the LED. Just a LED I picked up without being specific. [Link to the Documentation of the LED][3]

  [1]: https://i.stack.imgur.com/gKpE0.png
  [2]: https://github.com/cyborg5/IRLib2/blob/master/IRLib2/examples/record/record.ino
  [3]: http://www.produktinfo.conrad.com/datenblaetter/175000-199999/181709-da-01-en-IR_LED_5MM_HE1_220AC.pdf

title: Arduino emits signal A (infrared) but another Arduino receives everything but A (IR-LED problem)

Answers: 1

body:
Sorry not enough rep to comment. Had to answer instead.

So if your schematic is correct then you just fried your LED. You need a series resistor between vcc and the LED.

If it's not accurate and you have the resistor in place, I'd check the LED anyway, it could be a dud. Apply voltage with a resistor and look at it with your cell/mobile phone digital camera, you should see it through the camera glow dimly.

If all is good then it might be the wavelength of the LED, which is 850nm. Most IR LED's I've used are 950nm, actually they all were.

Now I don't know what the specs of your receiver are but it might be out of its sensing (is that a word?) range, also it only has a 20° viewing angle, so check the alignment of transmitter and receiver.

I'm also confused by your statement that your getting signals that don't look like IR. This makes me wonder if your sensor is hooked up properly. It could be background IR or from another source. Look around the room or test elsewhere.


body:
Following this tutorial: https://tutorials-raspberrypi.com/let-raspberry-pis-communicate-with-each-other-per-433mhz-wireless-signals/ I was able to easily send code from one Raspberry Pi Zero to another using a RF 433 MHz Transmissor, Receiver pair using the Ninjablock's 433Utils library.

Now I'm trying to do the same between two Arduinos UNO. I'm following the explanations of the library itself: https://github.com/ninjablocks/433Utils, but until now without success.

> **Arduino_Sketches**
>
> Place the Sketches in your normal Arduino Sketches location. Install
> any required libraries:
>
>     1) Servo motor library (Should be included in the Arduino IDE)
>     2) Arduino rc_switch library

The Arduino rc_switch library is installed in my Arduino IDE.

What I would like to confirm is the following:

While with the Raspberry Pis I go to the folder 433Utils/RPi_utils and type the command `sudo ./RFSniffer` in one terminal and `sudo ./codesend 1234` in another what I have to do with the Arduinos?

Upload the sketch `RF_Sniffer.ino` to one Arduino and the sketch `Send_Demo.ino` to the other and watch in the Serial Monitor the inputs/outputs appearing as magic?

That's unfortunately not working. :-(

May I install anything else? Modules and wiring is OK.

title: Sending and receiving data using 433 Mhz from Arduino to Arduino

Answers: 0


body:
My HM-10 bluetooth module is behaving weird.

In order to have it operate normally, I have to keep holding the small black button on it. If I ever release the button, it just disconnects from my phone (if it was connected) and doesn't show on the bluetooth devices list anymore, and its red LED light becomes low, not bright as usual.

It operated normally before.

How can I fix this?

What would some possibles causes be for this weird behavior?

UPDATE: picture showing the button on lower right corner.
[![HM-10 with button on lower right corner][1]][1]

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

title: HM-10 only works when holding button

Answers: 1

body:
**I just had to connect the RX/TX jumpers. There was no real issue.**

I though connecting the power jumpers was enough to just see HM-10 on my phone, since I didn't care about any data. Turns out if the RX/TX jumpers are not connect, the module behaves weird.


body:
I'm planning on buying an Arduino Due and there is a shield I would like to attach to it. I have seen a lot of things saying that some shields are **not** compatible with Arduino Due... I was wondering if the Arduino Due is compatible with the Dual VNH5019 Motor Driver Shield.

This is where I'm buying it from if you need any extra information on the items:

 - [The Arduino Due][1]
 - [The Dual VNH5019 Motor Driver Shield][2]

Answers greatly appreciated! If you need any specifications let me know.

  [1]: https://www.amazon.com/Arduino-org-A000062-Arduino-Due/dp/B00A6C3JN2/ref=sr_1_2_sspa?ie=UTF8&qid=1508614566&sr=8-2-spons&keywords=arduino DUE&psc=1&smid=AM0JQO74J587C
  [2]: https://www.pololu.com/product/2507

title: Is the Arduino Due compatible with a Dual VNH5019 Motor Driver Shield?

Answers: 1

body:
ok so I went ahead and bought the arduino due and officially tested it out and the Arduino Due **is** compatible with the Dual VNH5019 Motor Driver Shield!

hope this helps!


body:
For few days, I am trying to figure out, why my sensors do not work on external power. I bought NodeMCU along with couple different sensors etc. I was happily working with them, connecting them one by one to the 3.3v pin in the NodeMCU board, programming each of them. Everything was working as expected. After I have finished, I decided it's time to use them all at once, but I knew, that for that to work, I need to provide them with enough power, as USB probably won't be enough (plus, when I'm done, I don't plan to use USB to power the system anyway). I have a module that converts 230v AC into 5v DC, and then I am stepping it down to 3.3v in order to power the sensors. After checking with multimeter, the voltages are ok, and so is the current.

My problem is, that the sensors give completely random data (most of the time they don't give any information, but once in a while they send something like 1000 times the normal value). Below you can see the schematic that I use. Can you please help me figure this out?

**Edit:** I would just like to add - I did try to run NodeMCU solely on the Ext. Power - the circuit looked exactly as below, I just connected positive output of 3.3v power source, to the 3.3v connector on NodeMCU. The board was working (I was able to control the onboard LED via WiFI), but the sensor did not. I then reconnected the sensor from external power, to NodeMcu 3.3v, and it (the sensor) worked... I have no idea why.

<!-- 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/o9kbF.png)

<!-- End schematic -->

title: Sensors go crazy on external power

Answers: 2

body:
I have fiddled with it a little more. Turns out, that the resistor I was putting in the circuit was the cause of failure - the sensor did not have enough power.

Now this is very weird to me, as the sensor is rated at 190uA max, and it is not working on this current. Only after I removed the resistor (so the current was around 800mA) it started operating as it should have.

body:
Sorry I don't have reputation for a comment but this might be of help.

You didn't specify if the sensor was a breakout board. If it is then the board may already have the resistor in place, which is why removing it worked.

Now if you had the resistor in place when it was also connected to the nodeMCU, then perhaps power from it was high enough to still generate a stable operating condition (not familiar with nodeMCU) but more likely you have a power supply issue.

 - Is it a module and does it have resistor on board.

 - was the 27k resistor only in circuit on external power.

If the answer was yes to the above that is probably the issue.

If they are not the cause, my next check would be your external power. It could need calibration, power spikes/ripples etc but the easiest thing to do is put in a smoothing capacitor in circuit after your power supply.

Probably about 20-30% of my sensor issues are resolved by this. Another 60% are solved by fixing my screw ups and assumptions.


body:
Recently I have asked a question, why my sensors do not work on external power supply ([link][1]). I have found out, that I was limiting the current too much with the resistors. I have tried using two sensors:

 - DHT22, rated at 1.5mA max ([picture of my module][2])
 - BH1750, rated at 190uA max ([picture of my module][3])

My logic is, if they are rated at that current, I should put a resistor in the Vin, to restrict the current to given value. But it turned out that I was wrong, because they started working only after I removed my resistors.

My questions is - should I put a resistor in there? If yes, then how do I know what resistance should I have, if the data sheet values are misleading?

  [1]: https://arduino.stackexchange.com/questions/45795/sensors-go-crazy-on-external-power "link"
  [2]: https://img1.banggood.com/thumb/view/2014/xiemeijuan/07/SKU146979/SKU146979a.jpg "link"
  [3]: https://www.mysensors.org/uploads/57cc6e4595afb8801e529dab/image/BH1750.jpg.png "link"

title: Powering arduino sensors - what resistor should I use?

Answers: 1

body:
You should have NO resistor.

The datasheet states the current values the device will *pull* from the supply. Supplies DO NOT PUSH CURRENT.

Remove all resistors.

As long as the voltage is correct and the supply can provide *at least as much current as all devices combined want to use* then it will work.


body:
I'm porting some code from Arduino Uno over to a Mega and I want to replace a SoftwareSerial defined in the previous code with one of the built-in UARTs.

Rather than go through and replace all references to the serial port, I'd prefer to create an alias for Serial1. The alias can be a constant.

In my old code, I setup the Software Serial as follows:

    //SoftwareSerial HMI(HMIRX, HMITX); // Define software serial for the HMI adapter (RX, TX)

I"m not even sure where to start.

title: Is there a way to define an alias for a hardware Serial

Answers: 1

body:
it is simple
`#define HMI Serial1`


body: I am going to use few Figaro TGS sensors, which including TGS2600, 2602 and 2620 with my Arduino. I referred to the datasheet and found that these sensors need more than one voltage source. May I know the correct way to connect them to my arduino? (Arduino Mega or Uno probably)...(beginner here)

title: Arduino with Figaro TGS sensor

Answers: 0


body:
I am a beginner with Arduino. I am doing something to cool down my room temperature using an exhaust fan and cooler through relays. I am trying to reduce the temperature initially using an exhaust fan and wait for 10 minutes to see if the temperature reduced to a set range. If not, the exhaust fan is turned off and the rest of the cooling is done by the cooler.

At the beginning of the program all goes well: it turns on the exhaust fan and waits 10 minutes and if it's not dropping, it transfers the job to the cooler. But after one cycle, when the temperature increases, the cooler is turned on directly, without the exhaust fan urning on, or waiting for 10 minutes and things. I tried a lot but I can't understand what is happening. Please suggest something to solve the problem.

    #include <dht.h>

    dht DHT;

    #define DHT1_PIN 7 // dht11 connected to pin 7

    int exhaustpin = 4; // set pin for exhaust fan relay
    int coolerpin = 5; // set pin for cooler relay
    boolean exhaust;
    void setup(){
       Serial.begin(9600);
        pinMode(exhaustpin, OUTPUT);
      pinMode(coolerpin, OUTPUT);
      digitalWrite(exhaustpin,HIGH );
      digitalWrite(coolerpin,HIGH );
      exhaust= LOW;

    }
    void loop()
    {

        DHT.read11(DHT1_PIN);
      Serial.print(" MY Room Temperature = ");
      Serial.println(DHT.temperature);
      Serial.print("MY Room Humidity = ");
      Serial.println(DHT.humidity);
     delay(500);
      int  roomtemp =DHT.temperature;
      static unsigned long interval;
      long interval;
      if (exhaust== LOW){
      if ((roomtemp>=30)&&(digitalRead(coolerpin)==HIGH )){
        digitalWrite(exhaustpin,LOW ); // if temperature increses above 30 the exhaust starts to work
         interval = millis();
      }
      }
       if (digitalRead(exhaustpin)==LOW){
         exhaust= !exhaust;
     if ((millis()-interval) >= 600000){
        digitalWrite(coolerpin,LOW );
        digitalWrite(exhaustpin,HIGH );   // after the starting of exhaust fan it wait for 10 minutes ,then it turn
                                          // on the cooler and turns off the exhaust fan
           }
       }
      if (roomtemp<28){
        digitalWrite(coolerpin,HIGH );
         digitalWrite(exhaustpin,HIGH );
         exhaust= !exhaust;
       // i am trying here to start cooling the room with my exhaust fan
       // then wait 10 minutes ,if it is still not less than 28 degrees turn on the cooler to do the cooling
       // and turn off the exhaust fan
       }
      }

title: My sketch is not working as intended

Answers: 1

body:
      if (digitalRead(exhaustpin) == LOW) {
        static unsigned long interval = millis();
        if ((millis() - interval) >= 600000) {
          digitalWrite(coolerpin, LOW);
          digitalWrite(exhaustpin, HIGH);
          // after the starting of exhaust fan it wait for 10 minutes, then it turns on
          // the cooler and turns off the exhaust fan
        }
      }

`interval` is only ever set once. So 10 minutes after it is first set it will remain over 10 minutes.

The simplest fix is to set `interval` to `millis()` when you set `exhaustpin` to low:

    if ((roomtemp>=30)&&(digitalRead(coolerpin)==HIGH)) {
      digitalWrite(exhaustpin,LOW );
      // if temperature increses above 30 the exhaust starts to work
      interval = millis();
    }


body:
I have written a code that is supposed to blink the LED on PB5 pin, when a sequence of input matches a 4 digit password input from a keypad.But the program doesn't appears to be working as expected.

keypadGetKeyPressed() returns a char output of the keypad
and I want to blink led on PB5 /13 PIN

lcd.h has used PORTB is it because of that

            #include <avr/io.h>
   #include <util/delay.h>

   #include "lcd.h"
   #include "keypad.h"

   #include <string.h>

   int main(void) {

    // Password
    char password[4]="5678";

    char keyPressed, oldKeyPressed = 0;
    lcdInit();
    keypadSetupPins();

    lcdWriteCommand(DISPLAY_ON | BLINK | UNDERLINE);
    lcdWriteCommand(CLEAR_DISPLAY);

    char p1 = '1';
    char p2 = '2';
    char p3 = '3';
    char p4 = '4';
    char p5 = '5';

    //Sets the digital pin Pb5 or 13 as Output
    DDRB |= (1<<PB5);
    //Sets LED initially as ON, put ~ before the ( to set it off initially
   // DDRB |= (1<<PB5);

    // to count matched character
    int count=0;
    char message[]="Logged In";
    while (1) {

     keyPressed = keypadGetKeyPressed();
     if(keyPressed==password[count]){
      count+=1;
     }
     else{
      //if next char doesn't match reset counter
      count= (keyPressed==password[0])?1:0;
     }
     if(count==4){
      //Call the required function to toggle LED
       count=0;

       PORTB |= ~(1<<PB5);
      _delay_ms(1000);
      // Turn led off by setting corresponding bit low in the PORTB register.
         PORTB |= ~(1<<PB5);

         _delay_ms(500);
         lcdWriteString(message);

     }

     if (keyPressed != 0 && (keyPressed != oldKeyPressed))

     {
      lcdWriteChar(keyPressed);
     }

     oldKeyPressed = keyPressed;

     _delay_ms(20);

     if (keyPressed == p1 ) {

      lcdWriteString("done");
     }

    }

   }

 keypad.h file

    #ifndef KEYPAD_H_
    #define KEYPAD_H_

    #include <avr/io.h>

    #define NUM_COLS 3
    #define NUM_ROWS 4

    #define COL_DIR  DDRB
    #define COL_PORT PORTB
    #define COL_1_PIN 2
    #define COL_2_PIN 3
    #define COL_3_PIN 4

    //NB it is important that the row pins all trigger the same
    //Pin change interrupt - see p70 of the datasheet
    #define ROW_DIR  DDRC
    #define ROW_INPUT  PINC
    #define ROW_PORT   PORTC  //for pullups

    #define ROW_1_PIN 0
    #define ROW_2_PIN  1
    #define ROW_3_PIN 2
    #define ROW_4_PIN 3

    /*
     * Set up the keypad pin directions, enable the pin change interrupt
     * and drive the column pins low.
     */
    void keypadSetupPins(void);

    /*
     * Scan the keypad to determine which key is pressed.
     * Returns 0 if no key pressed and returns ascii code if key pressed.
     * Sets all the cols to low when done.
     */
    char keypadGetKeyPressed(void);

    #endif /* KEYPAD_H_ */

keypad.c file

    * Set up the keypad pin directions, pull up resistors
    * and drive the column pins low.
    */
   void keypadSetupPins(void)
   {
    //Set column pins as output pins
    COL_DIR |= ( (1<<COL_1_PIN) | (1<<COL_2_PIN) | (1<<COL_3_PIN) );

    //Set rows pins to be inputs
    ROW_DIR &= ~( (1<<ROW_1_PIN) | (1<<ROW_2_PIN) | (1<<ROW_3_PIN) | (1<<ROW_4_PIN) );

    //Enable Pullups on row pins
    ROW_PORT |= ( (1<<ROW_1_PIN) | (1<<ROW_2_PIN) | (1<<ROW_3_PIN) | (1<<ROW_4_PIN) );

    //Send out three 0's on COLs
    COL_PORT &= ~( (1<<COL_1_PIN) | (1<<COL_2_PIN) | (1<<COL_3_PIN) );

   }

   /*
    * Scan the keypad to determine which key is pressed.
    * Returns 0 if no key pressed and returns ascii code if key pressed.
    * Sets all the cols to low when done.
    */
   void passwordString(char string[])
   {
    int i = 0;

   }

   char keypadGetKeyPressed(void)
   {
    char retVal = 0;
    uint8_t rowPins;

    //Send 011 on the cols
    //Send out 0 on col 1

    COL_PORT &= ~(1<<COL_1_PIN);
    //Send out 11 on cols 2 and 3
    COL_PORT |= ( (1<<COL_2_PIN) | (1<<COL_3_PIN) );

    //CRUCIAL - delay to allow values to propagate to the rows
    _delay_us(1);

    //Read PIN reg and copy into var
    rowPins = ROW_INPUT;

     //Test row 1
     if( !(rowPins & (1<<ROW_1_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
     {
     //there is a 0 on row 1 pin => Key 1 is pressed
     retVal = '1';
     }

     //Test row 2
     if( !(rowPins & (1<<ROW_2_PIN)) ) //if the ROW_2_PIN in the ROW_INPUT reg is NOT high
     {
     //there is a 0 on row 1 pin => Key 4 is pressed
     retVal = '4';
     }

     //Test row 3
     if( !(rowPins & (1<<ROW_3_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
     {
      //there is a 0 on row 1 pin => Key 7 is pressed
      retVal = '7';
     }

     //Test row 4
     if( !(rowPins & (1<<ROW_4_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
     {
      //there is a 0 on row 1 pin => Key 7 is pressed
      retVal = '*';
     }

    COL_PORT &= ~(1<<COL_2_PIN);
    //Send out 011 on cols 2 and 3
    COL_PORT |= ( (1<<COL_1_PIN) | (1<<COL_3_PIN) );

    //CRUCIAL - delay to allow values to propagate to the rows
    _delay_us(1);

    //Read PIN reg and copy into var
    rowPins = ROW_INPUT;

     //Test row 1
     if( !(rowPins & (1<<ROW_1_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
     {
      //there is a 0 on row 1 pin => Key 1 is pressed
      retVal = '2';
     }

     //Test row 2
     if( !(rowPins & (1<<ROW_2_PIN)) ) //if the ROW_2_PIN in the ROW_INPUT reg is NOT high
     {
      //there is a 0 on row 1 pin => Key 4 is pressed
      retVal = '5';
     }

     //Test row 3
     if( !(rowPins & (1<<ROW_3_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
     {
      //there is a 0 on row 1 pin => Key 7 is pressed
      retVal = '8';
     }

     //Test row 4
     if( !(rowPins & (1<<ROW_4_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
     {
      //there is a 0 on row 1 pin => Key 7 is pressed
      retVal = '0';
     }

    COL_PORT &= ~(1<<COL_3_PIN);
    //Send out 011 on cols 2 and 3
    COL_PORT |= ( (1<<COL_1_PIN) | (1<<COL_2_PIN) );

    //CRUCIAL - delay to allow values to propagate to the rows
    _delay_us(1);

    //Read PIN reg and copy into var
    rowPins = ROW_INPUT;

     //Test row 1
     if( !(rowPins & (1<<ROW_1_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
     {
      //there is a 0 on row 1 pin => Key 1 is pressed
      retVal = '3';
     }

     //Test row 2
     if( !(rowPins & (1<<ROW_2_PIN)) ) //if the ROW_2_PIN in the ROW_INPUT reg is NOT high
     {
      //there is a 0 on row 1 pin => Key 4 is pressed
      retVal = '6';
     }

     //Test row 3
     if( !(rowPins & (1<<ROW_3_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
     {
         //there is a 0 on row 1 pin => Key 7 is pressed
      retVal = '9';
     }

     //Test row 4
     if( !(rowPins & (1<<ROW_4_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
     {
      //there is a 0 on row 1 pin => Key 7 is pressed
      retVal = '#';
     }

     return retVal;
     }

lcd.h file

                #ifndef LCD_H_
    #define  LCD_H_

    #include <avr/io.h>
    #include <util/delay.h>

    //If nibble mode is enabled it is assumed that D4->D7 on the LCD
    //are connected to pins 0->3 of the data port.
    #define USE_NIBBLE_MODE    0  //0 for false, 1 for true
    #define LINE_MODE          0 //0 for ONE line mode, 1 for TWO line mode

    #define LCD_CONTROL_PORT   PORTB
    #define LCD_CONTROL_DIR    DDRB
    #define RS_PIN             PORTB0
    #define E_PIN              PORTB1

    #define LCD_DATA_PORT      PORTD
    #define LCD_DATA_DIR       DDRD

    #define CLEAR_DISPLAY       0x01
    #define DISPLAY_CURSOR_HOME 0x02
    #define DISPLAY_ON          0x0C
    #define DISPLAY_OFF         0x08
    #define UNDERLINE           0x02    //OR this with DISPLAY_ON
    #define BLINK               0x01    //OR this with DISPLAY_ON
    #define ONE_LINE_MODE       0x34
    #define TWO_LINE_MODE       0x38
    #define SET_ADDRESS         0x80    //You must OR the appropriate address with this
    #define DISPLAY_SHIFT_LEFT  0x18
    #define DISPLAY_SHIFT_RIGHT 0x1C
    #define CURSOR_SHIFT_LEFT   0x10
    #define CURSOR_SHIFT_RIGHT  0x14

    void lcdInit(void);

    void lcdWriteCommand(uint8_t command);

    void lcdWriteChar(char ch);

    void lcdWriteString(char string[]);

    #endif  /* LCD_H */

lcd.c file

                #include "lcd.h"

    /***********************************************************
     * This function sets th direction of the pins that are
     * connected to the LCD.
     * The code makes use of the #defined names in lcd.h so that
     * if the pins connected to the LCD change only lcd.h needs
     * to be changed and not the code in this file.
     *
     * This function is complete.
     **********************************************************/
    void lcdInit(void)
    {
     //set direction of control pins to be outputs
     LCD_CONTROL_DIR |= (1<<RS_PIN);
     LCD_CONTROL_DIR |= (1<<E_PIN);

     //Set direction of data port pins to be outputs
     LCD_DATA_DIR |= 0xFF;
    }

    /****************************************************
     * Sends a a single command to the LCD
     * Takes care of the register selection,
     * placing data on the data pins and toggle of E pin
     *****************************************************/
    void lcdWriteCommand(uint8_t command)
    {
     PORTB &= ~(1<<RS_PIN);

     PORTD = command;

     PORTB |= (1<<E_PIN);

     _delay_us(2); //lcd boot delay

     PORTB &= ~(1<<E_PIN);

     _delay_ms(2);
    }

    /****************************************************
     * Sends a a single ascii char to the LCD
     * Takes care of the register selection,
     * placing data on the data pins and toggle of E pin
     *****************************************************/
    void lcdWriteChar(char ch)
    {
     PORTB |= (1<<RS_PIN);

     PORTD = ch;

     PORTB |= (1<<E_PIN);

     _delay_us(2); //lcd boot delay

     PORTB &= ~(1<<E_PIN);

     _delay_ms(2);
    }

    /****************************************************
     * Writes a string to the LCD
     * Steps through the string passed as a parameter and
     * calls lcdWriteChar() to send each character of the
     * string
     *****************************************************/
    void lcdWriteString(char string[])
    {
     int i = 0;

     while (string[i] != '\0')
     {
      lcdWriteChar(string[i]);
      i++;
     }
    }

title: Arduino program to Blink L LED when input matches a set pattern

Answers: 1

body:
The following proposed code:

 1. corrects the worst of the logic problems
 2. eliminates unused/unnecessary local variables
 3. performs the desired function
 4. keeps data declarations local to where they are used
 5. expects the keypad input function to perform the majority of the key debouncing.

and now the proposed code:

        #include <avr/io.h>
        #include <util/delay.h>

        #include "lcd.h"
        #include "keypad.h"

        #include <string.h>

        int main(void)
        {
            // Password
            char password[5]="5678";  // 5 to allow for trailing NUL byte

            char oldKeyPressed = 0;

            lcdInit();
            keypadSetupPins();

            lcdWriteCommand(DISPLAY_ON | BLINK | UNDERLINE);
            lcdWriteCommand(CLEAR_DISPLAY);

            //Sets the digital pin Pb5 or 13 as Output
            DDRB |= (1<<PB5);
            //Sets LED initially as ON, put ~ before the ( to set it off initially
            //  DDRB |= (1<<PB5);

            size_t count = 0;

            for( size_t i=0; i< strlen( password ); i++ )
            {
                char keyPressed = keypadGetKeyPressed();

                if(keyPressed==password[count])
                {
                    count+=1;
                }

                else
                {
                    count = 0;
                }

                if( count == strlen( password ) )
                {
                    char message[] = "Logged In";

                    //Call the required function to toggle LED
                    PORTB |= ~(1<<PB5);
                    _delay_ms(1000);
                    // Turn led off by setting corresponding bit low in the PORTB register.
                    PORTB &= ~(1<<PB5);

                    _delay_ms(500);
                    lcdWriteString(message);
                }

                // this code block should (probably) only be for debug
                if (keyPressed != 0 && (keyPressed != oldKeyPressed))
                {
                    lcdWriteChar(keyPressed);
                }

                // debounce the keypad
                oldKeyPressed = keyPressed;
                _delay_ms(20);

                // method of exiting the program before fully logged in
                if (keyPressed ==  '1' )  // so '1' cannot be part of the password
                {
                    lcdWriteString("done");
                    break;
                }
            }
        }


body:
whats the minimum number of pins to use when multiplexing 6 LEDs?

is there some kind of formula that can be applied to `n` LEDs?

Or in other words, how many LEDs can an Arduino Uno control without the help of a separate IC?

title: Minimum number of Pins to use for multiplexing LEDs

Answers: 1

body:
It depends on the style of multiplexing.

For basic Row-Column multiplexing you have N=RC - the number of LEDs is the number of rows multiplied by the number of columns. The LEDs, of course, don't have to be arranged physically in rows and columns, those are purely logical wiring concepts.

For [Charlieplexing](https://en.wikipedia.org/wiki/Charlieplexing) (used by the LOL shield) it's slightly more complex. The formula is: N = n² - n, where `n` is the number of pins, and `N` is the number of LEDs they can drive.

Charlieplexing can multiplex far more LEDs than traditional R/C multiplexing, but is harder to program for and wire up.


body:
I am new to Arduino and I'm trying my first Pro Mini. I was able to find DS1302 code from github that runs perfectly. My problem is trying to add some LM35 code to also display temperature data as well as the time data.

The code doesn't seem to run the Celsius and Fahrenheit functions. I have attached my code. Any help will be appreciated.

    //Required library - http://www.rinkydinkelectronics.com/library.php?id=5
    //Blog Post - http://overskill.alexshu.com/ds1302-real-time-clock-w-arduino/

    #include "U8glib.h"
    #include <DS1302.h>
    #include <PreciseLM35.h>
    //int float pinLM35 = A0;
    const int pinLM35 = A0;
    PreciseLM35 lm35(pinLM35, DEFAULT);

    DS1302 rtc(2, 3, 4);
    U8GLIB_ST7920_128X64 u8g(13, 11, 12, U8G_PIN_NONE);

    void setup(void) {
      rtc.halt(false);
      rtc.writeProtect(false);

      // The following lines can be commented out to use the values already stored in the DS1302
      // Once you flash the Arduino with the correct time.

      //rtc.setDOW(FRIDAY); // Set Day-of-Week to FRIDAY
      //rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
      //rtc.setDate(6, 8, 2010); // Set the date to August 6th, 2010

      // assign default color value
      if (u8g.getMode() == U8G_MODE_R3G3B2)
        u8g.setColorIndex(255); // white
      else if (u8g.getMode() == U8G_MODE_GRAY2BIT)
        u8g.setColorIndex(3); // max intensity
      else if (u8g.getMode() == U8G_MODE_BW)
        u8g.setColorIndex(1); // pixel on
    }

    void draw(void) {
      u8g.setFont(u8g_font_04b_03);
      u8g.drawStr( 2,5, "******************************");
      u8g.drawStr( 13,10, "Arduino Pro Mini Control ");
      u8g.drawStr( 24,20, (rtc.getTimeStr()));
      u8g.drawStr( 1,20, "TIME: ");
      u8g.drawStr(70,20,  "Temp (C): ");
      u8g.drawStr (80,20, (lm35.readCelsius()));
      u8g.drawStr( 25,30, rtc.getDOWStr());
      u8g.drawStr(70,30, "Temp (F): ");
      u8g.drawStr(3,30, "DAY: ");
      u8g.drawStr(80,30, (lm35.readFahrenheit()));
      u8g.drawStr( 24,40, rtc.getDateStr());
      u8g.drawStr(1,40, "DATE: ");
      u8g.drawStr(70,40, "AREF : ");
      u8g.drawStr(80,40, (lm35.readPreciseAref()));
      u8g.drawStr( 15,55, "DS1302 Real Time Clock");
      u8g.drawStr( 2,65, "********************************");
    }

    void loop(void) {
      // picture loop
      u8g.firstPage();
      do {
        draw();
      } while(u8g.nextPage()); //u8g.nextPage()
      // rebuild the picture after some delay
      delay(500);
    }

title: Display values from a function on GLCD

Answers: 1

body: Use an DS3231 RTC instead. It include a temperature sensor with digital output. No need to read an analog value and it means less component in your PCB.


body:
I have 5 types of such functions with different input parameters.

    blink(int a,char* b, int c);
    fade(int a,int b,int c);
    split(int a,int d);

and so on from serial input what i want is to call this three functions in any combinations that can be later executed in a loop. For example  my serial input is this ..

    [blink(a,b,c),fade(a,b,c),blink(a,b,c),fade(a,b,c),split(a,d),blink(a,b,c)]

The  Code should also be saved  in memory so that when a person reset Arduino. The order of functions execute without waiting for serial input.The order of functions would get change only when person enter serial data to arduino.
I have no clue where to begin please help me out.

title: How to call 5 different functions in a loop based on serial input?

Answers: 2

body:
This answer isn't going to give you the code to solve your problem, it is just ideas that you can look at and see what suits you best.

You should be able to find an example on how to read from a serial connection, I'm sure there is at least one example in the IDE.

You need to work out how to encode your data, having it in nice human friendly format (like you have above) is great if you are processing it on a PC but on a processor that is slow and have very limited memory using A,B,C... as the function names might be more practical.  It will be smaller to store and quicker to compare.

You want to store the input so it can be read back later.  There are a number of ways you can do this but they all need a non-volatile storage medium.  You could use an SD card, obviously you'd need an SD reader and the type of reader you get will affect the code you need, but these can be problematic.  You can also use EEPROM chips that, you can get little I2C interfaced modules, they have less space than an SD card, but are generally faster (they also have a shorter lifespan, but don't worry I don't you'll ware one out).  You can also use the EEPROM that is in the Arduino itself (I've never done this).

It is best to build you program up in small parts, get the reading from serial working, then calling functions, then saving and loading.  That way you only have to debug a small bunch of issues at once.  If you wanted you could abstract the storage device away from the code by writing a base class that has virtual save and load functions.  You could then inherit from this class for the EEPROM or the SD card and changing wouldn't affect the rest of the code.

Like I said at the start I appreciate this answer hasn't given you a step by step guide on how to solve your problem, but hopefully it has given you a few pointers on what you could do and you can research the options from there.  Remember when you get stuck on one particular aspect just post a minimal example of what you have tried and explain what you expect it to be doing and people will be more than willing to help.

body:
This answer isn't going to give you the code to solve your problem either, it is just tricks that you can look at and see what suits you best.

[I'm assuming your serial input is all readable text (no binary data).]

Made serial input fixed format: Every function name is 3 letter long, all parameters the same length, and if possible, all function the same number of parameter. That's make parsing things easy, later you can upgrade to variable length parameters.

Know you can write two small functions that read Serial and returns a single element:

    String getFunction();
    int    getArgument();

Each function will take care of commas and other delimiters. Also, `getArgument` will convert values as text to binary values.

You loop will look like (pseude-code, don't compile).

    void loop() {
      String fn = getFunction();

      if (fn.equals("blink")) {
        doBlink();
      }
      if  (fn.equals("fade")) {
        doFade();
      }
     ....
     }
     void doBlink() {
        int val1 = readArgument();
        int val2 = readArgument();
        int val3 = readArgument();
        // Do some blink.
        }
     void doFade() {
        // same thing.
        }
      }

Now, if you want to transmit char data (strings, texts), put them at the as last parameter. You will need a third function to read a variable length string until end of the line (or some marker you choose).


body:
I finally figured out to get the unique value from the Car's Head panel input and send the command to the JVC radio as per the input.
Everything seems to be working fine, just the problem is the SendCommand(Key) function is not working properly as expected. It works sometimes, like sometimes I have to click the button twice or thrice to make it work, sometimes it works in the first time and some times it works twice even if i pressed it once...

But every times it shows that the key is there using Serial.println(Key) function... and it has been sent to the function SendCommand(Key) but still it doesn't works every time...

So just want to know that is there anything wrong in the code...

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(7, 5); // RX, TX
    String readString;

    //JVC Controls
    #define VOLUP       0x04
    #define VOLDOWN     0x05
    #define SOURCE      0x08
    #define EQUALIZER   0x0D
    #define MUTE        0x0E
    #define TRACKFORW   0x12
    #define TRACKBACK   0x13
    #define FOLDERFORW  0x14
    #define FOLDERBACK  0x15
    #define UNKNOWN1    0x37
    #define UNKNOWN2    0x58

    // Connect optocoupler input through a 1k resistor to this pin
    #define OUTPUTPIN   8 // D8
    // On-board LED, useful for debugging
    #define LEDPIN     13 // D13
    // Pulse width in µs
    #define PULSEWIDTH 527
    // Address that the radio responds to
    #define ADDRESS 0x47
    void setup()
    {
      Serial.begin(57600);
      //Serial.setTimeout(2000);
      mySerial.begin(9600);
      pinMode(OUTPUTPIN, OUTPUT);    // Set the proper pin as output
    }

    unsigned char GetInput(int number, int prevNumber)
    {
      if(number == 143)
        return TRACKBACK;
        else if(number == 140)
        return TRACKFORW;
        else if(number == 142)
        return FOLDERBACK;
        else if(number == 139)
        return FOLDERFORW;
        else if(number == 1)
        return VOLUP;
        else if(number == 255)
        return VOLDOWN;
        else if(number == 60)
        return MUTE;
        else if(prevNumber == 52 && (number == 32 || number == 37 || number == 38))
        return SOURCE;

        return 0;
    }

     int prevNumber=0;
    void loop() {

      while (mySerial.available()) {
        delay(10);
        int number = mySerial.read();
        mySerial.flush();
          unsigned char Key = GetInput(number, prevNumber);  // If any buttons are being pressed the GetInput() function will return the appropriate command code
          if (Key) {  // If no buttons are being pressed the function will have returned 0 and no command will be sent
            Serial.println(Key);
            SendCommand(Key);
        }
        prevNumber = number;

    }
    }

    // Send a value (7 bits, LSB is sent first, value can be an address or command)
    void SendValue(unsigned char value) {
      unsigned char i, tmp = 1;
      for (i = 0; i < sizeof(value) * 8 - 1; i++) {
        if (value & tmp)  // Do a bitwise AND on the value and tmp
          SendOne();
        else
          SendZero();
        tmp = tmp << 1; // Bitshift left by 1
      }
    }
    // Send a command to the radio, including the header, start bit, address and stop bits
    void SendCommand(unsigned char value) {
      unsigned char i;
      Preamble();                         // Send signals to precede a command to the radio
      for (i = 0; i < 3; i++) {           // Repeat address, command and stop bits three times so radio will pick them up properly
        SendValue(ADDRESS);               // Send the address
        SendValue((unsigned char)value);  // Send the command
        Postamble();                      // Send signals to follow a command to the radio
      }
    }
    // Signals to transmit a '0' bit
    void SendZero() {
      digitalWrite(OUTPUTPIN, HIGH);      // Output HIGH for 1 pulse width
      digitalWrite(LEDPIN, HIGH);         // Turn on on-board LED
      delayMicroseconds(PULSEWIDTH);
      digitalWrite(OUTPUTPIN, LOW);       // Output LOW for 1 pulse width
      digitalWrite(LEDPIN, LOW);          // Turn off on-board LED
      delayMicroseconds(PULSEWIDTH);
    }
    // Signals to transmit a '1' bit
    void SendOne() {
      digitalWrite(OUTPUTPIN, HIGH);      // Output HIGH for 1 pulse width
      digitalWrite(LEDPIN, HIGH);         // Turn on on-board LED
      delayMicroseconds(PULSEWIDTH);
      digitalWrite(OUTPUTPIN, LOW);       // Output LOW for 3 pulse widths
      digitalWrite(LEDPIN, LOW);          // Turn off on-board LED
      delayMicroseconds(PULSEWIDTH * 3);
    }
    // Signals to precede a command to the radio
    void Preamble() {
      // HEADER: always LOW (1 pulse width), HIGH (16 pulse widths), LOW (8 pulse widths)
      digitalWrite(OUTPUTPIN, LOW);       // Make sure output is LOW for 1 pulse width, so the header starts with a rising edge
      digitalWrite(LEDPIN, LOW);          // Turn off on-board LED
      delayMicroseconds(PULSEWIDTH * 1);
      digitalWrite(OUTPUTPIN, HIGH);      // Start of header, output HIGH for 16 pulse widths
      digitalWrite(LEDPIN, HIGH);         // Turn on on-board LED
      delayMicroseconds(PULSEWIDTH * 16);
      digitalWrite(OUTPUTPIN, LOW);       // Second part of header, output LOW 8 pulse widths
      digitalWrite(LEDPIN, LOW);          // Turn off on-board LED
      delayMicroseconds(PULSEWIDTH * 8);
      // START BIT: always 1
      SendOne();
    }
    // Signals to follow a command to the radio
    void Postamble() {
      // STOP BITS: always 1
      SendOne();
      SendOne();
    }

title: SendCommand(Key) function is not working properly using digitalWrite()

Answers: 0


body:
So I wired Sharp Dust Sensor with Arduino Mega with below fritzing:

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

the connector cable only connects to the dust sensor as you can seee the image below:

[![enter image description here][2]][2]
however looking at other example projects the same dust sensor has wiring inverted. I followed the hookup and the code as given here: https://www.elecrow.com/wiki/index.php?title=Dust_Sensor-_GP2Y1010AU0F

but I get the result without having to connect the green wire to **A0** and Yellow wire connected to **D2**

    Raw Signal Value (0-1023): 346.00 - Voltage: 1.69 - Dust Density: 0.19
    Raw Signal Value (0-1023): 394.00 - Voltage: 1.92 - Dust Density: 0.23
    Raw Signal Value (0-1023): 398.00 - Voltage: 1.94 - Dust Density: 0.23
    Raw Signal Value (0-1023): 408.00 - Voltage: 1.99 - Dust Density: 0.24
    Raw Signal Value (0-1023): 433.00 - Voltage: 2.11 - Dust Density: 0.26
    Raw Signal Value (0-1023): 468.00 - Voltage: 2.29 - Dust Density: 0.29

if I connect the yellow to **A0** And green to **D2**  then I get below result.

    Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1020.00 - Voltage: 4.98 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1020.00 - Voltage: 4.98 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1022.00 - Voltage: 4.99 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1020.00 - Voltage: 4.98 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1022.00 - Voltage: 4.99 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
    Raw Signal Value (0-1023): 1005.00 - Voltage: 4.91 - Dust Density: 0.73
    Raw Signal Value (0-1023): 952.00 - Voltage: 4.65 - Dust Density: 0.69
    Raw Signal Value (0-1023): 712.00 - Voltage: 3.48 - Dust Density: 0.49
    Raw Signal Value (0-1023): 631.00 - Voltage: 3.08 - Dust Density: 0.42
    Raw Signal Value (0-1023): 559.00 - Voltage: 2.73 - Dust Density: 0.36
    Raw Signal Value (0-1023): 504.00 - Voltage: 2.46 - Dust Density: 0.32
    Raw Signal Value (0-1023): 463.00 - Voltage: 2.26 - Dust Density: 0.28
    Raw Signal Value (0-1023): 431.00 - Voltage: 2.10 - Dust Density: 0.26
    Raw Signal Value (0-1023): 409.00 - Voltage: 2.00 - Dust Density: 0.24
    Raw Signal Value (0-1023): 430.00 - Voltage: 2.10 - Dust Density: 0.26
    Raw Signal Value (0-1023): 413.00 - Voltage: 2.02 - Dust Density: 0.24
    Raw Signal Value (0-1023): 377.00 - Voltage: 1.84 - Dust Density: 0.21
    Raw Signal Value (0-1023): 453.00 - Voltage: 2.21 - Dust Density: 0.28
    Raw Signal Value (0-1023): 368.00 - Voltage: 1.80 - Dust Density: 0.21
    Raw Signal Value (0-1023): 367.00 - Voltage: 1.79 - Dust Density: 0.20
    Raw Signal Value (0-1023): 364.00 - Voltage: 1.78 - Dust Density: 0.20
    Raw Signal Value (0-1023): 361.00 - Voltage: 1.76 - Dust Density: 0.20
    Raw Signal Value (0-1023): 357.00 - Voltage: 1.74 - Dust Density: 0.20
    Raw Signal Value (0-1023): 356.00 - Voltage: 1.74 - Dust Density: 0.20
    Raw Signal Value (0-1023): 358.00 - Voltage: 1.75 - Dust Density: 0.20
    Raw Signal Value (0-1023): 357.00 - Voltage: 1.74 - Dust Density: 0.20
    Raw Signal Value (0-1023): 345.00 - Voltage: 1.68 - Dust Density: 0.19
    Raw Signal Value (0-1023): 309.00 - Voltage: 1.51 - Dust Density: 0.16
    Raw Signal Value (0-1023): 375.00 - Voltage: 1.83 - Dust Density: 0.21
    Raw Signal Value (0-1023): 395.00 - Voltage: 1.93 - Dust Density: 0.23
    Raw Signal Value (0-1023): 421.00 - Voltage: 2.06 - Dust Density: 0.25
    Raw Signal Value (0-1023): 441.00 - Voltage: 2.15 - Dust Density: 0.27
    Raw Signal Value (0-1023): 343.00 - Voltage: 1.67 - Dust Density: 0.18
    Raw Signal Value (0-1023): 352.00 - Voltage: 1.72 - Dust Density: 0.19
    Raw Signal Value (0-1023): 341.00 - Voltage: 1.67 - Dust Density: 0.18
    Raw Signal Value (0-1023): 339.00 - Voltage: 1.66 - Dust Density: 0.18
    Raw Signal Value (0-1023): 342.00 - Voltage: 1.67 - Dust Density: 0.18
    Raw Signal Value (0-1023): 307.00 - Voltage: 1.50 - Dust Density: 0.15
    Raw Signal Value (0-1023): 335.00 - Voltage: 1.64 - Dust Density: 0.18
    Raw Signal Value (0-1023): 343.00 - Voltage: 1.67 - Dust Density: 0.18
    Raw Signal Value (0-1023): 348.00 - Voltage: 1.70 - Dust Density: 0.19
    Raw Signal Value (0-1023): 351.00 - Voltage: 1.71 - Dust Density: 0.19
    Raw Signal Value (0-1023): 355.00 - Voltage: 1.73 - Dust Density: 0.19
    Raw Signal Value (0-1023): 359.00 - Voltage: 1.75 - Dust Density: 0.20
    Raw Signal Value (0-1023): 456.00 - Voltage: 2.23 - Dust Density: 0.28
    Raw Signal Value (0-1023): 477.00 - Voltage: 2.33 - Dust Density: 0.30
    Raw Signal Value (0-1023): 392.00 - Voltage: 1.91 - Dust Density: 0.23
    Raw Signal Value (0-1023): 443.00 - Voltage: 2.16 - Dust Density: 0.27
    Raw Signal Value (0-1023): 419.00 - Voltage: 2.05 - Dust Density: 0.25
    Raw Signal Value (0-1023): 379.00 - Voltage: 1.85 - Dust Density: 0.21
    Raw Signal Value (0-1023): 292.00 - Voltage: 1.43 - Dust Density: 0.14
    Raw Signal Value (0-1023): 341.00 - Voltage: 1.67 - Dust Density: 0.18
    Raw Signal Value (0-1023): 311.00 - Voltage: 1.52 - Dust Density: 0.16
    Raw Signal Value (0-1023): 307.00 - Voltage: 1.50 - Dust Density: 0.15
    Raw Signal Value (0-1023): 284.00 - Voltage: 1.39 - Dust Density: 0.14
    Raw Signal Value (0-1023): 322.00 - Voltage: 1.57 - Dust Density: 0.17
    Raw Signal Value (0-1023): 309.00 - Voltage: 1.51 - Dust Density: 0.16
    Raw Signal Value (0-1023): 331.00 - Voltage: 1.62 - Dust Density: 0.17
    Raw Signal Value (0-1023): 326.00 - Voltage: 1.59 - Dust Density: 0.17
    Raw Signal Value (0-1023): 304.00 - Voltage: 1.48 - Dust Density: 0.15
    Raw Signal Value (0-1023): 340.00 - Voltage: 1.66 - Dust Density: 0.18
    Raw Signal Value (0-1023): 385.00 - Voltage: 1.88 - Dust Density: 0.22
    Raw Signal Value (0-1023): 399.00 - Voltage: 1.95 - Dust Density: 0.23
    Raw Signal Value (0-1023): 420.00 - Voltage: 2.05 - Dust Density: 0.25
    Raw Signal Value (0-1023): 448.00 - Voltage: 2.19 - Dust Density: 0.27
    Raw Signal Value (0-1023): 479.00 - Voltage: 2.34 - Dust Density: 0.30
    Raw Signal Value (0-1023): 424.00 - Voltage: 2.07 - Dust Density: 0.25
    Raw Signal Value (0-1023): 438.00 - Voltage: 2.14 - Dust Density: 0.26
    Raw Signal Value (0-1023): 438.00 - Voltage: 2.14 - Dust Density: 0.26
    Raw Signal Value (0-1023): 330.00 - Voltage: 1.61 - Dust Density: 0.17
    Raw Signal Value (0-1023): 352.00 - Voltage: 1.72 - Dust Density: 0.19
    Raw Signal Value (0-1023): 350.00 - Voltage: 1.71 - Dust Density: 0.19
    Raw Signal Value (0-1023): 343.00 - Voltage: 1.67 - Dust Density: 0.18
    Raw Signal Value (0-1023): 314.00 - Voltage: 1.53 - Dust Density: 0.16
    Raw Signal Value (0-1023): 305.00 - Voltage: 1.49 - Dust Density: 0.15
    Raw Signal Value (0-1023): 306.00 - Voltage: 1.49 - Dust Density: 0.15
    Raw Signal Value (0-1023): 317.00 - Voltage: 1.55 - Dust Density: 0.16
    Raw Signal Value (0-1023): 341.00 - Voltage: 1.67 - Dust Density: 0.18
    Raw Signal Value (0-1023): 361.00 - Voltage: 1.76 - Dust Density: 0.20
    Raw Signal Value (0-1023): 384.00 - Voltage: 1.88 - Dust Density: 0.22
    Raw Signal Value (0-1023): 417.00 - Voltage: 2.04 - Dust Density: 0.25
    Raw Signal Value (0-1023): 435.00 - Voltage: 2.12 - Dust Density: 0.26
    Raw Signal Value (0-1023): 446.00 - Voltage: 2.18 - Dust Density: 0.27
    Raw Signal Value (0-1023): 310.00 - Voltage: 1.51 - Dust Density: 0.16
    Raw Signal Value (0-1023): 462.00 - Voltage: 2.26 - Dust Density: 0.28
    Raw Signal Value (0-1023): 432.00 - Voltage: 2.11 - Dust Density: 0.26
    Raw Signal Value (0-1023): 391.00 - Voltage: 1.91 - Dust Density: 0.22
    Raw Signal Value (0-1023): 339.00 - Voltage: 1.66 - Dust Density: 0.18
    Raw Signal Value (0-1023): 324.00 - Voltage: 1.58 - Dust Density: 0.17
    Raw Signal Value (0-1023): 306.00 - Voltage: 1.49 - Dust Density: 0.15
    Raw Signal Value (0-1023): 294.00 - Voltage: 1.44 - Dust Density: 0.14
    Raw Signal Value (0-1023): 283.00 - Voltage: 1.38 - Dust Density: 0.13
    Raw Signal Value (0-1023): 274.00 - Voltage: 1.34 - Dust Density: 0.13

If I connect the green wire to **A0** and Yellow wire to **D2** I get below result

    Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
    Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
    Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
    Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
    Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
    Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10

I am not really sure whether I am getting the correct result or not, and have I hooked up correctly.

  [1]: https://i.stack.imgur.com/XG0xR.png
  [2]: https://i.stack.imgur.com/NXJMZ.jpg

title: Help setting up Dust sensor with Arduino Mega

Answers: 1

body:
The outline diagram shows the connection order:

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

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

As you can see from the image in the second row pin 1 is closest to the edge of the unit. In your image that is red.  So following those down and matching them to the "Terminal Configuration":

1. V-LED = Red (Connect to 5V via resistor)
2. LED-GND = Black (GND)
3. LED = Yellow (D2)
4. S-GND = White (GND)
5. Vo = Green (A0)
6. Vcc = Blue (Connect direct to 5V)


body:
I'm trying to read input data from the parallel port of a PC and send it to another device. For this purpose the input data is saved, when it's available and is sent if a flag is set.

The whole procedure should be done in less than 10 ms. I need to know the running time. How can I compute the CPU cycles for `ReadParallel` and `WriteParallel` functions (`digitalRead`, `digitalWrite`, `bitRead`,`bitWrite`) in my code or any other instructions?

Here is the code for the Arduino Uno:

    #define InterruptInputPin 2 // For checking if the input data is available
    #define InterruptSensorPin 3 // For checking when to send data

    #define IN0 A0
    #define IN1 A1
    #define IN2 A2
    #define IN3 A3

    #define OUT0 5
    #define OUT1 6
    #define OUT2 7
    #define OUT3 8

    volatile int ParallelInput; // The input data

    //*************************************
    void ReadParallel() //Reads input and saves it in parallelInput.
    {
      if (digitalRead(IN0) == HIGH)
        bitWrite(ParallelInput,0,1);
        else
          bitWrite(ParallelInput,0,0);

      if (digitalRead(IN1) == HIGH)
        bitWrite(ParallelInput,1,1);
        else
          bitWrite(ParallelInput,1,0);

      if (digitalRead(IN2) == HIGH)
        bitWrite(ParallelInput,2,1);
        else
          bitWrite(ParallelInput,2,0);

      if (digitalRead(IN3) == HIGH)
        bitWrite(ParallelInput,3,1);
        else
          bitWrite(ParallelInput,3,0);

    }
    //***************************************

    void WriteParallel() //Writes ParallelInput to output.
    {
      detachInterrupt(digitalPinToInterrupt(InterruptInputPin));
      digitalWrite(OUT0,bitRead(ParallelInput,0));
      digitalWrite(OUT1,bitRead(ParallelInput,1));
      digitalWrite(OUT2,bitRead(ParallelInput,2));
      digitalWrite(OUT3,bitRead(ParallelInput,3));
      attachInterrupt(digitalPinToInterrupt(InterruptInputPin),ReadParallel,RISING);

    }

    void setup() {

      pinMode(IN0,INPUT);
      pinMode(IN1,INPUT);
      pinMode(IN2,INPUT);
      pinMode(IN3,INPUT);

      pinMode(OUT0,OUTPUT);
      pinMode(OUT1,OUTPUT);
      pinMode(OUT2,OUTPUT);
      pinMode(OUT3,OUTPUT);
      attachInterrupt(digitalPinToInterrupt(InterruptInputPin),ReadParallel,RISING);

    attachInterrupt(digitalPinToInterrupt(InterruptSensorPin),WriteParallel,RISING);

    }

    void loop() {

    }

title: The exact time for functions or CPU cycles for any function

Answers: 3

body:
There's two methods:

1. Profiling.
2. Clock counting.

The first method involves recording timestamps at different points in your program and calculating the time difference between them. That's the simplest, but not always the most accurate.

The second method is far harder and involves disassembling the program after you have compiled it (or obtaining the assembly language from part way through the compilation sequence) and examining all the assembly instructions, looking them up in the instruction list, and totalling how many clock cycles are used for each instruction. That gets very complex, especially when you have loops. However it will tell you precisely how many clock cycles, and thus how long, a block of code will take to execute (not including interrupts, which always throw a big spanned in the works).

body:
## Method summary

(section added on 2018-01-28)

There are several methods available for timing code. I am adding this
preliminary section to my answer in order to provide comparative data on
several methods. The methods covered in the table below are those
proposed as answers to both this question and a [duplicate question of
this][duplicate]. As this question has been tagged “arduino-uno”, all
this data assumes an AVR-based board clocked at 16 MHz.

Method comparison:

    | method         | resolution    | max. time       | typ. overhead  |
    |----------------|---------------|-----------------|----------------|
    | `millis()`     | 1 – 2 ms      | 49.7 days       | 0.69 – 1.3 µs  |
    | `micros()`     | 4 µs          | 71.6 min        | 2.8 – 2.9 µs   |
    | Timer 1        | 0.0625 µs     | 4.096 ms        | 0.25 – 0.5 µs  |
    | pin toggling   | scope-limited | ∞               | 0.125 µs       |
    | cycle counting | 0.0625 µs     | boredom-limited | 0              |
    | looping        | N.A.          | N.A.            | 0.25 µs        |

The methods are characterized by the following criteria:

* **Resolution** is the granularity of the measurement, the smaller the
  better.
* **Maximum measurable time**: any method that does timing arithmetics
  on the Arduino is prone to overflows if measuring too long times. Note
  that a timer rolling over to zero during the measurement [is not a
  problem][rollover], as long as the period being measured is less than
  the rollover period.
* **Typical measurement overhead**: the code used to measure the timings
  takes itself a finite time to execute, thus one ends up measuring the
  execution time of the “instrumented” code, which is slightly larger
  than the time taken by the code one is trying to profile. This
  overhead should in principle be subtracted from the result, but it is
  often not known exactly, as it depends on how the compiler optimizes
  _both_ the instrumented and the non-instrumented code.

The methods listed in the table are:

* **`millis()`**, which may be the most obvious choice, as it is so well
  known. Its low resolution, however, makes it ill-suited for timing
  code execution. It should be noted that the `millis()` counter is
  incremented every 1024 µs. Most of the time it is incremented by
  1 but, every 43 ms (roughly) it is incremented by 2 in order to
  avoid creeping drift. This is why its resolution is stated as
  “1 – 2 ms” in the table.
* **`micros()`**, as proposed in [ratchet freak's answer][], is usually
  a good choice, the main caveat being the 4 µs resolution, when
  one could naively expect 1 µs. It also has a significant
  overhead.
* **Timer 1**, which is discussed in the second part of this answer, is
  my favorite: it has single cycle resolution and low overhead. However,
  it is incompatible with other uses of the timer (PWM, Servo
  library...). It is also limited to measuring small delays.
* **Pin toggling**, as [proposed by 4ilo][], and by myself in the third
  part of this answer, is ideal if you have an oscilloscope handy. Any
  half-decent scope should provide single-cycle resolution. It is also
  minimally invasive on the code being measured and has minimal
  overhead.
* **Cycle counting**, as proposed in [Majenko's answer][], is arguably
  the “perfect” method: it is cycle-accurate, does not modify the code
  and has zero overhead. However, for anything beyond a handful
  instructions, it quickly becomes tedious. And it requires some
  understanding of the AVR assembly.
* **Looping**, as proposed in [Michel Keijzers' answer][], is not a
  measurement technique _per se_. It is meant to be used in conjunction
  with another technique in order to improve the resolution and dilute
  the overhead. However, lopping carries it's own overhead, which is
  typically 4 CPU cycles _per iteration_, assuming a 16-bit loop
  counter.

[duplicate]: https://arduino.stackexchange.com/questions/48922
[rollover]: https://arduino.stackexchange.com/questions/12587
[ratchet freak's answer]: https://arduino.stackexchange.com/a/48923
[proposed by 4ilo]: https://arduino.stackexchange.com/a/48987
[Majenko's answer]: https://arduino.stackexchange.com/a/45835
[Michel Keijzers' answer]: https://arduino.stackexchange.com/a/45846

------------------------------------------------------------------------

## Using Timer 1

(original answer of 2017-10-23)

One technique I often use is to make Timer 1 count at the full CPU speed
and use it to time the code I want to profile. For example:

    volatile uint8_t pin = 2;
    volatile uint8_t value = HIGH;

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

        // Set Timer 1 to normal mode at F_CPU.
        TCCR1A = 0;
        TCCR1B = 1;

        // Time digitalWrite().
        cli();
        uint16_t start = TCNT1;
        digitalWrite(pin, value);
        uint16_t finish = TCNT1;
        sei();
        uint16_t overhead = 8;
        uint16_t cycles = finish - start - overhead;
        Serial.print("digitalWrite() took ");
        Serial.print(cycles);
        Serial.println(" CPU cycles.");
    }

    void loop(){}

Note the `volatile` variables used to prevent the compiler from
optimizing them as constants.

Note also that when you profile some code you are inevitably slowing it
down, because of the time taken by the profiling operations themselves.
This is what the `overhead` variable above accounts for. In order to
know the exact overhead, I start with a guess, compile and disassemble,
and then count the number of clock cycles spent in profiling that will
be counted by the timer. Then I adjust the `overhead` value, compile and
disassemble again, and make sure the overhead has not changed. This is
also when you have to ask yourself what exactly you want to count. Here
I am counting the time needed to execute `call digitalWrite`, but not
the time needed to get the arguments in the proper registers, as I am
artificially slowing this down by making them `volatile`.

This method is good for anything that takes more than roughly a dozen,
and less that 65,536 clock cycles. Less than that, clock counting would
be simpler, since you still have to clock-count the overhead. More than
that, the count would overflow, and you could instead just use
`micros()`, and live with its inherent inaccuracy.

------------------------------------------------------------------------

## Toggling a pin

(section added on 2017-10-23)

If you have a scope, there is another method that is minimally
invasive on your code: toggle a pin just before and just after the thing
you want to time. E.g., assuming you have previously
`pinMode(13, OUTPUT)`:

    // Set pin 13 HIGH.
    PORTB |= _BV(PB5);

    // The thing we want to time.
    ...

    // Set pin 13 LOW.
    PORTB &= ~_BV(PB5);

This will create a pulse that you can measure on the scope. Note that
using direct port access, like here, the overhead is only two CPU cycles,
or 125 ns. Also, direct port access won't use any CPU register, so
chances are the compiler will not generate less efficient code than when
not including the timing part.

body:
To efficiently measure the time a block of code takes, run it for like 1,000 or 1,000,000 times and divide the time by the amount of iterations.

In some cases initialization/variables can be cached but in principle the times are quite accurate. You can easily check this by doing the test for e.g. 1,000 and 2,000 times and see that the time difference also is a factor 2.

For the time counter, use an unsigned long type to accommodate more than 65,535 (ms/us whatever the unit is used).


body:
Arduino Uno

I'm currently working on a project which will involve entering a sequence on a 12V keypad. The keypad and its documentation can be found here: https://www.jaycar.com.au/digital-keypad-with-rfid-access-control/p/LA5353

[![key pad][1]][1]

They keypad wants 9-18V AC/12~24V DC. I'll be using the keypad to output 26 bit Wiegand to the Arduino. I'm just wondering the best way to power this system. The schematics included with the keypad show that the keypad and the controller  (Arduino) should be sharing a power source. See image attached.

How can I power the 12-24V keypad through the arduino without frying it?

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

  [1]: https://i.stack.imgur.com/iIhjO.jpg
  [2]: https://i.stack.imgur.com/QlAli.png

title: Powering 12V keypad through Arduino Uno

Answers: 1

body:
> How can I power the 12-24V keypad through the arduino without frying it?

If you power the Arduino with slightly more than 12V (through the barrel jack) then you can get 12V (or slightly less than you power the Arduino with) from the VIN pin.

However the Arduino's on-board voltage regulator does tend to get a little hot when such a high voltage is used to power it. Better is just to power the keypad separately from the correct power source.

*And don't forget to connect the grounds together.*


body:
I am a student and currently doing a semester project. The first goal is to get accelerometer and gyroscope data from FIS1100 using the Arduino (Uno). I've got the FIS1100 Evaluation Kit [user guide][1] from my supervisor. I've simply separated the sensor PCB from the MCU and connected this sensor to an Arduino Uno as shown on this photo:

[![FIS+Arduino][2]][2]

The connections are as following:

- SCL (on the header of FIS) - A5 (Arduino)
- SDA (on the header of FIS) - A4 (Arduino)
- GND (on the header of FIS) - GND (Arduino)
- 3V3-to VIOREF (on the header of FIS) - 3V3 (Arduino)

I wrote this simple code, which I uploaded to the Arduino board. Unfortunately as a result, I got zeros as output.

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

    #include <Wire.h>
    const int I2C_address = 0b1101010;
    long a_X, a_Y, a_Z;
    float g_X, g_Y, g_Z;

    long gyro_X, gyro_Y, gyro_Z;
    float rot_X, rot_Y, rot_Z;

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

    }

    void loop() {
      recordAccelRegisters();
      recordGyroRegisters();
      printData();
      delay(800);

    }

    void setupFIS(){
      Wire.beginTransmission(I2C_address);
      Wire.write(0x02);
      Wire.write(0b00000000);
      Wire.endTransmission(true);

      Wire.beginTransmission(I2C_address);
      Wire.write(0x08);
      Wire.write(0b10000011);
      Wire.endTransmission(true);

      Wire.beginTransmission(I2C_address);
      Wire.write(0x04);
      Wire.write(0b00000000);
      Wire.endTransmission(true);

      Wire.beginTransmission(I2C_address);
      Wire.write(0x03);
      Wire.write(0b00000000);
      Wire.endTransmission(true);

      Wire.beginTransmission(I2C_address);
      Wire.write(0x05);
      Wire.write(0b00000000);
      Wire.endTransmission(true);

      Wire.beginTransmission(I2C_address);
      Wire.write(0x06);
      Wire.write(0b00000000);
      Wire.endTransmission(true);

      Wire.beginTransmission(I2C_address);
      Wire.write(0x07);
      Wire.write(0b00000000);
      Wire.endTransmission(true);
    }

    void recordAccelRegisters(){
      Wire.beginTransmission(I2C_address);
      Wire.write(0x19);
      Wire.endTransmission(false);
      Wire.requestFrom(I2C_address,6,true);
      //while(Wire.available()<6);
      a_X = Wire.read()<<8|Wire.read();
      a_Y = Wire.read()<<8|Wire.read();
      a_Z = Wire.read()<<8|Wire.read();
      processAccelData();
    }

    void processAccelData(){
      g_X = a_X/16384.0;
      g_Y = a_Y/16384.0;
      g_Z= a_Z/16384.0;
    }

    void recordGyroRegisters(){
      Wire.beginTransmission(I2C_address);
      Wire.write(0x1F);
      Wire.endTransmission(false);
      Wire.requestFrom(I2C_address,6,true);
      //while(Wire.available()<6);
      gyro_X = Wire.read()<<8|Wire.read();
      gyro_Y = Wire.read()<<8|Wire.read();
      gyro_Z = Wire.read()<<8|Wire.read();
      processGyroData();
    }

    void processGyroData(){
      rot_X = gyro_X/1024.0;
      rot_Y = gyro_Y/1024.0;
      rot_Z= gyro_Z/1024.0;
    }

    void printData(){
      Serial.print("Gyro(deg)");
      Serial.print(" X=");
      Serial.print(rot_X);
      Serial.print(" Y=");
      Serial.print(rot_Y);
      Serial.print(" Z=");
      Serial.print(rot_Z);

      Serial.print("   Accel(g)");
      Serial.print(" X=");
      Serial.print(g_X);
      Serial.print(" Y=");
      Serial.print(g_Y);
      Serial.print(" Z=");
      Serial.println(g_Z);
    }

So, I really need help to get some relevant data.

And also I have doubts concerning the I2C-address of the FIS1100. In the datasheet of the FIS1100 on page 50 it is said:

>the address is 0b1101010 in case when pin SA0 is left unconnected, internally there is a weak pull-down of 200k; the address is 0b1101011 in case when pin SA0 is pulled-up externally.

Now lets go again to user guide and on page 25 (schematic of pull-up/down resistors) we see that SA0 is externally pulled-down.

Question: which I2C-address should I use?

  [1]: https://www.fairchildsemi.com/evaluation-boards/febfis1100mems_imu6d3x.pdf
  [2]: https://i.stack.imgur.com/fSGii.jpg

title: FIS1100 (IMU)/ I2C/ Arduino

Answers: 1

body:
I think you'll find you need to add some pull up resistors to both connections on the I2C (SDA and SCL).

Also I'm not sure what you should be pulling them up to 3.3v or 5v.  You should check if you need a level shifter or if the device you are connecting is 5v tolerant.

According to you question you should be using the address 0x6A.  0x6B is when you have an external pull up resistor, which I don't think you do have.  So your code is correct.


body:
I'm trying to receive an SMS and show it on the serial monitor.

My code is as following:

    void setup()
    {

      Serial.begin(2400);
      Serial.write("AT+CMGF=1\r");           //set GSM to text mode
      delay(1500);

      Serial.write("AT+CPMS=\"SM\"\r");         //Preferred SMS Message Storage
      delay(1000);

      Serial.write("AT+CMGL=\"ALL\"\r");       //List SMS Messages from Preferred Storage
      while(1)
      {
        if(Serial.available())
        {
          Serial.write(Serial.read());
        }
      }
    }

    void loop()
    {
    }

The circuit diagram is as shown below.

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

The output that I am getting is as following:

    AT+CMGR=1
    AT+CMGF=1

    OK
    AT+CPMS="SM"

    ERROR
    AT+CMGR=1
    AT+CMGF=1

    OK
    AT+CPMS="SM"

    ERROR

    ERROR
    AT+CMGR=1
    AT+CMGF=1

I am not able to use `AT+CPMS` or `AT+CMGL` commands.

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

title: Unable to receive and print SMS on the serial monitor with Arduino Uno and SIM900A

Answers: 3

body:
The `Arduino UNO` that you are using only supports one Serial connection (over the `TX` and `RX` pins). Since you are using these pins to talk to the device, you cannot also send data over Serial.

Read [this article](https://www.arduino.cc/en/Reference/Serial) to see more about `Serial` and how it works on different boards.

body:
The RX/TX pins are on Uno connected to the USB chip. If you connect a device to RX/TX, you should not use Serial Monitor. It sometimes works, but the device receives the data send to Serial Monitor too and can't process them.

Use SoftwareSerial library for connecting the serial device, if you want to have Serial free for printing to Serial Monitor over USB.

body:
As others have stated, you **cannot** use the hardware serial port for communication with the device **and** communication over the USB cable.

**OPTION 1**

Switch to a different microcontroller, such as the arduino mega with multiple hardware serial ports on board.

**OPTION 2**

Implement the Software Serial library for communication with the sim card device and use the hardware serial for communication with your computer.

*Note: Software Serial implementations are more computationally intensive than the use of hardware serial. Do not expect the same performance from a software serial implementation and do not expect to be able to smoothly run multiple instances of it on a single 8 bit mcu.*

Example Code (Untested):

      #include <SoftwareSerial.h>

      void setup()
      {
      Serial.begin(9600);
      SoftwareSerial mySerial(10,11); //RX,TX pins
      mySerial.begin(2400);
      mySerial.write("AT+CMGF=1\r");           //set GSM to text mode
      delay(1500);

      mySerial.write("AT+CPMS=\"SM\"\r");         //Preferred SMS Message Storage
      delay(1000);

      mySerial.write("AT+CMGL=\"ALL\"\r");       //List SMS Messages from Preferred Storage
      while(1)
      {
        if(mySerial.available())
        {
          Serial.write(mySerial.read());
        }
      }
    }

    void loop(){}

Disconnect from pin 0 and pin 1 and connect to pins 10 and 11 respectively.


body:
I currently have a ton of 4 Digit 7 Segmented displays(TOFD-5465GGH-B).

[![display][1]][1]

The display is driven by a PT6961 LED Driver. Using a Library that I found [here][2] I was able to use the display with no issues. The pin out on the display is as such:

    1) 5V
    2) CS
    3) CLK
    4) DIN
    5) DOUT
    6) Common

Since the display has a DOUT does this mean I can run multiple display is series off of the same pins? If so, can someone point me in the right direction to do so. I am currently using a Particle Photon and I am limited as to the number of PWM pins.

  [1]: https://i.stack.imgur.com/eyQac.jpg
  [2]: http://gtbtech.com/?p=528

title: Using Multiple 4 Digit displays with the same pins

Answers: 1

body:
That is an SPI interface.  Using multiples should be easy.  Each one has a CS pin.  When that pin is pulled low it selects that chip as the one you are talking to.  Several displays could all share the CLK, DIN, and DOUT pins on the Arduino and each would have it's own pin on the Arduino for CS.  To update any given display, you pull its CS pin low and then transmit your data.  If you pull the CS pins on two displays low at the same time you'll send the data to both.  Whichever has the CS pin pulled low on it is the one that listens.

Google SPI and do a little investigation on SPI with Arduino.  That will help you learn a little about how SPI works and you will certainly get your question fully answered about how to drive multiple chips while sharing pins.  Driving multiple things with the same pins is the whole point of SPI.

The connection would look like this for an UNO -

Pin 13  ----  CLK pin on all chips

Pin 12  ----  DOUT on all chips

Pin 11  ----  DIN on all chips

Choose a different pin on Arduino for each chip and connect to the CS pin.

To use SPI, pin 10 MUST be configured as an output.  It cannot be an input.  So it would be a good idea to use 10 for one of the CS pins just to make sure it is going to stay an output.

EDIT:

I just looked at the page you linked to and it looks like the library you are using isn't using the SPI hardware but is bit-banging SPI from software using other pins.  The concept is still the same, all share CK and DIN and the CS pin picks the one you're talking to.

The code would be a lot faster and much more compact if you changed this library to use the SPI hardware instead of software.  It just limits which pins you have to use to the ones I listed above.

EDIT AGAIN:

I feel generous and it was really really really easy to do so I switched his code to run on the SPI hardware.  It compiles but hasn't been tested.  It should work though.  Hooking DOUT to pin 12 is optional, but you still can't use pin 12 for anything else so you might as well.

PT6961_SPI.h

    /*
      PT6961.h - Library for communicating with PT6961 LED driver.
      Created by Garrett Blanton January, 16, 2013.
      Released into the public domain.
    */

    #ifndef PT6961_SPI_H_
    #define PT6961_SPI_H_

    #include "Arduino.h"
    #include <SPI.h>

    class PT6961
    {
      public:

        PT6961(uint8_t CS);
        void initDisplay();
        void initRAM();
        void sendCmd(char cmd);
        void sendDigit(char digit, char val);
        void sendNum(int num, char colon);
        void sendDigits(char digit1, char digit2, char digit3, char digit4, char colon);

        const static char _DISPLAY_6X12 = 0x02;
        const static char _DISPLAY_7X11 = 0x03;
        const static char _AUTO_INCREMENT = 0x40;
        const static char _FIXED_ADDRESS = 0x44;
        const static char _DISPLAY_OFF = 0x80;
        const static char _DISPLAY_1_16 = 0x88;
        const static char _DISPLAY_2_16 = 0x89;
        const static char _DISPLAY_4_16 = 0x8A;
        const static char _DISPLAY_10_16 = 0x8B;
        const static char _DISPLAY_11_16 = 0x8C;
        const static char _DISPLAY_12_16 = 0x8D;
        const static char _DISPLAY_13_16 = 0x8E;
        const static char _DISPLAY_14_16 = 0x8F;

      private:

        uint8_t _CS;

    };

    #endif

PT6961_SPI.cpp

    /*
     PT6961.cpp - Library for communicating with PT6961 LED driver.
     Created by Garrett Blanton January, 16, 2013.
     Released into the public domain.
     */

    //0 - A
    //1 - B
    //2 - C
    //3 - D
    //4 - E
    //5 - F
    //6 - G
    //7 - Colon
    #include "Arduino.h"
    #include "PT6961_SPI.h"

    PT6961::PT6961(uint8_t CS) {

     pinMode(CS, OUTPUT);
     _CS = CS;

     SPI.begin();
     SPI.setBitOrder(LSBFIRST);

    }

    void PT6961::initDisplay() {
     sendCmd(_DISPLAY_6X12);
     sendCmd(_AUTO_INCREMENT);
     initRAM();
     sendCmd(_DISPLAY_14_16);
    }

    // Initializes RAM to all zeros
    void PT6961::initRAM() {
     //first clear 8 bytes of the display RAM
     digitalWrite(_CS, LOW);
    // shiftOut(_DIN, _CLK, LSBFIRST, 0xC0);
     SPI.transfer(0xC0);
     for (int i = 0; i < 8; i++) {
    //  shiftOut(_DIN, _CLK, LSBFIRST, 0x00);
      SPI.transfer(0x00);
     }
     digitalWrite(_CS, HIGH);
    }

    // Use to send command based on enumeration
    void PT6961::sendCmd(char cmd) {
     digitalWrite(_CS, LOW);
    // shiftOut(_DIN, _CLK, LSBFIRST, cmd);
     SPI.transfer(cmd);
     digitalWrite(_CS, HIGH);
    }

    void PT6961::sendDigit(char digit, char val) {
     digitalWrite(_CS, LOW);
    // shiftOut(_DIN, _CLK, LSBFIRST, digit);
    // shiftOut(_DIN, _CLK, LSBFIRST, val);
     SPI.transfer(digit);
     SPI.transfer(val);
     digitalWrite(_CS, HIGH);
    }

    void PT6961::sendNum(int num, char colon) {
     int digit1 = num / 1000;
     int digit2 = (num % 1000) / 100;
     int digit3 = (num % 100) / 10;
     int digit4 = (num % 10);

     sendDigits(digit1, digit2, digit3, digit4, colon);
    }

    void PT6961::sendDigits(char digit1, char digit2, char digit3, char digit4,
      char colon) {

     const char DISP[17] = { 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
       0x7f, 0x6f, 0x77, 0x7c, 0x58, 0x5e, 0x79, 0x71, 0x61 };

     digitalWrite(_CS, LOW);
    // shiftOut(_DIN, _CLK, LSBFIRST, 0xC0);
     SPI.transfer(0xC0);

     if (colon == 1) {
    //  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit1] | 0x80);
      SPI.transfer(DISP[digit1] | 0x80);
     } else {
    //  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit1]);
      SPI.transfer(DISP[digit1]);
     }

    // shiftOut(_DIN, _CLK, LSBFIRST, 0xC2);
     SPI.transfer(0xC2);

     if (colon == 1) {
    //  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit2] | 0x80);
      SPI.transfer(DISP[digit2] | 0x80);
     } else {
    //  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit2]);
      SPI.transfer(DISP[digit2]);
     }

    // shiftOut(_DIN, _CLK, LSBFIRST, 0xC4);
     SPI.transfer(0xC4);
    // shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit3]);
     SPI.transfer(DISP[digit3]);
    // shiftOut(_DIN, _CLK, LSBFIRST, 0xC6);
     SPI.transfer(0xC6);
    // shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit4]);
     SPI.transfer(DISP[digit4]);
     digitalWrite(_CS, HIGH);
    }

Example.ino

    #include "Arduino.h"
    #include <SPI.h>
    #include "PT6961_SPI.h"

    PT6961 LED(10);   /// This is the pin number for CS pin on each chip
    // PT6961 LED2(9);  // The next might look like this if it were connected to pin 9
    void setup()
    {
         LED.initDisplay();
         Serial.begin(9600);
    }

    void loop()
    {
         //count through 0-9,a-f
         for(int i=0; i<16; i++)
         {
              LED.sendDigits(0,0,0,i,0);
              Serial.println(i);
              delay(500);
         }
    }


body:
Arduino Mega 2560 board and SN74HC595 shift register(s). I'm working on a school assignment and having issues getting the shift register(s) working without using Arduino libraries.

I know with the libraries you can use functions such as `digitalWrite(....);` and `shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);`.

For my project, I've set up my individual pins as inputs and outputs, but I am having trouble converting the library code into basic code.

IE:

    digitalWrite(latchPin, LOW);

can be rewritten as

    DDRB &= ~(1 << DDB1);

where `latchPin` is the `SCK` pin.

At this stage in the project, we're just trying to get 8 LEDs lit up using 1 shift register, then 16 using 2 shift registers. Any help in understanding what I need to do or direction in which to look would be appreciated.

Thank you,

Nic

Edit:

This is what I have converted from the void setup from <https://www.arduino.cc/en/Tutorial/ShftOut12> :

    void setup() {
      //Clear the shift registers prev data, Need a low input to reset registers
      //PORTL0 to first SReg SRCLR, PORTL2 to second SReg SRCLR
      //* See data sheet for sn74hc595 shift registers
      DDRL &= ~((1 << PORTL0) | (1 << PORTL2)); //Pg 100 - 21.2.3
      //Use port L0/L2 for SRCLR pin on SReg
      PORTL |= (1 << PORTL0) | (1 << PORTL2); //Pg 100 - 21.2.3

      //Set OE (Enable) to 0 until after last bit is sent
      DDRL &= ~(1 << PORTL4); //Pg 100 - 21.2.3
      //TODO SPI DELAY HERE USING SPDR pg 199

      //Enable SCK as output to drive RCLK and SRCLK on SR
      DDRB &= ~(1 << DDB1); //Pg 96 - 13.4.6
      PORTB |= (1 << PORTB1); //Pg 96 - 13.4.5

      //Enable MOSI as output to drive SER Input on SR
      DDRB &= ~(1 << DDB0); //Pg 96 - 13.4.6
      PORTB |= (1 << PORTB0); //Pg 96 - 13.4.5

      Serial.begin(9600);
      Serial.println("reset");
    }

title: Using SPI and 2 shift registers WITHOUT libraries

Answers: 2

body:
My strategy: Write the sketch using the standard Arduino library. The goal is have the LED lit up, as you need.

Then, change all standard function calls in your sketch (like `digitalWrite`) with your own (called it `digitalWrite2`).

Now implement `digitalWrite2` using register manipulation.

Pros:

 - Divide and conquer. You know have two independent smaller problems (LED and registers).
 - When is time to implement digitalWrite2 you can learn from your classmate how to do that. I bet that they will start with the hard part (register manipulation).
 - It makes for a easier debuging. You can compare your own implementation against the standard implementation just by deleting/adding a single "2" in the call.

Of course, taking a look at the Arduino source code will made things trivial :-)
Is that cheating? No, we learn from others, we learn reading other people's code.

**Edit: Step by Step Example**

Let use Blink to show how to do it:

**Original**

    void setup() {
      pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }

For the new version I will replace `pinMode` and `digitalWrite` for the my own  implementation them. How?

Go to the directory where you put your Arduino binaries, which include the source code. There is a subdirectory with the sources (mine is ~/bin/arduino-1.8.3/hardware/arduino/avr/cores/arduino).

There is a file (wiring_digital.c) where I found the source code for `pinMode` and `digitalWrite`. Without any shame, I copy-paste and rename.

Note: the original includes a call to `turnOffPWM`, which I simply comment out, because we will not use it here and I want to cut it short.

That's all.

**New version**

    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode2(LED_BUILTIN, OUTPUT);
    }

    void loop() {
      digitalWrite2(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite2(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }

    void pinMode2(uint8_t pin, uint8_t mode)
    {
      uint8_t bit = digitalPinToBitMask(pin);
      uint8_t port = digitalPinToPort(pin);
      volatile uint8_t *reg, *out;

      if (port == NOT_A_PIN) return;

      // JWS: can I let the optimizer do this?
      reg = portModeRegister(port);
      out = portOutputRegister(port);

      if (mode == INPUT) {
        uint8_t oldSREG = SREG;
                    cli();
        *reg &= ~bit;
        *out &= ~bit;
        SREG = oldSREG;
      } else if (mode == INPUT_PULLUP) {
        uint8_t oldSREG = SREG;
                    cli();
        *reg &= ~bit;
        *out |= bit;
        SREG = oldSREG;
      } else {
        uint8_t oldSREG = SREG;
                    cli();
        *reg |= bit;
        SREG = oldSREG;
      }
    }

    void digitalWrite2(uint8_t pin, uint8_t val)
    {
      uint8_t timer = digitalPinToTimer(pin);
      uint8_t bit = digitalPinToBitMask(pin);
      uint8_t port = digitalPinToPort(pin);
      volatile uint8_t *out;

      if (port == NOT_A_PIN) return;

      // If the pin that support PWM output, we need to turn it off
      // before doing a digital write.
      // if (timer != NOT_ON_TIMER) turnOffPWM(timer); By Look Alterno

      out = portOutputRegister(port);

      uint8_t oldSREG = SREG;
      cli();

      if (val == LOW) {
        *out &= ~bit;
      } else {
        *out |= bit;
      }

      SREG = oldSREG;
    }

[![Pablo Picasso][1]][1]

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

body:
The main problem you seem to have is how to implement `shiftOut`. Well, that's actually quite simple once you understand how `shiftOut` actually works.

You already know how to set a pin HIGH or LOW - all you lack from that is the concept of *time*.

All `shiftOut` does is set the clock and data pins HIGH and LOW at the right *time*.

It's simply a case of:

1. Set the DATA pin to HIGH or LOW depending on the bit value to send
2. Set the CLOCK pin HIGH
3. Set the CLOCK pin LOW
4. Go back to 1 for 8 iterations total.

Getting the bit value from a byte can be done with boolean operators `&` and `<<`

The basic `shiftOut` code looks like this:

    void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
    {
        uint8_t i;

        for (i = 0; i < 8; i++)  {
            if (bitOrder == LSBFIRST)
                digitalWrite(dataPin, !!(val & (1 << i)));
            else
                digitalWrite(dataPin, !!(val & (1 << (7 - i))));

            digitalWrite(clockPin, HIGH);
            digitalWrite(clockPin, LOW);
        }
    }

Since your bit order is fixed you can reduce that down to this:

    void myShiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t val)
    {
        uint8_t i;

        for (i = 0; i < 8; i++)  {
            digitalWrite(dataPin, !!(val & (1 << (7 - i))));
            digitalWrite(clockPin, HIGH);
            digitalWrite(clockPin, LOW);
        }
    }

And then you can replace your `digitalWrite` calls with direct register manipulation.

    void myShiftOut(uint8_t val)
    {
        uint8_t i;

        for (i = 0; i < 8; i++)  {
            if (val & (1 << (7 - i))) {
                PORTB |= (1 << PORTB0);  // Data 1
            } else {
                PORTB &= ~(1 << PORTB0); // Data 0
            }
            PORTB |= (1 << PORTB1);      // Clock HIGH
            PORTB &= ~(1 << PORTB1);     // Clock LOW
        }
    }

Note that this code will now run considerably faster than the bloaty `digitalWrite` based version - so you may find it's now too fast. You may need to include some short delays around the clock HIGH and clock LOW lines. Depending on how long they need to be you could write a little delay loop to introduce a short delay:

    void delayLoop(uint32_t iterations) {
        while ((--iterations) > 0) {
            asm volatile("nop");
        }
    }

That will delay for `iterations` clock cycles plus the time taken to do the loop and call the function.  For very short delays it may be better to just insert a few `nop` instructions:

    PORTB |= (1 << PORTB1);      // Clock HIGH
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    PORTB &= ~(1 << PORTB1);     // Clock LOW
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");


body:
I am new to Arduino and I'm trying my first Pro Mini. I was able to find OLED display code from github that runs perfectly. My problem is trying to show 3 hex bytes sent by a remote control decoder module on the display.

The code will run under serial monitor with `serial.print("I Received");` and `serial.println(incomingByte, HEX);`.

I want to receive this code on the serial port and display it on the OLED screen.

Any help is welcome.

I attached my code any help will be appreciated.

    int incomingByte = 0
    void setup() (
      Serial.begin(9600)
    )

    void loop() (
      if (serial.available() > 0) (
        incomingByte = Serial.read();
        u8g.drawStr(10, 37" I Received"); //glcd text position
        u8g.setPrintPos(10,42);
        u8g.print(incomingByte, HEX);
      )
    )

title: Displaying 3 hex bytes sent to serial port on an OLED display

Answers: 1

body:
I'm going to assume you know the difference and significance between {} and () and the fact that the code you pasted in had a few syntax issues.

Below is a copy which should compile (I haven't tried it) I added a check to see if `Serial.read()` returned data, but otherwise its what you had.

    int incomingByte = 0;
    void setup()
    {
        Serial.begin(9600);
    }

    void loop()
    {
        if (Serial.available() > 0)
        {
            incomingByte = Serial.read();
            if (incommingByte != -1)
            {
                u8g.drawStr(10, 37, " I Received"); //glcd text position
                u8g.setPrintPos(10, 42);
                u8g.print(incomingByte, HEX);
            }
        }
    }

You've not actually said if the code works or not.  Please can you try this version and report the results.


body:
I am trying to use a nRF24L01+PA with an ATmega328P minimal breadboard system. I first connected the module to my Uno and verified it with the "scanner" example sketch from the rf24 library, which showed:

    STATUS   = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
    RX_ADDR_P0-1  = 0xe7e7e7e7e7 0xc2c2c2c2c2
    RX_ADDR_P2-5  = 0xc3 0xc4 0xc5 0xc6
    TX_ADDR   = 0xe7e7e7e7e7
    RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
    EN_AA   = 0x00
    EN_RXADDR  = 0x03
    RF_CH   = 0x4c
    RF_SETUP  = 0x07
    CONFIG   = 0x0e
    DYNPD/FEATURE  = 0x00 0x00
    Data Rate  = 1MBPS
    Model   = nRF24L01+
    CRC Length  = 16 bits
    PA Power  = PA_MAX

It also shows the readings from each channel after; I just omitted that part.

Removing the chip and reconnecting it to my breadboard ATmega, which has been bootloaded and tested with the blink sketch, I get the following:

    STATUS   = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
    RX_ADDR_P0-1  = 0x0000000000 0x0000000000
    RX_ADDR_P2-5  = 0x00 0x00 0x42 0x42
    TX_ADDR   = 0x1042082184
    RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
    EN_AA   = 0x00
    EN_RXADDR  = 0x00
    RF_CH   = 0x00
    RF_SETUP  = 0x00
    CONFIG   = 0x00
    DYNPD/FEATURE  = 0x00 0x00
    Data Rate  = 1MBPS
    Model   = nRF24L01
    CRC Length  = Disabled
    PA Power  = PA_MIN

I double-checked all my wires against an ATmega328P pin map and everything checks out.

Furthermore, running the "gettingstarted" sketch on my Uno returns the correct result in the serial monitor where the chip starts in receiving mode and waits for instructions or to receive packets. And because I don't have the other chip set up yet, nothing shows up. However, when I run the exact same program on my breadboard ATmega, I get the following right after it finishes uploading.

    RF24/examples/GettingStarted
    *** PRESS 'T' to begin transmitting to the other node
    Sent response 4194829060
    Sent response 4194829060
    Sent response 4194829060
    Sent response 4294967295
    Sent response 4294967295
    Sent response 4294967295
    Sent response 0
    Sent response 4294967295
    ... yada yada yada

The fact that it is picking up any signals doesn't make sense as I am not transmitting from anything... yet.

The only MAJOR difference between my breadboard setup and the uno is the uno is running off USB 5V and the antenna is getting power from the 3.3V pin. On my breadboard, I have my usb2serial jumpered to 3.3V right off the bat and it is running the ATmega328P with a 16MHz crystal basically at 3.3V (waiting on my 3.3V regulators to arrive this Friday so I can run the chip at 5 and drop down to 3.3 just for the chip, as it is a potential solution I have in mind but in the meantime I am asking for other possibilities). Yes I know it is low but so far other sketches like the blink work, and I am running the chip in receive mode anyways.

I am lost and would appreciate some guidance.

Thank you.

title: Error using nRF24L01+ with ATmega328P-PU. Works fine on Uno

Answers: 1

body:
The ATmega328P can't run at 16MHz at a supply voltage of only 3.3V (check the datasheet). Either raise the voltage or lower the frequency.

Also note that 16mHz would be 16 milliherz (16E-3), so you probably mean 16MHz, i.e. 16 megahertz (16E6).

Remember that the nRF24L01+ is a 3.3V device, so don't connect it to the ATmega's Vcc when changing the supply voltage to 5V.
The IO pins are 5V tolerant, so that's not an issue.


body:
> Arduino: 1.8.6 Hourly Build 2017/10/20 02:33 (Windows 10), Board:
> "Arduino/Genuino Uno"
>
> c:\users\hp\desktop\arduino-nightly\hardware\tools\avr\bin\../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe:
> unable to rename 'core\core.a'; reason: Permission denied
>
> exit status 1 Error compiling for board Arduino/Genuino Uno.
>
> This report would have more information with "Show verbose output
> during compilation" option enabled in File -> Preferences.

Please help me fix this problem. This is my code:

    int redled = 6;
    int yellowled = 9;
    int greenled = 12;

    void setup() {
      pinMode (6, OUTPUT);
      pinMode (9, OUTPUT);
      pinMode (12, OUTPUT);
    }

    void loop() {
      digitalWrite (redled, 1);
      delay(9000);
      digitalWrite (redled, 0); //stopped
      digitalWrite (yellowled, 1);
      delay (3000); // yellowled lights for 3 sec.
      digitalWrite (yellowled, 0);
      digitalWrite (greenled, 1);
      delay (9000);
      digitalWrite (greenled, 0);// greenled starts flashing
      delay (500);
      digitalWrite (greenled, 1);
      delay (500);
      digitalWrite (greenled, 0);
      delay (500);
      digitalWrite (greenled, 1);
      delay (500);
      digitalWrite (greenled, 0);
      delay (500);
      digitalWrite (greenled, 1);
      delay (500);
      digitalWrite (greenled, 0);
      delay (500);
      digitalWrite (greenled, 1);
      delay (500);
      digitalWrite (greenled, 0);
    }

title: Error compiling code for Arduino/Genuino Uno

Answers: 1

body:
The problem is just what the error message says it is.

> c:\users\hp\desktop\arduino-nightly\hardware\tools\avr\bin../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied

When you are compiling your code the compilation process is trying to rename a file called core.a (.a means a library). I'm guessing it is doing this because you have changed the board type and it needs to compile the library for that type of board.

You don't have permission to change this file. This could be because:

 1. You don't have Windows security permission.
 2. The file is in use already.
 3. It's because you have installed it on your desktop.

The easiest to check is 2, reboot you machine and start only one instance of the IDE and try again. If it works, something (don't ask what) was accessing the file.

If it doesn't work you need to change the security permissions of the parent folder and all sub folders and files. You will need to Google how to do that, and you will need to search for core/core.a.