message:
SPI communication Problem Arduino

I'm trying to set up SPI communication between two Arduinos (UNO and Mega),
I want to read the status of the slave output pin from the master.

I connected a diode to pin 9 of Mega and I wanted to display its state on the virtual terminal of the master (Uno). The problem is that when the LED flashes I do not receive values just at the terminal level but when I hold it to zero or 1 the display is correct.
I used another code I found online.

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

    #include <SPI.h>
    const byte btn =8;

    void setup(void) {

    Serial.begin (9600);
    pinMode (btn, INPUT_PULLUP);
    digitalWrite (SS, HIGH);
    SPI.begin ();
    SPI.setClockDivider (SPI_CLOCK_DIV8);

    }

    void loop(void) {

    byte Mvalsent,Mvalreceived;
    digitalWrite (SS, LOW);
    for (int jj=0; jj<255; jj++)
      {
          Mvalsent =jj;
          Mvalreceived =SPI.transfer (Mvalsent);
          Serial.print ("Retou d'etat ");
          Serial.print (Mvalsent);
          Serial.print ("\t ,l'etat de la diode est ");
          Serial.println (Mvalreceived);
          delay (400);
      }

      digitalWrite (SS,HIGH);

    }

SLAVE Code

    #include <SPI.h>
    byte state;
    const byte led =9;
    volatile boolean process_it;
    volatile byte Svalreceived, Svalsent;
    int jj=0;
    void setup (void)
    {
      Serial.begin (9600);
    pinMode (led,OUTPUT);
    //set MISO pin as output
    pinMode (MISO, OUTPUT);
    //turn on SPI in slave mode
    SPCR |= _BV (SPE);
    //get ready for an interrupt
    process_it = false;
    //now turn on interrupts
    SPI.attachInterrupt ();
    }
    ISR (SPI_STC_vect)
    {
      Svalreceived = SPDR;
      process_it =true;
    }
    void loop (void)
    {
     if (process_it)
     {

       digitalWrite (led, LOW);
       state =digitalRead(led);
       SPDR = state;
       Serial.print("l'etat de la diode est: ");
        Serial.println (state);
        delay (400);

        process_it =false;
      }
    }

body:
Why not use I2C slave-master between arduinos?  You can hook up other arduinos or devices on I2C simultaneously (as long as each uses a distinct address).

And you still keep the SPI for a microsd card adapter, for example.

Follow [this official tutorial][1]:

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

MASTER ARDUINO 1

 // Wire Master Writer
 // by Nicholas Zambetti <http://www.zambetti.com>

 // Demonstrates use of the Wire library
 // Writes data to an I2C/TWI slave device
 // Refer to the "Wire Slave Receiver" example for use with this

 // Created 29 March 2006

 // This example code is in the public domain.

 #include <Wire.h>

 void setup() {
   Wire.begin(); // join i2c bus (address optional for master)
 }

 byte x = 0;

 void loop() {
   Wire.beginTransmission(8); // transmit to device #8
   Wire.write("x is ");        // sends five bytes
   Wire.write(x);              // sends one byte
   Wire.endTransmission();    // stop transmitting

   x++;
   delay(500);
 }

SLAVE ARDUINO 2

 // Wire Slave Receiver
 // by Nicholas Zambetti <http://www.zambetti.com>

 // Demonstrates use of the Wire library
 // Receives data as an I2C/TWI slave device
 // Refer to the "Wire Master Writer" example for use with this

 // Created 29 March 2006

 // This example code is in the public domain.

 #include <Wire.h>

 void setup() {
   Wire.begin(8);                // join i2c bus with address #8
   Wire.onReceive(receiveEvent); // register event
   Serial.begin(9600);           // start serial for output
 }

 void loop() {
   delay(100);
 }

 // function that executes whenever data is received from master
 // this function is registered as an event, see setup()
 void receiveEvent(int howMany) {
   while (1 < Wire.available()) { // loop through all but the last
     char c = Wire.read(); // receive byte as a character
     Serial.print(c);         // print the character
   }
   int x = Wire.read();    // receive byte as an integer
   Serial.println(x);         // print the integer
 }

This is an alternative example of a setup using a nodemcu (which doesnt function in slave mode, btw).

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

  [1]: https://www.arduino.cc/en/Tutorial/MasterWriter
  [2]: https://i.stack.imgur.com/y4TDr.png
  [3]: https://i.stack.imgur.com/WOcfL.png


sender: user

message:
Ultrasonic sensors with 12v motors will not work! (ADRUINO)

ok... so I am using four 12V motors and one ultrasonic sensor with a motor shield... and I am getting some odd results...
in my code I have it so when the distance to a object is less than 4 cm it will go backwards and when something is not 4 cm in front of the robot it will go forwards... simple!
but the wheels on the left side of my robot will stop! and just do nothing!

The weirdest part about it is when I make some code JUST moving the wheels back and forth the wheels will work PERFECTLY fine. and when I use some code JUST for the sensors... it works fine! but together... it does all that weird stuff.

this is the shield I am using: https://www.pololu.com/product/2507

if there is any information I missed that you need let me know and I will get back with you. I am new to Arduino so I am extremely confused...

the code.

 #include "DualVNH5019MotorShield.h"
 DualVNH5019MotorShield md;

 #define trigPin 7
 #define echoPin 8

 void setup() {
    md.init();  //setting up wheel code
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
 }

 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;

 //This is the sensor testing if somthing is in range!
   if (distance < 4){
      Serial.println("in range");
      md.setM1Speed(100);
      md.setM2Speed(-100);
   }
   else {
      Serial.println("not in range");
      md.setM1Speed(-100);
      md.setM2Speed(100);
   }

   if (distance >= 200){
      Serial.println("!");
   }
   else {
      Serial.print(distance);
      Serial.println(" cm");
   }
    Serial.println(distance);
    delay(500);
 }

sender: assistant

body:
**TLDR:** change your project (both program and connection) to use ultrasound sensor on any two of pins 3,5,11 and it should work.

---

You are using `pins 7 and 8` for ultrasound.

At the same time you are using the shield  https://www.pololu.com/product/2507 for motors, but if you look at the shield description on picture `Dual VNH5019 motor driver shield with an Arduino (shield and Arduino powered separately).`https://a.pololu-files.com/picture/0J3753.1200.png?5877a2053bf73d6dbb43d10e7d268ce5 <img src="https://a.pololu-files.com/picture/0J3753.1200.png?5877a2053bf73d6dbb43d10e7d268ce5">
You will see, that the shield is using `pin 7` as `M2INA` and `pin 8` as `M2PINB`

So each loop you push `M2INA` (`trigPin`) LOW, then HIGH then LOW, then wait until the sensor write HIGH to `M2INB` (`echoPin`) just to immediately send PWM pulses to both `trigPin` (`M2INA`) and `echoPin` (`M2INB`) via commands

        md.setM1Speed(100);
        md.setM2Speed(-100);

No way it can work as you expect.

You must use other pins (unused by the shield) for your ultrasound sensor. I suggest to declare

    #define trigPin 3
    #define echoPin 5

and connect your ultrasound sensor there acordingly.

