body:
My transmitter is a Nano, the receiver is a Tiny85.
I use a Logic Analyzer to check if stuff is moving, I can clearly see data coming in at the receiver.

The receiver does not 'decode' the data, `man.receiveComplete()` is never `True` so in the end nothing happens.

I think the problem may be the difference in clock speeds, there are some things I have tried. The Nano is sending every second, in the logic analyzer I can see this come in every second so he is 'right on time'.
But I am not so sure about the ATTiny85..

 - ATTiny85
 - Tiny Core
 - 8MHz (burned bootloader 3x)

It is still to fast, counting to 3 is not working ok..

**Bootloader burning log**

        /home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/bin/avrdude -C/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/etc/avrdude.conf -v -v -pattiny85 -cstk500v1 -P/dev/ttyUSB0 -b19200 -e -Uefuse:w:0xFF:m -Uhfuse:w:0xD7:m -Ulfuse:w:0xE2:m

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

             System wide configuration file is "/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/etc/avrdude.conf"
             User configuration file is "/home/thijs/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/ttyUSB0
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
             AVR Part                      : ATtiny85
             Chip Erase delay              : 400000 us
             PAGEL                         : P00
             BS2                           : P00
             RESET disposition             : possible i/o
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
               flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

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

    avrdude: PAGEL and BS2 signals not defined in the configuration file for part ATtiny85, using dummy values
    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.05s

    avrdude: Device signature = 0x1e930b (probably t85)
    avrdude: erasing chip
    avrdude: PAGEL and BS2 signals not defined in the configuration file for part ATtiny85, using dummy values
    avrdude: reading input file "0xFF"
    avrdude: writing efuse (1 bytes):

    Writing | ################################################## | 100% 0.02s

    avrdude: 1 bytes of efuse written
    avrdude: verifying efuse memory against 0xFF:
    avrdude: load data efuse data from input file 0xFF:
    avrdude: input file 0xFF contains 1 bytes
    avrdude: reading on-chip efuse data:

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

    avrdude: verifying ...
    avrdude: 1 bytes of efuse verified
    avrdude: reading input file "0xD7"
    avrdude: writing hfuse (1 bytes):

    Writing | ################################################## | 100% 0.02s

    avrdude: 1 bytes of hfuse written
    avrdude: verifying hfuse memory against 0xD7:
    avrdude: load data hfuse data from input file 0xD7:
    avrdude: input file 0xD7 contains 1 bytes
    avrdude: reading on-chip hfuse data:

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

    avrdude: verifying ...
    avrdude: 1 bytes of hfuse verified
    avrdude: reading input file "0xE2"
    avrdude: writing lfuse (1 bytes):

    Writing | ################################################## | 100% 0.02s

    avrdude: 1 bytes of lfuse written
    avrdude: verifying lfuse memory against 0xE2:
    avrdude: load data lfuse data from input file 0xE2:
    avrdude: input file 0xE2 contains 1 bytes
    avrdude: reading on-chip lfuse data:

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

    avrdude: verifying ...
    avrdude: 1 bytes of lfuse verified

    avrdude done.  Thank you.

    /home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/bin/avrdude -C/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/etc/avrdude.conf -v -v -pattiny85 -cstk500v1 -P/dev/ttyUSB0 -b19200

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

             System wide configuration file is "/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/etc/avrdude.conf"
             User configuration file is "/home/thijs/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/ttyUSB0
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
             AVR Part                      : ATtiny85
             Chip Erase delay              : 400000 us
             PAGEL                         : P00
             BS2                           : P00
             RESET disposition             : possible i/o
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
               flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

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

    avrdude: PAGEL and BS2 signals not defined in the configuration file for part ATtiny85, using dummy values
    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.04s

    avrdude: Device signature = 0x1e930b (probably t85)

    avrdude done.  Thank you.

**high level**
[![analyzer1][1]][1]

**zoomed**
[![analyzer2][2]][2]

I have tried to use the Analyzer options for Manchester encoding in Saleae Logic but I do not know how to configure it right..

**Receiver Code**
<!-- language-all: lang-cpp -->

    #include <Manchester.h>
    #include <TinyWireM.h>                  // I2C Master lib for ATTinys which use USI
    #include "LiquidCrystal_attiny.h"

    LiquidCrystal_I2C lcd(0x27,16,2);

    #define RX_PIN 1
    uint8_t moo = 1;
    #define BUFFER_SIZE 4
    uint8_t buffer[BUFFER_SIZE];

    int curs = 0;

    void setup() {
    //  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
      delay(1000);
      pinMode(4, OUTPUT);
      lcd.init();
      lcd.backlight();
      lcd.home ();
      lcd.setCursor (0, 0);
      lcd.print("Start ");
      man.setupReceive(RX_PIN, MAN_1200);
      man.beginReceiveArray(BUFFER_SIZE, buffer);
      count();
    }

    void loop() {
      if (man.receiveComplete()) {
        uint8_t receivedSize = 0;

        //do something with the data in 'buffer' here before you start receiving to the same buffer again
        receivedSize = buffer[0];
        for(uint8_t i=1; i<receivedSize; i++)
          Serial.write(buffer[i]);

    //    pushtolcd(".");
        lcd.print(".");
        Serial.println();

        man.beginReceiveArray(BUFFER_SIZE, buffer);
        moo = ++moo % 2;
      }
    }

    void pushtolcd(String text) {
      lcd.home ();
      lcd.setCursor (0, curs);
      curs++;
      lcd.print(text);
      delay(500);
    }

    void count() {
      for (int i=0; i<3; i++) {
        lcd.print(i);
        delay(1000);
      }
    };

**Sender code**

    #include <Manchester.h>

    #define TX_PIN  5  //pin where your transmitter is connected
    #define LED_PIN 13 //pin for blinking LED

    uint8_t moo = 1; //last led status
    uint8_t data[20] = {11, '1','2', '3', '4', '5', '6', '7', '8', '9','1','2','3','4','5','6','7','8','9'};

    void setup()
    {
      pinMode(LED_PIN, OUTPUT);
      digitalWrite(LED_PIN, moo);
      man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84
      man.setupTransmit(TX_PIN, MAN_1200);
    }

    uint8_t datalength=2;   //at least two data
    void loop()
    {

      data[0] = datalength;

      man.transmitArray(datalength, data);
      moo = ++moo % 2;
      digitalWrite(LED_PIN, moo);

      delay(800);
      datalength++;
      if(datalength>18) datalength=2;
    }

  [1]: https://i.stack.imgur.com/ssPbb.png
  [2]: https://i.stack.imgur.com/L7ts0.png

title: Manchester 433MHz Nano to ATTiny85

Answers: 0


body:
I've actually messed up and posted into the stackoverflow site, even though I'm probably not meant to. I've been given [this][2] datasheet, but even though it does explain somewhat how each host interfaces works, it does not fully answer the questions I have at the moment and I probably don't even know what I'm doing in the first place, hence I'm giving this question another shot in the right place.

I've enrolled recently into a programming course, and one of the subject seems to be embedded software development revolving around an Arduino. Now, I'm tasked with explaining to the class how the MFRC522 works and where it might be applicable, but before all that, I probably am lacking the basic knowledge before I can proceed with my work.

I have [here][1] the image of the pinout from a MFRC522 and I have the following questions:

 - Theres UART, I2C and SPI. Are they all separate communication protocols or are they all involved somehow with each other on this device? If I plan to use only UART for example, is it possible that I just only use the RX and TX?
 - Are there restrictions as to which pins on the Arduino or the MFRC522 I could possibly use, depending on the protocol or circumstances? I can see in the datasheet the pins D1 to D7 being referenced, but I cannot find it anywhere on the MFRC522 itself.
 - In case they are separate protocols, I would like to know how each protocol is applicable for this specific device? Like a general idea as to why a protocol is suited for a certain every day device we have been using.
 - The device itself uses only 3.3V, but is it also 5V resistant? Like, will plugging it into a 5V fry the circuit board or will it work just as fine?

Thanks everyone for your time.

  [1]: https://i.stack.imgur.com/Bnpew.png
  [2]: https://www.nxp.com/documents/data_sheet/MFRC522.pdf

title: The working of a MFRC522 and its Interface protocols?

Answers: 1

body:
Let's have a look at [the datasheet of that chip](https://www.nxp.com/documents/data_sheet/MFRC522.pdf):

Paragraph 8.1 says

> The MFRC522 supports direct interfacing of hosts using SPI, I2C-bus or serial UART interfaces. The MFRC522 resets its interface and checks the current host interface type automatically after performing a power-on or hard reset. The MFRC522 identifies the host interface by sensing the logic levels on the control pins after the reset phase. This is done using a combination of fixed pin connections.

