body:
What power source should I use for my Arduino Mega project (involves 2 steppers, 2 servos and 2 dc motors)?

I tried to run two stepper motors with 9V battery. But the battery dried out. I am thinking of 8 AAA batteries. Is there a better option? How about powering through Arduino with the help of a DC adapter?

title: Powering my Arduino Mega project

Answers: 1

body:
To properly answer this, you first have to determine how long you want your application to be able to run on a full charge. Clearly, it'll run on a 9V battery, but not for very long.

To determine the appropriate power supply, you need to calculate the overall voltage and current requirements for the various components.

The Mega needs a pretty minimal power supply, just 5V @ [200mA][1].

You don't specify the ratings for your motors. Servos are typically 5-6V @ 500mA, but I'm only guessing. Steppers and DC motors vary quite a lot.

The first step would be to find the specifications for all your motors, and find the maximum values, specifically the operating voltage and stall current. Hypothetically, say the maximum voltage for all the motors is 5V, and the stall currents for the steppers, servos and DC motors are 1A, 1A, 500mA, 500mA, 3A, and 3A respectfully. (Again, this is just an example. Find the true values yourself). That means you'll need a supply that can safely deliver 1+1+0.5+0.5+3+3+0.1 = 9.1A @ 5V or 45.5 watts.

If you want to use a battery (instead of a stationary supply like a DC adapter), you'll need to chose a battery with adequate mAh rating, which is the total number of amps it can deliver in 1 hour.

Perfectly predicting battery life greatly depends on the battery chemistry and your application's average current draw, both of which great very complicated, so I won't go into that here. A battery is considered effectively "dead" when it's depleted to around 80% of it's fully charged voltage. You can lookup the formulas and do the math yourself, or you can use some [online calculators][2] to help you estimate discharge times for different battery and load configurations.

However, as a general rule of thumb, you want to select a battery with a voltage greater than the minimum voltage required by any of your components. For your application to run for 1 hour, it's mAh rating should also be greater than your application's total current consumption. To run longer, you'll need to find a battery with a higher mAh rating, or higher voltage that a switching regulator can use to convert that extra voltage into current.

The other important factor, which complicates these calculations, is the type of voltage regulators you use. If you want to power everything from a single battery, you'll definitely need some voltage regulators. Preferably, you should use high-efficiency switching regulators. For this purpose, you can find cheap UBECs used for RC applications on Amazon or Ebay. You should have one for the Arduino and each motor (or pair of motors if you want to save on cost or complexity). Just make sure the regulator's voltage and current requirements are greater than what's consumed by your components.

I find using 2 or 3 Lipo batteries in series, especially 18650 cells, are the cheapest and easiest way to provide power for mobile applications that have high spikes due to motors. For stationary applications, a 12V DC wall adapter with a high current rating would be simpler.

If you want to use akalines, I'd recommend using separate batteries for the Arduino and motors. Akalines aren't well known for being able to deliver high current. Motors can demand a lot of current, and if the battery can't deliver enough, it'll cause the voltage to drop, resulting in the Arduino browning-out. However, lipo batteries, or non-rechargeable lithium batteries are better suited for this.

  [1]: https://forums.adafruit.com/viewtopic.php?f=25&t=81006
  [2]: http://planetcalc.com/2283/


body:
After driving myself insane with an unreliable Leonardo, I narrowed down the problem to its serial port. Namely, it's not a true serial port, but some sort of simulated monstrosity that can't be reliably reset. This makes uploading sketches immensely difficult. I found that neither Arduino-Makefile nor the Arduino IDE can reliably upload sketches to a Leonardo, and succeed only 10% of the time.

It took me awhile to accept just how terrible the Leonardo was, because before this, I had only used the Uno and Mega, which are extremely reliable. They've always "just worked" for me, so I couldn't understand why Arduino would release a board as unusable as the Leonardo. I've since realized the Uno is so reliable, in part because it has a more complete serial port, and don't use the dreaded 32u4 chip and its fake serial port that doesn't support the DTR or RST pins.

That said, which Arduino's have a real serial port? Is it only the Uno and Mega? After months of banging my head against a Leonardo, I want to avoid anything else that uses the Atmega32u4 chip. Unfortunately, looking at all the [various boards][1], it looks like many, especially most of the newer ones, use the 32u4.

Am I missing something here? Everything I Google an error uploading with avrdude or the IDE, the results always mention problems with boards like the Leonardo and their unstable serial ports. Why does Arduino keep using the 32u4 chip if it's that unreliable?

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

title: Which Arduinos have a true serial port?

Answers: 1

body:
There seems to be quite a few Arduinos without a 32U4, like:

- Uno (you mentioned it already)
- Mega (same)
- Lilypad Snap
- MKR1000
- Pro
- Pro Mini
- Zero
- Due
- Ethernet
- Mini
- Nano
- MKR Zero

See the list at [Comparison table][1].

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


body:
I am working on a project that is supposed to record the time difference between two photoresistors that are 4in apart. The photoresistors are sensing the passing of water or other liquids on a chute/ramp.

The liquids range from water to milkshakes so the time difference shouldn't be more than 2 or 3 seconds at most (I would think). I'm okay with the accuracy being off by a a few tenths of a second.

I am using Photo cell (CdS photoresistor) for my project.

I have looked online and haven't seen a similar project. I want to be able to display the time difference on a lcd.

I have my lcd up and running but I'm not sure how to code the time difference. My photoresistors are connected to A0 and A1 and I am using digital pins 7-12 for the lcd. If anyone has any advice that would be very appreciated!

I'm sure I missed something so ask any clarifying questions

title: Measuring time between two photoresistors and printing time on lcd

Answers: 3

body:
I assume you want to measure the difference in time between drops or a change in the resistance of the photo resistors?

Measure every x ms the values of the photo resistors. You can use a sleep for this (or maybe you can just continuously measure).

You have to store the measurements probably, to calculate, when a signal is changing. Also you have to store the times.

E.g.

          Resistor 1    Resistor 2
     0 ms          10            20
    10 ms          10            20
    20 ms          30           600     Drop at resistor 2
    30 ms          30           620     Drop at resistor 2
    40 ms          45            20     Drop passed resistor 2
    50 ms         400            20     Drop arrived at resistor 1

So you know that the drop (delay) is 50 - 20 = 30 ms

You have to make an algorithm that will see this change, and also you might have to take into account multiple drops (so counting of drops/signal changes).

body:
The most accurate approach is via In out capture on your timer.

Alternatively you can use an interrupt to start and stop the timer.

The worst approach is to poll

However, phtoresistors are slow and generally inconsistent. This can lead to errors in reading. S phototransistor or diode works better.

Edit: it is crazy to try to read the signal in analog. Instead design the circuitry so that it breaches the digital low or high thresholds so you can use digitalRead instead.

You can simply use millis or micros to time stamp the events and calculate the difference.

If you want more precise timing measurements, Google ticks implementation.

edit 2:

here is what I tried:

    if (dtime_running==0) {    //event 1 has not arrived
     if (EVENT_ON(EVENT1_PIN)) {  //event 1 has arrived
      dtime = time_now();   //time stamp the event
      dtime_available = 0;  //data not yet available
      dtime_running = 1;   //time measurement running
     }
    } else {       //event 1 has arrived and now wait for event 2
     if (EVENT_ON(EVENT2_PIN)) {  //and event 2 has arrived
      dtime = time_now() - dtime; //calculate the timing difference
      dtime_available = 1;  //data now available
      dtime_running = 0;   //stop taking measurement
     }
    }

On two pulses that are 500ms apart, here is the measurement:
[![enter image description here][1]][1]

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

Notice that in the box on the upper right, dtime has a value of 500, just as we expected.

the risk with this approach is that if the loop has other tasks, jitters to the measurement will show up. but for slow events, or long time measurements, it may not matter that much.

body:
You are asking about

> the time difference between two photoresistors

This, to start with, makes little sense. Photoresistors are analog
devices. Their resistance, and thus the voltage you measure, is a
continuously varying quantity. The first thing you have to do is to turn
them into logic (i.e. either “off” or “on”) devices. The simplest
approach is to compare your analog reading to a threshold:

* if the reading is above the threshold, you will say LDR is in the
  `HIGH` state
* if it is below the threshold, the LDR is in the `LOW` state.

There is a problem with this simple approach though: when the reading is
close to the threshold, the ambient noise can make many spurious
transitions between `LOW` and `HIGH`. The simplest solution is to have
not one, but _two_ thresholds. This is called “[hysteresis][]” and is
something you definitely should have whenever you are using thresholds
against analog readings. This can be coded as follows:

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

    const int THRESHOLD_LOW  = 400;  // dummy value
    const int THRESHOLD_HIGH = 600;  // dummy value

    int HystereticRead(uint8_t pin, int previousState)
    {
        int reading = analogRead(pin);
        if (previousState == LOW && reading >= THRESHOLD_HIGH) {
            return HIGH;
        } else if (previousState == HIGH && reading < THRESHOLD_LOW) {
            return LOW;
        } else {
            return previousState;
        }
    }

Obviously, the thresholds you will use will not be these dummy values:
you will determine them from experiment.

Next thing is to record transitions. You do not want to look for a
particular state of the LDR, but for the moment it moves from one state
(say `LOW`) to the other. This is done by comparing the new state you
read to the previous one, as in:

    static int state0;  // state of the LDR 0
    int new_state = HystereticRead(A0, state0);
    if (state0 == LOW && new_state == HIGH) {
        // LDR 0 went from LOW to HIGH.
    }
    state0 = new_state;  // save for next time

Last thing, and really the simplest, is to record times. You just have
to call `millis()` to get a timestamp, and compute a difference between
timestamps to get a duration in milliseconds. Here is how you could
write it:

    void loop()
    {
        static int state0, state1;  // states of the LDRs
        static uint32_t time0;      // last time LDR 0 went HIGH

        // Check for LDR 0 going HIGH.
        int new_state = HystereticRead(A0, state0);
        if (state0 == LOW && new_state == HIGH) {
            time0 = millis();
        }
        state0 = new_state;

        // Check for LDR 1 going HIGH.
        new_state = HystereticRead(A1, state1);
        if (state1 == LOW && new_state == HIGH) {
            uint32_t time1 = millis();
            Serial.print(time1 - time0);
            Serial.println(" ms");
        }
        state1 = new_state;
    }

[hysteresis]: https://en.wikipedia.org/wiki/Hysteresis


body:
I'm writing a char array to a device with an arduino mega that should be giving me an echo back, instead, I'm getting an array back with different chars that correspond to my sent function, but not in a way I can figure out. for example `{1,6,250,0,91,233,252}` returns the array `{127,62,1,146,90,0,0}`
As 1 is always returning 127, I'm guessing it has something to to with how I'm casting my received data, but after messing with it for a few hours, I can't seem to get it to cast correctly.

# Main Function
gets destination address and data, echos back if requested