(You can use also pin 11 if you want. I would not recomend pin 13, as there is connected the Arduino LED, which is used by bootloader too so you could confuse the sensor, nor the pins 1 and 2, as they are used by Serial (and USB). Also you can use the "analog pins" A2..A5 as digital pins, but it may confuse you a little (AVR can use "analog" pins as "digital" but many beginers does not like constructs as "digitalWrite(A2)", "digitalRead(A3)").

Also keep in mind, that A4 and A5 are used for I2C communication, if you would use I2C later in project.


message:
Controlling common anode RGB LED with PWM - Can individual colors be done w/o transistors?

<br>
I am using PWM (*analogWrite*) with a common *anode* LED. My previous experience is using a common cathode. My breadboard is as shown:

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

<!-- End schematic -->

This creates a semi-bright white (ugly red-green-blue mixture) like I expected. I am using only one PWM output (It is currently fading).

Now, what I ask is how can I use multiple PWM outputs to make different colors display *without* transistors? I was thinking that I could have 3 dedicated pins on the Arduino that switch from ground to floating extremely fast, but is there an easier way?
If not, a little explanation on how to do it with transistors (mostly just a small wiring diagram) would be great. Cheers!

body:
As long as each LED in the array uses 20mA or less you can do it directly with the Arduino:

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

<!-- End schematic -->

Note that the blue LED will have a higher forward voltage than the red and green ones, hence the lower resistor.

Also note that the PWM will be inverted. Writing 255 to a channel will switch that LED off, while writing 0 will give it full brightness.


body:
> I am using only one PWM output (It is currently fading).

use three independent pwm channels to drive three leds.

> how can I use multiple PWM outputs to make different colors display without transistors?

the answer depends on the leds. for leds that require small current, it is totally doable, just connect the pwm output to them.

for leds that require lots of current, no solution.


message:
Generating a short pulse after a delay

I am trying to use one of the hardware timers on the arduino uno to generate a short pulse some number of microseconds after receiving a pulse on an input.

Currently my code looks like this:

    uint16_t pulse_delay = 12000; //half-microseconds
    uint16_t pulse_length = 20;

    void setup(){
      pinMode(8, INPUT);
      pinMode(9, OUTPUT);
      TCCR1A = 0;
      TCCR1B = _BV(ICNC1)  //input capture noise cancel
          | _BV(ICES1) //positive edge
          | _BV(CS11); // /8 prescaler
      TIMSK1 = _BV(ICIE1); //enable input capture interrupt
    }
    void loop(){}
    ISR(TIMER1_CAPT_vect){
      TCCR1A = _BV(COM1A0) | _BV(COM1A1); //set OC1A on match
      TIMSK1 |= _BV(OCIE1A); //enable match interrupt
      OCR1A = pulse_delay; //pulse begin time

      TCNT1 = TCNT1 - ICR1; //TCNT1 now contains time since input pulse, even if
                            //the interrupt isn't run immediately
    }
    ISR(TIMER1_COMPA_vect){
      TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
      TCCR1A = _BV(COM1A1); //clear OC1A on match

      OCR1A = pulse_delay + pulse_length;
    }

This code should theoretically do the task, but it doesn't produce any output at all - to my oscilloscope it looks like the output pin just stays low.

However, if I replace the last line (`OCR1A = pulse_delay + pulse_length;`) of the compare match interrupt with the following two lines, it outputs a pulse just fine. The issue with this is that it uses significantly more CPU time, and it can only count time from when the interrupt starts so if the interrupt is executed late the pulse will be longer.

      delayMicroseconds(pulse_length);
      TCCR1C = _BV(FOC1A); //manually trigger match event

All that the first version is doing differently is triggering the match event via an 'alarm' set on the timer, rather than waiting to trigger the match manually.

Why does the first version not work, and how can I make it work??

body:
Expanding on my comment, after checking experimentally that this was
indeed the issue.

## Short answer

You should do

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

    TIFR1 = _BV(OCF1A);  // clear interrutp flag

right before

    TIMSK1 |= _BV(OCIE1A);  // enable match interrupt

## Explanation

Whenever the timer reaches the value stored in one of its “compare
match” registers, this triggers a “compare match” event, which has the
effect of raising the corresponding interrupt flag (`OCF1A` in your
case). If the associated interrupt is enabled, that fires an interrupt
request, and the flag is automatically cleared when the CPU starts
executing the interrupt vector.

However, if the interrupt is _not_ enabled, the flag just stays set. If
you later enable the interrupt when the flag is already set, the
interrupt request is sent immediately. This is not what you want, you
want the interrupt to fire only on the _next_ match. For this to happen,
you have to clear the interrupt flag prior to enabling the interrupt.

The interrupt flags have a very non-intuitive behavior: you _clear_ the
flag by writing a logic _one_ to it. Thus the line:

    TIFR1 = _BV(OCF1A);  // clear interrutp flag

For completeness, I would also clear `ICF1` before enabling `ICIE1`,
although this seems to not be critical for the working of your program.

Also, as a side note, be aware that the timer can increment while the
CPU is in the middle of executing `TCNT1 = TCNT1 - ICR1;`. If you want
the cleanest possible timings, leave the timer free-running and just set
`OCR1A` to the appropriate values: `ICR1+pulse_delay`, then
`ICR1+(pulse_delay+pulse_length)`.


message:
Arduino MIDI Program Change to Voodoo Labs GCX Converter

To define the problem, the L6 Helix can generate 6 immediate MIDI messages. These messages are pretty flexible as to what you want, but the Voodoo Labs GCX needs at least 8 CC messages to properly configure it worst case. Also, I don't want to burn all of my immediate commands to control most of the GCX. So I had the idea to create a Arduino project that would take MIDI PC and MIDI Bank Select to produce a 8 bit value which I could then convert into 8 CC messages between CC#80 and CC#87.

body:
To solve this problem I used an Arduino UNO and a Olimex MIDI shield. I also want to use MIDI PC messages and Bank Selects.

For reference:

 - A Channel 16 PC 77 with Bank select 0 converts to binary 0x4D => Binary 01001101
 - A Channel 16 PC 77 with Bank Select 1 converts to binary 0xCD => Binary 11001101

Just to point out, the Bank Select value basically controls bit 8 and the PC value represents bits 6 down to 0

Based on the binary output, I scroll through bits 0 to 7 and send messages on CC 80 to CC 87. If a bit is a 1, I turn the loop on by setting the corresponding CC value to 127 and if it is a zero, I set the CC value to 0.

The Helix can generate a Bank Select and PC as one message, so for the price of one message, this project will make me 8 CC#'s effectively. ;)

It should allow other messages through, with the Arduino's SW loop latency. There maybe some other side effects to, but those should be limited to channel 16 only.

I have tested this on a Arduino UNO board with an Olimex MIDI Shield.

    // GCX Editor
    // By Rich Maes
    // Converts MIDI PC's on channel 16 to GCX CC's starting at 0x80
    // Allows everything else to pass.

    #define MIDI_PC_CH16 0xCF
    #define MIDI_CC_CH16 0xBF
    #define MIDI_SYSEX 0xF0
    #define MIDI_SYSRT_CLK 0xF8

    boolean byteReady;
    boolean sendCCMessage;
    int ccMsgsToSend;
    unsigned char midiByte;
    unsigned char capturePCByte;
    unsigned char captureCCByte;

    // Queue Logic for storing messages
    int headQ = 0;
    int tailQ = 0;
    unsigned char tx_queue[128];

    int getQDepth();
    void addQueue(unsigned char myByte);
    void addCCQueue(unsigned char captureCCByte, unsigned char capturePCByte);
    unsigned char deQueue();

    static enum {
        STATE_UNKNOWN,
        STATE_1PARAM,
        STATE_1PARAM_CONTINUE,
        STATE_2PARAM_1,
        STATE_2PARAM_2,
        STATE_2PARAM_1_CONTINUE,
        STATE_PASSTHRU
      } state = STATE_UNKNOWN;

    void setup() {
      // put your setup code here, to run once:
      //  Set MIDI baud rate:
      Serial.begin(31250);
      sendCCMessage = false;
      byteReady = false;
      midiByte = 0x00;
      state = STATE_UNKNOWN;
      captureCCByte = 0;
      capturePCByte = 0;
      ccMsgsToSend = 0;
    }

    int getQDepth() {
    int depth = 0;
        if (headQ < tailQ) {
            depth = 128 - (tailQ - headQ);
        } else {
            depth = headQ - tailQ;
        }
        return depth;
    }

    void addQueue (unsigned char myByte) {
        int depth = 0;
        depth = getQDepth();

        if (depth < 126) {
            tx_queue[headQ] = myByte;
            headQ++;
            headQ = headQ % 128; // Always keep the headQ limited between 0 and 127
        }
    }

    void addCCQueue(unsigned char myCaptureCCByte, unsigned char myCapturePCByte) {
        int i;
        if (getQDepth() < 80) {
            // There is enough space to add our CC messages
            for (i = 0; i < 8; i++) {
                addQueue(0xBF);
                addQueue(80 + i);
                addQueue(127 * ((((myCaptureCCByte * 128) + myCapturePCByte) >> i) % 2));
            }
        } else {
            // This is an error condition.  So reset the queue and pointers
            headQ = 0;
            tailQ = 0;
            byteReady = false;
            for (i = 0; i < 128; i++) {
                tx_queue[i] = 0;
            }
        }
    }

    unsigned char deQueue() {
        unsigned char myByte;
        myByte = tx_queue[tailQ];
        tailQ++;
        tailQ = tailQ % 128;  // Keep this tailQ contained within a limit
        // Now that we dequeed the byte, it must be sent.
        return myByte;
    }

    void loop() {
        if (byteReady) {
            if (midiByte >= 0xF0) {
                // This automatically passes all clocks and System Realtime Messages
                state = STATE_PASSTHRU;
            } else if (midiByte >= 0x80) {
                switch (midiByte) {
                case MIDI_PC_CH16:
                    state = STATE_1PARAM;
                    break;
                case MIDI_CC_CH16:
                    state = STATE_2PARAM_1;
                    break;
                default:
                    state = STATE_PASSTHRU;
                    break;
                }
            }  else {
                switch (state) {
                case  STATE_1PARAM:
                    capturePCByte = midiByte;
                    state = STATE_1PARAM_CONTINUE;
                    addCCQueue(captureCCByte, capturePCByte);
                    break;
                case STATE_2PARAM_1:
                    if (midiByte == 32) state = STATE_2PARAM_2;
                    else state = STATE_2PARAM_1_CONTINUE;
                    break;
                case STATE_2PARAM_2:
                    state = STATE_2PARAM_1_CONTINUE;
                    captureCCByte = midiByte;
                    break;
                default:
                    state = STATE_PASSTHRU;
                    break;
                }
            }
        }

        if ((state == STATE_PASSTHRU) && byteReady) {
            // Just pass messages unaltered.  Also don't let any of our modified message through if
            // we are passing though.  Our burst of modified CC# can wait.
            // Serial.write(midiByte);
            addQueue(midiByte);
            // state = STATE_UNKNOWN;
        }
        byteReady = false;

        if (getQDepth() > 0) {
            // We have a byte to send, dequeu and send it
            Serial.write(deQueue());
        }
    }

    // The little function that gets called each time loop is called.
    // This is automated somwhere in the Arduino code.
    void serialEvent() {
      if (Serial.available()) {
        // get the new byte:
        midiByte = (unsigned char)Serial.read();
        byteReady = true;
      }
    }


message:
Toggle a led with a switch

My code:

    const int buttonPin = 2;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin

    bool buttonState = 0;         // variable for reading the pushbutton status
    bool ledState = 0;
    void setup() {
      pinMode(ledPin, OUTPUT);   // initialize the LED pin as an output:
      pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
    }
    void loop() {
      buttonState = digitalRead(buttonPin);// read the state of the pushbutton value:
      if (buttonState == HIGH)
     {
      ledState = !ledState;
     }
      if (ledState == HIGH)
     {
       digitalWrite(ledPin, HIGH); // turn LED on:
     }
       else
     {
        digitalWrite(ledPin, LOW); // turn LED off:
     }
    }

So this is supposed to toggle a led's light on and off. currently it does do that but its not always the case. Currently, if the button is pressed on the arduino board, it has a 50-50 chance of changing its state. What part of the code is leading to this outcome?

body:
The mechanical switches bounces. That's all. It's too fast for you to see it but MCU is much faster, so output state is switched many times before contacts are stabilized and no more bounces are causing "turning on and off".

The term you are looking for is **debouncing**


body:
If you're connecting the button from pin 2 to ground and not using an external pull-up, it can lead to trouble. Either use an external pull-up or set the internal one:

    pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input:

Also, you need to [debounce the button][1].

  [1]: http://www.ganssle.com/debouncing.htm


body:
In addition to the debouncing suggested by the other answers, you have a further problem: your `loop()` will whiz through in a very short time, and run again while your finger is still on the button, turning the light off.  And then run again, turning it back on again, and so on.

You need to wait for the button to be released before registering another change.

    const int buttonPin = 2;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin

    bool ledState = 0;

    void setup() {
      pinMode(ledPin, OUTPUT);   // initialize the LED pin as an output:
      pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
    }

    void loop() {
      bool buttonState = digitalRead(buttonPin);// read the state of the pushbutton value:
      if (buttonState == HIGH)
      {
        // Poor-man's debounce. There are much better ways of doing this!
        delay(20);

        ledState = !ledState;
        if (ledState == HIGH)
        {
          digitalWrite(ledPin, HIGH); // turn LED on:
        }
        else
        {
          digitalWrite(ledPin, LOW); // turn LED off:
        }

        // Wait for the button to be released
        while (digitalRead(buttonPin)) {}

        // Poor-man's debounce. There are much better ways of doing this!
        delay(20);
    }


message:
Interrupt routine for button somehow respondng to room lamp turning off and on

I have a sketch that has been running fine on an Uno 24x7 for a few months now.  The part of interest is an interrupt routine associated with a momentary contact switch [on pin 2].  When pressed, the interrupt routine handles debouncing and simply toggles a boolean variable.  The main routine checks status, takes action, warbles a buzzer, and does a Serial.print of the event.

Today, I moved the unit to the other side of the room and plugged it into a different PC via USB. Whilst it was running, I happened to turn on a nearby fluorescent light [not connected to anything but a 120v outlet].

The Uno buzzer went off, and appropriate msgs were written to the serial connection.  I flipped the light back on, and got the same kind of results.  I repeated this numerous times and got the same.  I could flip the light or push the button attached to the Uno, and the results were indistinguishable.

I unplugged the USB cable and used the power jack instead.  I got the same results, sans the print msgs to the serial connection.

The board itself has only a DS3231, an 8x8 LED matrix, a button, two LEDs & resistors, and a buzzer.

What is happening?  How can I resolve the problem?  [If another person had posted this, I would be disinclined to believe it, but surely someone out there understands the situation.]

I can readily supply a minimal code set and a Fritzing if it would help, though I suspect it would not.

body:
My guess: pickup on the input line from interference.  (I'd expect this more if the switch were on a long cable away from the Arduino.)

If the button uses an external pull-up resistor, try a smaller value (maybe 5k?).  If it uses the internal pull-up, try adding an external one.


body:
Yours is a problem of EMI (electromagnetic interference). The ballast from the fluorescent light may interfere via two mechanisms:

 1. **Conducted EMI** through the power lines (unlikely). In order to rule out this condition, power your Uno through a battery or a battery-powered device (a laptop disconnected from mains). If EMI effects disappear, then you have a problem of conducted EMI and you must use some kind of power-line filter. If it doesn't disappear, then it's a problem of radiated EMI (continue reading).

 2. **Radiated EMI** (most likely). There are some things you can do to mitigate its effects:

* Use wires as short as possible.
* Twist wire pairs whenever possible.
* Avoid operating conditions that leave inputs unterminated (be sure they're always either pulled up or low). This can easily happen when switchs are used and they leave an input in a high-impedance (disconnected) state.
* Increase the debouncing time or use a more robust, glitch-tolerant debouncing routine.
* Consider polling the input instead of using an interrupt. However, doing this will be of little use if you don't improve your debouncing routine.
* Consider adding hardware debouncing.

Regarding the last three points, I recommend you to read this [this][1]. You'll have a better grasp about the art of debouncing inputs.

SPOILER: One thing you can do to make your debouncing routine far more robust is to **wait for N consecutive readings with the same value** (to happen during a given time T = N x Interval) before considering it good, instead of just waiting for a second reading after a constant time T.

  [1]: http://www.ganssle.com/debouncing.htm


message:
Arduino code is not working for unipolar stepper motor

I am using unipolar 1.8 degree stepper motor. I have written code to rotate stepper motor i.e. when A0 pin becomes HIGH it should rotate in clockwise and when A1 pin becomes HIGH it should move anti clockwise but motor is rotating only once when I am making A0/A1 HIGH and then stops. After that it is not rotating even if i am making A0, A1 pin high. I am very new to this please tell how to solve this problem. I am using microstepping drive, nema 17 stepper motor and Arduino Uno board.

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

    #include <Stepper.h>

    #define STEPS_PER_MOTOR_REVOLUTION 32

    #define STEPS_PER_OUTPUT_REVOLUTION 32 * 200 //2048

    Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 9, 8);
    int  Steps2Take;
    int buttonApin = A0;
    int buttonBpin = A1;
    int dirpin = 8;
    int steppin = 9;
    void setup()
    {
      pinMode(buttonApin, INPUT);
      pinMode(buttonApin, INPUT);
      pinMode(dirpin, OUTPUT);
      pinMode(steppin, OUTPUT);
      small_stepper.setSpeed(1900);
    }
    void loop()
    {
      int valA = digitalRead(buttonApin);

      if (valA == HIGH)
      { digitalWrite(dirpin, HIGH);
        for (int x = 0; x < 100; x++)
        { digitalWrite(steppin, HIGH);
          delayMicroseconds(1000);
          digitalWrite(steppin, LOW);
          delayMicroseconds(1000);
        }
      }
      int valB = digitalRead(buttonBpin);

      if (valB == HIGH)
      {
        digitalWrite(dirpin, LOW);
        for (int x = 0; x < 100; x++)
        {
          digitalWrite(steppin, LOW);
          delayMicroseconds(1000);
          digitalWrite(steppin, HIGH);
          delayMicroseconds(1000);
        }
      }
    }

body:
I have mentioned in the comments that you should read the buttons with `analogRead()`. But you can do it other way by simply connecting the button pin to digital inputs on arduino(any from 0-13). Analog pins are mostly used for accessing the sensor data as far as I know. I am correcting your code as below:

    #include <Stepper.h>

    #define STEPS_PER_MOTOR_REVOLUTION 32

    #define STEPS_PER_OUTPUT_REVOLUTION 32 * 200 //2048

    Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 9, 8);
    int  Steps2Take;
    int buttonApin = 4; //connect button to digital pin 4 on arduino
    int buttonBpin = 5; //connect button to digital pin 5 on arduino
    int dirpin = 8;
    int steppin = 9;
    void setup()
    {
      pinMode(buttonApin, INPUT);
      pinMode(buttonApin, INPUT);
      pinMode(dirpin, OUTPUT);
      pinMode(steppin, OUTPUT);
      small_stepper.setSpeed(1900);
    }
    void loop()
    {
      int valA = digitalRead(buttonApin);

      if (valA == HIGH)
      { digitalWrite(dirpin, HIGH);
        for (int x = 0; x < 100; x++)
        { digitalWrite(steppin, HIGH);
          delayMicroseconds(1000);
          digitalWrite(steppin, LOW);
          delayMicroseconds(1000);
        }
      }
      int valB = digitalRead(buttonBpin);

      if (valB == HIGH)
      {
        digitalWrite(dirpin, LOW);
        for (int x = 0; x < 100; x++)
        {
          digitalWrite(steppin, LOW);
          delayMicroseconds(1000);
          digitalWrite(steppin, HIGH);
          delayMicroseconds(1000);
        }
      }
    }


message:
Working on a simple door lock

this is my first project on an Arduino platform. My aim is to build up a door lock unlockable by playing a short melody on a one-octave piano keyboard. I think the idea is cool!
I'm thinking at everything, but I can't figure out how to make Arduino move something (which in my case would be the proper door lock). I thought about a little motor, but I don't know if it is or not  feasible...
To be clear, what I want to do is a simple door lock like this [![enter image description here][1]][1]
(or even simpler) being moved from an Arduino program. How can I do that?

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

body:
You want a [solenoid][1].

Looks like people sell [ones][2] which are specifically made for door locks.

  [1]: http://www.magnetschultz.co.uk/standard_and_special_solenoids/25/Miniature-solenoids
  [2]: https://thepihut.com/products/adafruit-lock-style-solenoid-12vdc


message:
Do (cheap) SD modules support file I/O?

I noticed there are cheap SD modules and complete SD shields.
I assume the last are used for a 'final' product and not for bread-boarding (?)

However, I was wondering, is there also a difference in functionality or more important, support for e.g. the sd library (thus having file I/O in addition  to SPI interface)?

E.g. can I use the file I/O and the SD library with the [This SD module](https://www.aliexpress.com/item/1pcs-lot-Micro-SD-card-mini-TF-card-reader-module-SPI-interfaces-with-level-converter-chip/32735273502.html?spm=2114.01020208.3.19.Rtw72Z&ws_ab_test=searchweb0_0,searchweb201602_1_10000073_10065_10068_10000077_10000074_10000132_10000033_10000030_119_10000167_10000026_10000175_10000126_10000129_10000023_10000123_432_10000069_10000068_10060_10062_10056_10055_10000062_10054_10000063_301_10059_10000120_10099_10000020_10000156_10000158_10000013_10000117_10103_10102_10000016_10000114_10096_10000111_10000056_10000059_10052_10053_10050_10107_10051_10106_10000097_10000094_10000090_10000147_10000091_10000144_10084_10000150_10000101_10083_10000100_10000011_10080_10000153_10000104_10082_10000045_10081_10110_10000108_10111_10000191_10112_10113_10000197_10114_10000089_10000086_10000179_10033_10000083_10000042_10000135_10000080_10078_10079_10000039_10073_10000140_10070_10000036_10122_10123_10121_10126_10124_10000187-10053,searchweb201603_9,afswitch_1,ppcSwitch_5_ppcChannel,single_sort_1_price_asc&btsid=ad51690d-b722-481d-bdec-759a968ea925&algo_expid=1bc7cb28-840e-4c59-ad94-ed0361e2bd1d-2&algo_pvid=1bc7cb28-840e-4c59-ad94-ed0361e2bd1d)?

body:
There are Uno compatible SD shields which are great for prototyping IF you are using an Uno, they don't work too well with a Nano.  The modules are fine, but you end up with wires everywhere, but they do work with more formats of Arduino.

The ability to do file operations is separate to the protocol you use to talk to the module (SPI).  Lots of device (not just SD cards) use SPI, but not all of them do file operations.  An LCD, a GPIO expander, an EEPROM memory chip are all examples of devices that could use SPI.

What actions the SD module/shield is capable of is really up to the library/software.  The module will have to comply to some set of standards and this will let the caller perform certain operations.  Lets say one of the operations is to read one byte from an address.  This operation would need to be used by the library to read a file, also it would need to use it to find where the file is.  It would also need it when writing a file, because it would need to know what free space was left on the card.  You are shielded from all this by the Library you probably have a read file, write file and delete file function.  (This is an example of abstraction which you will see a lot in programming).

The will also have a set of standards to allow a controller to interface with the module, SPI, I2C, Serial or a proprietary one.  These communication protocols allow the controller to send the file commands to the module, like the read command above, and lets the module return data to the controller.

So to answer your question

 1. If you use a module and shield that use the same IC (chip) to access
    the SD card and the same library then they will almost always behave
    the same.

 2. If you use two different shield (different ICs) which
    need different libraries then they MIGHT have different
    functionality.

 3. If you use two different shields which use the SAME library then the MIGHT have the same or different functionality.

Summary : Yes No Maybe :)

If you want something special find a library that does what you want and then find a bit of hardware supported by that library that also does it.  Otherwise, chances are you will be fine.

==== Edit ===

When you think of hardware/software abstraction think of it as a Television.  You deal with the TV at the very highest level, you turn it on/off and change channels.

When you change channel what really happens is the remote control converts your button press into an encoded infra-red signal which hopefully hits the TV and the TV decodes this and executes some code which selects a pre-programmed channel.

Now you don't care about that all you care about is you press the button and you favourite soap opera appears on the screen.

There is another level of abstraction that is happening when the TV selects the pre-programmed channel, it has to convert the signal into some reference to the stored information that produces some information that is passed to the tuner and....  Well it just gets silly, you just want to watch your soap.

So back to the subject in question, you buy a SD reader module, you find a library that works with it and in your code you call `WriteFile()`.  Does it really matter how it does it?  Do you care that the library is scattering you bytes across the SD card? Well as long as it retrieves it no not really?  Does it matter that `WriteFile()` is actually storing it on the hard disk of a PC somewhere in the world?

Your call to `WriteFile()` is abstracted away from the underlying process hiding it, because it doesn't really matter.  Most of the libraries use this Abstraction process, look at the code in Wire.cpp, it looks really simple when you are calling `read()` and `write()` but it isn't.


body:
Short answer. Yes, it will work.

I have used the same MicroSD Card Adapter module [it is marked MOSO instead of MISO on one of the pins] for a few projects.  I found no problems or special considerations doing so [except for getting the pin mapping correct].

In contrast, I've used one shield that worked sporadically, because of intermittent header contact.  It would work for a while, then stop until I "massaged" it properly.  It was probably just a bad assembly, though.

  Many people prefer working with shields, while I do not, and would rather build on PCB board once I have a working version of my project.  It's cheaper as well.


message:
A question on physical locations of the registers in ATmega328P

When I read about registers I always encounter the following illustration:

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

So there are 32 registers in the above diagram. They are processor registers.

But in the [data-sheet][2] of ATmega328P at page 428 there is a section called "Register Summary".

Here in that list there are much more than 32 registers. Do the rest of the registers physically stay somewhere else?

Lest's take an example of ADMUX register. Where is that register physically inside the DIP? It is not one of the 32 registers? And if stays somewhere else how does it connected to the ALU?

  [1]: https://i.stack.imgur.com/fszJd.gif
  [2]: http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf

body:
You are confusing CPU registers and SFRs, Special Function Registers.

CPU registers only exist within the CPU core. SFRs exist within the RAM bus's memory map.

CPU registers are used by the CPU to execute instructions and do calculations, etc. SFRs are a part of the logic of the rest of the chip and directly affect the working of the various peripherals.

As far as the CPU is concerned an SFR is just a bit of SRAM, but it affects physical workings when written to, and reflects physical states when read from.


message:
What controller should i use?

I'm working on a little DIY project in which I intend to make my own dataglove. Now I'm kinda stuck on choosing the right microcontroller. And since it can be quite costly, I thought to ask for some help.

So: I'm going to use 12 flex sensors (maybe 14) and 1 IMU (probably the 6050). now the problem is that I need a total of at least 14 AI.. And the small controllers only have about 6.

The controller can't be too big for dexterity reasons and also will need the availability to add a Bluetooth module.

I've been looking at some multiplexing/shield options but I'm just not confident (and rich) enough start ordering..

Peace out,

Lars

PS: other brands besides Arduino work for me to

body:
How about a Teensy? The guys that make Teensy have developed many of the well known Arduino libraries and have also helped develop the Arduino IDE in the past so they know their stuff.

I see the Teensy LC at about $11. the spec says its almost the same as Teensy 3.1 which has 20+ Analog In

https://www.pjrc.com/store/teensylc.html

https://www.pjrc.com/teensy/index.html

The 3.1 and 3.6 are more powerful and more expensive at around $29

note: Read the index for which boards are 5v tolerant if that's what you need.


message:
Initializing pointer to vector of objects inside another object

i want to create a somewhat complex structure of classes in an arduino. The short story is: a Device has Presets, and each Preset has a Patterns. For that i created the following structure (i am only posting the important stuff, if something is missing let me know):

**INO file**

    #include "LedDevice.h"

 LedDevice device;

 void setup() {
   device = LedDevice(10, 10, 10);
 }

 void loop() {
   Serial.println(F("Ticking"));
   device.Tick();
   delay(500);
 }

**LedDevice**

 #if !defined(_LEDDEVICE_H)
 #define _LEDDEVICE_H

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

 class LedDevice {
 public:
   Preset* Presets[];

   LedDevice(){}
   LedDevice(int numPixels, int numPresets, int numPatterns)
   {
     *Presets = (Preset*)malloc(sizeof(Preset) * numPresets);

     for (int p = 0; p < numPresets; p++)
     {
       Presets[p] = new Preset("test", numPixels, numPatterns);
     }
   }

   void Tick()
   {
     Serial.print(F("Preset ")); Serial.println(Presets[0]->Name);
     Presets[0]->Tick();
   }
 };

 #endif  //_LEDDEVICE_H

**Preset**

    #if !defined(_PRESET_H)
 #define _PRESET_H

 #include "Pattern.h"

 class Preset {
 public:
   char *Name;
   int NumPatterns;
   Pattern* Patterns[];

   Preset(char* name, int numPixels, int numPatterns) : NumPatterns(numPatterns)
   {
     Name = (char *)malloc(strlen(name) + 1);
     strcpy(Name, name);

     *Patterns = (Pattern*)malloc(sizeof(Pattern) * NumPatterns);

     for (int p = 0; p < NumPatterns; p++)
     {
       Patterns[p] = new Pattern(numPixels);
     }
   }

   void Tick()
   {
     for (int p = 0; p < NumPatterns; p++)
     {
       Patterns[p]->Tick();
     }
   }
 };

 #endif

**Pattern**

 #if !defined(_PATTERN_H)
 #define _PATTERN_H

 class Pattern {
 public:

   Pattern(int numPixels){}

   void Tick(){}
 };

 #endif

The code compiles but when i run the full version (this is a simplified version of the code) i get some strange behavior, so i would like to know if i am doing the initialization of the Presets and Patterns correctly.

Also when i try to print the Preset name in the LedDevice Tick function i get strange characters, so either i am not initializing the string correctly or the pointers to the Presets are wrong.

Can you tell if anything is not being done correctly in the constructors?

body:
This is wrong:

>     Device device;
>
>     void setup()
>     {
>        device = Device();
>     }

I don't know what your intentions are, but the first line instantiates `device`. You don't need to do anything in `setup` here. It sort-of looks like you are trying to call the constructor but that is called when the class instance is created (in the first line).

---

>     Preset* Presets[];

What's this? A pointer to an array of zero length?

---

>         *Presets = (Preset*)malloc(sizeof(Preset) * NumPresets);

Now you are allocating memory for a **pointer** to the array to be big enough to hold the **contents** of the array.

---

>     for (int p = 0; p < NumPresets; p++)
>     {
>         Presets[p] = new Preset("test", NumPixels, NumPatterns);
>     }

Now you are allocating memory for the contents of the array again.

---

There is too much dereferencing going on here. Please post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). For example, make the classes in question do not much. Then make code we can actually work on.

---

> I realize the first call is to the default constructor, but in the setup i do the real construction ...

Well, you can't call the constructor twice. What is commonly done is to do nothing (or almost nothing) in the constructor, and then make a `begin` function which you call in `setup`. This function can then do whatever is required at the proper time.


body:
Three things that need to be different:

    Pattern* Patterns[];

should be

    Pattern** Patterns;

It's a pointer to some pointers to patterns, not a pointer to an array (which is basically a pointer itself so same basic idea but an array implies a known size).

and

    *Patterns = (Pattern*)malloc(sizeof(Pattern) * NumPatterns);

should be

    Patterns = (Pattern*)malloc(sizeof(Pattern*) * NumPatterns);

*Patterns is the thing pointed to by Patterns which at this point is undefined. You want to set Patterns to the allocated address.
And we only need to allocate space for the pointers not the actual objects.

Your for loops then become

    for (int p = 0; p < NumPatterns; p++)
    {
      (Patterns+p) = new Pattern(numPixels);
    }

You then have the same issues with Presets.

And finally

    LedDevice device;
    void setup() {
      device = LedDevice(10, 10, 10);
    }

should be

    LedDevice device(10, 10, 10);
    void setup() {
    }


message:
Connecting two arduinos with wifi over the Internet

I have worked with Arduino before, but not with WiFi modules. I always used RF or other methods.

Now I am working on a project where i need to connect two UNOs, over long distance, but they will have a continuous internet connection.

One board with only send data, and one will only receive.

Will the esp8266 soc suffice for this? They will have fast network connection; at least 4g speeds. So can I send and receive real time data over the internet, and receive it fast? It should feel like there is no delay on the receiving side. Can I do this with the ESP, and if so, can any one point me towards the right material to get started.

thx in advance :)