But it seems that on **this specific board** the control pins are preconfigured for SPI. But, the [supporting library only supports SPI](http://playground.arduino.cc/Learning/MFRC522) so I guess that's OK. For other applications the control pins will be connected differently, and the pins will take up an i2c or serial async role. Applications for the other interfaces include microcontrollers without an SPI interface but with an i2c interface, or eg general purpose computers that have easy access to serial async interfaces, like PC's

 - the pin names D1-D7 in the datasheet are not related to the Arduino's pins with the same names, that's just a coincidence. If you use the aforementioned library, the Arduino pins to use are documented:

<pre>
     * Pin layout should be as follows:
     * Signal     Pin              Pin               Pin
     *            Arduino Uno      Arduino Mega      MFRC522 board
     * ------------------------------------------------------------
     * Reset      9                5                 RST
     * SPI SS     10               53                SDA
     * SPI MOSI   11               51                MOSI
     * SPI MISO   12               50                MISO
     * SPI SCK    13               52                SCK
</pre>

 - what the device will tolerate in terms of voltage on its pins is documented in chapter 11. Absolute max on most pins is 4.5 V, so the chance that 5V will fry the component is so high you probably don't want to try.

---
I think [this](http://www.sunrom.com/p/mifare-rfid-readerwriter-1356mhz-rc522) is your board, and luckily they include a schematic on that page:

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

Here's it clearly visible that pin 1 is connected to ground, and pin 32 is connected to 3.3V, which shows that it's indeed hardcoded to SPI mode.

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


body:
So, I have some simple code here. I'll just try and explain what I am trying to have my code do here.

I am trying to rotate my stepper motor by half a turn, and then move it back and forth by 200 steps or so.

The problem I have is in my loop function, where I have a variable called ctr. I am trying to increment this ctr when I execute an if statement. The ctr increments inside the if statement and I can see the result when I do Serial.println as it changes to 1. However, when I Serial.println(ctr) right below the if statement, it prints out as 0 even after the previous print statement prints out 1.

Why is this happening? I am a C/C++ noob, so is there something I am missing about variable scoping or pointers?

    void loop()
    {
        stepper1.run();
        int ctr = 0; //counter value to store how many times the back and forth motion has occured
        if(stepper1.currentPosition() == 1024){
          backMotion(stepper1.currentPosition());
          ctr++;
          Serial.println(ctr);
        }
        Serial.println(ctr);
        if(stepper1.currentPosition() == 824 && ctr > 0){
          forthMotion(stepper1.currentPosition());
        }
    }

    void backMotion(int value){
        int current = value;
        int back_distance = current - 200; //distance to move back by
        stepper1.moveTo(back_distance);
    }

    void forthMotion(int value) {
      int current = value;
      int forth_distance = current+200;
      stepper1.moveTo(forth_distance);
    }

title: Having some trouble incrementing counters

Answers: 2

body:
Make CTR static or place it in the global scope. As it stands you set it to 0 every time you go through loop.

The line:

    int ctr = 0;

literally means "Create a new variable on the stack called 'ctr' and give it the value 0", and that happens *every time `loop()` is executed*.

Instead making it *static* will change it so that it only happens *the first time `loop()` is executed* so it retains its value across successive executions of `loop()`.

    static int ctr = 0;

body:
loop() != main()

when declaring a variable inside a function, it is cleaned up when returning from the function.

if cnt was in a main() function, it would have worked (as it's the only function that may have an infinite loop in a program. In the arduino world, it's not the case. The main() function is hidden, but loop calls the loop() function.

Workaround is to use the static quelifier when you declare variables inside loop() (or in any other function if you want the variable to remain inside the function scope, but don't want it to be initialized each time you enter the function).


body:
I recently purchased a [Leonardo Eth][1] and a [5v POE module][2] in an attempt to have a POE micro-controller.  I installed the module in the holes closest to the Ethernet jack side of the board, but when I apply power, the green power light turns on every second or so, but never fully turns on.

What am I doing wrong? Did I install the module wrong? Is it the wrong module?

  [1]: https://www.amazon.com/gp/product/B013PUTJYO/ref=oh_aui_detailpage_o02_s00?ie=UTF8&psc=1
  [2]: https://www.amazon.com/gp/product/B01AMBBJJW/ref=oh_aui_detailpage_o02_s01?ie=UTF8&psc=1

title: POE with Arduino Leonardo Eth

Answers: 1

body:
From the arduino.cc website.

"The optional PoE module is designed to extract power from a conventional twisted pair Category 5 Ethernet cable. PoE module features are as follows: IEEE802.3af compliant Input voltage range 36V to 57V Overload and short-circuit protection 12V Output High efficiency DC/DC converter: typ 85% @ 80% load 1500V isolation (input to output)"

It sounds like you need the 12V PoE module


body:
Code:

    int motorPin = 9;  // the pin the motor is connected to

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

    void loop()
    {
     motorOnThenOff(); //motorAcceleration
    }

    void motorOnThenOff(){
      int onTime = 2500;  //the number of milliseconds for the motor to turn on for
      int offTime = 1000; //the number of milliseconds for the motor to turn off for

      digitalWrite(motorPin, HIGH); // turns the motor On
      delay(onTime);                // waits for onTime milliseconds
      digitalWrite(motorPin, LOW);  // turns the motor Off
      delay(offTime);               // waits for offTime milliseconds
    }

    void motorOnThenOffWithSpeed(){

      int onSpeed = 200;  // a number between 0 (stopped) and 255 (full speed)
      int onTime = 2500;  //the number of milliseconds for the motor to turn on for

      int offSpeed = 50;  // a number between 0 (stopped) and 255 (full speed)
      int offTime = 1000; //the number of milliseconds for the motor to turn off for

      analogWrite(motorPin, onSpeed);   // turns the motor On
      delay(onTime);                    // waits for onTime milliseconds
      analogWrite(motorPin, offSpeed);  // turns the motor Off
      delay(offTime);                   // waits for offTime milliseconds
    }

    void motorAcceleration(){
      int delayTime = 50; //milliseconds between each speed step

      //Accelerates the motor
      for(int i = 0; i < 256; i++){ //goes through each speed from 0 to 255
        analogWrite(motorPin, i);   //sets the new speed
        delay(delayTime);           // waits for delayTime milliseconds
      }

      //Decelerates the motor
      for(int i = 255; i >= 0; i--){ //goes through each speed from 255 to 0
        analogWrite(motorPin, i);   //sets the new speed
        delay(delayTime);           // waits for delayTime milliseconds
      }
    }

This code spins the motor. In the circuit, I have a button which I want to toggle the spinning of the motor.

This is the circuit:

https://circuits.io/circuits/4267039-spin-motor-spin/edit

How would I make it so that the button toggles the spinning of the motor? like a fan and its switch?

title: Control a motor with a button

Answers: 1

body:
add this variable at the top of your program:

    const int buttonPin = XX; // the pin for the button
    bool bState = false;

in the setup() function:

    pinMode(buttonPin, INPUT_PULLUP);
    // in case INPUT_PULLUP is not defined, comment the above line and uncomment below
    //pinMode(buttonPin, INPUT);
    //digitalWrite (buttonPin, HIGH);  // enable internal pull-up

in the loop() function, change your code with this:

    update_bState();

    if (bState) { digitalWrite(motorPin, HIGH); }
    else        { digitalWrite(motorPin, LOW); }

then, at the end of your program, add the getButton function:

 void update_bState(void)
 {
  static bool buttonDone = false;
  static uint16_t timeButton;

  if (!digitalRead(buttonPin))
  {
   if ((!buttonDone) && ((uint16_t) (millis() - timeButton) > 100))
   { // Do once when button is pressed for at least 100ms (debounce)
    bState ^= true;  // Toggle button state
    buttonDone = true;
   }
  }
  else
  {
   buttonDone = false;
   timeButton = millis();
  }
 }

Now that all the work is done, you should add acceleration when launching and deceleration when launching and stopping :D

By the way, I did not tested any code, so there may be some typo errors...


body: I recently purchased 10 units of MG996R servo motor and the 16 channel 12-bit PWM/Servo driver from Adafruit for a small project. I confirmed that all of my servos are functional and that my code is correct. My issue is that there seems to be a limit on the number of servos I can run. With 4AA batteries, I can power about 3 of the MG996R servos. Starting with the 4th one, they stop moving. I supposed that the current drawn from the servos is high, so I tried powering the servos by providing two 4AA batteries in parallel (8AA). This appeared to have increased the number of servos I can run. But after a few minutes, the servos stop responding and I have to disconnect the power for a while before the servos respond again. I read on Adafruit that I may need to add a capacitor to the PWM/servo drive if I have multiple servos. Is this my problem or I just need to provide more power? Why do the servos seem to respond initially but stop moving after a while? Thanks in advance.

title: Servos stop after a while in case of 8 servo motor control

Answers: 1

body:
If Adafruit say to use the kit to drive multiple servos you need to add a cap and without the cap you can't drive multiple servos, then yes your first port of call should be to add the cap.

However that's probably not all that's wrong.  If it runs for a bit before dying then it could be a number of causes.

 1. Not enough power.
 2. Something is overheating.
 3. Code problem.

1.  Use a decent transformer with more than enough amps to power your motors.
2. Use your nose, does something smell hot?  If you use your fingers you will get burnt!
3. We can't fix invisible code.


body:
i want to preserve video information for long time without communicating with arduino on lcd 1602, i'm tryng to use the command of liquidCrystal library `noDisplay()` but when i use it,this clear all display. On arduino website here is the description of this command "Turns off the LCD display, without losing the text currently shown on it." but i lose all on screen. Thanks for reply

there is my test code

    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup() {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print("hello, world!");
    }

    void loop() {
      // Turn off the display:
      lcd.noDisplay();
      delay(500);
      // Turn on the display:
      lcd.display();
      delay(500);
    }

with this code display blinking and don't show continuos "hello word".

title: Why the command noDisplay() clear all LCD screen?

Answers: 2

body:
I tried out your code. It's working absolutely fine.

Whenever `lcd.noDisplay()` executes then LCD not displaying `hello, word!`...
And whenever `lcd.display()` executes then LCD displaying `hello, word!`...

So, that's why "hello word" not continuously displaying.

And you can also find `the display() and noDisplay() functions to turn on and off
the display` comment on top of arduino sketch.

body:
> I tried out your code. It's working absolutely fine.
>
> Whenever lcd.noDisplay() executes then LCD not displaying hello,
> word!... And whenever lcd.display() executes then LCD displaying
> hello, word!...
>
> So, that's why "hello word" not continuously displaying.
>
> And you can also find the display() and noDisplay() functions to turn
> on and off the display comment on top of arduino sketch.

To follow on @Hasan's answer:
noDisplay() doesn't clear the previous displayed stuff, it just inhibits it, all displayed pixels are latched in the chip while it remains powered on.

In case you need to clear the display, you can use lcd.clear() function.


body:
Would it be possible to use TWO MIDI inputs (and a MIDI output) on an Arduino having only one RX/TX serial port? Timing will be somewhat critical so a software serial port is not usable probably. I need to listen continuously to both MIDI (in) ports not to miss messages.

Or is it better to use an Arduino Mega having 4 serial ports?

title: Using two MIDI inputs with Arduino UNO (with one serial)

Answers: 1

body:
Use a Mega. SoftwareSerial is shaky at best and cripples everything else while it runs, and there really is no substitute for real hardware UARTs.

Alternatively look around and see if you can find a board based around the ATMega328-PB (note the "B") which has a second UART built in.


body:
Could someone please demonstrate how to use a counter with the Arduino 'low power' library to wait for 10 minutes then digitalWrite 4000, HIGH and loop. (I don't mean the simple 'blink' sketch).

I'm trying to save as much power as possible, so any advice is appreciated.

Thanks!

title: Low Power Library 4 seconds ON, 10 minutes OFF

Answers: 2

body:
Your problem here is your 10 minutes mark. If you're willing to take a somewhat more complex route, you could use a low-power, programmable, external timer like [TPL5110][1]. You can set an interval of up to 120 minutes by selecting the appropriate value of the programming resistor.

This kind of timers can be used to drive the gate of a logic-level P-channel MOSFET that acts as a switch for the power line of the Arduino.

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

Then, you simply you do all your stuff on the `setup()` function and leave `loop()` empty. You can switch off the Arduino by sending back a DONE signal to the TPL5110 at the end for your `setup()`.

[![Timing][3]][3]

If, for whatever reasons, you really want your Arduino to be running for exactly 3 seconds, then you should run a timer in it (beware: not related in any way with TPL5110). Set it up so you the ISR of the timer breaks a do-while waiting loop just before the line of code that sends back the DONE signal.

  [1]: http://www.ti.com/lit/ds/symlink/tpl5110.pdf
  [2]: https://i.stack.imgur.com/3wtuv.png
  [3]: https://i.stack.imgur.com/okIDCm.png

body:
Agreed with what most others have already mentioned;
The Arduino as-is is not suitable for low power operation - it is best to turn it off completely. The circuit below should do what you want, and is based on a very simple and cheap IC, the 555 timer.

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

<!-- End schematic -->

A similar version of this has been working for me for about 2 years in a remote sensing setup. A few things to note to make sure that it works;

1. This needs the TLC555 chip which is a CMOS IC. The TTL version (NE555) will not work with such high value timing resistors.

2. The timing capacitor (shown as 141uF, just use 3 x 47uF in parallel) needs to be a tantalum capacitor. The normal electrolytic version has too high a leakage current.

3. As shown, this should turn off the Arduino for about 580s, and on for 120s. To turn off the Arduino sooner, drive digital pin 5 high. This will discharge C1 through R3 and Q1 quickly (about 500ms).

4. To change the delay times, alter R1, R2, and C1. The datasheet has all the equations that you need for this.

5. it would probably be wise to put a bypass capacitor between the supply rails very close to the TLC555 chip. 10uF should do.

6. This circuit should draw around 360uA while the Arduino is off.

One final thing - the task that you are using the Arduino for sounds pretty simple - driving a digital line high for 4 seconds every 10 minutes. I guess that you have more to it than that, but if not, then you could save yourself the cost and complexity, and do away with the Arduino completely. In that case, R1 should be about 6M1, and R2 about 41K, you can remove Q1, D1, R3 and R6, and whatever you are driving goes in place of the Arduino.


body:
I will implements an emergency backup feature before power off, on Arduino Mega 2650.
Arduino is powered by capacitor, for the time (I hope) of the EEPROM write.

On AVR2650 Datasheet is reported that the typical EEPROM writing time is 3.3ms.
But 3.3ms for what? a byte? a word? the whole EEPROM?

I need the data for calculate the capacitors.

title: EEPROM write time

Answers: 1

body:
> On AVR2650 Datasheet is reported that the typical EEPROM writing time is 3.3ms. But 3.3ms for what? a byte? a word? the whole EEPROM?

That is per byte (erase and write 3.4 ms, only write is 1.8 ms). When writing multiple bytes there are a few clock cycles to be gained by preparing for the next byte during an ongoing EEPROM write. Or even better use an ISR for the EEPROM feed. Not faster but allows some additional processing while a block is written. The largest gain is to have the EEPROM erased before the write (1.8 ms per byte instead of 3.4 ms).

Please see http://www.nongnu.org/avr-libc/user-manual/group__avr__eeprom.html,  http://www.atmel.com/images/doc2578.pdf and table 9-1, pp. 35, http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf.

Cheers!


body:
I would like to create a simple remote controller (IR) with my Arduino Nano that would control my PC. (Volume up/down, stop, play and that sort of things...)
I have no problem with creating 'hardware part' and Arduino script, that would send commands through serial as a reaction to IR signals.
I can imagine python script that would react to commands received on the serial port.

My problem is: "How can I detect on which port should I listen to?" What is the right way to do it?

title: Using Arduino as a pc remote controller

Answers: 1

body:
Since I can not commemnt due to low reputation, I'm "commenting" here.
You can search for LIRC and WinLIRC


body:
So, I am trying to move a stepper motor through a halfway revolution (1024 steps), and once that is completed, have it move back and forth by about 100 steps in either direction.

I am having some trouble with this though, because while it will move in one direction, it will not move in the other.

    void setup()
    {
        stepper1.setMaxSpeed(1000);
        stepper1.moveTo(1024);
        stepper1.setAcceleration(100);
        Serial.begin(19200);
        while(!Serial);
    }

    void loop()
    {
        stepper1.run();
        static int ctr = 0; //counter value to store how many times the back and forth motion has occured
        if(stepper1.currentPosition() == 1024){
          backMotion(stepper1.currentPosition());
          forthMotion(stepper1.currentPosition());
          ctr++;
        }
    //    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
    //      forthMotion(stepper1.currentPosition());
    //    }
    }

    void backMotion(int value){
        int current = value;
        int back_distance = current - 200; //distance to move back by
        stepper1.moveTo(back_distance);
    }

    void forthMotion(int value) {
      int current = value;
      int forth_distance = current+200;
      stepper1.moveTo(forth_distance);
    }

So, when I call the forthMotion function right after the backMotion function, it will just move forward. Which makes no sense to me. Shouldn't it be moving backwards, and then forwards in an infinite loop?
Because it will hit 1024, go back to 824, hit 1024 again, and so on and on...

Also, when I call the backMotion function, isn't the Arduino code supposed to be blocking in that, nothing else gets executed while that is running?

Edit: The code seems to work when I uncomment the if statement in the loop function.

title: Trying to move a stepper motor back and forth

Answers: 2

body:
Steppers don't typically have feedback about their position (as opposed to servos). Normally you're just telling a stepper how much and how quickly to rotate. As opposed to servos, which you tell which position to rotate to.

Are you sure you're using a stepper?

body:
I guess the solution might be this:

in back motion
```
void backMotion(){

    int back_distance = - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}
```

In forward motion
```
void forthMotion() {

  int forth_distance = 200;
  stepper1.moveTo(forth_distance);
}
```

In loop
```
void loop()
{
    stepper1.run();
    static int ctr = 0; //counter value to store how many times the back and forth motion has occured

    stepper1.moveTo(1024);
    while(ctr < 30){

      backMotion();
      delay(500);

      forthMotion();
      delay(500);
      ctr++;
    }
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

```
Your main code will be like this

```
void setup()
{
    stepper1.setMaxSpeed(1000);
    stepper1.moveTo(1024);
    delay(3000); // wait till stepper gets to destination
    stepper1.setAcceleration(100);
    Serial.begin(19200);
    while(!Serial);
}

void loop()
{
    stepper1.run();
    static int ctr = 0; //counter value to store how many times the back and forth motion has occured

    while(ctr < 30){

      backMotion();
      delay(500);

      forthMotion();
      delay(500);
      ctr++;
    }
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

void backMotion(){

    int back_distance = - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion() {

  int forth_distance = 200;
  stepper1.moveTo(forth_distance);
}

```


body:
I am trying to get an LED dimming reversely proportionate to natural light level in a room.
So as the sun rises, the LED dims and vice-versa.
I am using the standard LDR+ 10k Ohm resistor divider, an LED, and an Arduino Leonardo Clone.

The issue is, regardless of the values I adjust in `map()`, it does not change the flickering rate or brightness of the LED.
What range of map shuold I be using?

The LED ought to shut off while the LDR takes a reading.
I have two variations of the code; one uses PWM, the other simulates PWM using `delay()`

Here are my sketches:

    /set pin numbers
    //const won't change
    const int ledPin = 1;   //D1 the number of the LED pin (OR to MOSFET input wire for controlling high power LED
    const int ldrPin = A0;  // A0 the number of the LDR pin
    //10K ohm resistor as voltage reference.

    void setup() {

      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
      pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
    }

    void loop() {
      digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
      int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
      // KEEP LED OFF TIME BASED ON AMBIENT LIGHT LEVEL...
      int dim2 = map(ldrStatus, 0, 1023, 500, 0); //OFF FOR UP TO 0.50 seconds.
      digitalWrite(ledPin, HIGH);
      delay(dim2);

       }

Sketch two:

    //set pin numbers
    //const won't change
    const int ledPin = 1;   //D1 the number of the LED pin (OR to MOSFET input wire for controlling high power LED
    const int ldrPin = A0;  // A0 the number of the LDR pin
    //10K OHM resistor as voltage reference.

    void setup() {

      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
      pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
    }

    void loop() {
      digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
      int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
      int dim = map(ldrStatus, 0, 1023, 255, 0);     // scale it to use it with the LED (value between 0 and 255)
      digitalWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.

       }

title: Arduino LED Dimmer Proportionate to Ambient Light

Answers: 1

body:
For certain Arduino models, the PWM pins are different. For the iteaduino lite, a usable PWM pin is pin D5.

Here is the code updated to use D5 instead of D1, which lacks PWM abilities:

    //set pin numbers
    //const won't change
    const int ledPin = 5;   //D5 PWM the number of the LED pin (OR to MOSFET input wire for controlling high power LED
    const int ldrPin = A0;  // A0 the number of the LDR pin
    //10K OHM resistor as voltage reference.

    void setup() {

      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
      pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
    }

    void loop() {
      digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
      int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
      int dim = map(ldrStatus, 0, 1023, 0, 255);     // scale it to use it with the LED (value between 0 and 255)
      analogWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.
      Serial.println(dim);
       }

There is still flickering, but that is to be expected. `map()` ranges can be adjusted to set when the LED will be fully off or on.

It is still unclear how to allow the light sensor to take a reading while the LED is OFF, then power back on rapidly enough to not have a visible flicker.
If anyone has thoughts on that, it would be appreciated!
Thanks everyone for helping.


body:
I am having some major issues with my Arduino Yun.

When attempting to read a value from the analog pins, the Yun is giving me incorrect constant values.

I have attached everything to a common ground, and I am supplying 3.3 volts to the A0 pin on the Yun.

The weird thing is, the pins all give constant values in ascending order, no matter what is connected to them, or if nothing is connected at all.

- A0 - 18
- A1 - 19
- A2 - 20
- A3 - 21
- A4 - 22
- A5 - 23

The code I am running is a very simple script.

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

    float i;

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

    void loop() {
      i = A0;
      Serial.println(i);
      delay(1000);
    }

title: Arduino Yun Analog Read Problem

Answers: 1

body:
You are not reading from any analog pins. You are just printing out the digital pin number of the analog pin.

Look at some [basic examples](https://github.com/arduino/Arduino/blob/1.8.1/build/shared/examples/01.Basics/AnalogReadSerial/AnalogReadSerial.ino) on how to read analog values.

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

    /*
      AnalogReadSerial
      Reads an analog input on pin 0, prints the result to the serial monitor.
      Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
      Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

      This example code is in the public domain.
    */

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(A0);
      // print out the value you read:
      Serial.println(sensorValue);
      delay(1);        // delay in between reads for stability
    }


body:
I'm building a weather data collector and I want to be able to dump that weather data somewhere. I've considered the options, and since I'm going to be storing a fairly small amount of data (in the megabyte range) I don't want to use SD cards (also SD cards are expensive). I've heard of use of NAND flash memory chips (like the W25Q32), and I was hoping that I could possibly interact with them in a simple way (since most ways require writing to each individual address). Is there possibly a way to build a file system within one of these small flash memory chips and interact with them as simply as interacting with an SD card?

TLDR: I want to interact with a flash memory chip easily to store basic ASCII data

title: External Flash Memory File System

Answers: 3

body:
There is a way to do this. Using a $2 adaptor from eBay, you can hook it up to a micro sd card. An sad card for $4 can store 128mb of data, which is plenty for you.

[Arduino Storage Tutorial with weather][1]

[128mb Micro Sd card][2]

  [1]: http://apcmag.com/arduino-basics-5-add-sd-storage-to-arduino.htm/
  [2]: https://www.newegg.com/Product/Product.aspx?Item=9SIA4V21KS0187

body:
This lib offers a means of reading and writing ASCII arrays to flash devices. This would be a simple solution for such a data logger requirements. It's ASCII orientated.

https://github.com/schinken/Flash

body:
I don't think you need a file system: that is usually needed when you want to manage *many* files. Your weather data log sounds like a single file.

What you seem to need is to access EEPROM as a *stream*, exactly like you would for an open file. There are stream wrappers around some EEPROM libraries, e.g. [this one for ESP](https://github.com/lasselukkari/EepromStream). I suggest you check it out and see if you can adapt it to the EEPROM library you use.


body:
I was working on a project in which I need to collect soil moisture data for a farm. For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino. But, this is not possible as there are just 6 analog pins on Arduino Uno and 16 analog pins on Arduino Mega. I have restrictions on the number Arduino that I can use that is just one due to monetary constrains.
        The data would be collected at a delay of 5 seconds. The data gathered would be stored on SD card module which would be analyzed later.
      Any suggestion on how I can collect data from 70 analog sensors on a single Arduino would be highly appreciated. Are there any alternatives that I can use in place of Arduino? I heard that we could do something with AVR  atmega Microcontroller, am I correct? I don't know how to use Microcontroller; any useful resources will be highly appreciated. Thank You.

title: How to connect 70 analog sensor to a single Arduino (Mega or Uno) device?

Answers: 3

body:
You should use some cheap chips to collect the data and use only one with big capacity to finally combine and process the data further.

>Consider using a cheap small Arduino to build a "base module" that can do some of the tasks needed, build a bunch of them and hook them up to a R485 bus, and have one master Arduino control them all. That would be a much more flexible and expandable system. The cheapes Arduinos cost around 10$. If you build your own you could probably do it even cheaper.

**Source**:

 [1] http://forum.arduino.cc/index.php?topic=73861.0
(quote)

 [2] https://arduino-info.wikispaces.com/RS485-Modules (bus)

body:
There are fairly inexpensive chips called "analog multiplexers" which let you choose one input out of a range (8 or 16 is typical). You could take the reading, then switch to a different input, and take another reading.

I have a [page about analog multiplexers](http://www.gammon.com.au/forum/?id=11976).

Example of it in operation:

[![Multiplexer][1]][1]

In this example you have 8 inputs, and by setting the A/B/C pins appropriately, one of the 8 is selected and appears at the O/I pin (output/input).

There is a 16-channel model as well. I see the 16-pin chip (74HC4067) available on eBay for $US 1.26 right now. You can get four of them (which would give you 80 inputs) for $4.88.

Also see the [Wikipedia article on multiplexers](http://en.wikipedia.org/wiki/Multiplexer).

---

>  For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino.

Yes, well how will these sections get their data into one place? That is probably the bigger problem.

You may need to use a lengthy cable using [RS485](http://www.gammon.com.au/forum/?id=11428) (balanced signals) or maybe cheap radio transceivers.

Trying to use a "single Arduino" on what might be quite a large farm is the issue. It's not the Arduino's fault. You have to have some way of sending the data from the further points to where it is to be collected.

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

body: Given that good moisture sensors are going to be an order of magnitude more expensive than the logger, I'd suggest that you are giving yourself more problems than it's worth to try to connect that many sensors to the same unit. A Pro-mini based logger rarely comes in >$25. Even though we can connect that many one-wire sensors to a single logger ( https://thecavepearlproject.org/2015/03/01/using-ds18b20-sensors-to-make-a-diy-thermistor-string-pt-1-the-build/ ) it's not a good idea from the perspective of the amount of data that is lost if you have a single point failure. Generally we only put 10-15 sensors on any one unit, and we try to deploy them in "parallel" sets so that if one multi-sensor unit does fail, we loose spatial resolution, but still have enough information to work with.


body:
I am working on an Arduino Mega 2560. I want to read and write the internal EEPROM.

Can I use `EEPROM.get()/EEPROM.put()`?

I want to store 3 things in EEPROM:

1. Boolean status.

2. String password: length 5 digits.

3. String Mobile number: length 10 digits.

title: How do I write and read internal EEPROM?

Answers: 2

body:
Avoid the 'String' object, use a character array of fixed length. You might want to add one extra byte for the zero-terminator. Put everything in a 'struct' and then you can use the EEPROM.get() and EEPROM.put() to read and write the complete struct. I prefer a struct to keep the data from EEPROM together. That makes it easier to add a checksum and a version number for the data. When something is wrong with the data from EEPROM then default values could be used.

Instead of a struct, you can also read and write the seperate items. The EEPROM.get() and EEPROM.put() should be able to use a character array of fixed length.

body:
> How do I write and read internal EEPROM? Can I use EEPROM.get()/EEPROM.put()?

Yes, the Arduino Reference for EEPROM contains an example of what you are asking for. Below is a simple rewrite of the example for [EEPROMGet][1] for your info.

    struct MyObject{
      bool status;
      char password[6];
      char mobileNumber[11];
    };

    void setup()
    {

      int eeAddress = 0; //EEPROM address to start reading from

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

      MyObject customVar; //Variable to store custom object read from EEPROM.
      EEPROM.get(eeAddress, customVar);

      Serial.println(F("Read custom object from EEPROM: "));
      Serial.println(customVar.status);
      Serial.println(customVar.password);
      Serial.println(customVar.mobileNumber);
    }

For more details and examples see https://www.arduino.cc/en/Reference/EEPROM.

Cheers!

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


body:
As the title states. What's the difference between the two?

`analogWrite(pin,0-255)` vs `digitalWrite(pin,LOW-HIGH)`

title: What's the difference between analogWrite and digitalWrite?

Answers: 8

body:
digitalWrite sets the pin to an high or low value that remains at exactly that value until digitalWrite is called for that pin again.

analogWrite sets the pin to have an oscillating value which has a pulse length based of the duty cycle specified as the second parameter.

So:

    digitalWrite (5, HIGH);    // Pin 5 goes high
    analogWrite (6, 127);      // Pin 6 oscillates regularly between 0v and 5v (or 3.3v) at about 250Hz.

body:
digitalWrite will set the specified pin to one of two states - HIGH/LOW, which equate to 5v (3.3v on some boards) and ground respectively.

analogWrite can vary by the type of output used.

If applied to a PWM pin - it will set the pin to a periodic high/low signal, where the percentage of the signal spent high is proportional to the value written.
for example  -

        analogWrite(PWMpin,255)
Will be HIGH 100% of the time, while

        analogWrite(PWMpin,127)
Will be HIGH 50% of the time, and LOW 50% of the time

When applying analogWrite to a DAC pin (available on some boards, like the DUE <s>or MEGA</s>)
analogWrite will actually cause the specified pin to output a voltage level proportinal to the specified analog value

For example, on the Due, with maximal voltage of 3.3v and a default analog resolution of 8 bits -[0:255]

        analogWrite(DACpin,255)

Will cause the specified pin to output 3.3v, and-

        analogWrite(DACpin,127)
Will cause the specified pin to output 1.35v

body:
`digitalWrite` sets the output pin to either LOW or HIGH (where those voltages depend on the Vcc of the processor. For a Uno or Mega that would be 0V or 5V (or close to it).

Here's a screenshot of digitalWrite (LOW):

[![digitalWrite (LOW)][1]][1]

That is, the output pin is at 0V.

---

Now for digitalWrite (HIGH):

The output voltage is 5V.

[![digitalWrite (HIGH)][2]][2]

---

`analogWrite` really should have been named PWMwrite since it configures the processor timers to output PWM (pulse-width modulation).

Let's try analogWrite(1):

[![analogWrite (1)][3]][3]

You can see that the voltage level is 0V most of the time, and going to 5V for short periods. You also see that the frequency is 490 Hz which is what [the reference page for analogWrite](https://www.arduino.cc/en/Reference/AnalogWrite) says it will be.

---

Zooming in:

[![analogWrite (1) - zoomed][4]][4]

The output is high for 8 µs, which is exactly 1/256 of 2048 µs which is the period of the timer. So, we have a duty cycle of 1/256 (0.39%).

---

Let's try analogWrite(127) - half-way from 0 to 255:

[![analogWrite (127)][5]][5]

Now you can see that the output is HIGH exactly half the time, and LOW the rest of the time.

---

Let's try analogWrite(254):

[![analogWrite (254)][6]][6]

This is the opposite of analogWrite (1). The output is HIGH all the time except for a brief period. Zooming in:

[![analogWrite (254) - zoomed][7]][7]

Now the output is *off* for 8 µs - compared to the earlier image where it was on for 8 µs.

---

`analogWrite (0)` is the same as `digitalWrite (LOW)`.

`analogWrite (255)` is the same as `digitalWrite (HIGH)`.

This is proven by the relevant code in wiring_analog.c:

 if (val == 0)
 {
  digitalWrite(pin, LOW);
 }
 else if (val == 255)
 {
  digitalWrite(pin, HIGH);
 }

---

## Summary

`analogWrite` basically configures the hardware timers to output PWM. Once you do that the timer hardware outputs the requested duty cycle (from 0 to 255) where 0 is always off, 255 is always on, and some value inbetween gives you PWM (pulsed output).

---

For more information about the timers see [my page about timers](http://www.gammon.com.au/timers).

  [1]: https://i.stack.imgur.com/WvNjn.png
  [2]: https://i.stack.imgur.com/uWGLD.png
  [3]: https://i.stack.imgur.com/Ey2ij.png
  [4]: https://i.stack.imgur.com/ORIjA.png
  [5]: https://i.stack.imgur.com/hOTYO.png
  [6]: https://i.stack.imgur.com/JV9mL.png
  [7]: https://i.stack.imgur.com/OyLu6.png

body:
**analogWrite():**
Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to `analogWrite()`, the pin will generate a steady square wave of the specified duty cycle until the next call to `analogWrite()` (or a call to `digitalRead()` or `digitalWrite()` on the same pin). The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.

For details visit: https://www.arduino.cc/en/Reference/analogWrite

**analogRead():**
Reads the value from the specified analog pin. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega), 10-bit analog to digital converter. This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023. This yields a resolution between readings of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per unit. The input range and resolution can be changed using `analogReference()`.

For details visit: https://www.arduino.cc/en/Reference/analogRead

body:
**analogWrite():** The analogWrite() method sets the value of a PWM output pin. The analogWrite() is on a scale of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on), and analogWrite(127) is a 50% duty cycle (on half the time).

[![PWM Duty Cycle][1]][1]

**Syntax**: analogWrite(pin, val)

Where,

pin: the PWM output pin number.

val: int value of duty cycle between from 0(always off) to 255(always on)

**Example Code:**

    int outLed = 10;  //LED connected to digital pin 10
    int value = 0;    //variable to store the read value
    int analogIN = 3; //input pin

    void setup()
    {
      pinMode(outLed, OUTPUT); // set the PWM pin as OUTPUT
    }

    void loop()
    {
      value = analogRead(analogIN); // read the value of analogIN (values between from 0 to 1023)
      analogWrite(outLed, value/4); // sets the read value on outLed (values between from 0 to 255)
    }

**digitalWrite:** The digitalWrite() method sets the value of a digital pin as HIGH or LOW. Here, 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.

**Syntax:** digitalWrite(pin, val)

Where,

pin: the pin number

val: HIGH or LOW

**Example Code:**

    int ledPin = 13;                // LED connected to digital pin 13

    void setup()
    {
      pinMode(ledPin, OUTPUT);      // sets the digital pin as output
    }

    void loop()
    {
      digitalWrite(ledPin, HIGH);   // sets the LED on
      delay(1000);                  // waits for a second
      digitalWrite(ledPin, LOW);    // sets the LED off
      delay(1000);                  // waits for a second
    }

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

body: So what's the difference between analogWrite(X, 255) and digitalWrite(X, HIGH)? Probably nothing, except perhaps the processor has to do some extra stuff to work out that it doesn't need to use PWM, and also style.

body:
**digitalWrite** set the specified pin to one of two states - HIGH/LOW

Where, HIGH = 5 V and LOW = 0 V

**analogWrite** Set the PWM value of PWM pin

(In Arduino UNO, PWM pins are 3, 5, 6, 9, 10, 11)

It will set the pin to a periodic high/low signal.

    analogWrite(PWMpin,255)

Will be HIGH 100% of the time, while

    analogWrite(PWMpin,127)

Will be HIGH 50% of the time, and LOW 50% of the time

body: Another subtle difference between `analogWrite(pin, 255)` and `digitalWrite(pin, HIGH)` is that `digitalWrite` requires you to set the pin to output using `pinMode`. `analogWrite` sets the pin to output on each call, which makes it slower and might ruin the code which uses the same pin alternatively as input and output, and relies on the fact that writing to the input pin using `digitalWrite` doesn't switch it to output.


body: Im using Arduino connected to an SD card and PIR sensor , and based on the inputs from the PIR sensor the data needs to be written on the sd card , It is done , but for retrieving the data from the SD card is there any library for arduino ? Ive seen Extended Database library ,since im retieving huge amount of data from the SD card and i should be able to do Lots of sorting operations based on the CSV values in the file , So can i do Sorting operations in  Extended Database library from an Sd card ive seen the Examples but it doesnt have any sorting operations ,Is Querying data from the SD card using this library is Possible ?ie)Selecting data Based on some Conditions even if it can be done is there any tutorial ? Or is there any other alternative Library? for this purpose . Thank You

title: Arduino Sdcard database Library

Answers: 0


body:
I am using the following program to receive messages from a GSM module.

As we start our kit, we received two messages "*main door is open*" and "*store room is open*". (Depending upon sensor position)

This program is run properly, but the problem is that it repeats the message after some time. It does not depend on time.

Suppose our store room is closed. I receive this message on my given mobile number, but after some time two "*the store room is open*" messages are received and after this message immediately the message "*received store room is closed*". (means it sets sensor to its initial mode i.e. closed) Same problem is happening with this main door.

My kit contains an Arduino UNO board, GSM module SIM800 and two limit switches (one for the main door and second is for the store room)

I keep my both sensor and Arduino board distance over 17 meters by using CAT5e cable.

My code:

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

    const int Main = 7;  // pin define for main door sensor
    const int Store = 8; // pin define for store room sensor
    const int Main_led =  13;  // indication for main door sensor
    const int Store_led =  14;  // indication for store room sensor

    void setup() {
      Serial.begin(9600);
      pinMode(Main_led, OUTPUT);
      pinMode(Store_led, OUTPUT);
      pinMode(Main, INPUT);
      pinMode(Store, INPUT);
    }

    void sendMessage(char *text) {
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"+91-------------");
        Serial.print("\"\r\n");
        delay(5000);
        Serial.print(text);
        Serial.write(0x1A);
        delay(5000);
    }

    void loop() {
      static int oldState1 = -1;
      static int oldState2 = -1;

      int buttonState1 = digitalRead(Main);
      if (buttonState1 != oldState1) {
        digitalWrite(Main_led, buttonState1);
        if (buttonState1 == HIGH)
          sendMessage("Main Door is closed");
        else
          sendMessage("Main Door is open");
        oldState1 = buttonState1;
      }

      int buttonState2 = digitalRead(Store);
      if (buttonState2 != oldState2) {
        digitalWrite(Store_led, buttonState2 );
        if (buttonState2 == HIGH)
          sendMessage("Store room is closed");
        else
          sendMessage("Store room is open");
        oldState2 = buttonState2;
      }
    }

title: Problem regarding Arduino & GSM module kit

Answers: 0


body:
I am using an Arduino due and have multiple schedules running at the same time. I am using this [Library](https://github.com/arduino-libraries/Scheduler).

I have a function that 3 different loops use. Two of the loops are driven by user interaction so timing is not possible. The function does reset global variables and I would have no issue with the variables being reset multiple times as it wouldn't cause any problems for me.

What I was wondering, on the very slim chance that two loops called the function at the same time, is it possible for the loops to modify the same variable at identical times?

My understanding of the scheduler would lead me to believe that the scheduler will only yield to another loop after it has completed a line of code and thus the to instructions to reset the global variable could not happen at the very same time, just extremely quickly one after the other.

Would this be a correct assumption?

title: Scheduled loops using same function

Answers: 2

body:
From the [Arduino Reference][1] pages:
> This is a cooperative scheduler in that the CPU switches from one task
> to another. *The library includes methods for passing control between
> tasks.*

[emphasis mine]

Which means that your code decides when it yields control to another scheduled loop (by calling `yield()`. At a quick glance, it appears that it also yields by returning. So yes, your assumption is correct.

body:
It is a simple schedular. It only changes to another task when yield() is called. The delay() function uses yield() and a lot of code and libraries use delay().
That means that if you code does not contain a delay() then you need to call delay() or yield() now and then, or other tasks will never execute.
It is probably safe to use the same function, but every time a delay() is used, an other task could run or another task will continue from there.


body:
[![ATMEGA328 pinout][1]][1]

I would like to know which pins are connected to the output of the Arduino.

For example:

- PC6 is digital 12
- PB5 is analog 13
- etc...

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

title: I would like to know the ATMEGA wiring to Arduino

Answers: 6

body:
Image searching for the term ["arduino uno pinout"](https://www.google.si/search?q=arduino+uno+pinout&tbm=isch) reveals a better pinout diagram.

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

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

body:
I think this is the diagram you are seeking.
[![enter image description here][1]][1]

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

body:
I prefer this image, as it combines the arduino pin numbers and PWM capabilities, with the names and functions from the datasheet.

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

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

body: Updated: Pins PB6 & PB7 while available as I/O pins (D6 & D7) are committed to the external crystal on this board and not brought out to the connectors.

body:
Or you could simply look at the [Arduino Uno schematic][1], which has everything you should ever need to know.

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

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
  [2]: https://i.stack.imgur.com/1qrSc.png

body:
I usually preferred this image. It very useful for me every time.

[![Atmega Pin Mapping][1]][1]

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


body:
I was designing a circuit that measure distance using HC-SR04 and display it into a LCD.This circuit also have 4 LEDs indicator.But i have a problem.The LEDs doesn't turn on.The LCDs backlight turn on, but it didnt display anything. Btw, i'm using LCD with I2C module.Here is the code:
[![The Schematic][1]][1]

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
    #define trigPin 6
    #define echoPin 7
    int led5cm = 8;
    int led7cm = 9;
    int led10cm = 10;
    int ledoor = 11; //ledoor means LED Out of Range
    void setup() { // put your setup code here, to run once: lcd.begin(16,2); lcd.setCursor(0,0);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(led5cm, OUTPUT);
      pinMode(led7cm, OUTPUT);
      pinMode(led10cm, OUTPUT);
    }
    void loop() {
      long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration / 2) / 29.1;
      if (distance <= 5)
      { lcd.println("Distance < 5 CM");
        lcd.print("Distance = ");
        lcd.print(distance);
        lcd.print(" CM");
        digitalWrite(led5cm, HIGH);
        digitalWrite(led7cm, LOW);
        digitalWrite(led10cm, LOW);
        digitalWrite(ledoor, LOW);
        lcd.clear();
        delay(200);
      } else if (distance >= 5 || distance <= 7) {
        lcd.println("Distance < 7 CM");
        lcd.print("Distance = ");
        lcd.print(distance);
        lcd.print(" CM");
        digitalWrite(led5cm, LOW);
        digitalWrite(led7cm, HIGH);
        digitalWrite(led10cm, LOW);
        digitalWrite(ledoor, LOW);
        lcd.clear();
        delay(200);
      }
      else if (distance >= 7 || distance <= 10) {
        lcd.println("Distance < 10 CM");
        lcd.print("Distance = ");
        lcd.print(distance);
        lcd.print(" CM");
        digitalWrite(led5cm, LOW);
        digitalWrite(led7cm, LOW);
        digitalWrite(led10cm, HIGH);
        digitalWrite(ledoor, LOW);
        lcd.clear();
        delay(200);
      }
      else if (distance > 10) {
        lcd.println("Out of Range");
        lcd.print("Distance = ");
        lcd.print(distance);
        lcd.print(" CM");
        digitalWrite(led5cm, LOW);
        digitalWrite(led7cm, LOW);
        digitalWrite(led10cm, LOW);
        digitalWrite(ledoor, LOW);
        lcd.clear();
        delay(200);
      }
    }

Can you please help me solve this problem? Thank you very much!!

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

title: HC-SR04 and LCD Circuit Problem

Answers: 1

body:
To make your LCD work, add code like the following in `setup()`.  (Substitute appropriate values in place of `LCDcols` and `LCDrows`, or give them appropriate values via `const int ...` or `enum { ... };` statements.)

      lcd.begin(LCDcols, LCDrows);
      lcd.setBacklightPin(3,POSITIVE); // Might not need this, since info appears to be included in lcd declaration
      lcd.setBacklight(HIGH);
      lcd.clear();          // Clear the display
      lcd.home();

To make the LEDs work better, you may need to change the `||` connectives in some of the `if` statements to `&&`.  An `if` condition with terms joined by `||`, OR, is true if *any* of its terms are true; with terms joined by `&&`, AND, *all* of its terms must be true for the condition to be true.

For example, the condition `(distance >= 5 || distance <= 7)` is true if distance is 5 or more, or 7 or less; in other words, is always true.


body:
I am currently following [this][1] tutorial on building a Simple Audio Player for the Arduino. I was about to finish the circuit only to realize that the required board is an Arduino Due and I have the Uno.

Because the Uno does not have its own DAC port, I was wondering what other options are available for me to accomplish the same thing while keeping the circuit as similar to the one listed in the tutorial.

Thanks

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

title: Custom DAC for Arduino UNO

Answers: 3

body:
You can probably use the same circuit and the PWM "Analog" output of the Duo (after adding a low pass filter) to play simple tones, and maybe do something on the input side to allow you to change the frequency in response to some user input.

I don't think you'll get the Duo to read from the SD Card and play the audio simultaneously.

body:
There are three basic ways of creating a DAC.

The simplest, though roughest, is to use PWM, then low-pass filter it.  Not perfect, but rough and ready. Only needs a resistor and a capacitor.

The highest quality way, though slowest for interfacing, is to use an external DAC chip. Fine for low frequency response reproduction, and the linearity is second to none. The MCP4821/2 is a popular choice (SPI connected).

The third option is to build your own DAC using an R-2R ladder. You can make an 8-bit DAC with very fast response by using all 8 pins of a single IO port (such as pins 0-7 on the Uno are bits 0-7 of port D). However the linearity of an R-2R ladder very much depends on how well matched your resistors are.

The R-2R ladder should be buffered with an amplifier of some form before driving a low impedance device like a speaker.

None of them are really great for audio work - for that you need a chip with much more processing power and memory, and a high speed digital audio interface, such as I2S, to interface a proper audio CODEC chip. Personally I use PIC32MZ chips for audio work.

body:
The major problem you have is that the Audio library functions are specifically written for the ARM based Due.
You could certainly add an I2C 10 bit (Mono or Stereo) DAC chip to an Arduino Uno capable of producing stereo signals through an LM386, but you would have to re-write the Audio library to support that functionality on the Uno.


body:
I have a LG TV(LG 32SL800 ZB), which has a RS232-Port for Control and Service.

And I am wondering if I could control this port with my Arduino (NODE-MCU) and a module like this one [RS232 Board][1]?

How could I then control the TV? This is the [Manual][2] for the TV at page 124 there are the commands how to control it, but how can I send them?

My last question is, how long can the cables from the arduino to the module be? They have to be about 2-3m long! Is that possible without any other hardware?

  [1]: http://www.waveshare.com/rs232-board.htm
  [2]: https://drive.google.com/uc?export=download&id=0B_ayS6QBJX3VR2V1X1VxRlloZm8

title: Arduino Control TV over RS232

Answers: 1

body:
> And I am wondering if I could control this port with my Arduino (NODE-MCU) and a module like this one?

Yes, you can, though choose a board based around the MAX3232 for a 3.3V MCU board.

> How could I then control the TV? This is the Manuel for the TV at page 124 there are the commands how to control it, but how can I send them?

Exactly as they show in the manual. For example:

    Serial.print("ka 0 01\r");

That would turn on every TV connected to the serial bus.

> My last question is, how long can the cables from the arduino to the module be? They have to be about 2-3m long! Is that possible without any other hardware?

You can get away with no more than maybe 1 meter between the Arduino and the RS232 board. Keep that as short as possible. However between the RS232 board and the TV you can have up to 15 meters of cable.


body:
I want to use an SD card and when including the library both SPI.h and SD.h are included. Also later I want to use an external SRAM chip (probably using SPI.h as well). However, without the SRAM chip my sketch uses around 849 bytes of global memory, where I expect most of it taken by the SD.h / SPI.h combination. Without these includes only 9 bytes are used.

How can I reduce the amount of global memory (still I want to use the SD and SPI interface)?

Edit:

According to a remark below 512 bytes are used for the SD so that explains mostly of the 849 bytes. And some additional questions:

Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes ...I only need to read a file (128 KB) and copy it to an SRAM (external). And I don't mind if it will be transferred in 16 byte blocks. Actually, I could get rid of the buffer at all after the SD to SRAM copy.

My ultimate goal is to leave 1KB + some dynamic memory (for function call stacks/local variables). However, finally I need to move to the Arduina Mega anyway, but was hoping I could already start the project with my Arduino Uno.

title: Global memory reduction when using SPI/SD

Answers: 1

body:
> Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes

The Arduino SD library uses an internal file block caching (512 bytes) to improve performance. It is possible to read directly from a file block on the SD but that would be very slow. Every 16 bytes read would require reading from file block, discharging all preceding bytes (as the file block is read serially), reading the 16 bytes, and then stopping the block read.

There are a few tiny SD libraries that actually use this technique. See for instance Petit FAT File System http://elm-chan.org/fsw/ff/00index_p.html

Another technique is to block copy from the SD directly to the external SRAM without going through additional buffers. This requires a refactoring of the SD library so that it uses a callback instead of the internal buffer.

Cheers!


body: I am designing an industrial control panel using arduino. I have to use time delays as long as 10 seconds and since using delay() makes a halt in the controller I tried using millis(). But it is complicated and it will work only for 50 days. I want the system to work continuously without any maintenance and I need to control as many as 6 relays. So, I need a better solution (hardware or software based) to tackle this problem. How can I do this?

title: Time delay without using delay() and millis()

Answers: 3

body:
You may have to find a library that eases the use of what you're trying to do.
I made some timer library, called **SeqTimer**.
You can find it here: [Link](https://github.com/SMFSW/SeqTimer)
or use the Arduino library manager, it's there too.

It's a simple library using millis(), without callback, so it's pretty straightforward.
If you need more advanced timer, search for 'timer' for example in the arduino library manager, there's a bunch of libs related to timers.

Yet, I'm not really sure what you mean by:
 > work only for 50 days

body:
>  it will work only for 50 days.

it overflows in 50 days but comparisons based on it can be good even if it overflows. you just need to recognize the overflow and program accordingly.

so millis() is perfectly fine for what you are trying to do. no need to reinvent the wheels.

body: You misunderstand the 50 day thing. Yes it rolls over after 50 days but that doesn't mean it stops working. As long as you program your comparisons correctly (something people often don't do in online examples) then all it means is the *maximum delay* you can have is 50 days.


body: I salvaged an SPI interface LCD from an old CDMA telephone. It seems it uses SPI to display something on the screen. The pins marks are DATA, CS, SCLK, BL, VDD, GND, LED, A0, and RES. How do I wire it up to an Arduino?

title: Pin identification for a salvaged LCD

Answers: 1

body:
They seem pretty self-explanatory. Data, sclk and cs are normal SPI MOSI, CLK and CS. A0 is probably equivalent to C/D. RES is reset - tie high to run. Power and ground are obvious. The others look related to the back light.

However... How are you going to operate it? Do you know the SPI instructions to send? They will be specific to the display, so without a datasheet you're pretty much stuffed.


body: We're currently working on a direct sketch to printed circuit board printer for our design project. We need a sensor for the ink level since we're using a pen. Can we use this ( https://www.dfrobot.com/wiki/index.php/Non-contact_Liquid_Level_Sensor_XKC-Y25-T12V_SKU:_SEN0204) as a sensor even if its non-conductive type ink (normal ink we use for writing)? Thanks for the response!

title: Liquid level sensor

Answers: 1

body:
Your link page says:

>There are no special requirements for the liquid

So, I would not concern about the conductivity of the liquid.


body: Im connecting an SD card module to arduino pro with 3.3v , the card is getting initialized , but im getting an error message that FAT 32 partition is not available , but it is already in FAT 32 format , is this an voltage issue ? should i connect it to a 5v line? Ive tried it two libraries SD and sdfat libraries , im getting same results, im using 8gb memory card

title: SD card in Arduino

Answers: 1

body:
A SD card is 3.3V.
Have you read this: [Arduino.cc forum about SD Formatter][1] ?
Perhaps it is a cheap module with bad contacts.
Perhaps your 8GB card is not compatible. Do you have another memory card ? Preferably older and less memory.
Perhaps you use long wires, or a breadboard with bad contacts.

In most cases it should work without problem. When the initialization is okay then the wiring is probably okay. Therefor I suspect that the card itself or the partition on it, is not compatible.

  [1]: https://forum.arduino.cc/index.php?topic=228201.0


body:
I've two LEDs connected to the arduino uno's pin 12 and 13. I want to control the LEDs independently from the MATLAB serial command.

Here is my MATLAB serial command from where I'm sending char array

    s = serial('COM4','BaudRate',9600);
    fopen(s);
    output = [2,1];
    data = char(output);
    fprintf(s,'%d',data);
    fprintf(s);

And this is my Arduino code to receive char array

    char d[4];
    void setup()
    {
       Serial.begin(9600);
       pinMode(12,OUTPUT);
       pinMode(13,OUTPUT);
    }

    void loop()
    {
        if(Serial.available()>0)
      {
        for(int i=0;i<3;i++)
        {
          d[i] = Serial.read();
        }
        d1 = d[0]-'0';
        if (d1 == 1)
       {
        digitalWrite(12, HIGH);
        delay(1000);
         digitalWrite(12, LOW);
        delay(1000);
        }
      else if (d1 == 2)
        {
        digitalWrite(12, HIGH);
        delay(2000);
        digitalWrite(12, LOW);
        delay(1000);
        }
        d2 = d[1]-'0';
        if (d2 == 1)
       {
        digitalWrite(13, HIGH);
        delay(1000);
         digitalWrite(13, LOW);
        delay(1000);
        }
      else if (d2 == 2)
        {
        digitalWrite(13, HIGH);
        delay(2000);
        digitalWrite(13, LOW);
        delay(1000);
        }
      }
    }

The MATLAB command is intended to keep the LED on for the given seconds. When I tried this code for one LED(sending only single char) it worked fine. But when I tried it for two LEDs it turns on only LED connected to pin 12 twice.

Eg:
MATLAB command output = [2,1], turns on LED(pin 12) for 2 sec and then for 1 sec but I want it should be to turn on LED(pin 12) for 2 sec and LED (pin 13) for 1 sec.

title: Problem sending array data from matlab to arduino

Answers: 0


body:
I'm working on a project using 2 Arduinos connected to 2 computers to demo Serial to Serial communication.

We're using Arduino Uno connected to the computer via Serial and software serial for inter-Arduino communication. We used wires to connect software serial RX & TX lines, but we'd like to connect these pins to a laser transmitter and receiver.

We're trying to show wireless communication using an optical medium, which is why we wanted to use a Laser transmitter and receiver.

We're trying something like the setup in this YouTube video [$3 laser transmits audio over 100m (Arduino)](https://www.youtube.com/watch?v=MCTqC2-AN7o)

Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?

Receiver: [Laser Sensor Module non-modulator Tube Laser Receiver](http://www.ebay.com/itm/Laser-Sensor-Module-non-modulator-Tube-Laser-Receiver-New-Module-/401160430957)

Transmitter: [5V ... Board For Arduino AVR ... KY-008 Laser Transmitter](http://www.ebay.com/itm/5Pcs-5V-Sensor-Module-Board-For-Arduino-AVR-PIC-KY-008-Laser-Transmitter/282387608849?_trksid=p2047675.c100005.m1851&_trkparms=aid=2220072&algo=SIC.MBE&ao=2&asc=20131003132420&meid=2408f91403264ad2926b2048bf0c53c3&pid=100005&rk=1&rkt=6&sd=401160430957)

  [3]: https://www.youtube.com/watch?v=MCTqC2-AN7o

title: Laser emitter + receiver for Arduino (Arduino to Arduino communication)

Answers: 1

body:
> Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?

Looks like the receiver module has a [low-pass filter][1]. That could reduce the baud-rate depending on the RC-factor (10 Kohm * 10 nF gives a cut-off frequency of [1.6 kHz][2]). I would recommend checking the actual components. The above is a guesstimate.

Cheers!

  [1]: https://en.wikipedia.org/wiki/Low-pass_filter
  [2]: http://www.learningaboutelectronics.com/Articles/Low-pass-filter-calculator.php#answer1


body:
Many older amplifiers support wired remote control through connector jacks or ports. My 10-year old Marantz also supports this function, using [a simple RCA connector][1].

Originally these were used with [external IR receivers][2] when the unit was not kept in plain sight.

I wonder if there is a way to control the amplifier using an Arduino, which probably means by generating the required signal over the connector instead of receiving it from an IR receiver. Any pointer to a similar project is appreciated as well.

  [1]: http://manuals.marantz.com/NA8005/NA/EN/DNTXSYlyopmtcn.php
  [2]: https://www.wehkamp.nl/Winkelen/KenmerkAdviseurArtikel.aspx?CC=C26&SC=6F1&KAC=F17&artikelNummer=582788&MaatCode=0000&BC=GOA&BAC=ALG&cm_mmc_o=7BBTkwCjC-kTwFwwECVyBpAgfkblfbETzplCjC-ggwllBbywCaeCCjCoxDonIoo&utm_source=google&utm_medium=cpc&scid=scplp865827880000&sc_intid=865827880000&cm_mmca1=12913-AGI-23705142542-ASI-168204110942-865827880000&gclid=CM_xnPTb3dICFUkQ0wodeoAHGg&gclsrc=aw.ds&dclid=COrKpfTb3dICFdGWdwodqCgDSA

title: Controlling amplifier using remote control jack

Answers: 1

body:
According to this thread on [remotecentral][1] the signal on the RCA connector is just the inverted signal that the IR-LED receives. So if you load an RC5 library and invert the output (0=1 and 1=0), you should be able to send codes to that connector with an arduino. Or even better, use an ESP8266 and control it over wifi ;)<BR>
The RC5 codes and their functions are in this  [nice excel sheet][2] or use [this information][3] if you want to send raw hex

  [1]: http://www.remotecentral.com/cgi-bin/mboard/rc-theater/thread.cgi?4877
  [2]: http://m.us.marantz.com/DocumentMaster/US/Marantz 2014 IR Command Sheet.xls
  [3]: http://www.remotecentral.com/cgi-bin/codes/marantz/


body:
Using precisely this code - the ***eeprom_put*** example in the Arduino IDE, and am seeing some strange results...

The sketch does write correctly to eeAddress = 0, and the corresponding ***eeprom_get*** sketch does return the data.

Please note that I've initialized the entire EEPROM with 'FF's before any test...

The weird part is this sketch writes exactly the same data starting at Address = 2048. The loop is not running; I see no jump to offset 2048... I gotta be missing something!

I'm dumping EEPROM using avrdude, and viewing results in an external hex editor.

How is this stuff stored? Apart from not being able to directly view a float - OK, I get it - should the other data be simply *viewable* in hex?

My own experiments in writing hex bytes directly also work, but also write in two locations.

Small update to this: Precisely the same behavior seen with a RobotDyn Mega. Both the 'clone' Mega and the RobotDyn report: Device signature = 0x1e9801 (probably m2560)

    #include <EEPROM.h>

    struct MyObject {
      float field1;
      byte field2;
      char name[10];
    };

    void setup() {

      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      float f = 123.456f;  //Variable to store in EEPROM.
      int eeAddress = 0;   //Location we want the data to be put.

      //One simple call, with the address first and the object second.
      EEPROM.put(eeAddress, f);

      Serial.println("Written float data type!");

      /** Put is designed for use with custom structures also. **/

      //Data to store.
      MyObject customVar = {
        3.14f,
        65,
        "Working!"
      };

      eeAddress += sizeof(float); //Move address to the next byte after float 'f'.

      EEPROM.put(eeAddress, customVar);
      Serial.print("Written custom data type! \n\nView the example sketch eeprom_get to see how you can retrieve the values!");
    }

    void loop() {
      /* Empty loop */
    }

title: Arduino eeprom_put sketch writes data in two locations?

Answers: 1

body:
What is probably happening is [aliasing][1].  Let's say your processor has a 16 bit address bus.  16 bits can count up to 2^16 = 65536 = 64k memory addresses.  Each address is a byte (B) so your processor has 64k-Bytes of address space.  It can physically address 64kB of memory.

What happens if you only have one memory chip with 4KBytes of memory, with  only 12 address lines?  Well, if the designer was lazy (or cost-conscious), the first 12 address lines on the processor will be connected to the 12 lines on the memory chip.  The other 4 lines on the processor will be ignored.

So it doesn't matter what the processor does with address lines 13-16 -- they're not connected to the memory chip.  Therefore the contents of the memory chip appears where you expect, starting at address `0`, but also again at address 4096, and again at address 8192 and so on.

  [1]: https://en.wikipedia.org/wiki/Aliasing_(computing)


body:
I planed a 6x6 matrix with a Arduino Nano as controller.
Its only possible to let one LED in the matrix lighten up.
Any idea how I get the Code smaller? (Im a C Noobie ^^)

*~Nico*

Circuit diagram:
[![enter image description here][1]][1]

Code:

>     void setup() {
>       pinMode(1, OUTPUT);
>       pinMode(2, OUTPUT);
>       pinMode(3, OUTPUT);
>       pinMode(4, OUTPUT);
>       pinMode(5, OUTPUT);
>       pinMode(6, OUTPUT);
>       pinMode(7, OUTPUT);
>       pinMode(8, OUTPUT);
>       pinMode(9, OUTPUT);
>       pinMode(10, OUTPUT);
>       pinMode(11, OUTPUT);
>       pinMode(12, OUTPUT);
>       pinMode(13, OUTPUT);
>       pinMode(14, INPUT);
>       pinMode(15, INPUT);
>       pinMode(16, INPUT);
>       pinMode(17, INPUT);
>     }
>
>     void loop() {
>       int value1 = digitalRead(14);
>       int value2 = digitalRead(15);
>       int value3 = digitalRead(16);
>       int test = digitalRead(17);
>       int x1 = 2;
>       int x2 = 3;
>       int x3 = 4;
>       int x4 = 5;
>       int x5 = 6;
>       int x6 = 7;
>       int y1 = 8;
>       int y2 = 9;
>       int y3 = 10;
>       int y4 = 11;
>       int y5 = 12;
>       int y6 = 13;
>
>
>       // put your main code here, to run repeatedly:
>
>
>       if (test == HIGH) {
>         digitalWrite(x1, HIGH);
>         digitalWrite(y1, HIGH);
>         delay(15);
>         digitalWrite(y1, LOW);
>         digitalWrite(y2, HIGH);
>         delay(15);
>         digitalWrite(y2, LOW);
>         digitalWrite(y3, HIGH);
>         delay(15);
>         digitalWrite(y3, LOW);
>         digitalWrite(y4, HIGH);
>         delay(15);
>         digitalWrite(y4, LOW);
>         digitalWrite(y5, HIGH);
>         delay(15);
>         digitalWrite(y5, LOW);
>         digitalWrite(y6, HIGH);
>         delay(15);
>         digitalWrite(y6, LOW);
>         digitalWrite(x1, LOW);
>         digitalWrite(x2, HIGH);
>         digitalWrite(y1, HIGH);
>         delay(15);
>         digitalWrite(y1, LOW);
>         digitalWrite(y2, HIGH);
>         delay(15);
>         digitalWrite(y2, LOW);
>         digitalWrite(y3, HIGH);
>         delay(15);
>         digitalWrite(y3, LOW);
>         digitalWrite(y4, HIGH);
>         delay(15);
>         digitalWrite(y4, LOW);
>         digitalWrite(y5, HIGH);
>         delay(15);
>         digitalWrite(y5, LOW);
>         digitalWrite(y6, HIGH);
>         delay(15);
>         digitalWrite(y6, LOW);
>         digitalWrite(x2, LOW);
>         digitalWrite(x3, HIGH);
>         digitalWrite(y1, HIGH);
>         delay(15);
>         digitalWrite(y1, LOW);
>         digitalWrite(y2, HIGH);
>         delay(15);
>         digitalWrite(y2, LOW);
>         digitalWrite(y3, HIGH);
>         delay(15);
>         digitalWrite(y3, LOW);
>         digitalWrite(y4, HIGH);
>         delay(15);
>         digitalWrite(y4, LOW);
>         digitalWrite(y5, HIGH);
>         delay(15);
>         digitalWrite(y5, LOW);
>         digitalWrite(y6, HIGH);
>         delay(15);
>         digitalWrite(y6, LOW);
>         digitalWrite(x3, LOW);
>         digitalWrite(x4, HIGH);
>         digitalWrite(y1, HIGH);
>         delay(15);
>         digitalWrite(y1, LOW);
>         digitalWrite(y2, HIGH);
>         delay(15);
>         digitalWrite(y2, LOW);
>         digitalWrite(y3, HIGH);
>         delay(15);
>         digitalWrite(y3, LOW);
>         digitalWrite(y4, HIGH);
>         delay(15);
>         digitalWrite(y4, LOW);
>         digitalWrite(y5, HIGH);
>         delay(15);
>         digitalWrite(y5, LOW);
>         digitalWrite(y6, HIGH);
>         delay(15);
>         digitalWrite(y6, LOW);
>         digitalWrite(x4, LOW);
>         digitalWrite(x5, HIGH);
>         digitalWrite(y1, HIGH);
>         delay(15);
>         digitalWrite(y1, LOW);
>         digitalWrite(y2, HIGH);
>         delay(15);
>         digitalWrite(y2, LOW);
>         digitalWrite(y3, HIGH);
>         delay(15);
>         digitalWrite(y3, LOW);
>         digitalWrite(y4, HIGH);
>         delay(15);
>         digitalWrite(y4, LOW);
>         digitalWrite(y5, HIGH);
>         delay(15);
>         digitalWrite(y5, LOW);
>         digitalWrite(y6, HIGH);
>         delay(15);
>         digitalWrite(y6, LOW);
>         digitalWrite(x5, LOW);
>         digitalWrite(x6, HIGH);
>         digitalWrite(y1, HIGH);
>         delay(15);
>         digitalWrite(y1, LOW);
>         digitalWrite(y2, HIGH);
>         delay(15);
>         digitalWrite(y2, LOW);
>         digitalWrite(y3, HIGH);
>         delay(15);
>         digitalWrite(y3, LOW);
>         digitalWrite(y4, HIGH);
>         delay(15);
>         digitalWrite(y4, LOW);
>         digitalWrite(y5, HIGH);
>         delay(15);
>         digitalWrite(y5, LOW);
>         digitalWrite(y6, HIGH);
>         delay(15);
>         digitalWrite(y6, LOW);
>         digitalWrite(x6, LOW);
>
>
>
>       }
>     }

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

title: code optimazation 6x6 Matrix

Answers: 2

body:
You can use arrays to hold sets of row pin numbers or column pin numbers, which then allows use of `for` loops for `pinMode()` settings and for testing LEDs one after another, as shown in code below.

Note, using `enum { ... };` for integer-constant declarations is slightly more compact than a series of `const int` statements.  When a constant name in an `enum` does not have an `=` and value after it, it is given a value one larger than the previous constant.  So, for example, the first `enum` in the following code sets `x2` to 3, `x3` to 4, etc.

    enum { x1=2, x2, x3, x4, x5, x6};
    enum { y1=8, y2, y3, y4, y5, y6};
    const byte rowPins[] = { x1, x2, x3, x4, x5, x6};
    const byte colPins[] = { y1, y2, y3, y4, y5, y6};
    enum { nRow = sizeof rowPins / sizeof rowPins[0] };
    enum { nCol = sizeof colPins / sizeof colPins[0] };

    void setup() {
      for (byte i=0; i<nRow; ++i) pinMode(rowPins[i], OUTPUT);
      for (byte i=0; i<nCol; ++i) pinMode(colPins[i], OUTPUT);
      for (byte i=14; i<18; ++i)  pinMode(i, INPUT);
    }

    void loop() {
      byte test = digitalRead(17);
      if (test) {
        for (byte x=0; x<nRow; ++x) {
          digitalWrite(rowPins[x], HIGH);
          for (byte y=0; y<nCol; ++y) {
            digitalWrite(colPins[y], HIGH);
            delay(15);
            digitalWrite(colPins[y], LOW);
          }
          digitalWrite(rowPins[x], LOW);
        }
      }
    }

Note, subroutines and functions can be used to modularize code and (typically) reduce its volume.  See code sample below.  In the code as is, the subroutine doesn't particularly reduce volume, but definitely adds modularity.  You may find it useful to look up *refactoring*.

    enum { x1=2, x2, x3, x4, x5, x6};
    enum { y1=8, y2, y3, y4, y5, y6};
    const byte rowPins[] = { x1, x2, x3, x4, x5, x6};
    const byte colPins[] = { y1, y2, y3, y4, y5, y6};
    enum { nRow = sizeof rowPins / sizeof rowPins[0] };
    enum { nCol = sizeof colPins / sizeof colPins[0] };

    void setup() {
      for (byte i=0; i<nRow; ++i) pinMode(rowPins[i], OUTPUT);
      for (byte i=0; i<nCol; ++i) pinMode(colPins[i], OUTPUT);
      for (byte i=14; i<18; ++i)  pinMode(i, INPUT);
    }

    void lightup(byte x, byte y, unsigned int howLong) {
      digitalWrite(rowPins[x], HIGH);
      digitalWrite(colPins[y], HIGH);
      delay(howLong);
      digitalWrite(colPins[y], LOW);
      digitalWrite(rowPins[x], LOW);
    }

    void loop() {
      byte test = digitalRead(17);
      if (test) {
        for (byte x=0; x<nRow; ++x)
          for (byte y=0; y<nCol; ++y)
            lightup(x, y, 15);
      }
    }

body:
> Any idea how I get the Code smaller?

don't try to get the code smaller -> try to get it working.

for things like this, you should think about

1) how to structure the display data: typically it is done in a matrix format. I would structure it as an array of 6 chars / columns, with the rows in the lowest 6 bits;

2) how to track the column being displayed and updated: using a static variable typically;

3) how to update the display periodically: via a timer interrupt usually.

Each update would go something like this:

      turn off all columns;
      present row information;
      update the column index and turn it on;

what's left is to implement that in a way that the code is flexible and portable to a different application.

once that's done, all your application needs to do is to stuff the right information into the display buffer and the display routine, invoked via a timer isr, will take care of the updating all by itself, without user involvement.

if you still need help, let us know.

edit: i put this together quickly to demonstrate the concept.

it is a display routine, led_display(), being invoked via a timer2 interrupt, displaying data in an 8-char buffer, 0x11, 0x22, ..., 0x88.

the scanning is done by colomn (active high), and the rows are connected to D0..D7, and the cols D8..D13, A0, A1, all user configurable.

    //global variables
    uint8_t lRAM[COL_NUM]={   //display buffer
     0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88
    };

    const uint8_t row_pins[ROW_NUM]={ //pins tied to matrix' rows
     0, 1, 2, 3, 4, 5, 6, 7,
    };

    const uint8_t col_pins[COL_NUM]={ //pins tied to columns
     8, 9, 10, 11, 12, 13, A0, A1,
    };

once the initialial set-up is done, there is nothing the user needs to do, other than filling the display buffer with information s/he wishes to be displayed.

    void setup() {
       // put your setup code here, to run once:
       //pinMode(led, OUTPUT);
       led_init();       //reset the led module

       //set up timer2
       tmr2_init(TMR2PS_32x);    //timer2 with 32:1 prescaler -> 16Mhz / 256 / 32 = 2Khz per col.
       tmr2_act(led_display);    //install user handler to update the display periodically
    }

    void loop() {
       // put your main code here, to run repeatedly:
        //digitalWrite(led, HIGH);  // turn the LED on (HIGH is the voltage level)
        //delay(100);               // wait for a second
        //digitalWrite(led, LOW);   // turn the LED off by making the voltage LOW
        //delay(100);               // wait for a second
    }

and here is the execution.[![enter image description here][1]][1]

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

ps: the code was originally written to drive 8x7-segment displays but it works with 8x8 matrix as well -> they are essentially the same thing.

the display routine, led_display(), follows the general sketch laid out earlier.

    //update the display
    void led_display(void) {
     static uint8_t col_index=0;   //current col
     //turn off current col -> the only active col now
     COL_OFF(col_pins[col_index]);

     //update the column index
     col_index=(col_index==COL_NUM-1)?0:(col_index+1);

     //present row data
     if (lRAM[col_index] & (1<<0)) ROW_ON(row_pins[0]); else ROW_OFF(row_pins[0]);
     if (lRAM[col_index] & (1<<1)) ROW_ON(row_pins[1]); else ROW_OFF(row_pins[1]);
     if (lRAM[col_index] & (1<<2)) ROW_ON(row_pins[2]); else ROW_OFF(row_pins[2]);
     if (lRAM[col_index] & (1<<3)) ROW_ON(row_pins[3]); else ROW_OFF(row_pins[3]);
     if (lRAM[col_index] & (1<<4)) ROW_ON(row_pins[4]); else ROW_OFF(row_pins[4]);
     if (lRAM[col_index] & (1<<5)) ROW_ON(row_pins[5]); else ROW_OFF(row_pins[5]);
     if (lRAM[col_index] & (1<<6)) ROW_ON(row_pins[6]); else ROW_OFF(row_pins[6]);
     if (lRAM[col_index] & (1<<7)) ROW_ON(row_pins[7]); else ROW_OFF(row_pins[7]);

     //turn on the display
     COL_ON(col_pins[col_index]);
    }