calls **CRC**(this works fine) and **SkRead**(the problem area)

    void Create_Message(int Address, int Data, bool echo)
    {
      lcd.setCursor(0,1);
      lcd.print(Address);
      lcd.print(" ");
      lcd.print(Data);
      Address--;
      byte SvAdd = 1;
      byte FuCode = 6;
      byte AddHi = Address>>8;
      byte AddLo = Address;
      byte DatHi = Data>>8;
      byte DatLo = Data;
      byte AdDa[] = {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo};
      uint16_t crc=CRC(AdDa,sizeof(AdDa)/sizeof(AdDa[0]));
      byte CrcHi = crc >> 8;
      byte CrcLo = crc & 0xFF;
      /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
      * to
      *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
      */
      unsigned char cmd[8]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcLo,CrcHi};
      for (int i=0; i< 8; i++)
      {
      Serial1.write(cmd[i]);   // Send string
      if(echo){Serial.print(cmd[i]);Serial.print('.');}
      }
      if(echo){Serial.println();}
      if (SkRead(echo) == cmd)
      {
      Serial.print(Address);
      Serial.print('\t');
      Serial.println(Data);
      }
      //clear line
    }

----------
# CRC
(works fine, just wanted to show full code)

    /*---Create CRC Function---*/
    uint16_t CRC(byte AdDa[], int Size )
    {
      uint16_t crc16 = 0xFFFF;
      int pos = 0;
      int i = 0;
      /*Write CRC*/
      for (pos = 0; pos < Size; pos++)
      {
        crc16 ^= AdDa[pos];          // XOR byte into least sig. byte of crc
        for (i = 8; i!= 0; i--) // Loop over each bit
        {
          if ((crc16 & 0x0001) != 0)        // If the LSB is set
          {
            crc16 >>= 1;                      // Shift right and XOR 0xA001
            crc16 ^= 0xA001;
          }
          else
          {
            crc16 >>= 1;                      // Shift right
          }
        }
      }
      /*Note, this number has low and high bytes swapped,
      so use it accordingly (or swap bytes)*/
      return crc16;
    }

----------
# SkRead

This is my problem area, I'm sure the data is being sent and read correctly, but one of my assignments is throwing it off so the received echo is not received in a way that matches what is sent.

    unsigned char SkRead(bool echo)
    {
      digitalWrite(Pin13LED, HIGH);  // Show activity
      outputstring = "";
      unsigned long bide=millis()+2000;
      byte inChar;
      while(Serial1.available()<8 && bide>millis()){}
      while(Serial1.available())
      {
        inChar = (byte)Serial1.read();
        outputstring += (char)inChar;
      }
      //Serial.println(outputstring);
      digitalWrite(Pin13LED, LOW);  // Show activity
      int charl = outputstring.length() + 1;
      unsigned char outputschar[charl];
      outputstring.toCharArray(outputschar,charl);
      if (echo)
      {
        for (int i=0; i< charl; i++)
        {
         Serial.print(outputschar[i]);
         Serial.print('.');
        }
        Serial.println();
      }
      return outputschar;
    }

title: Echo from device not matching input

Answers: 1

body:
I don't know where to start.

 - You did not provide a full sketch. There is, for example, no Serial.begin1() in sight.
 - You did not provide enough information about the device. If you don't want to tell us what it is, then give an indication of its age. In the 1980's it was common to have 7E1 format (7 data bits, even parity, 1 stop bit).
 - You have to be sure what the baudrate is. To detect a wrong baudrate, you need a oscilloscope or logic analyzer. When the device has a processor and the baudrate is derived from it's clock, the baudrate could be different from the specified baudrate by a few percentage. That is already a problem with the Arduino.
 - It could be a problem with inverse voltage levels. What does the device use as idle and as active level ? The Arduino Mega uses +5V at the TX pin when idle, and low is active. That means that the TX pin is normally high, and the first low pulse is the start bit.
 - The device could return an error code instead of an echo.
 - Your SkRead function can be improved:
 - Using a String object to collect the incoming data and after that converting the String object to a unsigned char array to use it, is not the most elegant solution. You could just use a unsigned char array to read the incoming data.
 - It is not okay to add something to the millis value. That is a problem when millis does a rollover (after 50 days or so).
 - Normally a character is read as soon as it is available. You wait until 8 characters are in a buffer. No one else does that.

To solve this puzzle you need more information. Try to capture the RX and TX signals with a oscilloscope or logic analyzer. Or else try to write a very small sketch that creates the problem.

My best guess is that it is not your sketch, but perhaps a combination of inverse levels, parity and baudrate.

[**ADDED**]
After writing down the bits over the serial bus, it might indeed be inverse voltage levels and maybe something with 7 bits or parity. That would also explain the last bytes to be 255. Those 255 are not valid data.


body:
It would be easier to program led matrix if 1-8 pins corresponded to 1-8 rows and 9-16 pins corresponded to 1-8 columns.
Instead there is the following arrangement:
[![8x8 led matrix pins to rows/columns arrangement][1]][1]

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

Why is it made like this?

title: Why is 8x8 matrix pins do not correspond to rows and columns order?

Answers: 1

body:
It's probably easier to manufacture, other than that, I don't see why.
If this is a serious issue, you can contact your manufacturer, since he is most likely to know why.

You can:

 1. Work around the issue, by wiring pin 1 to input 9, pin 2 to input 14 etc.
 2. Make a software solution like:

    \#define ROW1 9

    \#define ROW2 14

 3. Buy an LED-matrix that has the pins in the correct order (check the datasheet before purchase).


body:
I am currently working on an ESP8266 with the Arduino IDE. I try to implement an ESP8266 in STA mode as multicast receiver. I was writing my code with the help of [this documentation][1]. Especially the following part:

> The WiFiUDP class supports sending and receiving multicast packets on STA interface. When sending a multicast packet, replace udp.beginPacket(addr, port) with udp.beginPacketMulticast(addr, port, WiFi.localIP()). When listening to multicast packets, replace udp.begin(port) with udp.beginMulticast(WiFi.localIP(), multicast_ip_addr, port). You can use udp.destinationIP() to tell whether the packet received was sent to the multicast or unicast address.

Sending to the multicast group with `udp.beginPacketMulticast(addr, port, WiFi.localIP())` and `udp.write(message, messageLength)`works flawlessly.

The receiving part of my code is as follows:

    #include <ESP8266WiFi.h>
    #include <WiFiUdp.h>

    #define BUFFER_LENGTH 256

    const char* ssid = "xxxxxx";
    const char* password = "xxxxxx";

    WiFiUDP Udp;
    IPAddress multicastAddress(226,1,1,1);
    unsigned int multicastPort = 4096;

    char incomingPacket[BUFFER_LENGTH];

    void setup(){
     WiFi.mode(WIFI_STA); //station
     WiFi.setOutputPower(0);
     while (WiFi.status() != WL_CONNECTED)
     {
         WiFi.begin(ssid, password);
         delay(500);
      }
      Udp.beginMulticast(WiFi.localIP(), multicastAddress, multicastPort);
    }

    void loop(){
     int packetLength = Udp.parsePacket();
     if(packetLength){
      int len = Udp.read(incomingPacket, BUFFER_LENGTH);
        if (len > 0){
          incomingPacket[len] = 0;
                Serial.printf("%s\n", incomingPacket);
        }
     }
    }

When sending a packet with a [simple][2] multicast sender (with matching IP and port), my multicast receiver on my linux laptop receives the packet, but the ESP8266 doesn't.

Maybe some of you have experienced a similar behavior and are able to give me some hints, where I might be wrong.

EDIT:
Since the time I asked this question I completely ruled out an error of the sender on the linux machine by using a verified, 100% working sender. The ESP8266 still doesn't receive any multicast datagramms.

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/udp-class.html
  [2]: http://ntrg.cs.tcd.ie/undergrad/4ba2/multicast/antony/example.html

title: ESP8266 UDP multicast doesn't receive packets

Answers: 1

body:
I recently had the same problem.

The unequivocal answer is that there is a power optimization (internal by Espressif) to save power, I guess, and it really creates havoc in the UDP Multicast receiving. Why? I have no idea. Same problem with the ESP32 and ESP8266.

Solution:

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

    #include "user_interface.h"

and after:

    WiFi.mode(WIFI_STA);
    // the below instructions and now u will receive.
    wifi_set_sleep_type(NONE_SLEEP_T); //LIGHT_SLEEP_T and MODE_SLEEP_T


body:
*The information on this is so greatly lacking to the extent that no related youtube videos could be found, no internet material and the seller seems to be very important and not answer to my questions as he is supposed to.
Also he appears to be the only seller to offer such a variety of arduino cameras.*
___
I want to choose colored arduino camera for my project, but I am unable to receive enough information so that I can choose the appropriate arduino camera.

The most important for me to know is does all arduino cameras need the arducam-f shield board in order to work properly (i.e be programmable, colored, with "decent" quality and be able to capture photos in less than 1~2 seconds)
___

 1. This is "5MP Mega pixel OV5642 Sensor Camera Module w CS mount Lens" It costs US $29.99. The description doesn't mention the need of any other 3rd party hadware in order to work.

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

2. This bellow is "Arducam-F Shield V2 Camera module shield /w OV2640 for Arduino UNO MEGA2560 DUE" it costs US $29.99 and is a camera that evidently comes with this magical shield. We can see that the version is slightly older than that on the other cameras.

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

3. This is "2 Mega pixel Camera Module MT9D111 JPEG Out + HQ lens" for US $21.99 and also, like in any other description, the need of shields is not mentioned

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

4. And this is "2Megapixel MT9D111 Auto Focus lens camera flex module with Adpater board" that has autofocus, is 2MP like the one above, comes with .... ?Adapter board"? (nothing like that is shown in the pictures or described in the description) and costs only US $9.99. It looks ugly compared to other cameras.

[![enter image description here][4]][4]
___
These was the 4 example arduino cameras I would choose from and do all of them need arduino shields in order to do what a camera should do?
(Explaining differences, pros and cons will be very useful to everyone who are in the same boat as I am)

  [1]: https://i.stack.imgur.com/JXp4T.png
  [2]: https://i.stack.imgur.com/i8w0w.png
  [3]: https://i.stack.imgur.com/5M0ZL.png
  [4]: https://i.stack.imgur.com/J6dhj.png

title: Do all arducam need the "Arducam-F Shield"?

Answers: 1

body:
You have three requirements:

* Good quality (colour)
* High resolution
* Fast operation

Those three requirements together mean you cannot use a normal Arduino.

1. The Arduino has nether the memory nor processing power to directly communicate with a camera module.
2. The ones you can communicate with have internal buffer memory and use a slow UART interface to transfer a frame. That is not fast.
3. The Arduino cannot deal with a large picture regardless of speed. All you can do is pass the image through to somewhere else for processing. Slowly.

So you can either have very low resolution or slow speed.

So use a Raspberry Pi or something similar which is more capable of using a camera (indeed, the Pi has a dedicated camera connection).


