message:
Shield Compatible third party motor driver

I recently purchased an Arduino UNO along with some other hardware. At the time of purchase, I didn't know about Arduino's motor shield and so I purchased a two channel stepper motor driver (2A per channel) that was said to be "Shield Compatible". I recently received my hardware and have been following the introductory tutorials since I'm completely new to the Arduino platform. Things are going well but I didn't receive any documentation with the motor driver. There is a datasheet provided on the vendor's website but it is beyond my current level of competency.

My question: since the driver is said to be "Shield Compatible", does this mean that I can assume that I can interface with it the same way as an authentic Arduino shield. In other words, can I follow the motor shield tutorial on Arduino's website without any risk of damaging hardware and expect the driver I purchased to function properly.

The product that I purchased can be seen here: http://www.robotshop.com/ca/en/dual-bipolar-stepper-motor-controller-arduino.html

body:
You should do you own research as the path followed here did not result in the identically pictured nor identically model numbered item.

You indicated you are using a certain Arduino motor driver board.  On that page there is an "made by" or "by" reference to an OEM.  On the OEM's web page there is a "Dual Bipolar Stepper Motor Shield for Arduino" but the part number and the picture do not (exactly) match your original link.  Regardless, there is what they are calling a "[WIKI page][1]" for this (slightly) different motor shield.  I scanned this page and the example code.  I don't see where any device driver is mentioned.  And I don't think the code will compile by its self.

In general, I suggest people who are starting out with Arduino's to stick with well known hardware and software.  Even then I have had problems with newly released hardware.  Also check if drivers and SDKs have been updated each time you start a project.

Another approach you might entertain is to follow a path starting with the chip used on your shield.  It appears to use two DRV8825.  (But I cannot be sure as pictures and model numbers do not (exactly) match.) [Here is a discussion][2] on the a well known Arduino web site where people are talking about boards with this chip on it.

  [1]: https://www.dfrobot.com/wiki/index.php/Stepper_Motor_Shield_For_Arduino(DRV8825)_SKU:DRI0023
  [2]: https://forum.arduino.cc/index.php?topic=327696.0


sender: user

message:
How do I connect Arduino to RS232 via USB?

I have a device that takes commands in the form of RS232 communication. I've connected the Arduino's USB port, through an adapter, to the device's 9-pin serial port, but no communication has happened.

The full chain of adapters is a printer cable (which would connect the Arduino to a computer), a female-to-female usb adapter, and a Sabrent USB to serial adapter.

I made sure the communication wasn't happening using the code `while (!Serial)` and blinked an LED in a certain pattern.

Is there something I'm missing? How do you get the devices to communicate?

sender: assistant

body:
This is effectively not workable.  USB is not a peer-to-peer standard, but a host/device one.  Both your Arduino and the USB-serial converter are intended to be devices, so they cannot communicate.  While it would be *possible* to use another microcontroller acting as a host to bridge to serial that would be pointless, as the actually central problem of RS232 vs. logic level serial would still need to be solved.

Instead, what you want is an inverting serial level shifter - essentially a board with an IC like a MAX232 or one its many successors.  You would either connect this to arbitrary digital pins of the Arduino and use a Software Serial instance, or decide that it is okay to block usage of the USB port by a computer while this is being operated, in which case you could connect it to the D0 & D1 pins used by the on-board USB interface (there are typically resistors in between the chips on the board to support this overriding).

Ironically, in a way what you want is one of the *original* Arduino boards that had a serial level shifter and 9-pin connector in place of the USB chip and USB connector of modern boards.  But then, you probably want something with an ATMega328p rather than the earlier, more primitive ATmega chips used on the original boards.  If you can still find a board of the original design, upgrading the chip may be an option, or it may be that your task is simple enough not to require it.

There have been many other non-Arduino embedded controller boards released with native RS232 ports as well, especially those dating from around a decade ago might give a good combination of fairly modern capability with not yet having abandoned RS232 in favor of USB.