body:
Have you considered using Particle Photons instead?
They're $19, wifi enabled, Arduino compatible and they come with a very extensive cloud API functions that will allow you to pass information between them really easily:
https://docs.particle.io/reference/firmware/photon/


body:
The ESPs are easy to work with and more than capable, BUT (there's always a "but"): with a public network in the middle, latency, routing, and traffic issues will be beyond your control. Look, for instance, at the variability in page load times when loading over the internet.

If you use an IoT server in the middle, there will be server delays outside your control as well, though connecting to a common server from both ends can make it much easier to get everything talking for the first time. (There may, however, be data-rate limits imposed on you if the server in the middle is a free service.)

> So can I send and receive real time data over the internet, and
> receive it fast?

Define "real fast". Do you mean "really quickly" (short delay from start of transmission to start of reception at the other end)? Or "really high throughput" (moving lots of data in a short time, or continuously without falling behind? Or something else?

Since you're working with an Uno, if you need to use a SoftwareSerial port to talk to the ESP, the SS will be limited to 9600 baud (equivalent to 960 Bytes/sec) and your ability to push data through it to somewhat under that. If you can use the built-in hardware UART your data-rate to/from an ESP can be much higher, at least 115200 baud or 11,520 B/sec (again, gross rate; rate of pushing data will be somewhat lower).

tl;dr: The network will be a much greater limitation than the ESP devices.

Update:

> the problem i see is the delay with communication over the internet
> between the two uno if i use a server.can i communicate between the
> two with out the use of a server

Of course. Using an intermediate server might be a useful step on the way to getting your devices to talk directly. It would allow you to focus on the clients themselves at first and leave (most of) the networking issues to work out later. But you'll still have the issues of any network and especially a public network. If you have no other choice, you build it and you get whatever you get for performance. How serious are the consequence of a delay or a lost packet? Inconvenience? Delayed system functions? Will it cost someone money? Could someone get hurt? Could someone die? How dire the consequences could be will determine how stringent (and expensive) your solution has to be and what backups might have to be in place.


message:
Does SoftwareSerial use hardware timer?

I'm asking this because I'm using a timer to generate a 38KHZ signal to drive an IR diode, and I also need to use SoftwareSerial to talk to an HC-12 radio using serial communication.

The code I'm using was written by Nick Gammon and is here:

    //Setup Conter/overflow to create 38KHZ drive for IR38KHZ
    //38khz, no interrupts
    #define IR_CLOCK_RATE 38000L
    // toggle on compare, clk/1
    TCCR2A = _BV(WGM21) | _BV(COM2A0);
    TCCR2B = _BV(CS20);
    // 38kHz carrier/timer
    OCR2A = (F_CPU/(IR_CLOCK_RATE*2L)-1);
    pinMode(IR38KHZ, OUTPUT);

I'm not quite up-to-date on the timer use on an Arduino (I'm using a Nano), plus I've no idea what the SoftwareSerial library uses.

body: No. It uses pin-change interrupts to trigger reception, and both reception and transmission use calibrated delay loops.  However, interrupts are disabled during both transmission and reception so that the calibrated delay loops remain always the precise length - so if you do anything with any other interrupts they will not work at the same time as SoftwareSerial.


message:
Arduino 5v output dead?

i've got a bit of a problem with my Arduino UNO.

So coming back to my (pretty basic) build after a bathroom break, I go to un-assemble my circuit (on the breadboard) and grabbing the LED causes a static shock.

Since then I haven't been able to get any power to come out of the Arduino to the breadboard circuitry.

**I have tried:**

 - Different Breadboards
 - All new parts, LED's/cabling/buttons/resistors.
 - Different power and ground cables (from Arduino to breadboard)
 - Giving the Board more time to 'cool down' (I heard there was a
   temperature based reset device?)
 - using the 3.5v output (I'm not sure if by doing this i should remove
   the resistor? i'm VERY new to electronics
 - using the alternate ground input

Looking around here for 'shorts' or 'damaged Arduinos' returns mostly results about non communication to the board. the difference here is *I can absolutely still upload programs to my Arduino and then run them* (I've only tried the pre-existing blink, but i don't think there is any difference). And my computer's USB ports are also fine. So if there is a duplicate question i apologize, but i haven't been able to find anything related.

Any help would be much appreciated!

body:
If you got zapped touching an LED and the circuit doesn't work any more, and since you're sure the Arduino uploads programs OK, then either the LED (or something else on your breadboard) or the pin driver within the Arduino is probably damaged.

 - Try changing the LED.
 - If that doesn't work, try changing the pin(s) the sketch uses to talk to your breadboard, rewire your breadboard to use those pins, and test again. If it works this time, the pin driver was probably damaged.
 - If there are any other components (e.g., not wires or resistors) on the breadboard whose failure might cause the LED not to light, replace those and test again.
 - If replacing the external components doesn't fix it, and if your Arduino's MCU is a 28-pin chip in a socket, a new one with the bootloader already loaded into it typically costs $5-$6 in the US.

Update:

> ...i have listed all these things as already tried.

Right - I read right past it. :( So you've done the right things (except no mention of testing other pins) so I'm not sure what your question is. The title asks about the board's 5v supply but that _must_ be up b/c your board uploads and runs Blink. That really leaves only the the pin driver(s) you were using when you zapped it.

You can salvage the board by testing all the pins in their input, output, analog, and other functions, and make a note of what capabilities have been lost. Clearly not all of them - pin 13 still works, for instance, because Blink worked. You can't repair damage internal to the chip without replacing it, and I would always consider it suspect, but it will be fine for many hobby uses if you just avoid the damaged functions.


message:
Arduino and USB power, what to choose

I am a beginner at Arduino. I want to power the Arduino through the USB cable that is usually plugged in the USB of the laptop, but plugged in the wall instead of the laptop.

Here are my questions:

 - Can I use a phone charger that has a USB (in which the end of the USB
   cable will go instead of the USB of the PC)?

 - What should I look for written on the charger so it is best
   compatible?

 - Is it ok to be done that way?

 - Will it be the same as means of power like when it is plugged in the
   PC (for example when later on I connect LCD display, diodes, etc.)?

I did my research, but it got confusing, so I wanted to ask my own question. Thanks in advance.

body:
Yes, you can power the Arduino using a USB phone charger.

The Arduino Uno draws less than 100mA when connected by itself. So ideally you would want the USB phone charger to provide at least 100mA. All of the USB chargers I have come across to date provide more than 400mA. Most of the modern USB chargers provide upwards of 1A for fast charging of your phone.

A USB(2) port of a laptop can provide up to 700mA to the Arduino (500mA continuous).

In terms of the overall current draw, it really depends on what you have connected to the Arduino. LEDs generally draw 20mA or less per LED. Some screens can draw anything from <100mA to a couple of amps. Most of the screens I have come across draw less than 1A. It really depends on the devices you want to connect.

For the most part, a USB charger will be sufficient.


body:
As you are still a beginner so I would not go into complex details. Your Arduino can run perfectly on a laptop powered USB but try to avoid connecting the power hungry electronics with your Arduino while powering it from the laptop USB port.

A Laptop USB port can give nearly 700mA that is enough for Arduino to run a couple of sensors easily.

Secondly, most wall chargers give 1A(1000mA) current that is better in my opinion. It can handle some power hungry electronics better then connecting your Arduino with the Laptop USB port.

I personally power my Arduino with either a Wall Charger or a power bank. Hope it helped solve your problem.

The more you dig into Arduino, the more fun it becomes. So have fun and be Creative.


message:
Arduino Serial and myserial clarification. How to print out rx output?

I currently have a camera I am trying to run off an Arduino. I am new to Arduino and I have had trouble figuring out what serial and myserial really do. I also don't understand why, when I have something like `serial.write(0x56)` I will get the output in the serial monitor to be V in hex, but If I have the Arduino also connected to an oscilloscope, I won't be able to see the signal.

Yet if I have `myserial.write(0x56)`, I won't see anything in the serial monitor, but will see the bits on my oscilloscope.

Also, if I send a command to my camera, my camera should send back some hex values if the write command is sent. I understand I can send commands via `myserial.write(0x56)`, but how would I read the hex values the camera would send back?

body:
It seems like you are using both the hardware UART pins and two other pins for [SoftwareSerial](https://www.arduino.cc/en/Reference/softwareSerial) i.e. UART emulated by the arduino.

When you write `Serial.read()` or `Serial.write()`, Arduino knows to use the UART hardware on the chip which is has RX/TX pins 0 and 1 for most Arduinos. So by using these functions you will be able to communicate with any device which is connected on these pins.

Generally, when you have the Arduino connected to your computer, these RX/TX pins internally go to a serial port on your computer via the USB, hence you can send/receive data to the computer and view it on the Serial Monitor. Great for debugging purposes!

Sometimes, like in your case for controlling the camera, you need to have another serial port for communication because UART is point to point i.e. only 2 devices can communicate via it. `SoftwareSerial` helps you do that by using  two other pins on the Arduino into RX/TX pins. If you look at the top of your code file you will see a line like this

    SoftwareSerial mySerial = SoftwareSerial(...);

Inside the brackets you will also see the two pin numbers which are being used as RX/TX. In the software serial example pins 10,11 are being used. So whatever is connected to these pins (i think your camera module is) will be able to send/receive data using `mySerial.write()` and `mySerial.read()`.

Hence, to be able to receive data from the camera you will use `mySerial.read()`.


message:
sleep and wake up arduino mega according to ds3231 interrupt

how can I make my arduino mega sleep during 6pm-7am..and wakes or stay up during 7am-6pm and doing its job like activating the solenoid valve based on my soil moisture sensor reading.this is for my backyard farm.anyone can help me making a code for it? please i really need it.

here is my code

    #include <DS3231.h>
    #include <Wire.h>
    #include <avr/sleep.h>

     int wakePin = 2;   // pin used for waking up
     int led = 13;

     DS3231 clock;
     RTCDAteTime dt;

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

     // initialize DS3231
     Serial.println("Initailize DS3231");
     delay(100);
      clock.begin();
      pinMode(wakePin,INPUT_PULLUP);
      pinMode(led,OUTPUT);

       //Disarm alarms and clear alarms for this example, beacuse alarms is battery backed.
       //Under normal conditions, the settings should be reset after power and restart microcontroller
       clock.armAlarm(false);
       clock.clearAlarm();

       //Set Alarm1 - Every 20s in each minute
       // setAlarm1(date or day,hour,minute,second,Mode,Arrmed=True)
         clock.setAlarm1(0,0,0,20,DS3231_MATCH_S);
         attachInterrupt(0,wakeUpNow,LOW);

       //check alarm settings
        checkAlarms();
      }

       void checkAlarms()
      {
       RTCAlarmTimea1;
       RTCAlarmTimea2;

        if (clock.isArmed1())
       {
        a1 = clock.getAlarm1();

         Serial.print("Alarm1 is triggered:);
         switch(clock.getAlarmType1())
        {

           case DS3231_MATCH_S:
           Serial.print("When seconds match: ');
           Serial.println(clock.dateFormat("_ _:_:s",a1));
           delay(100);
            break;
            default:
             Serial.println("UNKNOWN RULE");
             break;
         }
        }
       }

           void wakeUpNow()
       {
           //execute code here after wake-up before returning to the loop() function
          //timers and code using timers(serial.print and more...)will not work here.
         //we don`t really need to execute any special functions here, since we
         //just want the thing to wake up
          Serial.print("Woke up");
         delay(100);
         }

          void sleepNow()
         {
          set_sleep_mode(SLEEP_MODE_PWR_DOWN);  //sleep mode is set here
          sleep_enable();   //enables  the sleep bit in the mcucr register
          attachInterrupt(0,wakeUpNow,FALLING); //use interrupt 0(pin2) and run function
          sleep_mode();
             // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

             sleep_disable();  //first thing after waking from sleep: disable sleep
             detachInterrupt(0); //disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running
              time.
            }

             void loop()
            {
               dt=clock.getDateTime();

                 Serial.println(clock.dateFormat("d-m-Y H:i:s-I",dt));
                  delay(100);
               //Call isAlarm1(false)if you want clear alarm1 flag manualy by                     cleaAlarm1();
                  if(clock.isAlarm1())
               {
                     Serial.println("ALARM 1 TRIGGERED!");
                     digitalWrite(led,HIGH);
                       delay(1000);
                      digitalWrite(led,LOW);
                      Serial.println("Entering Sleep");
                        delay(100); //sleep fucntion called here
                         sleepNow();
                   }
                    delay(900);
                   }

body: First, Arduino Mega does not have an RTC (Real Time Clock) built-in. So, to program it the way you like, would mean either using a module like DS3231 or similar, or have the Mega connected to internet, with a network card module like ENC28J60 and getting the time from there. If you don't use any of those methods basing your scheduler only on the Arduino internal timer (using sleep for example) will result in program needing to set the correct time each time Arduino is powered.


message:
Arduino Serial Port. COM1 does not exist

Hello everyone I'am new to this site so please bear with me.

I have an **`Arduino Uno`** that I'm using in my simple project using `VS 2008`. I got this error says `The Port COM1 does not exist`. The flow of my project is after inserting a `coin` into the `coin slot` the arduino will pass the data into my project and it will display into a Label or Textbox the value of the inserted coin.

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

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

body:
Never used Visual Basic but:

 - There is no such thing as Serial1 on Arduino Uno. There is only Serial. (Serial1, 2, 3 are available on ArduinoMega) Reference: [Arduino]
 - For COM port you should check your device manager. Often it appears at COM3 so probably you should check this issue.

Just for curiosity: Why VB? Is it only your choice or it use less ram or memory, works faster or anything?

[Arduino]: https://www.arduino.cc/en/Reference/Serial


body:
Probably it is on another COM port. When I checked my IDE (from Arduino) the Arduino was found at COM3.

You probably have to iterate through the (PC) COM ports to find out where the Arduino is connected to.


message:
Explain what is meant by "Arduino core"

What is an "Arduino core"?

Are there many different "Arduino cores"? such as a core that applies to LCD
displays, another core that applies to servos, etc.?

body:
As far as I know the cores are the different products which can be found at [Products][1]. In this list the Arduino cores can be selected in the IDE: [Cores][2]

LCD display (driver) etc. are mostly referred as shields or modules. A shield is a small 'board' you can stack on top of the Arduino (Core) and a module is normally to be used on a breadboard.

  [1]: https://www.arduino.cc/en/Products/Compare
  [2]: https://www.arduino.cc/en/Guide/Cores


body:
The Core is the software API for a specific group of chips.

For instance, the AVR core supports the AVR chips found on most Arduino boards. The SAM3X core supports the Arduino Due. Etc.

It is the code that provides things like digitalRead(), analogWrite(), millis() etc.

Since each family of chips works differently that abstraction layer between your sketch and the physical hardware of the chip needs to be different.

In your default IDE installation the Arduino AVR core can be found within the `hardware/arduino/avr/cores/arduino` folder.

Cores are usually installed as part of a "boards" bundle in the boards manager. This includes definitions for the boards ("variants"), the core and, equally importantly, the compiler and firmware uploading software for the chip on the board.


body:
The "core" provides the low-level APIs (Application Programmer Interfaces) which are documented in the [Arduino Reference page](https://www.arduino.cc/en/Reference/HomePage). For example, `digitalRead`, `digitalWrite`, `delay` and so on.

The core files usually contain the "include" files from Atmel which provide documented names for the various registers in the chip (eg. `DDRB` for data direction register B).

Since each chip type will have different addresses for the registers you will need a different core for each processor chip. Also in some cases people have assembled the chip onto different boards, and the cores will reflect how the board is wired. For example "edge pin 8" on one board may connect to a different pin on the processor chip compared to another board. Thus if you buy a board from a third-party they may also supply their own core files.

---

> Are there many different Arduino cores such as a core that applies to LCD displays, another core that applies to servos?

These are usually implemented in **libraries** which you can optionally include into your code. The libraries *extend* the core. Often the same library will work with different cores as the core code handles the differences between chips, so that the library doesn't have to.

---

## Selecting a core

As Majenko mentions in his answer, selecting a board in the IDE (Integrated Development Environment) usually tells the IDE to select the appropriate core for that board/chip combination.

More recent versions of the IDE allow you to install more cores by providing a link to where the core files are to be found, and then allowing you to choose one or more cores from that site.


body:
The collection of MCU's that are part of the Arduino family have differences from one to another in features like the address in memory-space of the basic processor registers, the I/O pin assignments to the I/O registers, nature and operation of timers, A/Ds, etc. The kinds of things we do with calls like pinMode(), digitalWrite(), or attachInterrupt().

These are considered the basic or "core" functions to be presented to the programmer by using libraries to present a common interface and hide those differences. The core libraries are managed by the Arduino IDE and the proper one(s) are selected when you select a board-type from the Tools | Board menu.

This is different from the user-contributed and other non-core dependent libraries you keep in your workspace 'libraries' folder. Both kinds are code libraries, but the so-called "core-libraries" are specific to the kind of processor you are compiling your sketch to run on.


message:
Tiny RTC I2C module not working

I bought a Tiny RTC I2C module and it doesn't work.
When i run the TimeRTCSet from TIME library all i get is:

    Unable to sync with the RTC
    0:00:00 0 0 1970
    0:00:01 1 1 1970
    0:00:02 1 1 1970
    0:00:03 1 1 1970
    0:00:04 1 1 1970
    0:00:05 1 1 1970
    0:00:06 1 1 1970
    0:00:07 1 1 1970

The module is connected like this:

Vin -> 5V
Gnd -> Gnd
SCL -> A5
SDA -> A4

I'm using arduino uno.

I tried with a simple i2c scanner, but it returned two devices!

    Scanning...
    I2C device found at address 0x50  !
    I2C device found at address 0x68  !
    done

Only the clock is connected. I tried removing the battery for night to reset it, but it didn't fix it.

Could you help me?

body: Try using the example code from the MD_DS1307 library to find the settings on your RTC, when I first wired mine up the clock was not running and I couldn't set the time on it. After I enabled it, it worked just fine.


body: This issue can be fixed by deleting the library downloaded using arduino library manager and replacing it with the library from github.


message:
A confusion with setting timers

I was reading a [tutorial][1] on timers. My aim is to generate 16MHz pulse output from the pin 8.

Here is the code I modified from the tutorial (I use Arduino's ATmega328P):

    #include <avr/io.h>
    #include <stdint.h>

    int main (void)
    {
     DDRB |= (1 << 0); // Set LED as output
     TCCR1B &= ~(1 << CS11); // Set up timer
     TCCR1B &= ~(1 << CS12); // Set up timer
     TCCR1B |= (1 << CS10); // Set up timer

     for (;;)
     {
      // Check timer value in if statement
      if (TCNT1 >= 0)
      {
       PORTB ^= (1 << 0); // Toggle the LED
       TCNT1 = 0; // Reset timer value
      }
     }
    }

I use the following formula:

> Target Timer Count = (1 / Target Frequency) / (1 / Timer Clock
> Frequency) - 1

So Target Timer Count = 0 in my case.

But I get 615kHz on scope.

My timer setting should output 16MHz since I use no prescaler:

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

What am I doing wrong?

  [1]: http://www.avrfreaks.net/forum/tut-c-newbies-guide-avr-timers?page=all
  [2]: https://i.stack.imgur.com/UlhJ2.jpg

body:
If you want to output a signal at the same speed as the system clock, I would not recommend using a timer.  You can output the system clock to Port B Pin 0 by programming the CKOUT fuse on the 328P.

The reason I suggest not using a timer to output a signal at the same frequency of the system clock is that the compare of TCNT1 you have as well as the toggle of the output will take clock cycles so the output will never quite be the clock speed.

If you use a timer for outputting a signal, I suggest using CTC mode of Timer 1 using the output compare to set the top.  You can then either poll the appropriate Output Compare Match flag or handle the related interrupt.


message:
The program keeps skipping over the running 1 and 2 states even though the prereqs are met

The serial prints are for troubleshooting. All outputs are LEDs for testing purposes. The running 1 and 2 states are sometimes skipped over, but not always. I think this is from the light sensor being bad and jumping up and down, but using a higher value does nothing. I also tested the light sensor in the example program and got 1s and 2s so that really shouldn't be the problem. When it does work and the second light sensor is covered (the one that measures sugar level) it continuously cycles through and never returns to ready state. If more detail is needed please let me know

    //Digital Inputs
    int measureSwitch = 13; //switch that sets 2 tsp and 1 tsp

    //Digital Outputs
    int motor = 12;
    int buzzer = 11;
    int readyLed = 10;
    int running1Led = 9;
    int running2Led = 8;
    int doneLed = 7;
    int sugarLevelLed = 6;

    //Analog Inputs
    int cupSensor = 20; //the light sensor should read 0 when the cup is resting on it
    int lightSensor = 100; // the sugar should cover up thelight sensor so the light can pass thru, making it zero

    //different run times

    int running1Time = 100; //1 tsp tentative times
    int running2Time = 250; //2 tsp tentative times
    int buzzerTimer = 200; // how long the buzzer will go off for

    void setup() {
      Serial.begin(9600);
      pinMode(measureSwitch, INPUT);
      pinMode(motor, OUTPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(readyLed, OUTPUT);
      pinMode(running1Led, OUTPUT);
      pinMode(running2Led, OUTPUT);
      pinMode(doneLed, OUTPUT);
      pinMode(sugarLevelLed, OUTPUT);
    }

    //Ready State

    void readyState(){
      digitalWrite(readyLed, HIGH);
      digitalWrite(running1Led, LOW);
      digitalWrite(running2Led, LOW);
      digitalWrite(doneLed, LOW);
      digitalWrite(sugarLevelLed, LOW);
      digitalWrite(buzzer, LOW);
      digitalWrite(motor, LOW);
    }

    //Running 1 State

    void running1State(){
      digitalWrite(readyLed, LOW);
      digitalWrite(running1Led, HIGH);
      digitalWrite(running2Led, LOW);
      digitalWrite(doneLed, LOW);
      digitalWrite(sugarLevelLed, LOW);
      digitalWrite(buzzer, LOW);
      digitalWrite(motor, HIGH);
    }

    //Running 2 State
    void running2State(){
      digitalWrite(readyLed, LOW);
      digitalWrite(running1Led, LOW);
      digitalWrite(running2Led, HIGH);
      digitalWrite(doneLed, LOW);
      digitalWrite(sugarLevelLed, LOW);
      digitalWrite(buzzer, LOW);
      digitalWrite(motor, HIGH);
    }

    //Done State
    void doneState(){
      digitalWrite(readyLed, LOW);
      digitalWrite(running1Led, LOW);
      digitalWrite(running2Led, LOW);
      digitalWrite(doneLed, HIGH);
      digitalWrite(sugarLevelLed, LOW);
      digitalWrite(buzzer, HIGH);
      digitalWrite(motor, LOW);
    }

    //Waiting State
    void waitingState(){
      digitalWrite(readyLed, LOW);
      digitalWrite(running1Led, LOW);
      digitalWrite(running2Led, LOW);
      digitalWrite(doneLed, HIGH);
      digitalWrite(sugarLevelLed, LOW);
      digitalWrite(buzzer, LOW);
      digitalWrite(motor, LOW);
    }

    //Sugar Level State
    void sugarLevelState(){
      digitalWrite(readyLed, LOW);
      digitalWrite(running1Led, LOW);
      digitalWrite(running2Led, LOW);
      digitalWrite(doneLed, LOW);
      digitalWrite(sugarLevelLed, HIGH);
      digitalWrite(buzzer, LOW);
      digitalWrite(motor, LOW);
    }

    void loop() {
      while(analogRead(A0) > lightSensor){ //when there is no cup placed on the
    sensor, be in ready state
        readyState();
        Serial.println("READY STATE");
      }

    //when the cup is on the sensor and the switch is set to 1 tsp
        for(int time1 = 0; ((time1 < running1Time) &&
                            (analogRead(A0) < cupSensor) &&
                            (digitalRead(measureSwitch) == HIGH)) ; time1++){
        //run the running 1 state for 4 seconds
          running1State();
          delay(1);

          Serial.println("RUNNING STATE 1");
          Serial.println(time1);

      }

        //when the cup is on the sensor and the switch is set to 2 tsp

        for(int time2 = 0; ((time2 < running2Time) && (analogRead(A0) < cupSensor)

    && (digitalRead(measureSwitch) == LOW)); time2++){

    //run the running 2 state for 8 seconds

          running2State();
          delay(1);
          Serial.println("RUNNING STATE 2");
          Serial.println(time2);
          Serial.println(analogRead(A0));

      }

      for(int buzzerTime = 0; buzzerTime < buzzerTimer; buzzerTime++){

        doneState();
        Serial.println("DONE STATE");
        Serial.println(buzzerTime);
        delay(1);
      }

      while(analogRead(A0) < cupSensor){
        waitingState();
        Serial.println("WAITING STATE");
      }

      while(analogRead(A1) > lightSensor){
        sugarLevelState();
        Serial.println("SUGAR LEVEL STATE");
      }
    }

body:
Try pulling the output of the light sensor to ground via a 10k resistor, that should calm the values.

Note that you are going to need to completely change the value of the variable `lightSensor`. This is because it will now be outputting different values due to the extra resistor to ground.

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

<!-- End schematic -->


message:
Arduino DigitalWrite() Super Basic Circuit measure voltage with multimeter

I am having a problem measuring the voltage with a multimeter. I am not sure if arduino is even sending out a voltage from the Pin.

I will try to create a really basic circuit drawing for reference. (Drawing attached).

[![Basic Ciruit Diagram][1]][1]

What I am trying to do is to measure with a Multimeter the Voltage (or current) across the alligator clips.

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

I will attach the code below:

    //Code Section Start//

    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(10000);                  // waits for a second
    }

    //Code Section End//

Typically the digital write I believe will out put 5 volts and with a 1k Ohm resistor that is only 5mA current. I have heard Arduino can take up to 40mA currents so I don't think I am frying something.

There are two weird things I have noticed. When I try other Pins like "int ledPin = 10;" The green light on the Arduino does not light up. It only lights up when I use pin 13. However, even using Pin 13 or any other pin, I cannot find a voltage or current with the Multimeter. I am using an Arduino Micro.

Can someone please help me identify what I am doing wrong or some method of how to check what is wrong? So that I can have a complete circuit with a voltage I can measure.

body:
As you have drawn it, the alligator clips are clamped together (shorted togther).  You reading the voltage "across" a shorted element in the circuit should yield ~0V (shorts by definition have no to very little resistance, meaning there should be no voltage across them).  In order to get your proper voltage reading, you should place the multimeter positive clip above the resistor (where the voltage drop is occuring).

Remember.

Measure current THROUGH.

Measure voltage ACROSS.

p.s. if you're trying to alternate the pin, you should do something like DigitalWrite(pin10, digitalRead(pin10)!=HIGH); (if it's low, then the statement evaluates to true, setting the pin high, if it's high, then the statement evaluates to false, setting the pin low)


body:
As you connected the alligator clips (from the image it seems that they are touching each other) you won't be able to measure anything.

This is how to connect a multimeter to read the current (A) and the voltage (V). You can consider the `+` of E as the pin 13 and the `-` as the ground

 [![][1]][1]

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

Remember that your code will not change the state of pin 13, it will be always high.
If you want to make the signal change try this on your `void loop` :

      digitalWrite(ledPin, HIGH);
      delay(10000);
      digitalWrite(ledPin, LOW);
      delay(10000);


body:
you are telling that you are not getting any current or voltage on your multimeter
right......
i suggest you to use the following 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
    }
this will stay your arduino pin 13 always high then you can measure the voltage on that pin........


message:
Converting `millis()` to decimal seconds?

I would like to get my Arduino to print milliseconds as decimals of seconds.  For example, instead of printing 10456, printing 10.456

I have tried to set a float value or millis, and dividing by 1000 but that gives me a whole number "0" to "1" which is not ideal

The code I use is:

    float ourtime = (millis() / 1000);
    dataFile.print (ourtime);

What would be the easiest, and least taxing (for the processor) way of getting a script to return milliseconds as seconds while taxing the unit as little as possible ?

body:
Dividing an integer by an integer (1000) yields an integer, regardless of what you cast that result to.

Instead you need to divide the integer by a float, or cast the integer to a float first. The simplest way is:

    Serial.println(millis() / 1000.0, 3);

The `3` as the second parameter tells `Serial.println()` how many decimal places to print. The `.0` at the end of `1000.0` forces the compiler to see `1000` as a float value (you can also use `1000f` if you prefer).

Since floating point can be quite expensive it's possible to emulate it using integer division and modulus (although they are still quite expensive):

    uint32_t now = millis();
    uint32_t secs = now / 1000;
    uint32_t ms = now % 1000;

    Serial.print(now / 1000);
    Serial.print(".");
    if (ms < 100) Serial.print("0");
    if (ms < 10) Serial.print("0");
    Serial.println(ms);

You could replace the `%` with a x1000 and a subtraction too if you like:

    uint32_t now = millis();
    uint32_t secs = now / 1000;
    uint32_t ms = now - (secs * 1000);

    Serial.print(now / 1000);
    Serial.print(".");
    if (ms < 100) Serial.print("0");
    if (ms < 10) Serial.print("0");
    Serial.println(ms);

A further method would be to first "print" the milliseconds to a string, then split it into two chunks. Print the first chunk, then a decimal point, and finally the second chunk. This avoids the use of any division or multiplication, but does use expensive string operations:

    char num[10];
    snprintf(num, 10, "%lu", millis());
    uint8_t nlen = strlen(num);

    for (uint8_t i = 0; i < nlen - 3; i++) {
        Serial.write(num[i]);
    }
    Serial.write('.');
    for (uint8_t i = nlen-3; i < nlen; i++) {
        Serial.write(num[i]);
    }
    Serial.println();

So really there is no "perfect" method for converting milliseconds into seconds that uses hardly any CPU cycles. All base 10 operations tend to be a bit expensive on a small microcontroller without hardware support for integer MUL/DIV instructions, or a Floating Point Unit.


body:
Division is quite expensive.

Division can be done with subtraction, or shifting - right shift 10 (= /1024) and then compensate for that 24....

You may need too benchmark to see if on your chip this will yield any gaiin.

edit:

I did some quick benchmarking against the brutal force approach by Majenko (division followed by the mod operation), for full range 16-bit types, dividing by 1000, on a PIC16, XC8 free mode:

for 16-bit types
 1. Majenko's approach (1000 divisor + mod): 45.9M ticks;
 2. revised Majenko's approach (1000 divisor, no mod): 36.9M ticks;
 3. My approach (1024 divisor, no mod): 20.8M ticks.

[edit 2]for 32-bit types
 1. Majenko's approach (1000 divisor + mod): 101.6M ticks;
 2. revised Majenko's approach (1000 divisor, no mod): 63.0M ticks;
 3. My approach (1024 divisor, no mod): 19.3M ticks.

the same trend applies under the pro mode.

the same trend applies for AVR, with the speed gain being bigger.

edit 2: 32-bit benchmarking added.

I also revised my approach for 32-bit types to speed up the execution a little.

lessons learned:

1) mod ops shall be avoided as much as you can;

2) divisions shall be avoided as much as you can.

3) algorithm rules!

however, be cautious to extrapolate the data here. on a chip with hardware multiplier + divider (STM8, my favorite chip), this trend may not apply and you should benchmark on the target chip to be safe.


message:
ESP8266 and Arduino integration

I am trying to upload a sketch and getting below error:

    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed.

Connections:

    TX - TX
    CH_PD - 3.3 V
    RX - RX
    VCC - 3.3
    GPIO GND
    GND - GND

Before uploading the sketch I have reset the arduino and ESP and selected board as ESP8266 and baud rate as 115200 but still getting the same error.

body:
You don't say what you're using to program it (an FTDI board? the USB adapter on an Arduino?) but you probably want to connect

    TX - RX
    RX - TX


message:
Contoller for a stepper motor

I am currently implementing the following setup:

Arduino Mega 2650 -- [DRV8834](https://www.pololu.com/product/2134) -- Stepper motor

Everything works fine, however since it can provide a higher torque I want to run the stepper in half step mode. Each step is triggered by a single pulse coming from the Arduino to the driver. If one uses the Digital Pins for this purpose as done by [AccelStepper](http://www.airspayce.com/mikem/arduino/AccelStepper/), the maximum frequency is around 1000 pps (points per second). This is a third of what I want to achieve. The second option would be to use the PWM of the Arduino which naturally runs at 16 MHz (way to high). There is a way to downgrade this frequency, however the steps are only [discrete](https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM) and not accurate enough for a nice speed control.

Therefore I want to do the following

Arduino Mega 2650 -- Controller -- DRV8834 -- Stepper motor

whereby the Controller is creating a PWM with a frequency (100 to 3000 Hz) depending on some signal coming from the Arduino (I2C, voltage level or something else). I was now searching two days for a component and have no clue what I could use.

How can I create a PWM from 100 to 3000Hz with an arduino?

----------

Edit 1: I have to read out sensors while the motor is running. Therefore, the so called "bit banging" PWM

    void loop(){
    digitalWrite(pinSTEP, HIGH);
    delayMicroseconds(T/2);
    digitalWrite(pinSTEP, LOW);
    delayMicroseconds(T/2);
    }

where T = 1 / f is not feasible since I have to read out a sensor in the loop which destroys the motor timing.

----------

Edit 2: There is a method to change the register of the timers. One can adapt a so called prescalar values (from 0 to 7) which will define the frequency of our PWM. However with only seven discrete steps this leads to the following freuquencies:

    prescalar = 1 ---> PWM frequency is 31000 Hz
    prescalar = 2 ---> PWM frequency is 4000 Hz
    prescalar = 3 ---> PWM frequency is 490 Hz (default value)
    prescalar = 4 ---> PWM frequency is 120 Hz
    prescalar = 5 ---> PWM frequency is 30 Hz
    prescalar = 6 ---> PWM frequency is <20 Hz

which is not sufficient for my application.

For more about this method:

 - http://usethearduino.blogspot.ch/2008/11/changing-pwm-frequency-on-arduino.html
 - http://forum.arduino.cc/index.php?topic=72092.0

----------

Sometimes a solution is so easy that it hurts ;) Based on the input of this wonderful community I found my solution. Code:

    #include <TimerThree.h>
    // TimerThree PWM Pins 2, 3, 5

    #define pinPWM       2
    #define pinM0        22
    #define pinM1        24
    #define pinSleepnot  28
    #define pinDir       30

    void setup(void){

      // Define output pins
      pinMode(pinM0, OUTPUT);
      digitalWrite(pinM0, HIGH);
      pinMode(pinM1, OUTPUT);
      digitalWrite(pinM1, LOW);
      pinMode(pinSleepnot, OUTPUT);
      digitalWrite(pinSleepnot, HIGH);
      pinMode(pinDir, OUTPUT);

      // Initialize serial communication
      Serial.begin(9600);

    }

    void loop(void){

      for (float frequency = 500; frequency < 3000; frequency = frequency + 1) {
        float T = 1 / frequency * 1000000;
        Serial.print("Frequency: ");
        Serial.println(frequency);
        Timer3.initialize(T);
        Timer3.pwm(pinPWM, 100);
        delay(5);
      }
    }

body:
> the maximum frequency is around 1000 pps

Arduino pin operations takes about 100 ticks. Or 400 ticks for four pins. No more than another 100 ticks for processing and logic ops. So I would expect 500 ticks or 30k on a 16mhz Arduino.

Much faster if you use direct pin ops.

So maybe the code you used isn't well written or your Arduino is doing lots of other things?

edit:

> I found my solution. Code:

there is no reason for you to repeatedly initialize the module. this thing is simple, and others have laid out the thought process for you. write a set of routines that spin the motor - spin it left, spin it right. and then call those routines in a timer isr. nothing fancy here.


body: You might need to move away from the AccelStepper library, and 'roll your own', but as others have pointed out, the MCU certainly has the bandwidth to do this directly.  I understand that PWM resolution may not give smooth ramping, but I would probably look into using a timer interrupt.  The timer ISR would count steps and you would only need to adjust the timer compare register to change the step frequency.


body:
> How can I create a PWM from 100 to 3000Hz with an arduino?

Your question is really "How can I create a PWM from 100 to 3000Hz with an Atmega2560"?

The Atmega has various timers which can be configured in many ways. You can alter the prescaler (ratio of processor clocks to timer ticks) and the amount it counts up to. Certainly you can change the frequency and duty cycle.

I have a [page about timers](http://www.gammon.com.au/timers) which may help you.

---

> I have to read out sensors while the motor is running. Therefore, the so called "bit banging" PWM ... is not feasible

Yes, don't do "bit banging" when you have 5 hardware timers.

---

> One can adapt a so called prescalar values (from 0 to 7) which will define the frequency of our PWM.

Adapt the prescaler **and** the timer configuration. Between them you have very fine control.


message:
Problem with shift register

I have a problem with the shift register 74HC595.

The sketch I use is able to enable a specific led (8 are connected).

When I enable led 0 to 7 it behaves like normally (they switch on when I enter the numbers).

However, for the led connected to pin 15 (other side of the ic, see [layout][1]) it behaves differently.
 When I switch this led on, ALL leds go off. When I retry, nothing happens. When I enable another led, after a short time (but can be seconds) the led for pin 15 is emitting light together with all others which where already enabled.

This seems like a malfunction in the IC (I checked already another led, another cable, another resistor). The only think I haven't checked is moving the IC to another position of the breadboard (that would take a lot of time since I have to rewrite everything). Is it possible I missed something or is the shift register broken?

The code to switch on a led:

    void updateShiftRegister()
    {
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, LSBFIRST, leds);
      digitalWrite(latchPin, HIGH);
    }

where leds are the indices of the leds (0..7).

  [1]: http://2.bp.blogspot.com/-cIb_uYGrRk4/U1fxdfGhy-I/AAAAAAAAADg/kcuUjMcpzD0/s1600/Region+Capture.png

body:
You cannot directly give an index (0..7) to a shift register if you want the index to represent the LED number to be switched on.
You have to build a table similar to the following:

    byte led[8] = {
    0b00000001,
    0b00000010,
    0b00000100,
    0b00001000,
    0b00010000,
    0b00100000,
    0b01000000,
    0b10000000
    };

and later . . .

    shiftOut(dataPin, clockPin, LSBFIRST, led[leds]);

where leds is a number 0..7


message:
Is there a constant for the Maximum Unsigned Long value in an Arduino compiler?

I am writing a timer function that uses the micros() function which generates a unsigned long value.  To compensate for a roll over condition, I would like to use the maximum value for that variable type.  I have a number, 4,294,967,295, but was expecting that to be a constant somewhere.

Is there a MAX_UNSIGNED_LONG constant in the Arduino compiler files somewhere?

I have tried that name and know it probably isn't that.  Still poking around.

body:
Various `limits.h` files in the `avr-gcc` hierarchy define `ULONG_MAX`, which may be the value you want.  For example, on my system such files have paths ending with `hardware/tools/avr/lib/gcc/avr/4.8.1/include-fixed/limits.h` or with `hardware/tools/avr/lib/gcc/avr/4.8.1/install-tools/include/limits.h` and contain definitions like the following.

    /* Maximum value an `unsigned long int' can hold.  (Minimum is 0).  */
    #undef ULONG_MAX
    #define ULONG_MAX (LONG_MAX * 2UL + 1UL)

Note, `LONG_MAX` also is defined in `limits.h`.

Note, arithmetic done in a form like

    timeDelta = micros() - prevTime;

will be correct (regardless of whether `micros()` overflowed) for elapsed times up to 2³² microseconds, or about 4295 seconds.


body:
You don't need "to compensate for a roll over condition".

See my answer: https://arduino.stackexchange.com/a/33577/10794

---

> in an Arduino compiler?

The "Arduino" compiler is a C++ compiler. That is the starting point for most questions. If you Google for:

    maximum unsigned long in c++

You will find the first link leads to:

http://www.cplusplus.com/reference/climits/

In that it says:

    ULONG_MAX Maximum value for an object of type unsigned long int


body:
Did you try to do this?:

    unsigned long maxUnsignedLong = 0UL - 1UL;

or:

    const unsigned long ULONG_MAX = 0UL - 1UL;


message:
Arduino Zero (ATSAMD21G) - I2C - continuous wrong data flow

I encountered a strange behavior while running 2 way transmission tests  between 2 Arduino Zero (ATSAMD21G), one master and one slave. Wrong data is being continuously transferred both ways. The expected data is also being transferred in between. I have to filter out the received data to catch it (line 41 in Master's code and 33 in slave).

I'm using the stock wire libraries (being different for the 2 boards), along with Nick Gammon's "I2C_readAnything".

[Master's code][1]

[Slave's code][2]

I think this continuous flow doesn't allow the bus to be released. It might be what's making it impossible to communicate with a second master (and maybe causing my [previous problem][3])

I also tried my code between a Mega 2560 (slave) and a Zero (master). Fake data is, this time, only being sent one way (from the Zero to the Mega only).

Is there some specific code to add to send data properly from ATSAMD boards? Is it a bug in the SAMD Wire library?

I also had to add a 1ms delay after sending data from the Master. It wouldn't go through otherwise. Shouldn't it be handled by the ATSAMD or the Wire library?

  [1]: https://github.com/kb-/Arduino-I2C-2way-anydata/blob/master/Master_test_i2c_data/Master_test_i2c_data.ino
  [2]: https://github.com/kb-/Arduino-I2C-2way-anydata/blob/master/Slave_test_i2c_data/Slave_test_i2c_data.ino
  [3]: https://arduino.stackexchange.com/questions/34944/two-way-communication-on-multimaster-i2c-bus

body:
Start with a single byte, with a very small sketch, with both the Master and the Slave at 100kHz. When that is working 100% reliable, then you can try to transfer a struct.

The Slave RequestEvent function should always return valid data, not once every two seconds. The global variables that are used in receiveEvent or requestEvent **and** in the loop() should be made 'volatile'. Disable the interrupts in the loop() when reading or writing the global volatile struct.

With your sketch, you have to open the serial monitor for both the Master and Slave.

You could add more tests, for example testing the return value of Wire.endTransmissing, testing the 'howMany' parameter, testing the actual number that Wire.request returns.


body:
The code had several issues.

`receiveEvent`, on the slave side, contained a `millis` `if` condition timer that made it time out. I moved the timer to the master side before calling `Wire.requestFrom`.

`receiveEvent`, on the slave side, was also confusing real data with incoming `requestEvent`. I added an `if` statement to compare the `receiveEvent` data size with the expected size. Half of the data was wrong without this filter (this should ideally be handled in the `Wire` library)

I set the global variables used in events as `volatile`. The code is working too without this tho.

[fixed Master code][1]

[fixed Slave code][2]

[1]: https://github.com/kb-/Arduino-I2C-2way-anydata/blob/f781617142bd0198ea9d41a78125e3cb52f5399c/Master_test_i2c_data/Master_test_i2c_data.ino
[2]: https://github.com/kb-/Arduino-I2C-2way-anydata/blob/f781617142bd0198ea9d41a78125e3cb52f5399c/Slave_test_i2c_data/Slave_test_i2c_data.ino


message:
Right way to convert 120VAC to 5V?

I am currently using a Particle Photon to control a relay that turns a lamp on and off. I would like to power the Photon and the lamp from the same power cord.

Currently, I have a power cord for the lamp and I am also using a usb cable to power the Photon.

I found [this (Enclosed AC DC Converter)][1] and I am wondering if this will work if I split the 120V power cord to go to the relay and the converter. Will I need anything else? Are there any other concerns I should worry about? Do I need to worry about polarity?

Thanks for your help in advance.

  [1]: https://www.digikey.com/product-detail/en/rohm-semiconductor/BP5038A1/BP5038A1-ND/756609

body:
I highly recommend reading the datasheets for any electronics because they have an incredible amount of information.

**Short Answer, No**

If you read the [datasheet for the Particle Photon][1], it recommends no less than a 1A power supply. Unfortunately, the [datasheet for the AC/DC Converter][2] you found shows it has a maximum output current of 30mA, which is nearly 30x smaller than you would want for the Photon.

**How to Make This Work**

Because you're trying to get ~1A @ 5V and you're working with 120VAC, you don't have to reinvent the wheel--or in this case, the USB Charger Brick!

Literally any off-the-shelf USB charging brick for a phone or tablet will work. I can't think of any that are less than 1A-rated anymore, but if you want a hobbyist-level supply, something like [this one][3] may be right for you (not to plug for Adafruit, though they are a great learning resource).

Basically, you'll have a box that houses the Photon and the relay. You simply put this in the box with it, and voila! you have 5V power for the Photon.

**Bonus Points**

You can even go nuts and remove the device from its housing (DISCLAIMER: This may void the UL listing and any warranty) and just grab the innards to package neatly in a nice enclosure.

EDIT:

**Easiest Solution**
Just install one of [these][4] at the receptacle you intend to use.

  [1]: https://docs.particle.io/datasheets/photon-datasheet/
  [2]: http://rohmfs.rohm.com/en/products/databook/datasheet/module/power_module/acdc_converter/bp5038a1.pdf
  [3]: https://www.adafruit.com/products/501?gclid=Cj0KEQiA0L_FBRDMmaCTw5nxm-ABEiQABn-VqbbpG3K3rVPtn01mbKr3J9tlkb8CP5K8yCYrUjuRFNMaAv_T8P8HAQ
  [4]: https://images-na.ssl-images-amazon.com/images/G/01/aplusautomation/vendorimages/bf5475b0-12da-4b13-a9e2-94a9fc27e1ce.jpg._CB311932683__SL300__.jpg


message:
How to communicate with GPS SIM900a without Serial Monitor

I am fairly new to Arduino. I was working on a project where I use a GSM SIM900a modem interfaced with an Arduino. The AT commands are sent via the Arduino to the GSM Modem. The problem, however, is that the commands are only sent when I open the Serial Monitor. I have an IR proximity sensor and I would like the AT commands to be sent when the sensor detects an object. I am putting the code for the GSM modem below (I have not yet put in the code for the IR sensor).I want to know how to send the AT commands when the Arduino is hooked up to a battery and not to a PC

    #include <SoftwareSerial.h>
    SoftwareSerial myGsm(7,8);
    float temp;
    int tempPin = 0;
    void setup()
    {
     myGsm.begin(9600);
     Serial.begin(9600);
     delay(500);

    myGsm.println("AT+CIPSHUT");
     delay(1000);
     printSerialData();

     myGsm.println("AT+CIPMUX=0");
     delay(2000);
     printSerialData();

     myGsm.println("AT+CGATT=1");
     delay(1000);
     printSerialData();

     myGsm.println("AT+CSTT=\"bsnlnet\",\"\",\"\"");//setting the APN,2nd parameter empty works for all networks
     delay(5000);
     printSerialData();

     myGsm.println();
     myGsm.println("AT+CIICR");
     delay(6000);
     printSerialData();

     myGsm.println("AT+CIFSR"); //init the HTTP request
     delay(2000);
     printSerialData();

     myGsm.println("AT+CIPSTART=\"TCP\",\"122.178.80.228\",\"350\"");
     delay(5000);
     printSerialData();
     delay(5000);

     myGsm.println("AT+CIPSEND");
     delay(2000);
     printSerialData();

    sendtemp();
    delay(3000);
    myGsm.println("AT+CIPCLOSE");
    printSerialData();

    myGsm.println("AT+CIPSHUT");
    delay(1000);
    printSerialData();
    }

    void loop()
    {
    }

    void printSerialData()
    {
     while(myGsm.available()!=0)
     Serial.write(myGsm.read());
    }

    void sendtemp()
    {
      temp = analogRead(tempPin);
      temp = temp * 0.48828125;
      Serial.print("TEMPERATURE = ");
      Serial.print(temp);
      Serial.print("*C");
      Serial.println();
      delay(5000);
     myGsm.println(temp);
     delay(3000);
     printSerialData();
     myGsm.write(0x1A);
     delay(3000);
       printSerialData();

    }

body: Well, I too had the same problem until now. The simple way to fix is just to delay the void setup() before Serial communication begins. Add delay(15000); //15 Seconds so that GSM module boots up and connects to the network. And there is no need of changing any part of code. Hope this helps someone out there like me. :)