body:
I purchased 3 ACS758 Hall Effect Current Sensors [datasheet](http://www.allegromicro.com/~/media/Files/Datasheets/ACS758-Datasheet.ashx) on ebay. A 50,100 and 200A, all three are bi-directional. They look like [this](https://www.tindie.com/products/BBTech/allegro-acs758-current-sensor-module-50a100a150a200a/).

With **no** current the 50A outputs 477 on the analogue input (2.33v), the 100A outputs 509 (2.48v) and the 200A outputs 512 (2.50v). At no current they should all be at exactly mid range i.e. 512 (2.50v). The datasheet says they're factory calibrated as such. I've tested them one after the other, both with 5v from the Audrino and with a separate 5v supply. As I've tested one after the other it's not likely to be stray magnetism or VCC.

I've then put them in a circuit drawing about 9amps. Accounting for the offset of zero amps the 50A and 100A measured the increased voltage correctly. The 200A doesn't change.

Is there any other tests I can do to see if I'm doing something dumb or are they all damaged?

title: Problems with ACS758 Hall Effect Current Sensors - Calibration and no Signal

Answers: 1

body:
I contacted Allegro they were really helpful which was pleasantly surprising.

The 200A has almost certainly failed. The 2.48v is within tolerance and the 2.33v is probably out.

I've been able to better understand the datasheet sections on 0A calibration. "VIOUT(Q) may drift over the lifetime of the device by as much as ±25 mV." and there is an electrical offset voltage noted. @25C it's +/-5mv. It's +/-20mv between 0c and 50c. So still only 45mv. Even allowing for noise it's only 55mv.

About 2.445V at zero amps would be the limit.


body:
I'm working on a project where I have to communicate to several devices over I2C using a Genuino 101. Now I'm trying to get data off the bus but `wire.available()` stays at 0, even though my trace clearly shows there's data being sent.

[![ i2c trace][1]][1]

with the following timings

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

[![timings][2]][2]

Because the wire is never available my readbuf will always be empty.

    Rdbuf[0] is: 0 Hex is: 0
    Rdbuf[1] is: 0 Hex is: 0

I'm using the following code to read from the I2C bus.

    void i2cRead(unsigned char device, unsigned char memory, int len, unsigned char * rdBuf) {
      ushort memstart = memory;
      bool available = true;;
      while (len > 0 && available) {
        available = false;
        ushort blockSize;
        /*If the number of bytes is smaller than the block size, read that size*/
        (len < RD_BLCK_SIZE) ? blockSize = len : blockSize = RD_BLCK_SIZE;
        Wire.beginTransmission(static_cast<int>(device));
        //send i2c START command
        Wire.write(memory);
        //Write memory address
        Wire.endTransmission();
        //send i2c STOP command
        Wire.requestFrom(static_cast<int>(device), blockSize,true);
        //Request blockSize bytes from the device
        /* for every byte in the response add that byte to the read buffer */
        while (Wire.available() && (len != 0)) {
          available = true;
          rdBuf[memory - memstart] = Wire.read();
          memory++;
          len--;
        }
      }
    }

I'm not quite sure what I'm doing wrong, any help would be much appreciated.

# Edit:

Below is an image of the current (minimal) setup. On the left there's the board with the ADC and multiplexer visible.

[![Arduino setup][2]][2]

The third set of wires goes to my protocol analyzer.

  [1]: https://i.stack.imgur.com/UVF5L.png
  [2]: https://i.stack.imgur.com/kasgb.jpg
  [3]: https://i.stack.imgur.com/ZyYa6.png

title: I2C device responding, but data is nacked

Answers: 2

body:
You want to get the resulting code working, but you should do small minimal tests.

Start with the [i2c scanner][1].
Connect only one sensor, and if it is detected, add more sensors.

How long are the wires, and what is the value of the pullup resistors ?
Perhaps you have too many modules with sensors, and the total pullup value it too low. The I2C bus is specified for maximum 3mA pull down current.

Do you have a more common 3.3V Arduino board ? For example the Arduino Due or the Arduino Zero ?

  [1]: https://playground.arduino.cc/Main/I2cScanner

body:
Since this has been reopened i figured i'd post what the problem was, in the end and what i did to fix it.

it turns out, that even though the documentation of the Curie tells us to apply a level shifter for i2c communications, this level shifter is already in-place on the genuino 101.

skimming over the documentation of the 101, i had overlooked this.
The fix, in the end was removing the level shifter.


body: I'm actually working on a robotic project for which I'm planning to use arduino to drive the wheels.For this, I want to send signals from my Onboard embedded computer (which has Windows Embedded Compact 2013 OS) to arduino. Is this possible? If not possible, what are the other alternatives?

title: Can I run arduino on Windows Embedded Compact 2013?

Answers: 1

body:
What OS is running on two different devices exchanging messages/signals, does not matter. What matters is the protocol.

You can use a lot of different ones:

- Wireless:
  - IR (infrared)
  - RF (radio), like 433 MHz, 2.4 GHz
  - WIFI (internet)
  - Bluetooth
- Wired
  - SPI
  - 'simple wires' / Wire library
  - Serial
  - USB (not on most Arduinos)

This list is not complete, just some examples.

Arduino supports all above (except USB fully), I don't know what Windows Embedded Compact OS supports.


body:
I'm not sure why my SD card fails to initialize when I run my code (below) but works when I just check to see if it is being read by the Arduino with the CardInfo code in the Arduino library.

The data logger is from Adafruit and the sensor that I'm connecting to it is a MaxBotix one. I've tried reseting the SD card and the Arduino and switching out the SD card. When I verify the code in Arduino there are no issues, so I'm not entirely sure why this isn't working. Any help is greatly appreciated.
UPDATES:
I was able to get it to initalize the SD card by moving

    if (!SD.begin(chipSelect)) {
      error("Card failed, or not present");
    }
after the

    Serial.println().

but now it's not saving data or even creating a new document and it's not printing data as a new line. Things went south when I added the averaging portion of the code because before then it was printing data as a new line and the SD card initializing.
My time is extremely wrong I'm getting a date like 2165/165/165 165:165:85.
[![\[attached image of circuit\]][1]][1][1]

    #include <SPI.h>
    #include <SD.h>
    #include <Wire.h>
    #include "RTClib.h"
    /*
    The goal of this code is to collect 10 data points a minute, average them, and store them to an SD card
    */
    #define LOG_INTERVAL 6000 // mills between entries (reduce to take more/faster data)
    // how many milliseconds before writing the logged data permanently to disk
    // set it to the LOG_INTERVAL to write each time (safest)
    // set it to 10*LOG_INTERVAL to write all data every 10 datareads, you could lose up to
    // the last 10 reads if power is lost but it uses less power and is much faster!
    #define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
    uint32_t syncTime = 0; // time of last sync()

    #define ECHO_TO_SERIAL   1 // echo data to serial port
    #define WAIT_TO_START    0// Wait for serial input in setup()
    RTC_DS1307 RTC; // define the Real Time Clock object
    // The analog pin that connect to the sensor
    const int ultrasonicPin = A0; // declare the input pin for the ultrasonic sensor
    unsigned long time;
    // for the data logging shield, we use digital pin 10 for the SD cs line
    const int chipSelect = 10;
    const int numReadings = 10; //define number of samples to keep track of
    int readings[numReadings]; //the readings from the analog input
    int readIndex = 0; // the index of the current reading
    int total = 0; // the running total
    int average = 0; // the average
    // the logging file
    File logfile;

    void error(char *str) {
      Serial.print("error: ");
      Serial.println(str);
      // red LED indicates error
      //digitalWrite(redLEDpin, HIGH);
      while(1);
    }

    void setup() {
      Serial.begin(9600);
      Serial.println();
      //initialize all the readings to 0:
      for(int thisReading = 0; thisReading < numReadings; thisReading++) {
        readings[thisReading] = 0;
        #if WAIT_TO_START
          Serial.println("Type any character to start");
          while (!Serial.available());
        #endif //WAIT_TO_START
        // initialize the SD card
        Serial.print("Initializing SD card...");
        // make sure that the default chip select pin is set to
        // output, even if you don't use it:
        pinMode(10, OUTPUT);
        // see if the card is present and can be initialized:
        if (!SD.begin(chipSelect)) {
          error("Card failed, or not present");
        }
        Serial.println("card initialized.");
        // create a new file
        char filename[] = "LOGGER00.CSV";
        for (uint8_t i = 0; i < 100; i++) {
          filename[6] = i/10 + '0';
          filename[7] = i + '0';
          if (! SD.exists(filename)) {
            // only open a new file if it doesn't exist
            logfile = SD.open(filename, FILE_WRITE);
            break;  // leave the loop!
          }
        }
        if (!logfile) {
          error("couldnt create file");
        }
        Serial.print("Logging to: ");
        Serial.println(filename);
        // connect to RTC
        Wire.begin();
        if (!RTC.begin()) {
          logfile.println("RTC failed");
          #if ECHO_TO_SERIAL
            Serial.println("RTC failed");
          #endif  //ECHO_TO_SERIAL
        }
        logfile.println("millis,stamp,datetime,depth");
        #if ECHO_TO_SERIAL
          Serial.println("millis,stamp,datetime,depth");
        #endif //ECHO_TO_SERIAL
        // If you want to set the aref to something other than 5v
        analogReference(EXTERNAL);
      }
    }

    void loop() {
      DateTime now;
      // delay for the amount of time we want between readings
      delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));
      // log milliseconds since starting
      uint32_t m = millis();
      logfile.print(m); // milliseconds since start
      logfile.print(", ");
      #if ECHO_TO_SERIAL
        Serial.print(m); // milliseconds since start
        Serial.print(", ");
      #endif
      // fetch the time
      now = RTC.now();
      // log time
      logfile.print(now.unixtime()); // seconds since 1/1/1970
      logfile.print(", ");
      logfile.print('"');
      logfile.print(now.year(), DEC);
      logfile.print("/");
      logfile.print(now.month(), DEC);
      logfile.print("/");
      logfile.print(now.day(), DEC);
      logfile.print(" ");
      logfile.print(now.hour(), DEC);
      logfile.print(":");
      logfile.print(now.minute(), DEC);
      logfile.print(":");
      logfile.print(now.second(), DEC);
      logfile.print('"');
      #if ECHO_TO_SERIAL
        Serial.print(now.unixtime()); // seconds since 1/1/1970
        Serial.print(", ");
        Serial.print('"');
        Serial.print(now.year(), DEC);
        Serial.print("/");
        Serial.print(now.month(), DEC);
        Serial.print("/");
        Serial.print(now.day(), DEC);
        Serial.print(" ");
        Serial.print(now.hour(), DEC);
        Serial.print(":");
        Serial.print(now.minute(), DEC);
        Serial.print(":");
        Serial.print(now.second(), DEC);
        Serial.print('"');
      #endif //ECHO_TO_SERIAL
      analogRead(ultrasonicPin);
      delay(10);
      int value = analogRead(ultrasonicPin);
      for (int i=0; i < 50; i++) {
        if (millis() < 60000*(++i)) {
          // subtract the last reading:
          total = total - readings[readIndex];
          //read from the sensor:
          readings[readIndex] = analogRead(ultrasonicPin);
          // add the reading to the total:
          total = total + readings[readIndex];
          //advance to the next position in the array:
          readIndex = readIndex + 1;
          //if we're at the end of the array
          if (readIndex >= numReadings) {
            //wrap around to the beginning:
            readIndex = 0;
          }
          //calculate the average:
          average = total / numReadings;
          delay(6000);
        } else if (millis() == 60000*(++i)) {
          logfile.print(",");
          logfile.print(average);
          Serial.print("Ultrasonic Reading = ");
          Serial.println(average);
          //Serial.print("Time: ");
          //time = millis();
          //prints time since program started
          //Serial.println(time);
          //wait a second so as not to send massive amounts of data
          // Now we write data to disk! Don't sync too often - requires 2048 bytes of I/O to SD card
          // which uses a bunch of power and takes time
          if ((millis() - syncTime) < SYNC_INTERVAL) return;
          syncTime = millis();
          delay(100);
        }
      }
    }
    // this reads in cm

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