body:
Any network of USB devices involves [a single **host** talking to many slave **devices**](https://en.wikipedia.org/wiki/USB#System_design). The typical connection to program an Arduino board is, on the USB side:

    PC (USB Host) <-> USB Cable <-> Arduino (USB Device)

On the Arduino board you have the serial side of this communication:

    USB Serial Adapter <-> TTL serial lines <-> Microcontroller (RX/TX on D0/D1 pins)

The microcontroller itself has no idea that any USB communication is involved. The USB serial adapter functions as a device only, not a host, so plugging it into another USB device (though a cable with device connectors on both ends, rather than the usual host connector on one end) will not do anything.

(There are some Arduino boards, such as the [Leonardo](https://www.arduino.cc/en/main/arduinoBoardLeonardo) and the [Micro](https://www.arduino.cc/en/Main/ArduinoBoardMicro), that use an [ATmega32U4](http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf) microcontroller with a USB device interface built in. These work in substantially the same way as above except with the without the serial adapter and TTL serial link. The built-in USB interface also cannot be used as a USB host.)

### Arduino USB Host Shield

If you really want to use USB communication, SparkFun sells as [USB Host Shield](https://www.sparkfun.com/products/9947) that you can add to a standard Arduino Uno or similar device. The [library](https://www.circuitsathome.com/arduino_usb_host_shield_projects/) for it apparently supports USB serial, though you'd want to confirm that before buying the shield. This would leave the Arduino's USB/Serial interface used for programming free to remain hooked up when using the USB host shield, making development easier.

### Direct Serial Connection

A better method (IMHO) is to drop the USB stuff altogether and, as [Chris Stratton describes in his answer](https://arduino.stackexchange.com/a/36588/31794), have the Arduino talk TTL serial directly to a level shifter (e.g., this [breakout board](https://www.sparkfun.com/products/449) or [this shield](https://www.sparkfun.com/products/13029)) that is connected to your RS-232 device. I would go with communications on non-programming pins (i.e., not digital pins 0 or 1) using the [SoftwareSerial](https://www.arduino.cc/en/Reference/SoftwareSerial) library or the [AltSoftSerial](http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html) library. (You don't mention the speed of the link, but software serial is generally ok up to 57,600 bps and, depending on the device and what else you're doing, even 115,2000 bps.) This will let you use the serial link to the computer for debugging while running your application.

If you need to work at higher speeds or you just prefer to use a [UART](https://en.wikipedia.org/w/index.php?title=UART) (hardware serial), you have two options:

1. Use the [USART](https://en.wikipedia.org/w/index.php?title=USART) on digital pins 0 and 1, and be unable to talk to the computer while you're using it to communicate with your RS-232 device.

2. Use an Arduino board with more UARTs or USARTs on it, such as the [Mega](https://www.arduino.cc/en/Tutorial/MultiSerialMega).


message:
ESP8266 not sending temperature data to text message

i am trying to use a ESP8266 module to send temperature data using twilio and send it to my phone via text message. However it does not send the sensor data but the text i placed. Is it possible if i can get it to send sensor data instead? If so how can i do this?

    strcat(data,"From=");
        strcat(data,PHONE_FROM);
        strcat(data,"&");

        strcat(data,"To=");
        strcat(data,PHONE_TO);
        strcat(data,"&");

        strcat(data,"sid=");
        strcat(data,TWILIO_ACCOUNT_SID);
        strcat(data,"&");

        strcat(data,"token=");
        strcat(data,TWILIO_TOKEN);
        strcat(data,"&");

        strcat(data,"Body=");
        const char TEXT_MESSAGE_BODY []  = "temperature", temperature;
        strcat(data,TEXT_MESSAGE_BODY);

        wifi.httpPost("iot-https-relay.appspot.com","/twilio/Messages.json",data);

temperature should be getting sensor raw data and paste it after the "temperature" but it is not working.

body:
Not 100% sure what you are trying to do with the line:

    const char TEXT_MESSAGE_BODY []  = "temperature", temperature;

This will not assign the value in temperature to TEXT_MESSAGE_BODY, it will create a variable of type char called temperature.

You will need to get your temperature value into a string (array of char) using sprintf() or similar to convert from the base type (float, double?).

Replace const TEXT_MESSAGE_BODY [] ... etc with :

    strcat(data,"temperature");

    char temperature_s[20];
    sprintf(temperature_s, "%f", rawTemperature);
    strcat(data,temperature_s);

Above assumes rawTemperature is a float holding the value read from the sensor, but the same idea applies for other data types..  There is no checking for buffer overflow etc, but you get the idea.


message:
Arduino auto power of circuit possible issue with higher voltage agains output pin?

I've use the following circuit to be able to shutting the my Arduino down after some time of it not being used:

<img src="https://dl.dropboxusercontent.com/u/5426092/AutoPower Off.png">

I'm now concerned that while you press the button to turn on the Arduino, the 9V from the battery can flow directly to the PIN X (one of the digital pins of the Arduino configured as output). After the Arduino is started the PIN X will be set to high, to keep the Arduino running when the button is released.

Is this a problem which I need to solve? And if yes how. The finished project is intended for a child, so I assume that the on button can be hold for a long time just as it is funny to press on the button. The circuit itself is running fine.

As a possible solution I thought to add a diode between the junction after the R1 and the PIN X. Would this be an ok solution?

The circuit is not my own invention I've found it here: http://educ8s.tv/auto-power-off-arduino-simple-circuit/

body:
No.  It is not possible for a modern IC such as an MCU having I/O protection diodes to enable/disable its own power using a *single* external N-Channel or P-Channel device.  The reason is that the path broken by the single switch ends up being partially completed through I/O pin's internal protection diode and your pulldown resistor, and depending on the voltage drop that results across that, partial turn on the FET itself.  This is enough to have the processor at least partially on - perhaps not enough to *operate*, but enough to keep consuming battery, and in some cases also enough to make clean startup on manual operation of the power switch unworkable.

To make this work, you need two stages of switching - two fets are a possibility.

However another easy one is to use one of the USB power switches chips intended to be included in the rarely seen "full" USB hubs that have software control of the downstream ports' power.  These are hardly ever fitted in the hubs sold, but they exist as a part, are easy to apply, typically have low leakage, and are often specified to operate correctly both substantially below and somewhat above the 5v they would see in a USB application.  Most importantly, they are multi-stage solutions in a single package - typically they function as high side switches, but they are enabled by an input going high, and as result, they do not suffer the parasitic partial turn on issue via the MCU's protection diodes in the way that a high side switch enabled by an input going low would.  I believe the RT9701 that I used in the past to do this with an ESP8266 is officially discontinued, but still available and likely replaced by newer similar parts.

Given your input voltage, another thing to consider would be using a regulator with an active-high enable input.  But realize that a *linear* regulator is an inherently wasteful device, and a lot of the compact switchers don't have very high input voltage allowance.


body:
Having 9 volts reaching pin X through R1 is indeed a problem, one that could destroy transistors in the pin's IO structure.  The problem is mentioned in some comments following the video, but no solution is mentioned there.  Presumably users of the circuit usually get away with ignoring the problem because it is one of short duration:  A few milliseconds after the MCU starts up, it sets pin X to +5 V, which then leads to 4 V at 40 μA being dropped harmlessly across R1.  (Note, R1 is 100KΩ rather than 100Ω, per video and its notes.)

One approach to guard against the problem is to place a 5.3–5.7 V zener diode from ground to pin X.

Another way is to use a better and more capable on-off circuit, a [Pololu Pushbutton Power Switch #2808](https://www.pololu.com/product/2808).  This costs about $4, and is rated for operation from 2.2 V to 20 V at up to 6 A.  The board is about 15x18 mm and has a small pushbutton on it, but you can parallel a momentary switch of your own if you like.  The pushbutton toggles power on or off.  The board also has control inputs called On, Off, and Ctrl, with the first two turning the board on or off.

A big advantage of the #2808 switch is its current draw is small (less than 0.1 μA) when switched off.  The circuit illustrated in the link has close to 0.5 mA draw when off, which is enough to run a battery down in a few weeks.


message:
Press on pressure sensor, then wait 5 seconds, turn on LED

I'm having some trouble wrapping my head around timers in Arduino. I've got a FSR Pressure Sensor and I want it to turn on my NeoPixel LED after pressing on it for 5 seconds. Any help is much appreciated!

My goal:
FSRReading > 1022 then wait 5 seconds, turn on NeoPixel
FSRReading < 1022, then reset timer, turn off NeoPixel

This is what I currently have for my code, I can detect and act on sensor readings, but no timer:

    #include <Adafruit_NeoPixel.h>
    #define PIN 6
    #define NUMPIXELS 16
    #include "Timer.h"

    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

    int fsrPin = 9; // FSR is connected to analog 0
    int fsrReading; // the analog reading from the FSR resistor divider int LEDbrightness;
    int LEDbrightness;
    Timer t;

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

    void loop(void) {
    fsrReading = analogRead(fsrPin);
    Serial.println(fsrReading);
    Serial.print("Analog reading = ");

    // we'll need to change the range from the analog reading (0-1023) down to the range // used by analogWrite (0-255) with map!
    LEDbrightness = map(fsrReading, 0, 1023, 0, 255);

    if (fsrReading < 10) {
    Serial.println(" - No pressure"); } else if (fsrReading < 200) {
    Serial.println(" - Light touch"); } else if (fsrReading < 500) {
    Serial.println(" - Light squeeze"); } else if (fsrReading < 800) {
    Serial.println(" - Medium squeeze"); } else {
    Serial.println(" - Big squeeze"); }
    delay(50);

    for(int i=0;i<NUMPIXELS;i++){

      // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
      if (fsrReading>1022){
      pixels.setPixelColor(i, pixels.Color(0,255,0));
      } else if (fsrReading<1022) {
      pixels.setPixelColor(i, pixels.Color(0,0,0));
      }

      pixels.show(); // This sends the updated pixel color to the hardware.
     }
     }

body:
The basic concept for tracking timing in the loop() is as follows:

1) when your event occurs, you store the current time in a variable:

    unsigned long lastReading = 0;
    uint8_t waiting = false;

    if ( !waiting && fsrReading > 1022 ) {
      lastReading = millis();
      waiting = true;
    }

2) you compare the lastReading variable against the current time and when enough time has passed, you can perform you timed action. ie:

    int timeToWait = 5000; // 5 seconds

    // are we waiting? and has enough time passed?
    if ( waiting && millis() - lastReading > timeToWait ) {
       waiting = false; // reset

       // Light up lights
       ...
    }

Note: this specific implementation only requires the sensor to rise above 1022 once, then wait 5 seconds before executing the timed action. If you want the sensor reading to be maintained above 1022 for the entire duration then you would add a check for a release with something like:

    if ( fsrReading < 1022 ) {
      waiting = false; // reset because reading fell below 1022
    }


body:
> My goal: FSRReading > 1022 then wait 5 seconds, turn on NeoPixel FSRReading < 1022, then reset timer, turn off NeoPixel

something like this will do.

      static uint32_t pressed_time; //last time the pressure sensor is pressed
      static uint8_t pressed_state=0; //the previous state. '1'->pressed, '0'->not pressed

      if (pressed()) {
        if (!pressed_state)) { //first time the pressure sensor is pressed
          pressed_state = 1;  //pressure sensor has been pressed
          pressed_time = millis(); //take time now
        }
      } else {                //no longer pressed
        pressed_state = 0;  //reset pressed state
        turnOffled();       //turn the led off
      }

      if ((millis() > pressed_time + LED_DLY) && pressed_state) turnOnled();

untested code, use at your own risk

edit:

the above code in action, with a minor modification to return the desired led state (active high):

       //turn on / off the led pins
      if (led_ctrl()) digitalWrite(LED_PIN, HIGH); //turn on the led, active high
       else digitalWrite(LED_PIN, LOW);  //turn off the led
    }

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

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

Note:
1. pressed() is active low;
2. the led is programmed to turn on 100ms after the button goes low.

hope it helps.


message:
Detecting the light source location using multiple photoresistors

I am not an expert yet, so please forgive any possibly wrong terminology that I may have used.

I am planning to place 6 light sensors in 1 meter (or maybe more) distance from one another, like this (sorry about the bad schematic, I am not an expert, but I hope it makes sense):

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

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

<!-- End schematic -->

I am going to place them in a relatively dark room. My goal is, when I am pointing a flash light towards them to be able to tell which sensor is measuring the highest values (where the light is coming from), and for how long (in milliseconds).

I know how to do the connections and measure values. My questions are two:

1. Which is the most efficient way to detect which of the 4 sensors is recording the higher values? I am assuming I have to compare the values that they are recording. However, I think that if in each loop I sort the captured values, the process might become heavy. I guess I could minimise the comparisons, since for example if LDR1's value is higher than LDR2 and LDR3, I can assume that the light source is cannot be pointing towards LDR6 for example. However, I am thinking that maybe there could be an even more efficient way to detect that (not necessarily in software).

2. Since the room will not be completely dark, the analog pins will record some values even when I am not pointing the flash light towards them. Is there a way to filter that out? I have come across calibration (https://www.arduino.cc/en/tutorial/calibration), but I am not sure whether this is the optimal solution. Please take into account that the light source might not be very strong (but its light will definitely be brighter than the room light).

body:
There's only one ADC (analog to digital converter) on the ATmega328P; the analog input pins are multiplexed so that you choose which particular pin you want to sample. (See Section 28 of [the datasheet](http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf) for details.)

Taking a sample takes time; how long depends on how you do it. The [`analogRead()` function](https://www.arduino.cc/en/Reference/AnalogRead) is documented to take about 100 microseconds. Reading your six sensors is thus going to take at least 600 microseconds.

The sample returned is a 10-bit integer and so easily fits into two bytes, or even one byte if you drop the low two bits (which is reasonable for some applications, and probably yours, because they're likely to be more sample error than data anyway). Whether you do that or not, however, you're left with a very tiny amount of data to sort from one set of reads: just six values.

The Arduino runs the ATmega328P at 16 MHz, and most instructions run in single clock, giving you performance approaching 16 instructions per microsecond.

We could work out, based on the type of sort you use, the number of comparisons and swaps you're likely to make in the average and worst cases, but there's no point to that on such a tiny data set because the total time your routine takes is almost certainly going to be dominated by other overhead. So I'm just going to say that the sort will be something on the order of a hundred clock cycles.

That means your sort would add around 6 or 7 microseconds to your 600 microsecond total read time you've got so far, or 1%; you don't have to worry about it at all.

You'll actually spend a lot more time doing other sorts of processing. But it's a pretty fast CPU, as we've seen above, so there's a good chance if you're careful that your loop will still be dominated by the sampling time of the ADC for each of the sensors.

My suggestion is to go ahead and write the thing but record actual timings in your loop for the sampling and the processing. After you've played around with it for a bit you'll have a better idea of the particular costs for each for your particular application and then you can worry about whether or not you need optimization. I suspect you won't.

Regarding the "filtering," that's going to be an integral part of your processing algorithm because the "room light" values can be vastly different from time to time depending on the current lighting in the room. I don't think you want to "filter" anything out, but instead compare the values of all of the photoresistors; at a first guess, similar values from all of them would mean that there's no flashlight and some giving you significantly higher values would indicate that there is one. But my second guess is that a) you'll want your sensors a lot further apart than 1 meter (perhaps in the corners of the room) and b) it's not going to be so simple; you're likely to see fairly different values from the sensors even in a quiescent room. This is where you get to play and experiment to find out how this really works!

It also occurs to me that putting the photoresistors several meters away from the ADC is going to involve a lot of wire, which adds resistance, capacitance and noise, all of which are going to interfere with your measurements. There's not a lot you can do about this; you can play a bit with measuring known-value resistors at the ends of the wires to see how bad the problem is, but if it's terrible you'd probably need to use a separate Arduino for each sensor and have them communicating back to a central place for analysis.


body:
The answer from Curt Sampson provides several good design considerations, plus the quite-reasonable suggestion that you run some experiments to characterize your LDRs and their placements.

Note that if you want to know which sensor has the highest reading, a simple find-maximum-value loop will do that, without any sorting:

    int maxR = reading[1], maxS=1;
    for (byte i=2; i <= nSensors; ++i) {
      if (reading[i] > maxR) {
        maxR = reading[i];
        maxS = i;
      }
    }
    // Now we know sensor maxS has max reading, maxR

The code above follows the 1–6 numbering scheme given in the question, and assumes that `reading[i]` stands for the reading from sensor `i`.

Code below, however, numbers the sensors and their readings from 0 to 5 instead of from 1 to 6, to allow simpler conditions in `for` loops.  From a programming standpoint, it makes sense to call the first sensor 0 if its data is stored in cell 0.

---

**Finding x, y direction of the light**

Assumptions behind the following code are that higher readings indicate more light, and that if necessary some background-lighting calibration has been done, and that background lighting has already been subtracted from readings data.  We also assume that maximum readings are less than (2¹⁵)/N, where N is number of sensors.

The point of the following code is to set two variables, `x` and `y`, that represent the relative location of a light source.  For example, if `x` and `y` are both positive, the light is above and to the right of the top right LDR.  If  `x` is negative and  `y` is near zero, the light is to the left of the middle-left LDR.  If knowing the signs of `x` and `y` is adequate for your purpose, then there's no need to do more arithmetic than shown.  On the other hand, if you want to compute some sort of angle, you can use `atan2(y, x)` to compute the direction of the light, in radians.

    int reading[nSensors];
    const int xdir[] = { -1, 1, -1, 1, -1,  1}; // x-direction sensor weights
    const int ydir[] = {  1, 1,  0, 0, -1, -1}; // y-direction sensor weights
    int x=0, y=0;
    for (byte i=0; i < nSensors; ++i) {
      x += xdir[i] * reading[i];
      y += ydir[i] * reading[i];
    }

---

*Edit 1:* **Tracking the time a light is on**

Issues with light-timing include what levels to start or stop timing at; necessary resolution (milliseconds? minutes?); necessary range (eg, is what happened a minute ago relevant); and when to reset accumulated time data.  It may be simplest to track the on times of all the sensors at the same time, then select one of the times or combine some times.  Do you want the largest time, the newest time, the newest large time, or the time corresponding to the largest light?

For example, the code below tracks light levels that remain high long enough to register, in smoothed averages, as above some threshold.  At intervals, current indications are rotated into bit maps that track the last 16 on-off levels for each LDR, and counts of number-of-ons are updated too.

    // Initialization ...
    uint16_t expAvg[nSensors]={0};  // Exponential averages over time
    uint16_t bitMaps[nSensors]={0}; // Track each sensor's last 16 on-off levels
    byte onCounts[nSensors]={0};    // Number of recent times sensor avg > threshold
    unsigned long prevMilli=millis();
    const int markInterval=50;   // ms interval for recording light levels
    const int onThreshold=547*16; // Some light-is-on threshold

    // In each pass of loop() ...
    for (byte i=0; i < nSensors; ++i)
      expAvg[i] = reading[i] + 15*expAvg[i]; // exponential averaging with 1:16 weight

    // In loop(), at intervals ...
    if (millis()-prevMilli >=  markInterval) {
      prevMilli = millis();
      for (byte i=0; i < nSensors; ++i) {
        onCounts[i] += (expAvg[i] > onThreshold) - (!(bitMaps[i] & 0x8000));
        bitMaps[i] = (bitMaps[i]<<1) | (expAvg[i] > onThreshold);
      }
    }


message:
Cannot get HC-12 to function with Arduino Pro Micro clone

[first time usage]

I'm checking this config out with a simple sketch derived from one @ https://www.allaboutcircuits.com/projects/understanding-and-implementing-the-hc-12-wireless-transceiver-module/.

The sketch acknowledges a command from the Serial Monitor and responds accordingly along with an "OK".  I have used this sketch countless times before with numerous HC-12 and UNO, and this particular HC-12 functions properly when connected to such.

For the Pro Micro, the command is echoed back instead, which, in my experience, indicates that the HC-12 is not receiving/responding.

The Pro Micro test config is very basic: Pro Micro, HC-12, USB connection, 5 direct jumper connections for vcc, gnd, pins 4-6. Vcc output reads 4.2 volts.

I specify:

    const byte HC12RxdPin = 4; // "RXD" Pin on HC12
    const byte HC12TxdPin = 5; // "TXD" Pin on HC12
    const byte HC12SetPin = 6; // "SET" Pin on HC12

    SoftwareSerial HC12(HC12TxdPin, HC12RxdPin)

I have also tested with an IN4007 in the power connect for the HC-12, but results are the same.

I've swapped HC-12s, and checked out the requisite pins by using another sketch that toggles an led on each.
The Arduino IDE is 1.8.2, and I am specifying a Leonardo board.  This is the suggestion I found whilst researching.

I have seen a few projects using the HC-12 with the Pro Micro and other small boards, but noticed no special considerations for such.

Have you any suggestions or solutions [even better]?

body:
Solution to problem is as follows:
 For the Arduino Pro Micro [as for the Leonardo], Serial1 must be used instead of a SoftwareSerial specification, e.g.,

    SoftwareSerial HC12(HC12TxdPin, HC12RxdPin).

Code is to be modified by changing HC12.available() to Serial1.available().  The same holds true for the reads and writes.
Pins are to be wired such that the HC-12 RXD pin connects to the Pro Micro TXD pin, and the HC-12 TXD pin connects to the Pro Micro RXD pin.
My thanks to @mico for providing the reference that explains it all.


message:
Substitute for FTDI board?

I am thinking forward to buy a set of Arduino pro mini. I have a very low budget and I can't think of buying a FTDI board. Is there any substitute for the FTDI board that is compatible with these arduino pro mini.

body:
All prices in USD w/ free shipping.

**FT232RL breakout board:**

- Aliexpress: $1.55
- eBay: $1.81

They are probably counterfeit. A Windows driver update (AKA "FTDIgate") at one point "bricked" them but I'm not sure that's an issue anymore. Even if it is it's Windows only and easy enough to work around. I've used these for years on Windows and they work fine for me.

If that's still beyond your budget there are a few other common options. I haven't used these breakout boards but I do have quite a few boards that use the CH340G and they work perfectly once you install the driver. There's a decent chance some of these will also be counterfeit. Some didn't break out the DTR/CTS pin for auto reset but if you're on such a low budget maybe it's worth it to you to press the reset button on every upload to save a few cents. They may not have the standard FTDI header pinout and if so would require you to use jumpers to connect them to the Pro Mini rather than plugging directly into the header.

**PL2303 breakout board:**

- Aliexpress: $0.50
- eBay: $0.74

These don't appear to break out the DTR or CTS pins so they won't do auto-reset.

**CH340G breakout board:**

- Aliexpress: $0.72
- eBay: $0.93

These don't appear to break out the DTR or CTS pins so they won't do auto-reset.

**CP2102 breakout board:**

- Aliexpress $1.00
- eBay: $1.31


body:
Basically, you need any way to talk to the [serial](https://www.arduino.cc/en/Reference/Serial) interface (on digital pins 0 and 1) on the Pro Mini. Remember that for programming you'll also need to be able to [manipulate the reset line](https://rheingoldheavy.com/arduino-from-scratch-part-11-atmega328p-dtr-and-reset/) on the target board, usually done via DTR.

If you already have an Arduino board with USB, you could write a small sketch that uses that as the interface. Using the [SoftwareSerial](https://www.arduino.cc/en/Reference/SoftwareSerial) library or the [AltSoftSerial](http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html) library you could have the USB Arduino talk to the Pro Mini via a couple of data pins and relay the data back and forth. Depending on the Arduino you use and how you program it, it may or may not be able to keep up with 115,200 bps, but rates at or below 57,600 bps should be fine. You'll also need to handle the DTR and CTS signals for programming; this can be done with a couple more data pins.

In general what you're trying to do (whether you go with my solution or another one) is not a beginner project. If you're not familiar enough with Arduino systems to answer the question you posed, I'd strongly suggest buying an [Uno](https://store.arduino.cc/product/A000066), [Nano](https://store.arduino.cc/product/A000005) or other board with integrated USB rather than trying to play with the Pro (which is called that for a reason).

If the cost of a single Arduino board is an issue, make sure you're looking around for the cheapest sources. You can find "non-brand" versions of many boards, such as [this "Nano"](https://smile.amazon.com/dp/B00E87VWY4) for considerably lower prices than you'll see from the name-brand vendors. They're lower quality and you're not supporting the Arduino ecosystem, but they help when you have a very limited budget.


message:
How to control a Nema 17 stepper motor with an arduino? (too much current / heat)

I am trying to control a Nema 17 motor with a L298n dual bridge and an Arduino Mega.

My wiring is from this Instructable:

http://www.instructables.com/id/Control-DC-and-stepper-motors-with-L298N-Dual-Moto/?ALLSTEPS

When I connect it to my laboratory power supply the current limitation blinks. Normally when there is too much current needed the LED is all the time on and not blinking.

So I increase the current limit and the motor just starts moving on 3.1A @ 12V (doesn't move if less current) and in the description of the motor on amazon
they say "Rated Current/Phase:1.2A" so I am wondering what did I do wrong here?

From my understanding "Rated Current/Phase:1.2A" means that I should run this motor (it's a bipolar stepper motor with 2 phases) not higher than 2.4A?

These are the informations from amazon about this motor:

**Specifications**:

- Led screw diameter: 8mm

- Lead screw length: 300mm

- Step angle :1.8 degree

- Nut material: Brass

- Holding Torque: 400mN*m

- Thrust(full step): 12.5kg

- Rated Current/Phase:1.2A

- Rate Voltage: 3.3v

- Rated Resistance/Phase:2.2±10%ohm

What would be a good voltage to run this motor? I thought 12V is a good idea with.

The motor L298n gets really hot when I run it at 3.2A or more so I think my setup will destroy the dual bridge and / or the motor.

I really appreciate help on this! :-)

[![Arduino Mega with L298n dual bridge, Nemi 17 stepper motor, Arduino Mega and QJ3005EIII][1]][1]

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

body:
The stepper motor does not directly control or limit its own current.  When using the L298n for stepper control, the motor current control is performed by a PWM signal to the L298n ENABLE pin.  If you have ENABLE high (100% duty), current will be a factor of only the DC resistance of the stepper winding and the power supply voltage.  Here you are trying to drive a 1.2A@3.3V-rated stepper from 12V, so naturally the current will be ~3 times greater.

To adjust the motor current to a safe range for the driver, use analogWrite() from a PWM-capable pin on the Arduino connected to the ENABLE pin on the L298n, and set it to something less than 255 (50% is usually a good starting point).  Even then, the instantaneous current draw on the L298n will likely be stressing it outside of its operating envelope.

EDIT: I reviewed the info at the link, and this is the relevant area of the code:

    // set speed to 200 out of possible range 0~255
    analogWrite(enA, 200);
    // set speed to 200 out of possible range 0~255
    analogWrite(enB, 200);

Here is where the code is setting PWM of the two ENABLE pins to 200 (~80% duty cycle).  Drop this to 50 (~20% duty cycle) and you would likely resolve your overcurrent issue.  Reading further still, even the author gives you your first hint at what is happening:

> This is not a speed value, instead power is applied for 200/255 of an
> amount of time at once.


message:
Benchmarking String.toInt() vs Checking individual characters gives unexpected result

I'm trying to check whether the input string contains all digits or not. I achieved this using 2 different algos. One is to convert the string to integer using String.toInt() and then checking if its value lies between the integer of length of the input string.

e.g. If input string is "123". The corresponding integer must lie between 100-999.

Second, I wrote a function that iterates over each character of the string and checks if its ASCII values lies between 48-57. If not, it returns false.

When I bench marked these two algos, I found that when the string contains only digits, the 2nd algo is about 9 times faster than the 1st one. **But when the string contains even a single non-digit character, the 1st algo takes ~1ms, but the 2nd algo always takes ~5ms.** Why is this? I've not been able to figure this out.

The code:

    unsigned long start;
    unsigned long middle;
    unsigned long end;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // send an intro:
      Serial.println("String toInt():");
      Serial.println();
    }

    void loop() {
      // Read serial input:
      if (Serial.available()) {
        String r = Serial.readString();

        start = micros();
        unsigned long rInt = r.toInt();
        int rLen = r.length();

        if ((rInt >= floor(pow(10, rLen))) || (rInt < floor(pow(10, rLen-1)))) {
          Serial.println("Please enter valid integer value!");
        } else {
          Serial.println(rInt+1);
        }

        middle = micros();

        bool isInt = doesContainInteger(r);
        if (isInt) {
          Serial.println(r);
        } else {
          Serial.println("Please enter valid integer value!");
        }

        end = micros();

        Serial.println(middle-start);
        Serial.println(end-middle);
      }
    }

    bool doesContainInteger(String s)
    {
      int sLen = s.length();
      for (int i=0; i<sLen; i++) {
        char sChar = s.charAt(i);
        if (sChar<48 || sChar>57) {
          return false;
        }
      }
      return true;
    }

body:
As pointed out by [Majenko](https://arduino.stackexchange.com/users/4143/majenko) in his (slightly annoyed) comment, you need to change your timing code to time only the calculations you want benchmark, not the I/O or other irrelevant code. For checking the conversion using `toInt()`, for example, try:

    // time our conversion
    unsigned long start = micros();
    unsigned long rInt = r.toInt();
    bool invalid = rInt == 0;
    unsigned long end = micros();

    // print the result
    if (invalid) {
        Serial.print("in");
    }
    Serial.print("valid conversion took ");
    Serial.print(end - start);
    Serial.print(" microseconds.");

Note that your assumption that a three-character input that's a valid integer will be between 100 and 999 is wrong; `"003"` and `"-17"` are both three-character inputs that should be correctly converted.

According to the [`toInt()` documentation](https://www.arduino.cc/en/Reference/StringToInt), `0` is returned on failure to convert, so I check for that in the code above. But since one can't tell the difference between a successful conversion of `"0"` and unsuccessful conversion of `"abc"` or some other non-integer, you really should be sure _before_ you call `toInt()` that you've got a valid integer int the string.


message:
Trying to make a heart rate analyser with Arduino that will calculate the BPM of a person

I am trying to make a heart rate analyzer device using an Arduino board that will calculate the BPM of a person by using raw sensor signals greater or equal to the threshold value to calculate pulses/heartbeat in 10 seconds and then multiply the number of pulses by 6.

The circuit is fairly simple: it has a led that is going to flash on the finger of the person. In-front of the finger there is going to be a photoresistor that is going to read changing values of light falling on it. The values will be varying because of the blood flowing through the finger. When there is going to be a  pulse/heart-beat the amount of light falling on the photoresistor will increase, hence the reading of the photoresistor will also increase.

If the raw values read by the sensor are equal to or greater than the threshold value the code will increment the number of pulses by 1. To calculate the heartbeat rate we will have to count the number of pulses/heart-beats for 10 seconds and then multiply the count by 6.

In short the code that I will use will convert raw analog sensor data into BPM (Beats Per Minute) so that a user can get a standard measurement of his pulse rate.

I took the code that I am going to use from [a website][1]. Here is a link to page so that you can also have a look at the code.

  [1]: https://github.com/GeeveGeorge/SUMO_ppg/blob/master/Edison_Sketch.ino

I had some problem in the code and was wondering if anyone could help me with it. The full code is given below:

    int sensorValue = 0;
    int sensorValue = 0;
    // variable to store the value coming from the sensor
    int count=0;
    unsigned long time1=0; // store the initial time
    unsigned long time2; // store the current time

    void setup() {
      // declare the ledPin as an OUTPUT:
      pinMode(sensorPin, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      // read the value from the sensor:
      if(count==0) {
        time1=millis();
      }
      time2=millis();
      sensorValue = analogRead(sensorPin);
      if(sensorValue>156) {
        increment();
      }
      if(time2>=time1+10000) {
        counter();
      }
    }

    void increment() {
      count++;
      while(sensorValue>156) {
        Serial.print("Sensor value is greater than .75V\n");
      }
    }

    void counter() {
      count=count*6;
      Serial.print("Heartbeat rate is ");
      Serial.print(count);
      Serial.print(" per min\n");
      time1=0;
      time2=0;
      count=0;
    }

Part of the code I'm not able to understand. This is located at the very top of `void loop()`:

[note: i pretty much understand how increment and counter functions work but i am not able to understand how the program is able to take input for 10 seconds.basically how the counter function runs for 10 seconds]

     if(count==0) {
        time1=millis();
      }
      time2=millis();
      sensorValue = analogRead(sensorPin);
      if(sensorValue>156) {
        increment();
      }
      if(time2>=time1+10000) {
        counter();

Although I know that this part of the code that I am not able to understand counts the pulses for 10 seconds by taking raw sensor values and checking if these values are above or equal to the threshold value, I am not able to understand how it is working.

I would be highly obliged if anyone could help me with this problem of mine.

body:
    // Record the start time into time1
    if(count==0) {
      time1=millis();
    }

    // Set time2 to the current time
    time2=millis();

    // Read the sensor
    sensorValue = analogRead(sensorPin);

    // If the sensor value is high enough, increment the beat counter
    if(sensorValue>156) {
      increment();
    }

    // If the current time is greater than, or equal to, the start time
    // plus 10,000 milliseconds (10 seconds), show the heart rate
    if(time2>=time1+10000) {
     counter();
    }


body:
    int sensorValue = 0;
    // variable to store the value coming from the sensor
    int count=0;
    unsigned long time1=0; // store the initial time
    unsigned long time2; // store the current time

    void setup() {
      // declare the ledPin as an OUTPUT:
      pinMode(A1, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      // read the value from the sensor:
      if(count==0) {
        time1=millis();
      }
      time2=millis();
      sensorValue = analogRead(A1);
      if(sensorValue>800) {
        increment();
      }
      if(time2>=time1+10000) {
        counter();
      }
    }

    void increment() {
      count++;
      while(sensorValue>800) {
        Serial.print("Sensor value is greater than .75V\n");
      }
    }

    void counter() {
      count=count*6;
      Serial.print("Heartbeat rate is ");
      Serial.print(count);
      Serial.print(" per min\n");
      time1=0;
      time2=0;
      count=0;
    }


message:
Uploading Arduino code, OTA, via connected ESP8266-12E running Esp-Link

#1. A short preliminary introduction

I'm deploying a small network of three MEGAs connected trough an RS-485 bus.
Each MEGA is connected to up to 16 push-buttons (wall-mounted) and two relay-module (2 x 8-SSR; located close to the MEGA). The objective is to manage the lighting of the whole house (aka: "switching 'ON' the relay 'R1' when the push-button 'PB1' is pressed").

At the moment, everything runs fine: MEGAs are able to 'broadcast' events along the BUS and each node is able to properly react to both locally-generated events, as well as events coming from the BUS.

Above system is running from a couple of weeks and... I'm starting struggling about "updating" the code: having around 40 push-buttons and 35 relay distributed on the three nodes, chances are "high" that some "tuning" (aka: "trial-and-error") is required.

Things get even worse when... you start enjoying the powerfullness of the system (aka: "Hai! What about turning-OFF _ALL_ the lights of the main-floor by long-clicking PB1?"). This, obviously, requires a "patch" to the code and a related "upload" the the MEGAs. And so on: _LOTS_ of uploads :-(

Having some ESP8266-12E modules sitting around, I decided to investigate the possibility to use them, as a sort of "WiFi gateway": reaching them via WiFi; sending them the new code; asking them to kindly "upload" the code to its own MEGA that is phisically connected via USART.

As mentioned in lots of places (including a comment on [this other question][1]) I decided to test the [ESP-Link][2] firmware.

As I'm having problems interconneting the MEGA with the ESP, here I'm, asking this community :-)

#2. Hardware involved
As for the Arduino side, I'm using a common MEGA (a Chinese one, BTW), so I don't get into details, here, 'cause there is nothing special.

As for the ESP8266, strictly speaking I'm **NOT** using a straight ESP8266-12E, but a Development Board. Actually, I'm using a **Lolin NodeMCU v3**, [this][3], that you can see here below:

[![Lolin NodeMCU v3][4]][4]

My plan is to connect _DIRECTLY_ the USART of the ESP to the USART of the MEGA. This raises some problems, described below.

#3. GPIO voltage issues
One of the very first issues that I addressed relates to GPIO voltage.
While it's **crystal clear** that:

- GPIO PINs, on MEGA, are 5V based and, as such:
   * the TX on the MEGA side will send out a 5V current;
   * the RX on the MEGA side expect to receive a 5V current;

-  GPIO PINs, on ESP8266-12E, are 3.3V based and, as such:
   * the TX on the ESP side will send out a 3.3V current;
   * the RX on the ESP side expect to receive a 3.3V current;

I still am **NOT** able to understand if this is --in my case-- a real problem. I'm saying this, 'cause:

1 - Transmission from ESP to MEGA should **NOT** be an issue, as the HIGH/3.3V signal coming in into MEGA should still be recognized as HIGH, from the MEGA, as it's higher than 2.5V;

2 - Transmission from MEGA to ESP **COULD** be a problem, if PINs on the ESP are **NOT** 5V tolerant

As for point 2) I deeply searched all-around and found plenty of contradictory assertions. In the end, I would like to "trust" [the Hackaday article: "Ask Hackaday: Is The ESP8266 5V Tolerant?"][5] as, in several comments, reports various semi-official statements (like a message from Expressif CTO sent from a Facebook account or a message from an "internal" of Espressif) asserting that: "*Yes! GPIO PINs on the ESP8266-12E are 5V tolerant*").
So, again, I decided: "Ok! Let me go! Let's connect the two, **straight**, without a level-shifter". And yes: I know that with such a decision, I'm taking some risks and... can "burn" something, especially on the ESP side.

So, here's my:

> **Question 1: How much I'm "brave" in connecting straight-away the TX/RX of the ESP8266 to the RX/TX of the MEGA? Would you suggest it? And why?**

#4. Ground issues
While working on my RS-485 bus, I learnt that it's critically important to have a "common ground" among my MEGAs. That sounds understandable... as otherwise there is **NOT** a common reference to evaluate the same signal among different devices.

So, now that I've **TWO** equipment and I'm giving them POWER via two distinct sources (MEGA directly connected to my PC; ESP connected to another PC), I'm wondering if:

> **Question 2: Do I need to connect a GND PIN on the MEGA to a GND PIN on the ESP? Do the two boards, to properly operate, need a shared/common GND?**

#5. RESET line on the MEGA
In order to trigger the flashing of the new sketch on the Arduino side, the ESP need to RESET it. To do this, the ESP need to be connected to the RESET line of the MEGA. The RESET PIN is clearly shown on the MEGA so the connection is really easy.

Nevertheless, after some preliminary test... it looks to me that the ESP is **UNABLE** to reset the MEGA.

This lead to:

> **Question 3: Is, an ESP8266-12E OUTPUT PIN (operating at 3.3V), able to properly handle the RESET PIN of the Arduino?**

I'm asking also 'cause based on the [official documentation of the MEGA][6] I read:

    Reset PIN: Bring this line LOW to reset the microcontroller.
    Typically used to add a reset button to shields which block
    the one on the board.

#6. Physical connections
In the [official documentation of ESP-Link][7] I read about potential problems generated (to Arduino) by the ESP as, right after a reboot of the ESP, it send out on TX some debug messages. Due to the USART connections, such characters transmitted by the ESP to the MEGA are received by the MEGA. It's not clear, to me, WHY this could be a problem. Anyway, the same documenation say: "*...If you need to avoid this, you can configure esp-link to swap the uart pins...*"

So, in the end, I connected the two devices following the official doc, with USART PINs swapped:

* GPIO13: connect to TX of microcontroller
* GPIO15: connect to RX of microcontroller and use a pull-down to ensure proper booting
* GPIO12: connect to RESET of microcontroller
* GPIO14: connect to ISP of LPC/ARM microcontroller (not used with Arduino/AVR)
* GPIO0: either a 1k-10k pull-up resistor to 3.3v or a green "conn" LED via a 1k-2.2k resistor to 3.3V (indicates wifi status)
* GPIO2: either a 1k-10k pull-up resistor to 3.3v or a yellow "ser" LED via a 1k-2.2k resistor to 3.3V (indicates serial activity)

As I don't need (currently) any LED feedback, I haven't used GPIO0 and GPIO2. Also, as I don't have an ARM, I haven't used GPIO14.

With help of [this][8] mapping I ended with following connection:

[![enter image description here][9]][9]

#7. Results (...and problems)
To test what's going on, I've uploaded to Arduino a simple sketch that turn ON/OFF the internal LED every second and dump an increasing counter on the console. Here it is:

    unsigned long counter;

    void setup() {
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      counter = 0;
    }

    void loop() {
      Serial.print("[");Serial.print(counter);Serial.print("] ");
      Serial.println("on");
      digitalWrite(13, HIGH);
      delay(1000);
      Serial.print("[");Serial.print(counter);Serial.print("] ");
      Serial.println("off");
      digitalWrite(13, LOW);
      delay(1000);
      counter++;
    }

so, from the console output, I can see if Arduino is correctly operating and if it's restart.

On the ESP-Link side, I've configured the PIN as shown below:

[![enter image description here][10]][10]

With all the above in place, up to know, I've been experimenting the following:

- If I connect ONLY the RESET line and the TX/MEGA to the D7/GPIO13/ESP, I can succesfully reset the Arduino from the ESP-Link web interface and I can see the "console" of the MEGA (I can be sure of succesfully reset, as the counter in the Arduino console, restart);
- Above apply:
   - when the MEGA is powered via a full-USB connection from a PC;
   - when the MEGA is connected via a power-only USB cable from the PC;
   - when the MEGA is powered via a USB-power-bank, but in this case _ONLY_ if thereis a shared-GND between ESP and MEGA

- As soon as I connect the D8/GPIO15/ESP to the RX/MEGA, everything still work, but up to next reset. If I "reset" the Arduino via the ESP-Link web-interface, it reset but.... never boot (I'm sure, as the "blinking" never start).

So, the last question:

> **Question 4: What's wrong with above testbed? Why the D8/GPIO15/ESP disrupt the boot process on the MEGA? I've swapped the UART PINs exactly to avoid this... as far as I understood...**

Sorry to be so long but... I think that details matter :-)

  [1]: https://arduino.stackexchange.com/q/24350/13193
  [2]: https://github.com/jeelabs/esp-link
  [3]: https://it.aliexpress.com/item/new-Wireless-module-CH340-NodeMcu-V3-Lua-WIFI-Internet-of-Things-development-board-based-ESP8266/32556303666.html?spm=2114.46010108.5.1.jxTxQA&&scm=1007.12783.72505.0
  [4]: https://i.stack.imgur.com/ILpco.jpg
  [5]: http://hackaday.com/2016/07/28/ask-hackaday-is-the-esp8266-5v-tolerant/
  [6]: https://www.arduino.cc/en/Main/ArduinoBoardMega
  [7]: https://github.com/jeelabs/esp-link/blob/master/FLASHING.md
  [8]: https://github.com/nodemcu/nodemcu-devkit
  [9]: https://i.stack.imgur.com/LNg2z.jpg
  [10]: https://i.stack.imgur.com/JkaNZ.jpg

body:
I have successfully used ESP-link firmware with esp-01 and Arduino Pro Mini.

For the ESP-01 and Pro Mini, you can find out more on my [blog post][1]. I have connected GPIO 0 of ESP-01 to reset pin of Pro Mini and the Pro Mini can be reset using ESP-Link the web interface. I try to use the same voltage level for both micro-controllers and a single power source. For my example, the Pro Mini is driving the ESP-01 and of-course sharing the common ground.

To answer your questions.

1. I try not do that as ESP has stated that all the GPIO pins are only 3.3v compatible.

2. Yes, both controller must share a ground.

3. My understanding is RESET is an output pin. If connected to ESP8266, there is a possibility that the ESP will be damaged.

4. Not sure if your wiring is correct. You may reference my diagram on how the ESP and Arduino Pro Mini is wired up. For your case, I will recommend a level shifter to prevent damaged to your ESP.

  [1]: http://iotdiary.blogspot.sg/2017/09/using-esp-link-transparent-bridge.html


message:
Arduino Com port and PHP Bug

so please read this whole thing.

My Project: I am making a bell system that is based on PHP. The bell is connected to the arduino UNO via a relay and the arduino is connected to the computer via a USB cable. The interface with the database is built with PHP and MySql. Then we have the code which checks every minuit if the bell has to be rung and if it does send a numeric value to the arduino. There is also an option for a longer bell if we send a '0' to the arduino.

My Code: So this is the file that checks if bell has to rung and sends value to arduino

    <?php
    include('database.php');
    $usb_comPort = "COM3";
    date_default_timezone_set("Asia/Kolkata");
    $time = date("H:i");
    $time = trim($time);
    $sql = "SELECT bell_amount FROM bell_db WHERE DATE_FORMAT(bell_time,'%H:%i') LIKE '$time'";
    $result = mysqli_query($conn, $sql);
    $numRows = mysqli_num_rows($result);
    if ($numRows == 0) {
      echo 'Error: Nothing found!';
    } else {
      $row = mysqli_fetch_assoc($result);
      $bellAmount = $row['bell_amount'];
      $runCommand = "ECHO " . $bellAmount . " > $usb_comPort";
      echo $runCommand;
      exec($runCommand);
    }
    ?>
    <html>
    <meta http-equiv="refresh" content="60">
    <body>
    </body>
    </html>

and this is the arduino's code:

    int b = 0;
    void setup() {
    Serial.begin(9600);
    pinMode(10, OUTPUT); //relay
    }

     void loop() {
      b = Serial.read();

        b = b - 48;
        if(b == 0){
          digitalWrite(10,HIGH);

          delay(3000);
          digitalWrite(10,LOW);
          }
        else{
        for (int i=0; i < b; i++){
          digitalWrite(10, HIGH);
          delay(200);
          digitalWrite(10, LOW);
          delay(200);
          }

        }

    }

The Issue that i am facing: My aim is that the code should run automatically when the computer is turned on. The code works fine but there is random bug. The code is uploaded to the arduino. When the computer is turned on i want that the system should work but when i run the file  (the one that checks if there is a bell to be rung or not ) it processes the code but it is not able to send a value to the com port so the bell does not ring(the serial light on the arduino does not flash). But if i go to the arduino ide and send a value through the serial monitor once then run the php file, it works!

I am running this on a windows 10 computer, i have an arduino UNO and i have tried this with 2 arduino's same result on both.

So anyone know what i can do?

body:
Sounds like the COM port is not setup. Opening the Arduino IDE probably does this automatically.

Try running the following command, only once, after turning on your pc to initialize the COM port.

    mode COM3 BAUD=9600 PARITY=n DATA=8

Ps. I'm not a windows user, so this is an educated guess - [reference](https://batchloaf.wordpress.com/2013/02/12/simple-trick-for-sending-characters-to-a-serial-port-in-windows/).

Pps. I think you're winning the award for the most complicated way to ring a bell. :)


message:
Is setting clock divider worth changing on delay() to save power?

Along all the "advanced" methods [described in this article][1], does simple method as downscaling processor while `delay` makes a difference on power consumption? How much time does the clock alternation takes itself?

Is below example valid?

    #include <avr/power.h>

    void setup() {}

    void loop {

        /*
           here some jobs to do...
        */

        clock_prescale_set(clock_div_256); // downscale clock
        delay(200); // wait
        clock_prescale_set(clock_div_1); // restore clock
    }

  [1]: http://www.gammon.com.au/power

body:
Reducing the CPU frequency should work, but I would expect better
savings by sleeping during the busy loop:

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

    #include <avr/sleep.h>

    void sleepy_delay(uint32_t duration)
    {
        uint32_t start = millis();
        while (millis() - start < duration) {
            sleep_mode();
        }
    }

Note that the sleep will be interrupted at least on every Timer 0
overflow interrupt, which happens every 1024 µs (that's what
increments the value returned by `millis()`), so there is no risk of
oversleeping. You could add some `power_*_disable()` calls for better
savings.


message:
Interface with mux-controlled LED rope

I'm working on using a GUI in Processing to control some [LED rope from Adafruit][1], and using this [multiplexer][2].

I've gotten the following Arduino code working the way I want to cycle through the various strands of LED rope and turn them on:

    #include <SoftwareSerial.h>

    //Mux1 control pins
    int s0 = 8;
    int s1 = 9;
    int s2 = 10;
    int s3 = 11;

    //Mux2 control pins
    int s4 = 12;
    int s5 = 13;
    int s6 = 14;
    int s7 = 15;

    //Mux in "SIG" pin
    int SIG_pin = 3;

    //Voltage vlaue to write to the LEDs
    int testValue = 255;

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

      pinMode(s0, OUTPUT);
      pinMode(s1, OUTPUT);
      pinMode(s2, OUTPUT);
      pinMode(s3, OUTPUT);
      pinMode(s4, OUTPUT);
      pinMode(s5, OUTPUT);
      pinMode(s6, OUTPUT);
      pinMode(s7, OUTPUT);
      pinMode(SIG_pin, OUTPUT);

      digitalWrite(s0, LOW);
      digitalWrite(s1, LOW);
      digitalWrite(s2, LOW);
      digitalWrite(s3, LOW);
      digitalWrite(s4, LOW);
      digitalWrite(s5, LOW);
      digitalWrite(s6, LOW);
      digitalWrite(s7, LOW);
    }

    void loop(){

      for(int i = 0; i <= 19 ; i ++){
        Serial.println(i);
        testValue = 255;
        writeMux(i);
        delay(500);
    //    testValue = 0;
    //    writeMux(i);

      }

    }

    int writeMux(int channel){
      int controlPin[] = {s0, s1, s2, s3, s4, s5, s6, s7};

      int muxChannel[20][8]={
        //Mux 1
        {0,0,0,0,0,0,0,0}, //channel 0
        {1,0,0,0,0,0,0,0}, //channel 1
        {0,1,0,0,0,0,0,0}, //channel 2
        {1,1,0,0,0,0,0,0}, //channel 3
        {0,0,1,0,0,0,0,0}, //channel 4
        {1,0,1,0,0,0,0,0}, //channel 5
        {0,1,1,0,0,0,0,0}, //channel 6
        {1,1,1,0,0,0,0,0}, //channel 7
        {0,0,0,1,0,0,0,0}, //channel 8
        {1,0,0,1,0,0,0,0}, //channel 9

        //Max 2
        {1,1,1,1,0,0,0,0}, //channel 0
        {1,1,1,1,1,0,0,0}, //channel 1
        {1,1,1,1,0,1,0,0}, //channel 2
        {1,1,1,1,1,1,0,0}, //channel 3
        {1,1,1,1,0,0,1,0}, //channel 4
        {1,1,1,1,1,0,1,0}, //channel 5
        {1,1,1,1,0,1,1,0}, //channel 6
        {1,1,1,1,1,1,1,0}, //channel 7
        {1,1,1,1,0,0,0,1}, //channel 8
        {1,1,1,1,1,0,0,1}, //channel 9
      };

      //loop through the 4 sig
      for(int i = 0; i < 8; i ++){
        digitalWrite(controlPin[i], muxChannel[channel][i]);
    //    Serial.println("CHANNEL IS ");
    //    Serial.println(muxChannel[channel][i]);

    //    Serial.println("Control pin IS ");
    //    Serial.println(controlPin[i]);
      }

      //write the value at the SIG pin
      analogWrite(SIG_pin, testValue);

    //    Serial.println("Test value IS ");
    //    Serial.println(testValue);

      //return the value
      return 0;
    }

I'm working on converting this Arduino code to a Processing sketch so I can control the lights with a GUI. I've run the Standard Firmata sketch on my Uno before running my Processing sketch. However, nothing seems to happen...I know that my circuit is working (since it worked for the Arduino sketch), and most of my Processing code should be correct. Logging shows the sketch is trying to write the values I want. Anyone have any ideas? Below is the relevant part of the Processing sketch:

    import cc.arduino.*;
    import processing.serial.*;

    int [] muxChannel;

    //Mux1 control pins
    int s0 = 8;
    int s1 = 9;
    int s2 = 10;
    int s3 = 11;

    //Mux2 control pins
    int s4 = 12;
    int s5 = 13;
    int s6 = 14;
    int s7 = 15;

    //Mux in "SIG" pin
    int SIG_pin = 3;

    //Voltage vlaue to write to the LEDs
    int testValue = 255;

    void setup() {
      size(700,400);
      noStroke();
      cp5 = new ControlP5(this);
      println(Arduino.list());

      //// Set up Arduino and pin output modes
      arduino = new Arduino(this, Arduino.list()[1], 96000);

      arduino.pinMode(s0, Arduino.OUTPUT);
      arduino.pinMode(s1, Arduino.OUTPUT);
      arduino.pinMode(s2, Arduino.OUTPUT);
      arduino.pinMode(s3, Arduino.OUTPUT);
      arduino.pinMode(s4, Arduino.OUTPUT);
      arduino.pinMode(s5, Arduino.OUTPUT);
      arduino.pinMode(s6, Arduino.OUTPUT);
      arduino.pinMode(s7, Arduino.OUTPUT);
      arduino.pinMode(SIG_pin, Arduino.OUTPUT);

      arduino.digitalWrite(s0, Arduino.LOW);
      arduino.digitalWrite(s1, Arduino.LOW);
      arduino.digitalWrite(s2, Arduino.LOW);
      arduino.digitalWrite(s3, Arduino.LOW);
      arduino.digitalWrite(s4, Arduino.LOW);
      arduino.digitalWrite(s5, Arduino.LOW);
      arduino.digitalWrite(s6, Arduino.LOW);
      arduino.digitalWrite(s7, Arduino.LOW);
    }

    void draw() {
      background(bgColor);

        for(int i = 0; i <= 19 ; i ++){
        testValue = 255;
        writeMux(i);
        delay(500);
      }
    }

    int writeMux(int channel){
      int controlPin[] = {s0, s1, s2, s3};

      final int[][] muxChannels = {
        //Mux 1
        {0,0,0,0,0,0,0,0}, //channel 0
        {1,0,0,0,0,0,0,0}, //channel 1
        {0,1,0,0,0,0,0,0}, //channel 2
        {1,1,0,0,0,0,0,0}, //channel 3
        {0,0,1,0,0,0,0,0}, //channel 4
        {1,0,1,0,0,0,0,0}, //channel 5
        {0,1,1,0,0,0,0,0}, //channel 6
        {1,1,1,0,0,0,0,0}, //channel 7
        {0,0,0,1,0,0,0,0}, //channel 8
        {1,0,0,1,0,0,0,0}, //channel 9

        //Max 2
        {1,1,1,1,0,0,0,0}, //channel 0
        {1,1,1,1,1,0,0,0}, //channel 1
        {1,1,1,1,0,1,0,0}, //channel 2
        {1,1,1,1,1,1,0,0}, //channel 3
        {1,1,1,1,0,0,1,0}, //channel 4
        {1,1,1,1,1,0,1,0}, //channel 5
        {1,1,1,1,0,1,1,0}, //channel 6
        {1,1,1,1,1,1,1,0}, //channel 7
        {1,1,1,1,0,0,0,1}, //channel 8
        {1,1,1,1,1,0,0,1}, //channel 9
        };

      //loop through the 4 sig
      for(int i = 0; i < 4; i ++){
        arduino.digitalWrite(controlPin[i], muxChannels[channel][i]);
      }

      //write the value at the SIG pin
      arduino.analogWrite(SIG_pin, testValue);

      int val = 0;
      return val;
    }

  [1]: https://www.adafruit.com/products/2440
  [2]: http://bildr.org/2011/02/cd74hc4067-arduino/

EDIT: I put the project and a little explainer on GitHub to show what this type of project can or can't be useful for here: https://github.com/narner/Analog-LED-Multiplexing-Example

body:
You're using a 16-channel analog multiplexer to talk to your devices (the LED ropes) via a single pin on your Arduino. "Multiplexer" is just a fancy name for a switch; "analog" means that it's switching analog connections, basically, wires that can have any voltage on them, as opposed to digital connections that carry only logic high (usually +5 volts) or low (0 volt) signals.

The first place to start is the datasheet. From the [product link], we can see that the chip we're using is a CD74HC4067. Their datasheet links don't work, but searching in [Octopart] for just "74HC4067" eventally led me to an actual [datasheet]. These datasheets are the key source for information on the parts you're using and are always worth reading through. Even if you don't understand everything in them, they'll usually have the information you need, and reading them gets easier with practice.

Section 5 has a functional diagram (Fig. 1) which shows the important connections.

* Z is what you'll hook up to an I/O pin on your Arduino. When the
  chip is enabled, Z will be connected to one of the Y connections.
* Y0 through Y15 are what you'll hook up to your individual devices;
  one (and only one) of these at a time will be connected to Z,
  connecting the device to your Arduino I/O pin.
  (The other Y connections will be in a [high impedance] state.)
* Ē is the "enable" signal, the bar over top indicating that it's
  "active low." That is to say, when you ground (0 V) Ē the mux will
  be active and the selected Y will be connected to Z. When you hold Ē
  high (5 V) the mux will be inactive and all the Ys and Z will be
  disconnected (high impedance again).
* S0 through S3 are the select inputs to the mux; they determine which
  Y is connected to Z (when the device is active) in a way we'll show
  below.

Depending on the project, you may not want to switch the connection between the Z and Y pins (by changing S0-S3) while the devices connected to the Ys are active so that you don't accidentally get a a little bit of signal meant for one device going to another. The steps to do this would be as follows:

1. You start by having Z connected to, say, Y0, with the signal you
   want to send to Y0 going through Z.
2. Disable the device by bringing Ē high. Now Y0 (and all other Ys)
   are disconnected.
3. Change the value on S0-S3 to select, e.g., Y1.
4. Change the signal you're sending to Z to the correct signal for Y1.
5. Bring Ē low to enable the device and now Z will be connected to Y1.

In your project you likely don't need to worry about being this careful with your switching so long as you change S0-S3 and Z as closely together as possible, so I'm going to simplify the code I show here by leaving out the enabling and disabling step; you can just wire Ē to ground for the moment.

The key to the switch is what you send on S0-S3 to select which Y is connected to Z. This input is just a binary number, which you'll need to understand to use it effectively. Following is a short summary, but if you don't understand it completely (or the C code later on), there are plenty of tutorials on the web that can give you further help.

Counting in binary is just like counting in tens except you have only the numbers 0 and 1. So instead of counting 0, 1, 2, ..., 9, 10, 11 you count 0, 1, 10, 11, 100, 101, ... (which represent the numbers 0, 1, 2, 3, 4, 5, ... in decimal). The S0 input on the mux is the least signifcant bit (the one furthest right), the S1 in put the second least significant bit (second from the right) and so on.

So you need to hook up four digital ouput pins from your Arduino to the S0 through S3 inputs on the mux and then manipulate those pins to send the appropriate number to the mux to select your chosen Y that you want to connect to X.

The following program, which counts sequentially from 0000 (0) through 1111 (15) on the four output pins; shows you how to do this. It would be a good idea to build up a small circuit on a breadboard with four LEDs (remember to use a 330 Ω or so resistor in series with the LED) that you can hook to your four pins so you can see visually what your program is doing as you experiment.

We start by declaring some constants for the pins:

    // Multiplexer control pins are assumed to be sequentially
    // assigned from `mux_base` onward.
    //
    const int mux_base = 8;
    const int mux_len = 4;                  // 2^4 values, 0 through 15
    const int mux_max = (1 << mux_len) - 1;

`mux_base` is the first pin of the four sequental pins you'll hook up to the S0-S3 (or the LEDs); I use pin 8 here but you can use pretty much any pin you like. `mux_len` is the number of bits in the mux selector input; S0, S1, S2, S3 is 4 bits, so this determines that I'm using pins 8, 9, 10 and 11 on the Arduino to control the mux.

`mux_max` is purely a calculation (from the previous two constants) of the highest value you can select on the mux; in this case it's 15. The details of how I caculate it are a bit beyond the scope of this answer, but it's worth working out yourself how that C code works from what you learn later in the code and can find out elsewhere on the web.

We need, as usual, to set up our chosen pins as digital outputs; `setup_mux()` does just that:

    void setup_mux() {
        for (int pin = mux_base; pin < mux_base+mux_len; pin++) {
            pinMode(pin, OUTPUT);
            digitalWrite(pin, LOW);
        }
    }

We start with the first selector pin and loop through to the last one, for each one setting it to output mode and setting the current value to `LOW` so that we have known starting conditions.

For the selection of the Y to connect to Z on the multiplexer, it's convenient to have a function that takes an `int` indicating that Y and sets our selector pins to the correct values for this. Thus, `set_mux(value)` below. This is probably the most complex part of this answer, and bears detailed study.

    void set_mux(int value) {
        for (int offset = 0; offset < mux_len; offset++) {
            int bit = (value >> offset) & 1;
            digitalWrite(mux_base + offset, bit ? HIGH : LOW);
        }
    }

1. The first line loops through our `mux_len` (4 from above) selector
   pins; each of these will have to be set to the correct `HIGH` or
   `LOW` value for the desired Y selection.
2. The second line determines the binary bit from `value` for the
   particular selector pin we're setting in this iteration of the
   loop. We do this by doing a binary shift of the value to the right,
   and then clearing all bits except the lowest one, leaving us with a
   final value for `bit` of 1 or 0. For example, if we pass 14 to the
   function, which is 1110 in binary, when the offset is 2 in the loop
   we'll use the `>>` operator to shift that right two bits, through 0111
   to 0011. (With each shift the right bit drops off and a 0 is added
   at the left.) Doing a logcal AND (the `&` operator) of 0011
   with 0001 keeps only the bits that are set in both, leaving us
   with 0001. (Only the far right bit is set in both.)
3. We then need to set the output pin to HIGH if `bit` is 1 or LOW if
   `bit` is 0; the ternary operator (_condition_ `?` _when-true_ `:`
   _when-false_) provides a concise way of doing this.

That's our core "library" code, if you will. In this simple example the only setup we need to do is to call `setup_mux()`:

    void setup() {
        setup_mux();
    }

Our main program, for demonstration, will count upwards in binary on the selector outputs, delaying a half second between each count so you can see your LEDs blink:

    int counter = 0;

    void loop() {
        set_mux(counter);
        delay(500);
        counter++;
        if (counter > mux_max)
            counter = 0;
    }

Once you understand this example, you have everything you need to start using your multiplexer with something more sophisticated than just counting.

One last important thing to emphasize: the mux allows you to use just one signal I/O (plus the four selector outputs) on your Arduino, but that signal I/O is connected to only one device at a time. This won't work if you must always be sending a signal to several devices at the same time, which it appears might be the case from your [other question]. That said, if there's any time at which you're sending 0 V to a device, that is time you could be spending sending a non-0 V signal to another device.

For example, holding Z at +5 V and cycling the signal outputs through Y0-Y3 quickly will give you what's effectively a +5 V PWM with 25% duty cycle on Y0-Y3. In some cases, this technique can be useful.

Oh, one additional note: this example controls just one multiplexer; you can easily control two with two sets of selector pins, but this starts to use up a lot of pins. Instead, you may wish to have one set of selector pins on the Arduino hooked up to _both_ your muliplexors (and one I/O pin hooked up to both Zs) and use two more Arduino pins to control the Ē on each mux, having only one mux enabled at a time. This will save you three pins, at the cost of some complexity, but it's a good exercise to see if you really understand multiplexing technique since it's a straightforward extension of what you're doing with a single mux.

[product link]: http://bildr.org/2011/02/cd74hc4067-arduino/

[Octopart]: https://octopart.com
[list of parts]: https://octopart.com/search?q=cd74hc4067
[TI product page]: https://www.ti.com/product/cd74hc4067/technicaldocuments?HQS=TI-null-null-octopart-df-pf-null-wwe

[datasheet]: http://datasheet.octopart.com/74HC4067DB,112-Philips-datasheet-11553400.pdf
[high impedance]: https://en.wikipedia.org/wiki/Three-state_logic
[other question]: https://arduino.stackexchange.com/questions/36856/


body:
After reading your github page, I came to realize that:

1. you do not require full color control, but only setting the strips to
   full red or full blue
2. you are using MOSFETs for driving them.

Given these conditions, I believe the project may be feasible with your
current setup. The trick is that MOSFETs have some gate capacitance: if
you set the gate either HIGH or LOW, and then disconnect it, it will
keep that state for some time, until the charge stored in the gate
leaks. This means you do not need to address each MOSFET _continuously_:
you can just periodically “refresh” them, and let the gate capacitance
“remember” the state between refreshes. This is similar to how DRAM
memory works.

I wrote the following code based on this idea. Note that I did not test
it, as I do not have the required hardware. It uses a timer interrupt
firing every 1024 µs to cycle through the ten used mux channels:
each channel gets then refreshed every 10.24 ms. It also uses
[direct port access][] instead of `digitalWrite()`: not only it's way
faster (and you want to be fast in an ISR) but, more importantly, it
allows changing several outputs _simultaneously_. This is important in
order to avoid glitches.

    /*
     * Patterns to send to the multiplexers. bit_patterns[mux][chann] is the
     * pattern to send to the multiplexer `mux' in order to update the
     * channel `chann'. Bits 0..3 hold the channel number, bit 4 is the
     * data. The data bits are all initialized to zero.
     */
    volatile uint8_t bit_patterns[2][10] = {
        { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
        { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
    };

    /*
     * Periodically cycle through the 10 used multiplexer channels, updating
     * the MOSFETs. The TIMER0_COMPA interrupt has to be enabled for this to
     * automatically run every 1024 microseconds.
     */
    ISR(TIMER0_COMPA_vect)
    {
        static uint8_t i;            // channel index
        PORTB = bit_patterns[0][i];  // update MUX 0
        PORTC = bit_patterns[1][i];  // update MUX 1
        if (++i >= 10) i = 0;        // cycle channels
    }

    void setup()
    {
        DDRB   =  0x1f;         // set PB0..PB4 as outputs
        DDRC   =  0x1f;         // set PC0..PC4 as outputs
        TIMSK0 |= _BV(OCIE0A);  // enable TIMER0_COMPA interrupt
    }

This code relies on Timer 0 being in the standard Arduino configuration,
where it loops every 1024 µs. It also needs a specific wiring,
where each multiplexer is connected to a single AVR port, as follows:

    Arduino   multiplexers
    ----------------------
       8      S0 of MUX 0
           ...
      11      S3 of MUX 0
      12      SIG of MUX 0
      A0      S0 of MUX 1
           ...
      A3      S3 of MUX 1
      A4      SIG of MUX 1

In order to change the strip colors, you just have to update the stored
bit patterns:

    /*
     * On each of PORTB and PORTC, bits 0..3 are wired to the address select
     * pins of a multiplexer, whereas bit 4 goes to the SIG pin of the same
     * multiplexer.
     */
    const uint8_t SIG_BIT = 0x10;

    /* These are the only available colors. */
    typedef enum { BLACK, RED, BLUE, MAGENTA } color_t;

    /* Set the color of a strip. Strips are numbered from 0 to 9. */
    void set_color(uint8_t strip, color_t color)
    {
        /* Find the relevant multiplexer and channels. */
        uint8_t mux, red_ch, blue_ch;
        if (strip < 5) {
            mux = 0;
            red_ch = 2 * strip;
        } else {
            mux = 1;
            red_ch = 2 * (strip - 5);
        }
        blue_ch = red_ch + 1;

        /* Update the bit patterns. */
        if (color == RED || color == MAGENTA)
            bit_patterns[mux][red_ch] |= SIG_BIT;
        else
            bit_patterns[mux][red_ch] &= ~SIG_BIT;
        if (color == BLUE || color == MAGENTA)
            bit_patterns[mux][blue_ch] |= SIG_BIT;
        else
            bit_patterns[mux][blue_ch] &= ~SIG_BIT;
    }

The function `set_color()` assumes the following connections between the
multiplexers and the strips:

    MUX  channel    strip  color
    ----------------------------
     0      C0        0     red
     0      C1        0     blue
     0      C2        1     red
     0      C3        1     blue
                ...
     0      C8        4     red
     0      C9        4     blue
     1      C0        5     red
     1      C1        5     blue
                ...
     1      C8        9     red
     1      C9        9     blue

**Hardware considerations**

All this scheme may or may not work depending on some hardware factors
such as the gate capacitance of your MOSFETs, the leakage current of the
multiplexers when in high-impedance and the timing characteristics of
the same multiplexers. If the gate capacitance is too weak to hold the
value for 9 ms, you may want to add capacitors in parallel, maybe
something in the 100 pF range. If you add more than that, you may
also want to put resistors in series with pins 12 and A4 of the Arduino,
in order to protect them from the inrush current. But then you may also
want to slow down the scanning of the channels, which would require
configuring a timer.

[direct port access]: https://www.arduino.cc/en/Reference/PortManipulation


message:
Need Help to implement MODBUS TCP Master over Atmega32 MCU

I am doing a project where I have to interface with Fronius Solar Inverter with Atmega32 MCU over **MODBUS TCP**. I want to set the MCU as client and The inverter as Server and I have to implement two MODBUS Function only these are **READ_HOLDING_REGISTER** and **WRITE_SIGLE_REGISTER** and Function Code are **0x03** and **0x06** respectively.  I am newbie in this field and dont know about networking. Please anybody help me How can I develop the Software in C for this purpose??

The Document of Fronius Inverter for MODBUS TCP is [Fronius MODBUS TCP Datamanger][1]

  [1]: https://drive.google.com/open?id=0B7NXiG9jOGhmbFpMckJkNDFMdEE

body:
So if you want to the atmega as client this means it will start the conection and made the request for values, so translating into modbus words your atmega will be a modbus master and the solar will be a modbus slave.

first you need a way to interface the micocontroller to the tcp/ip stack. you can use an ic or arduino shield which has this ic like a w5100 or enc28j60.

then you can write a library over tcp sockets to start the comunication or change some from the arduino.

https://www.google.com.br/url?sa=t&source=web&rct=j&url=http://myarduinoprojects.com/modbus.html&ved=0ahUKEwj9zMvjiYDTAhXJkpAKHfsNBz0QFggpMAE&usg=AFQjCNEfRhDgPGJNK-IUqrUw1FXEnBcxwQ&sig2=Xs0JNEWi_F_XiPgkTQdy-w


message:
How to connect receiver in an Arduino with a motor shield?

I have an Adafruit motor shield v1 stacked on an Arduino Uno. I want to add a 433Mhz receiver to the Uno so I can control it wirelessly. However as you know the motor shield completely covers the Arduino board and all its pins, except perhaps the analog ones (it appeared to me).

So can you please suggest a way to connect the receiver if possible. I desperately need it and can't afford to buy a Mega now.

Please help asap.

body:
Adfruit Motor Shield v1 takes digital pins(D12 to D2) left only digital pins (D13,D1,D0) and all Analog pins of Arduino uno. So if you want to hookup RF receiver with Arduino then you have go this way.. connect RF Receiver output to the Digital pin D0 that is RX.

Here the schematic

[![Wiring RF receiver with Arduino][1]][1]

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


message:
MPU6050: Setting Gyro Output Range Throws of Positional Reading

I am using the MPU6050 in conjunction with an Arduino and Jeff Rowberg's i2cdev library, and my project requires that the gyro rate outputs be more precise than the default setting, which is 1/16.4 of a degree (+/-2000 deg/sec range). The gyro outputs can be changed with `mpu.setFullScaleGyroRange(uint8_t range)` for which I passed in `MPU6050_GYO_FS_500` for range to get a higher precision

In this project, I also need the YPR position, which I obtain through `mpu.dmpGetQuaternion(&q, fifoBuffer)` and `mpu.dmpGetGravity(&gravity, &q)` and `mpu.dmpGetYawPitchRoll(ypr, &q, &gravity)`.

The problem is with the new gyro output range, the YPR position changes drastically when the MPU is being rotated and slowly catches up again once the MPU is held still. I think there is an error in the filter that combines the gyro and accel data that is making the gyro to sensitive. Maybe the DMP is dividing the GYRO rate data by the default sensitivity factor (16.4) when it should be dividing by the new one (131)?

**How can I get accurate YPR readings without delay?**

Here is a screenshot of the data. The axis aren't labeled, but the x-axis represents about 16 seconds of time. The blue line is the **gyro rate data**, and the pink line is the **roll position** of the MPU. The graph shows two rotations of the MPU.
[![enter image description here][1]][1]

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

body:
Had the same problem, it appears that MPU6050 DMP code works like that once you change accelerometer and gyro scales.

Works better once you use +\-2000 deg/sec and +\-2g scaling settings.

        mpu.setFullScaleGyroRange(MPU6050_GYRO_FS_2000);
        mpu.setFullScaleAccelRange(MPU6050_ACCEL_FS_2);

The issue lies in the way "DMP" inner logic fuses data, i suppose it has "constants" that are tuned for these settings only.

In case you need both "changed settings" and "yaw\pitch\roll" data, you might want to implement sensor data fusion by yourself or use existing libs.

The easiest i may suggest would be implementing Complementary Filter.
More complex, yet accurate would be using Kalman Filter, all depends on time and patience you have to research those topics :)


message:
Using MCP23017 to control Servos

Using Servo.h it is possible to run a servo from just about any pin.....obviously the more pins the more servos...hence the question
" how can I do this with a MCP23017 ? ".
I have searched the web a fair bit but no luck.
Is there a modified Servo library out there??
It's such an obvious solution i figure it must have been done before.
Any suggestions..Thanks.

body:
> Using Servo.h it is possible to run a servo from just about any pin.....obviously the more pins the more servos...hence the question " how can I do this with a MCP23017?

The Servo library could be modified to allow toggling of GPIO pins on a MCP23017 but there are some issues with timing.

The library uses Timers and Interrupt Service Routines (ISR) to handle the pulse width. The servo pin is toggled in the ISR.

At 100 KHz (100 Kbps) I2C at least 3 bytes need to be transmitted to the MCP230017 to toggle a pin. That is approx. 300 us and not possible to do from the Servo ISR. Another execution pattern is required.

Cheers!


body:
Theoretically, yes. It would be pretty interesting to see, but running multiple servos would account for a huge amount of what you can reasonably do with your code and probably be a huge headache.

Perhaps a better solution would be to use a PWM expander like the [PCA9685][1].

  [1]: https://core-electronics.com.au/adafruit-12-channel-16-bit-pwm-led-driver-spi-interface-tlc59711.html


body:
> how can I do this with a MCP23017 ? ".

you can but it would be fairly expensive in processing power, as you need to keep track of both rising and falling edges of every channel at all times, and send the data to the chip -> may not be doable given i2c's speed limitations.

> I have searched the web a fair bit but no luck.

I wrote a variety of approaches / implementations on driving multiple servo channels off of one timer, with or without output compare, here: https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/

it will branch out to a few other variants, depending on resources available to you.


body:
For PWM, the MCP23017 would have to be software-driven.
I would suggest one of the PCA9685 boards, which give you hardware PWM (and can also provide digital pins).
These are a bit more expensive, but very easy to use, and are driven by I2C in the same way.


body:
For example...

    unsigned long long servo_timing[2]={0,0};
    int A_data=0;
    void servo_ini()
    {
      Wire.beginTransmission(0x20);
        Wire.write(0x00);      // address bank A
        Wire.write(0x00);
        Wire.endTransmission();
    }
    void servo_set(unsigned int servo_tim,bool servo_mod){
       if(servo_mod==1){
        servo_tim=map(servo_tim,0,180,200,1900);
       }
       //if(servo_vector<=0)/*lcd_tim=650;*/servo_tim=220;/0
       //if(servo_vector==1)/*lcd_tim=1400;*/servo_tim=1000;/90
       //if(servo_vector>=2)/*lcd_tim=2255;*/servo_tim=1870;/180
       if(micros()-servo_timing[0]>servo_tim)
       {
         A_data&=0b11111110;
         Wire.beginTransmission(0x20);
         Wire.write(0x12);      // address bank A
         Wire.write(A_data);
         Wire.endTransmission();
         if(micros()-servo_timing[1]>(20000-servo_tim))
         {
           A_data|=0b00000001;
           Wire.beginTransmission(0x20);
           Wire.write(0x12);      // address bank A
           Wire.write(A_data);
           Wire.endTransmission();
           servo_timing[0]=micros();
           servo_timing[1]=micros();
         }

      }
    }


body:
I succeeded in pwm (servo control) with mcp23017.
Moreover, it is 16ch.
The mcp23017 in the Arduino Library also has a wordwrite write, but the frequency still couldn't catch up.
There is no choice but to create a library by yourself and generate a pulse of 0.5msec .. 2.5msec in 20msec 50Hz to drive the servo motor.
We are currently organizing the library
thank you
https://twitter.com/chrmlinux03/status/1534834169737789441?s=20&t=EqkVXJ2v1H3i_tfZsXfjHQ

https://github.com/chrmlinux/


message:
Confusion about String handling

I am trying to execute some webbased calls, but my string keep "disappearing", and I am highly confused about why.

I can println a string directly, but if I have it in a variable, it will disappear :I

I tried googling around, but could not find a reason for it. Is it because of the curly brackets ? Is it a memory issue ?

I feel I really can't code on and juggle web calls, if I can't even handle regular string commands..

**Code:**

 Serial.println(" - CONSOLE/STRING WEIRDNESS - ");
 String message = "Testing time {0}";
 Serial.println(message);
 Serial.println(String(message));
 Serial.println("Testing time {0}");
 Serial.println(message.substring(3,6));

**Response:**

    - CONSOLE/STRING WEIRDNESS -
    (nothing)
    (nothing)
    Testing time {0}
    (nothing)

[![The code and the debugger][1]][1]

**Update**

This seems to happen whenever there is a number inside a string, it even happends with a simple string like this:

**Code:**

 Serial.println(" - CONSOLE/STRING WEIRDNESS - ");
 String message = "Testing time here is a number 0";
 Serial.println(message);
 Serial.println(String(message));
 Serial.println("Testing time here is a number 0");
 Serial.println(message.substring(3,6));

**Response:**

    - CONSOLE/STRING WEIRDNESS -
    (nothing)
    (nothing)
    Testing time here is a number 0
    (nothing)
  [1]: https://i.stack.imgur.com/Fw3nP.jpg
  [2]: https://i.stack.imgur.com/YPfRZ.png

body:
The {0} denotes an extra parameter (which you want to print), it seems you just want to print the string without any variable 'value' so you can remove the {0}.

I'm not so familiar with using {0} in C++, but in C# {0} means argument number 0 (after the initial string), since this argument is not given, probably an empty string is created ... it would be more intuitive if the compiler give an error or warning (maybe it gives a warning and you can check for it).

Also converting a string to String() does not do anything but I think it was just for debugging/checking purposes.

Also in Arduino to save SRAM space, normally it is wise to add before each string, the F function like:

    Serial.println(F("Some string to print"));

This will create a memory in Flash and will not be copied to SRAM which is normally quite scarce.

To print out arguments you can simply use multiple print commands (which does not add a new line) and the last part of the line with println, like:

    Serial.print(F("Test time: ");
    Serial.println(test_time);


body:
Give this article a read, it highlights how strings are actually stored in the Arduino memory, and explains how strings should be used.

https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/


message:
What is the correct way to create large project files?

I am currently working on a 10x10 RGB LED screen (using Neopixels from Adafruit) and my project files are starting to get rather large.
I have several different devices used in this project:

 - The LED matrix
 - A DS3232 RTC
 - An MSGEQ7 DSP chip
 - 7 push button switches

Currently i'm using separate classes for each of the devices (RTC, DSP & buttons) as well as the Adafruit GFX and Neopixel library.

What would be the best way to organize this project? Should I put the patterns for the screen in the main.ino file or should they have their own class.

Any help would be greatly appreciated, I can upload the source code if its needed.

Cheers

As a side note, I'm using "Sublime Text 3" along with Stino.

body:
Good to hear you are splitting large amount of code, it will benefit you a lot in the long run.

It's very hard to say what is best, it depends on the interaction of those patterns with other classes. Normally it is best to put them in the location where they BEST belong to, i.e. where the least association with other classes exist.

If it has a lot of interactions, maybe you should put the patterns itself in a different class.

Normally what I keep as guidelines:
- Not more than a few hundred lines in a class
- Not more than 7 (class) variables in a class
- Not more than 7 functions/methods in a class

Of course these are guide lines. If you have a lot of simple (constant) pattern definitions the file will become larger without getting more hard to understand.

Also try to think of a class to have only ONE responsibility. If you want to be serious about splitting classes or how to organize them, read about [SOLID][1].

  [1]: https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)


message:
Specific noise while using arduino ADC in free running mode

To make an oscilloscope in matlab environment, for data acquisition on arduino side, when inbuilt `analogRead()` is used, it's working fine, but with very low sampling rate, that aliasing is clearly observed. That too, non-uniform sampling. Thus listing out the drawbacks:

 1. Very slow data rate, even if, sent with 115200 baudrate,
 2. Aliasing
 3. Non-uniform sampling

[![Observed waveform, analogRead()][1]][1]

Thus, to overcome above, ADC in free running mode was used, with 16 as prescaling factor, thus 76.9KHz sampling rate (counting each ADC as 13 clock cycles). Thus, data is uniformly sampled now. Also it is quite fast, because of sampling, and is observed. The only problem now exists is, output has a specific noise. The data being sampled is 50Hz sinusoidal current waveform by current sensor ACS712. It overlays instantaneous current waveform over a bias of 2.5V. Thus, when signal is not present, a constant voltage of 2.5V is observed, thus, 512, because of mapping to 255 range.. 127. But in the case of free running mode, along with 127, 191, 63 only are observed. And it can also be seen that nearly 127 = 63*2, and 191 = 63*3. And when current waveform exists, it's highly distorted, but perceptible that it's not the previous signal of just 127, 191, 63. In the below plot, current is passed since 33.5sec.
[![Observed waveform, free running mode][2]][2]

I am unable to understand this, structured noise. What may be the reason ? I have once read, last two MSB bits get noisy at this sampling rate, but then how would 127, jump to 191. Why is 63 getting added, subtracted at each instant ?
I understand the reason for non-uniform sampling now is because of `Serial.print()`, whose interrupts are obstructing the ADC interrupts, but don't understand the reason behind the noise observed.

Following is the code uploaded in arduino. Serial data is read from matlab by `fread()` function.

    long t1=0,ts1=0,ts2=0;
    int aval=0, val=0;

    void setup() {

     TIMSK0 = 0x00;           // disable timer (causes anoying interrupts)
     DIDR0 = 0x3F;            // digital inputs disabled
     ADMUX = 0x40;            // measuring on ADC0, right adjust, AREF reference
     ADCSRA = 0xAC;           // AD-converter on, interrupt enabled, prescaler = 16
     ADCSRB = 0x00;           // AD channels MUX on, free running mode
     bitWrite(ADCSRA, 6, 1);  // Start the conversion by setting bit 6 (=ADSC) in ADCSRA
     sei();
     Serial.begin(115200);
     t1=millis();
     }

    ISR(ADC_vect)
    {
     aval = ADCL;
     aval += ADCH << 8;
    }

    void loop() {
    val = map(aval, 0, 1023, 0, 255);
    Serial.write(val);
    delay(10);
    }

  [1]: https://i.stack.imgur.com/kuBUf.png
  [2]: https://i.stack.imgur.com/4wkzE.png

body:
If you use an ISR to retrieve the ADC result, you will need to protect the read of the variable. An interrupt may occur when reading `aval` in the `loop()`, as this is a 16-bit value and the read requires several instructions. This may give corrupt values.

    void loop() {
      noInterrupts();
        val = aval;
      interrupts();
      val = map(val, 0, 1023, 0, 255);
      Serial.write(val);
      delay(10);
    }

Cheers!


body:
Not sure what "structured noise" you are referring to but some advices.

1. Check the datasheet to see adc timing requirement. When not enough time is given, acc results are highly correlated serially.

2. In the acc isr, make sure that atomicity is preserved.

3. Isr has its overhead so make sure that it is consistent with your acc speed setting.

4. If you are using only the msb. You can configure the acc to be left alighened, saving you lots of time and headache.