title: Arduino Uno SD card fails to initialize

Answers: 2

body:
You cannot initialize the SD card more than once.  Pull this code out of the `for` loop:

    if (!SD.begin(chipSelect)) {
      error("Card failed, or not present");
    }

Put it after the `Serial.println()`.

body:
Make a new sketch that initialize the SD Card and write data to it, without loop.

If this doesn't works,maybe the sdcard is damage.

So, as shash-dev says,initialize the SD card before you start the for cicle and after the Serial.printl().


body:
I am connecting Arduino Uno R3 with HC 08 module lie following

    Arduino 5v -> HC 08 Vcc
    Arduino gnd -> HC 08 gnd
    Arduino Pin 5 -> HC 08 RXD
    Arduino Pin 6 -> HC 08 TXD

Then I connected two LEDs to 9 and 10 pins

Then loading following sketch.

    #include <SoftwareSerial.h>

    int availableLEDpin = 9;
    int notAvailableLEDpin = 10;
    SoftwareSerial hc_08(5, 6); // RX-5, TX-6
    void setup() {
      pinMode(availableLEDpin, OUTPUT);
      pinMode(notAvailableLEDpin, OUTPUT);
      Serial.begin(9600);
      hc_08.begin(9600);

    }

    void loop() {
      hc_08.listen();
      if (hc_08.available()) {
        Serial.println(hc_08.read());
        digitalWrite(availableLEDpin, HIGH);
        digitalWrite(notAvailableLEDpin, LOW);

      }
      else {
        digitalWrite(availableLEDpin, LOW);
        digitalWrite(notAvailableLEDpin, HIGH);
      }
      delay(100);
    }

I am trying to connect to bluetooth from y iOS application. The application is searching and connecting to the HC 08 correctly. And sending data successfully - Swift code log showing sent successfully.

But back in Arduino, always led connected to pin notAvailableLEDpin is glowing and nothing is printing in serial monitor. What is wrong with my implementation?

title: Arduino with HC 08 bluetooth module

Answers: 2

body: You have the receive port on your arduino connected to the receive port on your bluetooth module. Connect pin 5 to the Tx on your module and connect pin 6 to the Rx on your module.

body: it's better to use digital pin 8/10 as RX, digital pin 9/11 and TX as your softwareserial pins since these pins are dedicated for softwareserial knowing you use the generic softwareserial library and mind your supply to only use 3v3 volts as much as possible, specially for the TX softwareserial pin of your arduino going to RX pin of HC08, you need to lessen the voltage output of that arduino pin into 3v3 volt also, using voltage divider. It will harm your HC08 module and might not work properly.


body:
So I'm trying to make use of my Arduino Uno while I purchase the components for my next project.

I've made use of the Digital Hourglass project from the Starter Kit to make sure I get up and move around every 20 minutes while I'm at home. A temperature sensor was included in the Starter Kit as well, so I figured I might as well make use of it since I have extra I/O pins.

I wrote the code for in the Arduino IDE to display the temperature and the current time. I'm using: `#include (Time.h)` to also show the current time. I have two questions.

End Goal:

A Google spreadsheet (Cloud) that I can access anywhere that can show me the temperature of my apartment throughout the day. I can track how the trend changes over time through the day, week, or month.

1. What is the best way to output the current time; as seconds since 1970 (Unix time) or date and time format? I guess it's a preference.

2. How do I output the data from the Arduino serial port directly to Google Sheets? That may be difficult, so the other option is to energize the Arduino in the morning and remove power at the end of the day, output the Serial port to a `.txt` file, and then import into Google sheets. How do I do this?

title: Sending Analog Input Data from Serial Port to Google Sheets

Answers: 2

body:
I'd use an ESP8266 and IFTTT.

https://ifttt.com/maker_webhooks
https://ifttt.com/google_drive

You could write something on your PC that took the serial output from the Aurdino and posts a REST message to IFTTT.

body:
1. Use Google's time stamp format: `MM-dd-yyyy hh:mm:ss`, see [Google Sheets API v4 - Date and Number Formats][1].

2. There are a few ways. For example:

+ A PC connected to the Internet with software on it that listens for data form the Arduino. It would get the Arduino data over serial then send that via the Internet to Google.

+ A Wi-Fi, or network, shield connected to the Internet. You could then use Google's API to send the data directly from the Arduino, see [Google Sheets API v4 - Writing][2].

+ Or - as you mentioned - physically get the SD card and manually upload.

  [1]: https://developers.google.com/sheets/api/guides/formats
  [2]: https://developers.google.com/sheets/api/guides/values#writing


body:
I am wondering what the second line of code does:

    int16_t GyX;
    GyX=Wire.read()<<8|Wire.read();

Also, how can I write the GyX value to EEPROM?

From what I understand, int16_t is a two-bytes value. The Wire.read() returns a single byte. The <<8 shifts the bits by one byte to the left in order to read the higher order bits, and the last part writes the next wire read (lower order bits). Basically, reads wire twice and stores those values in the int. Is that correct?

For the writing, would

    EEPROM.write(addr, GyX >> 8);
    EEPROM.write(addr, GyX & 0xff);

do the trick? (First line records the higher order bits, while second records the lower order ones)

title: Understanding bitwise operations

Answers: 2

body:
@PetioPetrov, Arduino has macros to make it easier: [highByte][1], [lowByte][2], and [word][3].

You don't have to split and combine bytes and words. The [EEPROM.put][4] and [EEPROM.get][5] can write and read two bytes if you want to. It's all documented in the reference of [EEPROM][6].

There is a lot going on in this piece of code:

    int16_t GyX;
    GyX=Wire.read()<<8|Wire.read();

Shifting a single byte 8 bits to the left would be wrong. However, the Wire.read returns an integer and the GyX is an integer. Therefor the compiler uses integers for everything and shifting 8 bits to the left is valid.
At this moment with the current Arduino and avr-gcc compiler version, it will call the Wire.read for the high byte first and then the Wire.read for the low byte. That is **pure luck** as @EdgarBonet has corrected me below. In the c++ language there is no specified order of calling functions.
The bitwise 'OR' with the '|' could be a problem when there was no data and -1 was returned by Wire.read.

  [1]: https://www.arduino.cc/en/Reference/HighByte
  [2]: https://www.arduino.cc/en/Reference/LowByte
  [3]: https://www.arduino.cc/en/Reference/WordCast
  [4]: https://www.arduino.cc/en/Reference/EEPROMPut
  [5]: https://www.arduino.cc/en/Reference/EEPROMGet
  [6]: https://www.arduino.cc/en/Reference/EEPROM

body:
> `GyX=Wire.read()<<8|Wire.read();`

This is a bug. It reads two bytes from the I2C bus and builds a 16-bit
number from them. One of the bytes (we don't know which one) will be the
most significant byte of the result. The other byte will be the least
significant byte.

This instruction is likely to work just fine on some particular version
of some particular compiler with some particular compiler options.
Presumably it did work for the author. But you should not expect it to
work consistently across compilers, or even across different versions of
the same compiler.

The proper way to do this is to perform the two reads in different
instructions:

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

    GyX = (uint16_t) Wire.read() << 8;
    GyX |= Wire.read();

assuming the bytes come most-significant first.

**Edit**: added `(uint16_t)` cast. C.f. [this answer](https://arduino.stackexchange.com/a/36399).


body:
So, I've found the address of my device using a I2C device scanner. I then looked up the [datasheet][1] for a magnetic sensor I am trying to grab data from.

  [1]: http://www.memsic.com/userfiles/files/Datasheets/Magnetic-Sensors-Datasheets/MMC3416xPJ_Rev_C_2013_10_30.pdf

I'm now trying to communicate with the device by following the 'Example Measurement' section in the data sheet.

Here is my code so far...

    #include <Wire.h>
    #define address 0b110000 // find the actual address, it is at 0x30, which is 0b00110000

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

    void loop() {
      int x, y, z;

      Wire.requestFrom(0b00110000, 1); // START condition?, starts with a 0 to indicate a WRITE request
      if(Wire.available() > 0) {
        Serial.println("1");
        Wire.read();
      }
      Serial.println(Wire.read());
      Wire.write(0b00000111);
      if(Wire.available() > 0) {
        Serial.println("2");
        Wire.read();
      }
      Wire.write(0b00000001);
      if(Wire.available() > 0) {
        Serial.println("3");
        Wire.read();
      }
      Wire.requestFrom(0b00110000, 1); // write request
      if(Wire.available() > 0) {
        Serial.println("4");
        Wire.read();
      }
      Wire.write(0b00000110);
      if(Wire.available() > 0) {
        Serial.println("5");
        Wire.read();
      }
      Wire.requestFrom(0b10110000, 1); // READ request
      if(Wire.available() > 0) {
        Serial.println("6");
        Wire.read();
      }
      // not sure what to do for the 7th cycle???
      // am I even doing the previous correct?
      Wire.endTransmission(address);
      delay(1000);
    }

The numbers in each of the if statements represent the cycle within the 'Example Measurement' section of the datasheet, I'm never able to read data from the device and I am sure that I am doing something wrong.

I appreciate any help! This is my first time ever trying to understand I2C, and I've just been staring at this datasheet for too long without getting anywhere.

title: Confusion receiving I2C data from magnetic sensor

Answers: 1

body:
This is how you send a byte to your slave:

      Wire.beginTransmission(SLAVE_ADDRESS);
      Wire.write(someByteValue);
      Wire.endTransmission();

You must sandwich the writes between a beginTransmission/endTransmission. Output buffer is 32 bytes long, so keep things short.

Wire.write() doesn't write; just put thing in an output buffer, waiting for your endTransmission().

If you need an answer (said, a byte), first you said how many bytes you want and then read them:

      byte pin;
      Wire.requestFrom(SLAVE_ADDRESS, 1);
      if (Wire.available() == 1) {
        pin = Wire.read();
      }

Your are Wire.read()ing, but you are not capturing the return value!

Disclaimer: after requestFrom, you have to be prepared to wait for the data (it may be not inmediatly available). Also, data may arrive in chunks.


body:
I have an Arduino Uno which is going to receive a long binary string.  I know that this string will correspond to English when decoded.  How can I convert the incoming binary string to text, so that I can read it in the Serial Monitor?

Bonus Points: This string will almost definitely have random noise digits.  How would I noise-proof the string, or how could I have the code detect and ignore noise?

UPDATE: It might help if I mention my end goal.  So I have this contained clean space that is locked up to avoid contamination.  It is quite small, and used for growing silicon crystals.  I want to be able to take a greyscale image every hour, and transmit it to a receiver on the other end of the room, through a window.  The window is two half inch panes of glass with an inch of space between them.  I have on hand 2x Arduino Uno, 1x Arduino Beetle, and 1x Raspberry Pi.  The whole text string thing is just for testing purposes so that I can understand what I'm doing.  From what I've read on the subject previously, I need to take the image, convert it to Hex, convert that to binary, transmit it, receive it, convert back to Hex, convert back to an image.  I have 0 experience with Arduino or Raspberry, have a limited idea of how to execute this, and appreciate all the help I can get!

title: Convert Bitstring to Textstring

Answers: 2

body:
A string is also a 8-bit 'binary' string ... so I don't think you need to do anything special... if you can read byte by byte, you might have to construct a string adding the characters, or print it directly to the serial monitor (last is even better because you don't have to think about memory).

If the 8-bit binary string does not contain ASCII data (which I doubt), print out the byte values as number and see how it should be converted to a textual character.

Noise is a bit more tricky .. afaik it is possible with some libraries (for the RF) to automatically resend. If that is not good enough, you have to make your own CRC ... calculate a CRC, send it (maybe a few times to be sure there is no noise in the CRC) and check it against the received string; if not received correctly, send it again.

If you have only 1 directional transmitting, than it is more tricky. You can add extra bits to 'fix' noise, or using special schemes for it.

See for more info [wikipedia][1]

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

body:
Perhaps you have asked the wrong question. Because there is a library for those cheap 433MHz modules: [RadioHead][1].
Use the RH_ASK mode, and try the 'ask' examples

You might see [VirtualWire][2] used a lot with those 433MHz modules. That is the same as RadioHead. The RadioHead is newer and has a few bugs fixed, but it uses also more memory.

The RadioHead library uses a far more superior protocol than anything else, that makes the range better than with other libraries. It also has a (simple) CRC checksum in the protocol. That means that when you receive something, you can be (almost 100%) sure that the data is correct.

Other protocols require that a message is transmitted 10 times, to be sure that it will be received. With the RadioHead library, sending a message just once is good enough.

Those cheap 433MHz modules have a disadvantage: they can only be turned on and off (ASK modulation) en you need a library for the protocol. That means that if the Arduino is doing more things that uses interrupts or code that disables interrupts, then the protocol is disturbed and it will not work very well.
The RF transceiver modules have a chip on the module itself that takes care of the protocol, that is so much better. Sparkfun has a [Wireless Buying Guide][3] and [Adafruit uses the RFM69][4] a lot.

Those cheap modules require an antenna, or else the range could be less than the size of the table they are on. Solder a 16cm piece of wire to the antenna pin. Any piece of wire of any length is better than no antenna.

  [1]: http://www.airspayce.com/mikem/arduino/RadioHead/
  [2]: http://www.airspayce.com/mikem/arduino/VirtualWire/
  [3]: https://www.sparkfun.com/pages/wireless_guide
  [4]: https://www.adafruit.com/product/3177


body:
In the following schematic you can see that `Q1` and `Q4` both are connected to a Arduino's Digital Input Pin. So if `Q1` is high and `Q4` is low, would there be current flowing from `Q1` through `Q4` (and through the chip) to Ground - or is there already some protection inside?

[![schematic without diode][1]][1]

Are the output pins on the 74HC595 shift register protected from connected voltages in the realms of their own VCC? Or do you need to put a diode in?

[![schematic including diode][2]][2]

I feel like this is a very basic question, which makes it very weird that I didn't find an answer to this, already... :-( Am I looking into the wrong resources? I had a look into the provided datasheet, but couldn't find any information. Didn't get any results from searching for existing posts on Stack Exchange or other sites.

  [1]: https://i.stack.imgur.com/f0Kal.png
  [2]: https://i.stack.imgur.com/Qnv6c.png

title: Are the output pins on the 74HC595 shift register protected against shorting?

Answers: 1

body:
In [this data sheet][1] it says:

> When the output-enable (OE) input is high,the outputs are in the
> high-impedance state.

However on page 3 you will notice that the *OE pin controls all outputs at the same time.  So if you connect 2 output pins and one is high and the other is low and you hold *OE low ... you will likely burn out the driver for one of the 2 output pins if not the chip its self.

If you add diodes to BOTH outputs you are essentially creating a [wired or gate][2].  (You should add a resistor.  See the examples in the provided link.) This is fine as long as you understand how a wired or gate works.

  [1]: https://www.sparkfun.com/datasheets/IC/SN74HC595.pdf
  [2]: https://en.wikipedia.org/wiki/Wired_logic_connection#The_wired_OR_connection


body: I'm new to electronics. I'm trying to build something that will involve controlling the direction of rotation of a DC motor. A lot of online resources seem to recommend using an Arduino motor shield. But why shouldn't I just use some combination of an H-circuit (to control the direction of rotation) and a MOSFET (to switch power to the motor on and off)?

title: I want to control a single DC motor with an Arduino. Why would I use an Arduino motor shield as opposed to an H-circuit and a MOSFET?

Answers: 2

body:
A Arduino motor shield **is** just a H-bridge (plus some other bits), but it's a H-bridge that works.

Drawing a H-bridge and a MOSFET is easy. Building one that works is much harder. Online resources recommend the shield because trying to walk someone through the development of a functional equivalent is complex.

body: The major benefit to using a shield vs building the same circuit yourself is convenience. Assuming that your circuit is identical to the circuit on the shield then they should both work in an identical manner (barring any minor variations due to the quality of solder joints or circuit paths). The nice thing about the shield is it is almost plug and play. It has the same footprint as the Arduino and you don't have to design and assemble the circuit on a perf board. Generally, you will end up with fewer wire leads running around making for a cleaner assembly and easier prototyping.


body:
I bought a [Chipdot Ethernet shield][1] from Amazon. It does not have any MAC address on it. I connected this shield to an Arduino Uno. I tried to run the `DHCPAdressPrinter` code from Ethernet library on it, using the default MAC address of this code. And Serial monitor shows

>Failed to configure Ethernet using DHCP

I have tried all the MAC IDs one by one as suggested on reviews but nothing worked. Is there any way to configure or assign a MAC ID to the Ethernet shield? Or is there are any way to know the Ethernet shield's  MAC address?

Thanks in advance.

  [1]: http://www.amazon.in/Chipdot-3-01-0441-2-Ethernet-Network-Expansion/dp/B00AXVX5D0/ref=sr_1_2?ie=UTF8&qid=1487141745&sr=8-2&keywords=arduino ethernet shield for mega","http://www.amazon.in/Chipdot-3-01-0441-2-Ethernet-Network-Expansion/dp/B00AXVX5D0/ref=sr_1_2?ie=UTF8&qid=1487141745&sr=8-2&keywords=arduino ethernet shield for mega

title: Arduino Ethernet shield cannot establish connection

Answers: 1

body:
The W5100 chip doesn't have a mac address by itself. You can assign any mac address to it that you want. With `Ethernet.begin(mac);` you assign the mac address to the W5100 chip.
The official Arduino Ethernet shield comes with a paper with a unique mac address. That is a nice service, but that is just a number, the Ethernet shield hardware is without any mac address.

There has been complaints about wrong resistor values near the ethernet connector. Can you read the numbers on those resistors ? They should be labeled as "510" and not as "511" : [Arduino forum about ethernet resistors][1].

The Ethernet Shield uses more power than most other shields, and the W5100 can get pretty hot. Do you have enough power ? Is the 5V pin still above 4.5V ?

It is possible that your router does not accept the old W5100.

If the resistors are okay, I suggest to try an example with both mac and ip: `Ethernet.begin(mac, ip);`

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


body:
I want to make a system that can count coins. The problem that I know have is that I need a way to detect the size of the coin.

The idea that I have is a beam that becomes smaller if you a inject a coin. The size of the beam depends than on the size coin. See it as a button that you can press a little bit or very deep.

But how can I know far the button (beam) is pressed?

title: How can I know how far a button is pressed?

Answers: 1

body:
Following on from [Mark's comment][1], I'm not convinced that you can measure the size of the beam, using a single optical (analogue) device - generally optical switches, like other switches, are binary, either on or off, and as such would use one of the Arduino's digital inputs.

The type of (hypothetical) button that you describe, taking a mechanical analogue (rather than your optical beam example), would require the use of an analogue input pin, and your "switch" would actually be a linear potentiometer, i.e. a slider, or lever, and the analogue input could then measure the input voltage, which would be proportional to the amount that the button (or lever) has been pressed (or moved). However, the usual linear potentiometer is not spring loaded, so the button would not really have the usual expected push button behaviour, unless, of course, you rigged up some sort of spring loaded button, with a long throw, mechanically connected to a linear potentiometer.

An analogue version of this sort of set up, as far as I am aware, does not exist for a optical solution.

What you could use is a series of optical digital (not analogue) switches (or a single light source and a series of receivers), arranged in a line (perpendicular to the base along which the coin is rolled along) in such a way that they can detect the size of the coin*. If the light is broken for a particular detector, then you know that the radius/size/width of the coin is *at least* the same as that detector's distance from the base.

[![Coin detector][2]][2]

These optical detectors are then connected to a series of digital inputs, i.e. `D5`, `D6`, `D7` and `D8`, and a series of `if` statements would enable your code to determine the size of the coin.

Assuming that the broken light beam results in a `low`, then the pseudo code would be something like this:

    if D5 = low & D6 = high
     then coin is a cent
    if D5 = low & D6 = low & D7 is high
     then coin is a nickle
    if D5 = low & D6 = low & D7 = low & D8 = high
     then coin is a dime
    if D5 = low & D6 = low & D7 = low & D8 = low
     then coin is a quarter

Obviously you would need a trigger when to take the "snapshot" of the coin passing the detector at the *correct time*, when it is fully blocking the lights, and not just partially blocking the light beams (which could result in a false reading).

-----

* I have just realised that this is *exactly* what Jot described in [his comment][3].

  [1]: https://arduino.stackexchange.com/questions/39988/how-can-i-know-how-far-a-button-is-pressed/40012#comment81324_39988
  [2]: https://i.stack.imgur.com/DZnou.png
  [3]: https://arduino.stackexchange.com/questions/39988/how-can-i-know-how-far-a-button-is-pressed/40012#comment81287_39988


body:
In my recent project, I have to parse incoming JSON data in Arduino and I successfully did it. But it is only for one constant data string.

For example, if my incoming JSON string like:

    {"TPS":"0.40","MAP":"0.95","LOAD":"14"}

And Arduino code for parsing this data is below:

    #include <LiquidCrystal.h>
    #include <ArduinoJson.h>

    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

    String response = "";
    bool begin = false;

    void setup() {
      Serial.begin(9600);
      lcd.begin(16, 2);
    }

    void loop() {
      StaticJsonBuffer<100> jsonBuffer;
      while(Serial.available() || !begin) {
        char in = Serial.read();
        if (in == '{') {
          begin = true;
        }
        if(begin) {
          response += (in);
        }
        if(in == '}') {
            break;
        }
        delay(1);
      }
      JsonObject& root = jsonBuffer.parseObject(response);
      String TPS = root["TPS"];
      String MAP = root["MAP"];
      String LOAD = root["LOAD"];
      lcd.setCursor(0, 0);
      lcd.print(TPS);
      lcd.setCursor(8, 0);
      lcd.print(MAP);
      lcd.setCursor(0, 1);
      lcd.print(LOAD);
    }

Then the output looks like:

    TPS  : 0.40
    MAP  : 0.95
    LOAD : 14

That's fine, but when the incoming JSON string changes, what should I do?

Suppose the incoming JSON string looks like:

    {"LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

Because I have to handle both incoming JSON strings, I can't replace any part like:

      String LOAD = root["LOAD"];
      String RPM = root["RPM"];
      String INJECTION_TIME = root["INJECTION_TIME"];
      lcd.setCursor(0, 0);
      lcd.print(LOAD);
      lcd.setCursor(8, 0);
      lcd.print(RPM);
      lcd.setCursor(0, 1);
      lcd.print(INJECTION_TIME);

Instead of

      String TPS = root["TPS"];
      String MAP = root["MAP"];
      String LOAD = root["LOAD"];
      lcd.setCursor(0, 0);
      lcd.print(TPS);
      lcd.setCursor(8, 0);
      lcd.print(MAP);
      lcd.setCursor(0, 1);
      lcd.print(LOAD);

title: How to get different parsed JSON data?

Answers: 2

body:
If you want to read 3 values of a object that you don't know the names of the key, you can use an iterator as shown in the [ArduinoJson library's docs][1].

And as already mentioned in the comments, you can also replace all the serial reading code with just `Serial` passed into the `jsonBuffer.parseObject` function.

    #include <LiquidCrystal.h>
    #include <ArduinoJson.h>

    const struct LCDPos {
      uint8_t x;
      uint8_t y;
    } lcd_pos[] = {
      {0, 0},
      {8, 0},
      {0, 1},
    };

    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

    void setup() {
      Serial.begin(115200);
      lcd.begin(16, 2);
    }

    void loop() {
      StaticJsonBuffer<100> jsonBuffer;
      JsonObject& root = jsonBuffer.parseObject(Serial);
      if (root == JsonObject::invalid())
        return;

      uint8_t i = 0;
      for (JsonObject::iterator it = root.begin(); it != root.end() && i<(sizeof(lcd_pos)/sizeof(lcd_pos[0])); ++it, i++)
      {
        lcd.setCursor(lcd_pos[i].x, lcd_pos[i].y);
        lcd.print(it->value.asString());
      }
    }

You will need to make sure, that the values are sent in the order that you want them on your LCD.

EDIT:
I don't have an LCD screen, so I didn't test the code with an LCD, but the code that just dumps the parsed data back to serial works.

    //#include <LiquidCrystal.h>
    #include <ArduinoJson.h>

    const struct LCDPos {
      uint8_t x;
      uint8_t y;
    } lcd_pos[] = {
      {0, 0},
      {8, 0},
      {0, 1},
    };

    //LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

    void setup() {
      Serial.begin(115200);
      //lcd.begin(16, 2);
    }

    void loop() {
      StaticJsonBuffer<100> jsonBuffer;
      JsonObject& root = jsonBuffer.parseObject(Serial);
      if (root == JsonObject::invalid())
        return;

      Serial.println("JSON received");
      uint8_t i = 0;
      for (JsonObject::iterator it = root.begin(); it != root.end() && i < (sizeof(lcd_pos) / sizeof(lcd_pos[0])); ++it, i++)
      {
        //lcd.setCursor(lcd_pos[i].x, lcd_pos[i].y);
        //lcd.print(it->value.asString());
        Serial.print(i);
        Serial.print(':');
        Serial.print(lcd_pos[i].x);
        Serial.print(',');
        Serial.print(lcd_pos[i].y);
        Serial.print(' ');
        Serial.println(it->value.asString());
      }
      Serial.println();
    }

If I send

<!-- language: none -->

    {"TPS":"0.40","MAP":"0.95","LOAD":"14"}{"LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

over the serial, it returns

<!-- language: none -->

    JSON received
    0:0,0 0.40
    1:8,0 0.95
    2:0,1 14

    JSON received
    0:0,0 2.40
    1:8,0 4200
    2:0,1 4.87

  [1]: https://bblanchon.github.io/ArduinoJson/doc/decoding/#check-values

body:
Finally got the solution. I'm using the extra key name.

So, my modified serial data string now looks like:

    {"ActionOne":"ONE","TPS":"0.40","MAP":"0.95","LOAD":"14"}
    {"ActionTwo":"TWO","LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

and so now using `containsKey()` function, just check which one is coming. If `ActionOne` is coming then according to that serial data we got. And If `ActionTwo` is coming then according to that serial data we got.

    #include <LiquidCrystal.h>
    #include <ArduinoJson.h>

    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

    String response = "";
    bool begin = false, finished;

    void setup() {
      Serial.begin(9600);
      lcd.begin(16, 2);
    }

    void loop() {
      StaticJsonBuffer<100> jsonBuffer;

      while (finished == false)
      {
        if (Serial.available())
        {
          const char in = Serial.read();
          if (in == '{')
          {
            response = "";  // Blank the string
            begin = true;
          }
          if (begin)
          {
            response += (in); // Only write if within the {}
          }
          if (in == '}')
          {
            begin = false;   // Prevent any chars between } and { leaking through.
            break;
          }
        }
        delay(1);
      }

      JsonObject& root = jsonBuffer.parseObject(response);

      const char* ActionOne = root["ActionOne"];
      const char* ActionTwo = root["ActionTwo"];

      if(root.containsKey("ActionOne"))
      {
        float TPS = root["TPS"];
        float MAP = root["MAP"];
        int LOAD = root["LOAD"];

        lcd.setCursor(0, 0);
        lcd.print(TPS);

        lcd.setCursor(8, 0);
        lcd.print(MAP);

        lcd.setCursor(0, 1);
        lcd.print(LOAD);
      }

      if(root.containsKey("ActionTwo"))
      {
        float LOAD = root["LOAD"];
        int RPM = root["RPM"];
        float INJECTION_TIME = root["INJECTION_TIME"];

        lcd.setCursor(0, 0);
        lcd.print(LOAD);

        lcd.setCursor(8, 0);
        lcd.print(RPM);

        lcd.setCursor(0, 1);
        lcd.print(INJECTION_TIME);
      }
    }


body:
I hope I'm in the right place to ask, I couldn't find anything so I ask here, please tell me if I missed some relative topic.

I was following this tutorial : https://learn.adafruit.com/force-sensitive-resistor-fsr/using-an-fsr#in-depth-code-for-analog-fsr-measurements
and the only difference is that I have a potentiometer instead of a 900K resistor. I put it to 14350 Ohms because it fits the tutorial just above the last one, on top of the same page.
So here is the thing : I want to know the force in Newtons but the values I end up with are clearly wrong. A medium touch on the FSR is already > 3 Newtons, and it changes a lot when I turn the potentiometer to a higher resistance (and changing the value of that pota in the code too) : same force applied, different value of that force on the screen.

I know nothing about elecs so I would also like to know more about this part :

    // Use the two FSR guide graphs to approximate the force
    if (fsrConductance <= 1000) {
      fsrForce = fsrConductance / 80;
      Serial.print("Force in Newtons: ");
      Serial.println(fsrForce);
    } else {
      fsrForce = fsrConductance - 1000;
      fsrForce /= 30;
      Serial.print("Force in Newtons: ");
      Serial.println(fsrForce);
    }

Where does the /80 and -1000 then /30 come from ? Why is it a different operation and not just only different values ?
I'm using the same FSR but with 3.3V. I have the same graph as this one : https://learn.adafruit.com/force-sensitive-resistor-fsr/overview#how-to-measure-force-slash-pressure-with-an-fsr

I would really appreciate clear and simple explanations. Thank you by advance !

title: Reading force from an FSR in Newtons

Answers: 1

body:
[Sparkfun also sells FSR's][1] and they explain it better: "Use them to sense if it’s being squeezed, but you may not want to use it as a scale".

On that Sparkfun page is also a datasheet. It's inaccuracy is 25%, and that is only when the force is applied evenly. When someone presses it with a finger, the inaccuracy is 50% or more.

The quick-and-dirty calculation in the Adafruit example is just for fun, it is not serious measuring the force in Newton.
There are two different calculations, for 'fsrConductance' above and below 1000. When it is above 1000, the 1000 offset is substracted to start the calculation at zero. The difference in calculation is that for one the value is divided by 80 and in the other divided by 30. It's just a rough calculation to get some kind of force value.

To measure weight or force, you need a **load cell**.

  [1]: https://www.sparkfun.com/products/9375


body:
I have an Arduino micro for some time and everything always worked well. Today, when I was uploading a code on this board using Arduino IDE, I accidentally started the Arduino Board update and the upload failed. After a while I retried again and again and again but upload always failed. Now my PC doesn't recognize my board and, looking at *Windows Device Manager*, when I connect my board, appears this screen:

[![Unknown USB device][1]][1]

What should I do? Do I have to reflash bootloader?

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

title: Arduino micro not recognized

Answers: 2

body:
So I was facing this issue for the past few hours and this is how I managed to get it to work.
After reading similar issues on knockoff NANOS,  [I downloaded and installed this as many knockoff NANOS uses a different Serial CHIPSET.][1]

After that, on the IDE side, just press compile to ensure your code is good to go. And then when you hit upload, wait for it to finish compiling and the second it says UPLOADING, hit the reset button. It should upload now and be available in your COM port.

  [1]: http://www.wch.cn/download/CH341SER_EXE.html

body:
I had this issue a while back and in order to fix it as suggested above I had to re flash the boot loader using a 2nd Arduino as an ISP. I used this page as a guide:

https://schou.dk/linux/arduino/isp/

Before connecting the wiring I first updated the UNO with the "ArduinoISP" Sketch, connected the wiring, then flashed the boot loader.


body:
I would like to use 7 MCP23S17 as output expanders on one SPI bus. Every IC has its own address from 0 to 6. The first MCP23S17 can be written with no problem. The second chip did not work properly. The CS pin of the MCP23S17 is set like at the all other 4 ICs.

Does anybody have experience with more then 4 MCP23S17 on SPI? Could anyone help?

    #include <SPI.h>
    #include <MCP23S17.h>

    MCP A(0, 10);
    MCP B(1, 8);
    int d = 250;

    void setup() {
      A.begin();
      B.begin();
      for (int k = 1; k <= 16; k++) {
        A.pinMode(k, OUTPUT);
        B.pinMode(k, OUTPUT);
      }
    }

    void loop() {
      //////////// ON THE LIGHT ONE BY ONE  FROM BEGGING
      for (int f = 1; f <= 16; f++) {
        A.digitalWrite(f, HIGH);
        delay(d );
      }
      for (int f = 1; f <= 16; f++) {
        B.digitalWrite(f, HIGH);
        delay(d );
      }
      ////////////  OFF THE LIGHT ONE BY ONE  FROM BEGINNIG
      for (int f = 1; f <= 16; f++) {
        A.digitalWrite(f, LOW);
        delay(d);
      }
      for (int f = 1; f <= 16; f++) {
        B.digitalWrite(f, LOW);
        delay(d);
      }
    }

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

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

  [1]: https://i.stack.imgur.com/YVkd2.png
  [2]: https://i.stack.imgur.com/jXDop.jpg

title: More than 4 MCP23S17 on 1 SPI bus

Answers: 2

body:
     MCP A(0, 9);
     MCP B(1, 8);
     MCP C(2, 7);
     MCP D(3, 6);
     MCP E(4, 5);
     MCP F(5, 3);

 - `CS` on pin 10 is often used for Ethernet
 - `CS` on pin 4 is often used for SD

body:
Assuming that the adressing is correct and all the modules work fine individually, there are some things you can do:

- try to disable the slave select of the modules that aren’t require to communicate at a certain time, there are examples for that

- add a bit of code where you define chip select as an input for all but one and see if you can communicate with that one. Do that for all of them

- remove MISO pin from all but one and see if you can communicate with that one. Do that for all of them

- use a tri-state buffer through which you connect the MISO pin and use chip select for enabling the buffer. This buffer puts the MISO pin into a state of high impedance when a certain module is not used for communication and prevents fata from being lost


body:
I know this is a basic question, but as a hardware electronics guy and not a programmer I cannot seem to fathom how to do this - so any examples of code would be greatly appreciated:

I want the arduino to spit out some initialization chatter on startup - (ok, done easy).

Then I want it to listen for serial commands, they can all be same length if that helps but I want them to be strings. i.e. identifier followed by value

Command --- Result

PWR_TRUE --- Power on device

PWR_FLSE --- Power off device

REP_FREQ --- Print frequency over serial

SP000752 --- Set power value to 752

SP016675 --- Set power value to 16675

Obviously the commands are two types, the first two being booleans and then integers, but I cant seem to find any examples not working off a single ascii character value, which is useless to me. I need more information and then from the message be able to break it down into something the arduino does.

An example of how to import whole commands and either do something, and / or chop the command up to get the value out, would be most useful.

Many thanks in advance :)

EDIT/UPDATE:
I now seem to have found a solution thanks to Edgar as given in the comments. However I now have another question relating to updating the variables so as to effect the loop, as well as performing actions upon receipt of commands (which itself now works)
[LINK HERE][1]

  [1]: https://arduino.stackexchange.com/questions/40015/how-can-i-update-global-variable-within-a-loop-from-outside-the-loop

title: Constructing my own serial command syntax to control arduino

Answers: 3

body:
You need to read the serial input into a string(char[]) or String.  You then need to parse that string to read a series of acceptable characters and then convert that into an action.

***This is semi-pseudo code (not compiled, not tested, not complete)***

    bool quit = false;
    const int MaxCommand = 10;
    char command[MaxCommand];
    while (!quit)
    {
       int index[0];
       bool wholeCommand = false;
       bool invalidCommand = false;
       while (!wholeCommand && !invalidCommand)
       {
          while (!Serial.available())
            ;
          command[index++] = Serial.read();
          invalidCommand = CheckInvalidCommand();
          wholeCommand = CheckWholeCommand();
       }
       if (invalidCommand)
       {
          Serial.print("That's an invalid command");
       }
       else if (wholeCommand)
       {
          if (strcmp(wholeCommand, "PWR_TRUE") == 0) // 0 means it matches
          {
             power(true);
          }
          else if strcmp(wholeCommand, "PWR_TRUE") == 0) // 0 means it matches
          {
             power (false);
          }
       }
    }

However That's the hard way to do it.  A much easier way is to utilities the user's CPU a bit more and get them to type data in a more computer friendly method.  After all users are easier to program, particularly with a base ball bat.

Make you language fixed length:

 - POWER TRUE |FALSE
 - REPOR FREQ
 - SETPW NUMBER

For instance use 5 letters for the command and then until the end of the line for arguments.

Probably the easiest way of manipulating strings for a newbie is to look at the String object class, but the C library string functions maybe the only way to truly get what you want (strcmp, strlen, strtok, strcpy, etc)

----------

EDIT
If you are struggling to code something on the Arduino then what I do is try and knock it up on Visual Studio.  In this case you will need a simulated Serial object.

    /// Code to simulate a Serial object on a Windows PC - Not Arduino code!!!
    #pragma once
    #include <afx.h>

    class CSerial
    {
    public:
     CSerial () {}
     virtual ~CSerial () {}

     void begin (const int& baudRate) {}
     void flush (void) {}
     int available (void) {return 1;}
     unsigned char read (void) {return 42;}

     void print (const char* data) {_tprintf(L"%s", data);}
     void println (const char* data = NULL) {_tprintf(L"%s\n", data);}
     void print (const int& data) {_tprintf(L"%d", data);}
     void println (const int& data) {_tprintf(L"%d\n", data);}
    };

    static CSerial Serial = CSerial();

You will need to change `read()` and `available()` so that they return meaningful data.  You could do this be adding a `char[]` to the class that is prepopulated with data, such as `"POWER TRUE\nREPOR FREQ\nPOWER FALSE"` and then use an `int` as an index into that.

body:
Perhaps you should consider using [https://github.com/j123b567/scpi-parser][1]

  [1]: https://github.com/j123b567/scpi-parser
It's an API library that allows you to build an 'instrument' that uses a recognized standard 'SCPI' as the communications protocol. It makes your device compliant with an industry standard, and can be implemented using tested code. Your example protocol is pretty SCPI-like already.

body:
Expanding on my comment... I wrote a simple command line interpreter
that you can use as a base, or an inspiration, for your own interpreter.
In order to not make a link-only answer, I will put here an annotated
and simplified version.

The incoming characters are handled by `loop()`. They are stored into a
static buffer until a carriage return (CR = `'\r'`) is received. When
the CR is received:

* the buffer is NUL-terminated in order to make it a proper C string
* it is handed to the `exec()` function for interpretation
* the variable storing the command length is reset to zero for the next
  command

Here is the code:

    while (Serial.available()) {
        static char buffer[BUF_LENGTH];
        static int length = 0;  // length of line received so far
        int data = Serial.read();
        if (data == '\r') {
            buffer[length] = '\0';     // properly terminate the string
            if (length) exec(buffer);  // give to interpreter
            length = 0;                // reset for next command
        } else if (length < BUF_LENGTH - 1) {
            buffer[length++] = data;   // buffer the incoming byte
        }
    }

The `exec()` interpreter function uses [`strsep()`][strsep] to split the
command line into a command verb and subsequent parameters. It then
compares the command verb with all supported commands in a long `if`...
`else if` sequence, like this:

    static void exec(char *cmdline)
    {
        char *command = strsep(&cmdline, " ");

        if (strcmp(command, "mode") == 0) {
            int pin = atoi(strsep(&cmdline, " "));
            int mode = atoi(cmdline);
            pinMode(pin, mode);
        } else if (strcmp(command, "read") == 0) {
            int pin = atoi(cmdline);
            Serial.println(digitalRead(pin));
        } else if (strcmp(command, "write") == 0) {
            int pin = atoi(strsep(&cmdline, " "));
            int value = atoi(cmdline);
            digitalWrite(pin, value);
        } else {
            Serial.print(F("Error: Unknown command: "));
            Serial.println(command);
        }
    }

This one supports the three commands:

* `mode <pin> <mode>`, meaning `pinMode()`
* `read <pin>`, meaning `digitalRead()`
* `write <pin> <value>`, meaning `digitalWrite()`

The full version is here: [Simple Arduino command line
interpreter][interpreter]. Compared to the version in this answer, the
main differences are:

* it echoes the characters it reads, and does so in a way which is
  friendly to terminal emulators:
  * it echoes CR as CRLF
  * it handles BS (backspace) and echoes it as BS + space + BS
* it uses `strcmp_P()` instead of `strcmp()`, with the `PSTR()` macro,
  in order to keep the constant strings in Flash only
* it supports more commands, including "help".

[strsep]: https://www.freebsd.org/cgi/man.cgi?strsep(3)
[interpreter]: https://gist.github.com/edgar-bonet/607b387260388be77e96


body:
I would like to use an arduino to read 433 MHz transmission from multiple Soil Moisture Sensors. Since I can never be sure all transmissions reach the receiver I'd like to set a countdown from the moment the first transmission is received. If another transmission is received, the countdown starts again.
After a defined amount of time (e.g. 10 Minutes) without any more signals or if all signals have been received (e.g 4 Sensors) the receiving unit should stop and come to decision based on the data it got to the point.

For transmitting and receiving I am using the `<RCSwitch.h>`library.

The loop of the receiving unit and one Sensor looks like this:

    #include <RCSwitch.h>
    RCSwitch mySwitch = RCSwitch();
    void Setup(){
    Serial.begin(9600);
    mySwitch.enableReceive(4);
    }
    void loop() {
    if (mySwitch.available()) {
    int value = mySwitch.getReceivedValue();

    if (value == 0) {
      lcd.clear();
      Serial.print("Unknown encoding");
      }
      else {
      Serial.print(mySwitch.getReceivedValue());
      Serial.print("%");
    }
The full code includes some differentiation mechanism for all sensors but I figured that might not be relevant for my question.

Question:
What's the best way to do this without a real time clock module. As far as I know I can't wait by using `delay(...)`since then I won't receive any data while the processor waiting.

title: Trigger countdown with 433MHz transmission

Answers: 1

body:
You say _The full code includes some differentiation mechanism for all sensors_ so I'll assume there's some function `GetSensorId()` that returns 0 to NUM_SENSORS - 1.

So, you need to keep track of a) how many sensors have reported in and b) time since the last report. You can't just count how many sensors have reported in since there may be a chance one could report in more than once. So I would use an array:

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

    // Assume you never receive 0 from sensor.
    const int NO_DATA = 0;
    const int NUM_SENSORS = 4;
    int sensor_data[NUM_SENSORS];

    void setup() {
        // Initialize array
        for (int i = 0; i < NUM_SENSORS; i++) {
            sensor_data[i] = NO_DATA;
        }
    }

Also, a variable to keep track of time of last message:

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

    uint32_t last_message_time = 0;

So, in `loop()`:

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

    void loop() {
        // Check for data
        if (mySwitch.available()) {
            int value = mySwitch.getReceivedValue();
            if (value == 0) {
                lcd.clear();
                Serial.print("Unknown encoding");
            }
            else {
               // Determine which sensor sent the data
               int sensor_id = GetSensorId();
               Serial.print(value);
               Serial.print("%");
               // Save the data and the time of the message
               sensor_data[id] = value;
               last_message_time = millis();
           }
        }
        // See if all sensors reported
        byte sensors_reported = 0;
        for (int i = 0; i < NUM_SENSORS; i++) {
            if (NO_DATA != sensor_data[i]) {
                sensors_reported += 1;
            }
        }

        // When 0 sensors have reported in, do nothing
        if (0 != sensors_reported) {
            // Otherwise, at least one sensor
            // check the time
            uint32_t elapsed = millis() - last_message_time;

            // If have all data or time's up, do something
            if (NUM_SENSORS == sensors_reported || elapsed > SENSOR_TIMEOUT) {
                // Do something

                // Reset state
                for (int i = 0; i < NUM_SENSORS; i++) {
                    sensor_data[i] = NO_DATA;
                }
            }
        }
    }


body:
I have a Arduino Uno board and phone power bank

Power bank details

 - Capacity - 8000 mWh
 - Input  - DC 5 V and 1 A
 - Output - DC 5 V and 1 A

Can I give the power to Arduino Uno using this power bank, through the Arduino Uno USB?

title: Arduino Uno power input - is 5 V at 1 A enough?

Answers: 2

body:
I dont see why not - YES you can!

I regularly use usb powerbanks to power projects for testing. so long as you dont ask for too much current (unlikely but project specific) you will be fine!

body:
Short answer:  Yes.

It depends on how you are feeding the power into the Uno and what you are trying to do with it.

My Unos use right at 0.35 amps, as measured by my USB volt/amp meter, until I begin adding things like DHT-22 temperature sensors and maybe a DS3231 RTC, then it will go up a bit.  I can generally just run from USB power.

Feeding power via USB is not a long-term solution in general, since most other USB sources are current-limited to 500 mA.  You could end up building a circuit that works fine on your power supply but not when running on just computer power.

Through testing using metered laboratory power supplies feeding into the barrel connector I am confident that 5V/1A is OK for light work.

And if you are POSITIVE that it is EXACTLY 5V then you can run it directly  into the 5V pin and avoid the regulator, which drops the voltage some.
(Of course, without the regulator you put the board at risk.)

Note that If you are trying to run an anemometer you need 9-12V for power for it.

Also, if you want to run a 432 MHz serial radio you will likely need more than 1A to make them work since they need a couple of hundred milliwatts just for the radio.  1A might work, but USB power certainly will not - (they won't even try to work with just USB power).

In any case, it sounds like you are set up nicely to fire the thing up and start programming.

Have fun!


body:
I have this code, but its not working. If I type "ReportFRQ 1" (or 0) it reports back that FrqON variable has changed but the behaviour of the loop doesnt. Basically I am trying to switch parts of the loop on and off using variables, which are updated by serial command.

The main body of the code was kindly provided by another answer as a way of commanding the arduino remotely with custom commands. I can get the arduino to do various things, but updating the behaviour of the loop by activating and deactivating different variables does not seem to work...

Any ideas? Thanks

    #include <avr/pgmspace.h>
    #include <FreqCounter.h>

    #define BUF_LENGTH 128  /* Buffer for the incoming command. */

    unsigned long int frq;
    unsigned int frqON;

    static bool do_echo = true;

    /* Execute a complete command. */
    static void exec(char *cmdline)
    {
    char *command = strsep(&cmdline, " ");

    if (strcmp_P(command, PSTR("help")) == 0) {
        Serial.println(F(
            "echo <value>: set echo off (0) or on (1)\r\n"
            "freq: reports current frequency"
            ));
    } else if (strcmp_P(command, PSTR("echo")) == 0) {
        do_echo = atoi(cmdline);
    } else if (strcmp_P(command, PSTR("freq")) == 0) {
           FreqCounter::f_comp= 8 ;             // Set compensation to 12
           FreqCounter::start(10);            // Start counting with gatetime of 100ms
           while (FreqCounter::f_ready == 0)         // wait until counter ready
           frq=FreqCounter::f_freq;            // read result
           if (frq<1) Serial.println("OFF");
           if (frq>1) Serial.println(frq);
    } else if (strcmp_P(command, PSTR("ReportFRQ")) == 0) {
           int frqON = atoi(strsep(&cmdline, " "));
           Serial.println(frqON);

    } else {
        Serial.print(F("Error: Unknown command: "));
        Serial.println(command);
     }
     }

     void setup()
     {
    Serial.begin(57600);
    Serial.println("Frequency Counter");
    }

    void loop() {

    /* Process incoming commands. */
    while (Serial.available()) {
        static char buffer[BUF_LENGTH];
        static int length = 0;

        int data = Serial.read();
        if (do_echo) Serial.write(data);
        if ((data == '\b' || data == '\177') && length) {  // BS and DEL
            length--;
            if (data == '\177') Serial.write('\b');
            Serial.write(" \b");
        }
        else if (data == '\r') {
            if (do_echo) Serial.write('\n');    // output CRLF
            buffer[length] = '\0';
            if (length) exec(buffer);
            length = 0;
        }
        else if (length < BUF_LENGTH - 1)
            buffer[length++] = data;
     }

     if (frqON = 1) {
            frq=FreqCounter::f_freq;            // read result
           if (frq<1) Serial.println("OFF");
           if (frq>1) Serial.println(frq);
     }

        /* Whatever else needs to be done... */
     }

title: How can I update global variable within a loop from outside the loop?

Answers: 1

body:
You have multiple problems here. First one:

You have a global variable:

    unsigned int frqON;

However in your `exec` function you're creating a variable of the same name and writing to it. This doesn't change the global variable.

    else if (strcmp_P(command, PSTR("ReportFRQ")) == 0) {
           //creates new local variable "frqOn" which overshadows global variable
           int frqON = atoi(strsep(&cmdline, " "));
           Serial.println(frqON);
    }

To solve this and change the global variable, simply omit the `int` decleration.

Also your `if` check is wrong:

    if (frqON = 1) {
            frq=FreqCounter::f_freq;            // read result
           if (frq<1) Serial.println("OFF");
           if (frq>1) Serial.println(frq);
     }

When you do `if(frqOn = 1)` you **set** the variable `frqOn` to `1`. You however want to compare the values, i.e. use the comparison operator `==`.


body: I'm trying to turn a laser on and off with an external button. When I press the button, the laser should turn on. When I release the button the laser should turn off. However, I don't want the laser to turn off immediately. I want it to turn off linearly over 500 ms. I'm using PWM to alter the strength of the laser over time. However, will my laser power increase and then decrease in the extremely short time segments due to PWM fluctuation? Will it even be able to execute this reduction of power?

title: Using PWM signal to decrease power of laser over time

Answers: 1

body:
I dont know your circuit but...
Do you effectively want to use an RC filter to reduce PWM fluxuations so that the laser sees an analog voltage which will translate to a power (presumably)? - that will avoid the pulsing of the laser, but I did believe that the pulsing at full voltage was neccersary in most laser drivers - please post a schematic... Anyway if you want this to be less of an issue if an RC filter is not for you you could increase the PWM frequency (google is your friend) on the arduino...

To have it turn of slowly if your using analog, the RC filter could possibly have large enough capacity to slow the laser turn off. It will also effect rise time so suitable values for R and C will need to be found to suit. Otherwise you could dial down the PWM gradually before hard power off in the arduino software, by initiating a loop which gradually reduces power with time.

Somewhere to start anyway :)


body:
As I embark on my first Arduino project, I have lots of questions. Specifically, what considerations should I make when selecting equipment, and what are the critical parameters to safe operation?

Some elaboration upon my questions can be seen below. However, outlining general principals of equipment selection would be highly useful.

I have an Arduino Uno. The Uno has an input voltage of 6-20 V, and operating voltage of 5 V as from the tech specs. Does this mean that I can select any sensor with less than 20 V output to send data to my Arduino?

I am interested in using a sensor like this
 [Texas Instruments HDC1080 High Accuracy Digital
Humidity Sensor][1], which has a supply of 5.5 V. If my logic is correct, this output should be fine. I should know whether or not I need to buy some sort of shield based purely upon the output pins of the sensor, correct? I know I have 6 analog and 6 PWM/digital pins on the Arduino, so the digital signal should be capable of being processed by my Arduino. However, the interface type on the sensor product is I2C, but I am unsure as to what this means or if it needs to be a consideration.

  [1]: http://www.mouser.es/new/Texas-Instruments/ti-hdc1080-sensor/

title: How to select hardware for my Arduino board?

Answers: 2

body:
One question you have (3rd paragraph) brings a caution to mind. Your inputs to the Arduino are typically going to be 5v based, either digital or analog, although I may be phrasing this slightly loosely. A sensor not of the type you reference would provide a digital signal (Low/High relative to ground) or analog, which would be limited via external circuitry to 5v or lower. I think there's a good chance that if you find and use a sensor that pumps 20v into your Arduino, the smoke might be released.

I've read over the sensor you've linked. It was fascinating reading. It appears that the device is focused on being connected to a PC with USB and a Windows interface, but permits direct register access for specific data.

You'd want to research the best way to connect an i2c device to your Arduino, and I'm certain there are plenty of libraries for that. A good place to start is the reference on the "official" [Arduino web site for i2c.][1] This same page references use of the library, calling/polling the device and reading/writing data.

What I read in the volumes of the data sheets and user guides for the device you linked appears to cover everything you need to know and a tremendous amount of information you may not need.

It looks like a fun project and well engineered, at least from the sensor reference.
[![Temperature Sensor][2]][2]

  [1]: https://www.arduino.cc/en/Reference/Wire
  [2]: https://i.stack.imgur.com/Aj3C1.png

body:
For your first project, power the Arduino Uno with the USB cable and use everything at 5V.
There are tutorials which guide you step-by-step to make something. The Adafruit tutorials are very good.

The HDC1080 is a sensor that works at 3.3V and at 5V. That means you can use it with the 5V Arduino Uno without problem.
This [Tindie HDC1080 module][1] points to [a HDC1080 library on Github][2]. I suggest you try to make that work.

If you can not get data out of the sensor, then you should start with something very simple. A few leds (with series resistors) or a LDR light sensor is fun to start with.

As soon as you start using higher voltages (for example 12V) you might consider buying a spare Arduino Uno, because the Arduino Uno will be blown when 12V touches one of the pins.

Be also careful with sensors that can only handle 3.3V and not 5V. Since the Arduino Uno runs at 5V, a pin of the Arduino could feed 5V into the sensor and damaging the 3.3V sensor.

  [1]: https://www.tindie.com/products/closedcube/hdc1080-high-accuracy-humiditytemperature-sensor/
  [2]: https://github.com/closedcube/ClosedCube_HDC1080_Arduino