body:
I have been trying to make a communication with my industrial drive. All I want to do is read a few values of drive, like current, voltage etc.
For that I am using a library:

I don't understand why it's happening. When the same code I have used before and the sketch was uploaded on the board, very well.

Here's the code from an example:

    #include <SimpleModbusMaster.h>

    // led to indicate that a communication error is present
    #define connection_error_led 13

    //////////////////// Port information ///////////////////
    #define baud 9600
    #define timeout 1000
    #define polling 200 // the scan rate

    // If the packets internal retry register matches
    // the set retry count then communication is stopped
    // on that packet. To re-enable the packet you must
    // set the "connection" variable to true.
    #define retry_count 10

    // used to toggle the receive/transmit pin on the driver
    #define TxEnablePin 2

    // This is the easiest way to create new packets
    // Add as many as you want. TOTAL_NO_OF_PACKETS
    // is automatically updated.
    enum
    {
      PACKET1,
      PACKET2,
      // leave this last entry
      TOTAL_NO_OF_PACKETS
    };

    // Create an array of Packets for modbus_update()
    Packet packets[TOTAL_NO_OF_PACKETS];

    // Create a packetPointer to access each packet
    // individually. This is not required you can access
    // the array explicitly. E.g. packets[PACKET1].id = 2;
    // This does become tedious though...
    packetPointer packet1 = &packets[PACKET1];
    packetPointer packet2 = &packets[PACKET2];

    // The data from the PLC will be stored
    // in the regs array
    unsigned int regs[9];

    void setup()
    {
      // read 3 registers starting at address 0
      packet1->id = 2;
      packet1->function = READ_HOLDING_REGISTERS;
      packet1->address = 0;
      packet1->no_of_registers = 3;
      packet1->register_array = regs;

      // write the 9 registers to the PLC starting at address 3
      packet2->id = 2;
      packet2->function = PRESET_MULTIPLE_REGISTERS;
      packet2->address = 3;
      packet2->no_of_registers = 9;
      packet2->register_array = regs;

      // P.S. the register_array entries above can be different arrays

      // Initialize communication settings etc...
      modbus_configure(baud, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS);

      pinMode(connection_error_led, OUTPUT);
    }

    void loop()
    {
      unsigned int connection_status = modbus_update(packets);

      if (connection_status != TOTAL_NO_OF_PACKETS)
      {
        digitalWrite(connection_error_led, HIGH);
        // You could re-enable the connection by:
        //packets[connection_status].connection = true;
      }
      else
        digitalWrite(connection_error_led, LOW);

      // update the array with the counter data
      regs[3] = packet1->requests;
      regs[4] = packet1->successful_requests;
      regs[5] = packet1->total_errors;
      regs[6] = packet2->requests;
      regs[7] = packet2->successful_requests;
      regs[8] = packet2->total_errors;
    }

Also, here is the error I am receiving upon uploading the sketch

    This report would have more information with
      "Show verbose output during compilation"
      enabled in File > Preferences.
    Arduino: 1.0.6 (Windows 7), Board: "Arduino Uno"
    SimpleModbusMasterExample:110: error: 'packetPointer' does not name a type
    SimpleModbusMasterExample:111: error: 'packetPointer' does not name a type
    SimpleModbusMasterExample.ino: In function 'void setup()':
    SimpleModbusMasterExample:120: error: 'packet1' was not declared in this scope
    SimpleModbusMasterExample:127: error: 'packet2' was not declared in this scope
    SimpleModbusMasterExample:136: error: invalid conversion from 'int' to 'HardwareSerial*'
    SimpleModbusMasterExample:136: error: invalid conversion from 'Packet*' to 'unsigned char'
    C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h:143: error: too few arguments to function 'void modbus_configure(HardwareSerial*, long int, unsigned char, long int, long int, unsigned char, unsigned char, Packet*, unsigned int, unsigned int*)'
    SimpleModbusMasterExample:136: error: at this point in file
    C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h: In function 'void loop()':
    C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h:125: error: too many arguments to function 'void modbus_update()'
    SimpleModbusMasterExample:143: error: at this point in file
    SimpleModbusMasterExample:143: error: void value not ignored as it ought to be
    SimpleModbusMasterExample:155: error: 'packet1' was not declared in this scope
    SimpleModbusMasterExample:158: error: 'packet2' was not declared in this scope

title: Arduino throwing error while using modbus RS485 code

Answers: 1

body:
The code you are using is the example provided with the SimpleModbusMaster library found on GitHub: [https://github.com/angeloc/simplemodbusng][1]

It appears that the SimpleModbusMaster library isn't installed. This can happen if you install a new version of the Arduino IDE.

To install this library:

 1. Go to the link above and download the zip of the code.
 2. Extract the contents and then copy the folder "SimpleModbusMaster".
 3. Paste the folder into the Arduino/libraries folder located on your computer.  (On my computer it is: `C:\Program Files (x86)\Arduino\libraries`).
 4. Restart the  Arduino IDE. You can go straight to the example code by selecting: `File > Examples > SimpleModbusMaster > SimpleModbusMasterExample`

This procedure compiled for me with no errors.

  [1]: https://github.com/angeloc/simplemodbusng


body:
I have successfully setup up a RFID reader with Arduino Uno and EM-18 Card Reader Module.

Its program for Arduino is below:

    int count = 0; // count = 0

    char input[12];                                         // character array of size 12

    boolean flag = 0;                                       // flag =0

    void setup()
    {
       Serial.begin(9600);                                  // begin serial port with baud rate 9600bps
    }

    void loop()
    {
       if(Serial.available())

    {

    count = 0;

    while(Serial.available() && count < 12)          // Read 12 characters and store them in input array

    {
    input[count] = Serial.read();
    count++;
    delay(5);
    }

    //Serial.print("Card ID - ");

    Serial.print(input);      // Print RFID tag number

    }

    }

But when try to read the code over serial in the program for locking/unlocking mouse in Processing the values of strings don't match.
Hence the mouse doesn't get unlocked.

The program for processing is as below:

    import processing.serial.*;
    import java.awt.AWTException;
    import java.awt.Robot;

    Robot robot;
    boolean locked = false;
    Serial port;
    void setup()
    {
      println(Serial.list()); //Prints available ports

      port = new Serial(this, Serial.list()[36], 9600); //Chooses the first available port
      try
      {
        robot = new Robot(); //Creates robot
      }
      catch (AWTException e)
      {
        e.printStackTrace();
      }
    }

    void draw()
    {
      if (locked == true) robot.mouseMove(0, 0); //If locked, moves mouse to top left corner
      while (port.available() > 0)
      {
        String input = port.readString();
        //println(input);
        if (input.equals("11006F26DC84") == true) locked = false; //If it read my card it will unloack.
      }
    }

    void keyPressed ()
    {
      if (key == 'l')
      {
        locked = true; //Locks it
      }

      if (key == 'u')
      {
        locked = false; //Unlocks it
      }

      if (key == ESC)
      {
        key = 0; //Disables escape as quit
      }
    }

Please point the incorrect syntax and suggest correct one.

title: Read RFID Card Number in Processing over Serial

Answers: 1

body: `input` has to be 13 characters in size; you forgot to include a byte for the null-terminator. Then right before `Serial.print(input)`, you write `input[12] = 0`. Also the argument to `string.equals()` should be a String as well; you must write the statement like this: `input.equals(String("11006F26DC84"));`


body:
Trying to latch a 200 mS, LOW event to log the event.  LOW only occurs when external Watchdog timer sends reset pulse to the Arduino.

Is a D Latch suitable for this application?  It has been years since my digital class; help most appreciated.

How would you proceed?

title: How to latch a 200mS LOW pulse?

Answers: 1

body:
I understand your question to be :  you want to latch (and indicate) whenever an external watchdog timer has reset your Arduino.

D type flip flop (latch) can be used.  You would use the clock input as the trigger. However, most D types clock on a rising edge. You could use an inverter on the input to the clock to get the D type to clock on a falling edge. You would also connect the D (Data) input high (logic 1). Then when your input (event) goes low, the Q output will latch high.  The 200 mS is irrelevant because the latch ocurrs at the change from high to low (low to high on clock input).

You would also need a means of resetting the latch, which many D types have a reset input or a clear input.

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

You could also use a more simple SR latch (set reset latch) using 2 Nand gates.  SR latch changes state when the “set” input goes low (providing that R input was high).  Make the R input go low to reset the latch.

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

POSSIBLE ALTERNATIVE :  If you have some means of operator intervention (or even a switch).  You could have your program light an LED at startup.  Operator (person) could reset LED.  Then afterwards,  any reset (restart of program) would light the LED.

  [1]: https://i.stack.imgur.com/iLDH3.jpg
  [2]: https://i.stack.imgur.com/nAjFT.jpg


body:
I am building a motion following robot. It has two PIR sensors on the left and right. It has an ultrasonic sensor in the front. When either of the PIR sensors detect motion then it turns to that side.

When both the PIR sensors sense motion then I calculate the distance first( with the ultrasonic sensor, if distance <= 50 cm and > 5 cm then the robot moves forward. But it could mean that the motion is either in the front or in the back. Thus, my robot moves forward even the motion is behind it.

 I need some help devising a method so that when motion is detected behind then the robot will turn back. I tried making the robot turn right when both the sensors detect motion, then it will turn towards the left(i.e. front) or right(i.e. back). But in reality this method is not so practical as it would to a lot of confusion when the intruder we are trying to detect is still in motion. Plz help. A sample sketch would help.

title: Detecting Motion behind a robot

Answers: 1

body:
This is a basic problem of only having two sensors.  There is no way that two sensors of this simple type (some motion yes/no) can be used to work out where the motion comes from except when there is a difference between the two sensors.  Anything else is, and always will be, ambiguous.

If you think of it as a circle divided in two, you have only three possible conditions:

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

That is, *left*, *right* or *somewhere*.  Not ideal.

So you need more data to be able to make a decision.  That means more sensors.  The ideal scenario is four sensors - left, right, front and rear.  That gives you many possible scenarios, including:

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

As you can see from that you have a full 360° idea of where the motion is. You can even know how far to the left it is by if the front or rear is also on.  For instance, using sailing terminology, those 8 circles would mean (in order):

1. Motion on the left beam
2. Motion on the port bow
3. Motion dead ahead
4. Motion on the starboard bow
5. Motion on the starboard beam
6. Motion on the starboard quarter
7. Motion dead astern
8. Motion on the port quarter

Also the dead-ahead and dead-astern could be indicated by just the forward or rear sensor on and the left/right sensors both off.  You could even use that fact to give some indication of the distance of the motion depending on the angular coverage of the different sensors.

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


body:
I am newbie, I need to measure precise voltage in range 0.00-0.80V, two digits precision.

The voltage will not be greater than 1V-1.2V.

I wonder if I need divider or not, I am sure that voltage won't rise above 1.2V.

Can I connect the point to measure directly to analog input, or I still need to use divider? Please explain why.

title: Precision voltmeter using Arduino

Answers: 1

body:
A divider is used to (as the name suggests) reduce a higher voltage to a lower voltage.  Using a divider on a small voltage will only make it smaller and harder to measure.

To get the most out of your measuring you need to have the *reference* voltage as close to the highest voltage you want to measure as possible.  The highest voltage that can be applied is not dependent on the reference voltage, but the supply voltage, and as 1.2V is way less than 5V (or 3.3V on a 3.3V board) you have no worries there.

So you need to change the reference voltage - the voltage that the ADC uses as its upper *measurement* voltage.  That's simple enough, since many of the Arduino boards include an internal 1.1V analog reference voltage generator that you can switch to (see: [analogReference()](https://www.arduino.cc/en/Reference/AnalogReference))

So when you have switched to the 1.1V analog reference the ADC is capable of measuring 0-1.1V in 1024 steps.  That's 1.1/1023=0.00107V per bit of precision.

The formula is:

    V = ADC / 1023 * Vref

So a reading of 1 would give you 0.00107V - a reading of 2 would be 0.00215V, etc.  That's plenty of resolution to meet your 2 decimal places requirement.

***One thing to note*** though is that the internal 1.1V reference isn't that stable or accurate (or not even there on some chips).  If you need better stability and accuracy then it could pay to use an external voltage reference chip.  These are like a linear voltage regulator but are far more accurate and stable (and can't provide lots of current).  Pick one that is greater than your upper measurement voltage but as close to it as you can get (so just above 0.8V) and feed the output into the external *ARef* pin and switch the analog reference to the `EXTERNAL` mode.

You *could* use a voltage divider on the external ARef pin to provide a low reference voltage, but the stability and accuracy will be no better (and probably worse) than the internal 1.1V voltage reference, so there really is no point.


body:
How do I rectify this error?
Clearly it says there is some error in the library, so how do I correct it?

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:1: error: expected unqualified-id before 'if'

title: SoftwareSerial library

Answers: 2

body:
As you haven't shown the code that produces the error when it's compiled, I can't say for sure what the problem is.  However, here are links to three instances of the same error:

• *[error: expected unqualified-id before 'if'](https://stackoverflow.com/q/8690446)* on stackoverflow

• *[Arduino: error: expected unqualified-id before 'if' (using ping sensor)](https://stackoverflow.com/q/14538210)*, also on stackoverflow

• *[error: expected unqualified-id before 'if'](http://forum.arduino.cc/index.php?topic=26465.0)* on arduino.cc.

In each case, the problem was due to executable code (as opposed to declarations) appearing outside of a function.  You may have put some executable statements outside of `loop()` or `setup()`, etc.

body:
Your copy of the SoftwareSerial library has become corrupted. Why is anyone's guess: maybe your hard drive is dying?

Replacing the file with a good copy will solve the problem. The simplest way to do that is to reinstall the IDE.


body:
I am trying to get this pH project working and I've noticed that the serialEvent3 never sets the boolean value sensor_string_complete to true.  I am not sure if it is actually capturing the values from the probe.  What I want is for every loop through it should grab a pH value and that is not happening right now.  Most times through the loop the serial3 port is not providing any values.  Here is my code:

    String sensorstring = "";
    boolean sensor_string_complete = false;
    float pH;

    void setup() {
      Serial.begin(38400);
      Serial3.begin(38400); // pH stamp
    }

    void serialEvent3() {                                 //if the hardware       serial port_3 receives a char
      sensorstring = Serial3.readStringUntil(13);         //read the string until we see a <CR>
      sensor_string_complete = true;                      //set the flag used to tell if we have received a completed string from the PC
    }

    void loop() {
      getPh();
      if (sensor_string_complete == true) readph();
    }

    void getPh() {
      Serial.println("we are here");
      Serial3.print("r");
      Serial3.print(13);
    }

    void readph(){
      Serial.println("read ph here");
      if (isdigit(sensorstring[0])) {
        pH = sensorstring.toFloat();
        Serial.println(pH);
      }
      else{
        Serial.println(sensorstring);
      }

      sensorstring = "";
      sensor_string_complete = false;
    }

This returns values such as
we are here
we are here
we are here
read ph here
7.0
we are here
read ph here
7.0
we are here
we are here
we are here
read ph here
7.0

I want this to return these values every loop.  I expect to see:
We are here
read ph here
7.0
We are here
read ph here
7.0

Any help on this would be great.  Thanks so much!

title: Atlas Scientific pH project - serialEvent3 problems

Answers: 1

body:
On a typical Arduino, the delay between `loop()` ending and `loop()` running again is a few microseconds.  `Serial.println()` in `getPh()` is interrupt-driven so that call too takes only a few microseconds.  Writing two bytes with `Serial3.print()` at 38400 bps will take about half a millisecond.  In short, there is plenty of time for `loop()` to run several times before  `serialEvent3()` sets `sensor_string_complete`.

To call  `getPh()` once and `readph()` once per `loop()`, instead of

    if (sensor_string_complete == true) readph();

say

    while (!sensor_string_complete) {}
    readph();

This will stall the loop while the pH sensor takes and reports a reading.

Note, in `getPh()` instead of using two separate `Serial3.print()` statements, you can just say `Serial3.print("r\r")`.


body:
I have a project that involves sending messages from an Android device to an Arduino using a bluetooth module. I am using an HC-05 bluetooth module and an Arduino Mega 2560.

It works as long as I power the Arduino to my laptop using a USB cable. However, I need to use an external power source and have been using a 6F22 9V battery connected through the VIN pin for this purpose, without facing any problems. But on connecting the HC-05, it does not even light up.

The Arduino is also connected to four dc motors, five servo motors (all of which are externally powered, only get digital signals from the Arduino), and seven HC-SR04 ultrasound sensors, whcih are powered through the 5V pin.

I have connected the HC-05 to the Arduino as follows:

HC-05   Arduino

VCC      3.3V

GND      GND

TX       RX

RX       TX           through a voltage divider

I am new to all this, and would be grateful for any help. Thank you.

title: Using Bluetooth module HC-05 when Arduino is powered using a battery

Answers: 1

body:
6F22 (PP3) batteries are among the wimpiest of batteries available.  They are not a good choice for anything except extreme low power applications, and anything involving radio transmitters is definitely not an extreme low power application.

Use a better battery.  I would recommend 6 AA batteries (you can get 6xAA battery holders with the same connector as a PP3 battery) which will give you considerably more power than a little PP3.

Either that or a 7.2V "2S" Li-Ion battery pack.


body:
I am trying to build an oscilloscope using an Arduino Due and an LCD. I have the LCD running perfectly and started working on using the ADC peripheral to sample signals. Here's what I have so far:

    #define SAMPLE_BUFFER_SIZE 800
    volatile int sample_buffer[SAMPLE_BUFFER_SIZE];
    volatile bool sample_buffer_full = 0;
    volatile int sample_buffer_idx = 0;

    void adcm_init() {
        pmc_enable_periph_clk(ID_ADC); // To use peripheral, we must enable clock distributon to it
        adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST); // initialize, set maximum posibble speed
        adc_disable_interrupt(ADC, 0xFFFFFFFF);
        adc_set_resolution(ADC, ADC_12_BITS);
        adc_configure_power_save(ADC, 0, 0); // Disable sleep
        adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1); // Set timings - standard values
        adc_set_bias_current(ADC, 1); // Bias current - maximum performance over current consumption
        adc_stop_sequencer(ADC); // not using it
        adc_disable_tag(ADC); // it has to do with sequencer, not using it
        adc_disable_ts(ADC); // deisable temperature sensor
        adc_disable_channel_differential_input(ADC, ADC_CHANNEL_7);
        adc_configure_trigger(ADC, ADC_TRIG_SW, 1); // triggering from software, freerunning mode
        adc_disable_all_channel(ADC);
        adc_enable_channel(ADC, ADC_CHANNEL_7); // just one channel enabled
        adc_enable_interrupt(ADC, ADC_IER_DRDY);            // Data Ready Interrupt Enable
        NVIC_EnableIRQ(ADC_IRQn);
        adc_start(ADC);
    }

    void ADC_Handler(void)  {
        if (!sample_buffer_full) {

            if ((adc_get_status(ADC) & ADC_ISR_DRDY) == ADC_ISR_DRDY) {

                sample_buffer[sample_buffer_idx] = adc_get_latest_value(ADC);
                sample_buffer_idx++;

                if (sample_buffer_idx == SAMPLE_BUFFER_SIZE) {
                    sample_buffer_full = 1;
                    sample_buffer_idx = 0;
                }
            }
        }
    }

    void setup()
    {
        adcm_init();
        Serial.begin(115200);
    }

    void loop() {
        Serial.print("Loop\n");
        if (sample_buffer_full) {
            for (int i = 0; i < SAMPLE_BUFFER_SIZE; i++) {
                Serial.print(sample_buffer[i]);
                Serial.print(" ");
            }
            Serial.print("\n");
            sample_buffer_full = 0;
        }
    }

This was copied and slightly modified from somewhere on the internet (can't remember where, though). I have also studied the docs and this code seems to make perfect sense and it should work.

The idea is for the sampling to be interrupt-based. However, if I set the ADC to freerunning mode and enable interrupts, it just gives up and stops working.

What I mean by that is: on my serial monitor, after pressing reset, all I see are 2 lines saying "Loop" and it just stops there. Normally it should print "Loop" indefinitely, and also print ADC values from time to time.

If I disable interrupts, "Loop" is printed indefinitely, but of course no values are shown. If I disable free-running mode, "Loop" is printed and no values are shown unless the buffer size is 1, in which case the same value is printed over and over (as expected, in that case the interrupt runs only once, right at the beginning).

The CPU clock freq. is 84Mhz, I'm going for the fastest I can get out of the ADC, so a sample is taken (and an interrupt is fired) every 1Mhz. That means 84 clock cycles per interrupt. Don't know for sure if that is enough for the rest of the program to work, but my gut tells me that's not a problem. Besides, I tried with a lower ADC clock value and it still didn't work.

Any ideas? I'm really at a loss here...

title: Arduino Due: Interrupt-based ADC hangs processing

Answers: 1

body:
In your interrupt handler, `ADC_Handler()`, you set `sample_buffer_full` when the buffer is full.  <s>I don't see anywhere in the code where  `sample_buffer_full` ever gets reset (cleared) once it's been set.</s>

While `sample_buffer_full` is set, it disables the body of the interrupt handler – ie, the handler's structure is

    if (!sample_buffer_full) { ...body of handler... }

– and in particular, prevents `adc_get_latest_value(ADC);` from occurring.  The [source code](https://android.googlesource.com/platform/external/arduino-ide/+/f876b2abdebd02acfa4ba21e607327be4f9668d4/hardware/arduino/sam/system/libsam/source/adc.c?autodive=0///) of `adc_get_latest_value();` is like

    uint32_t adc_get_latest_value(const Adc *p_adc) {
      return p_adc->ADC_LCDR;
    }

which accesses the ADC data register.  According to section 43.6.4 *Conversion Results* on page 1322 of the data sheet, Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf,

>The channel EOC bit in the Status Register (ADC_SR) is set and the DRDY is set. In the case of a connected PDC channel, DRDY rising triggers a data transfer request. In any case, either EOC and DRDY can trigger an
interrupt.
>
>Reading one of the ADC_CDR registers clears the corresponding EOC bit. Reading ADC_LCDR clears the DRDY bit and EOC bit corresponding to the last converted channel.

It appears to me that your code enables interrupts, fills a buffer, sets `sample_buffer_full`, then spins in `ADC_Handler()`.  That is, repeatedly executes `ADC_Handler()` without clearing the EOC bit.

Note, for  oscilloscope applications with a Due, I suggest using DMA buffers instead of one interrupt per conversion.  See [thread #137635](http://forum.arduino.cc/index.php?topic=137635.5), *speed of analogRead*, in forum.arduino.cc for DMA code to read one or two analog channels on a Due at one sample per microsecond.  Also see [edaboard.com/thread283843](http://www.edaboard.com/thread283843.html) and [forum.arduino.cc #186169](http://forum.arduino.cc/index.php?topic=186169.0)

*Edit note:* Although `sample_buffer_full` does get reset, that reset happens after a time-consuming for-loop.  Whether it takes some hundreds of microseconds or a few milliseconds, the for-loop is enough of a delay that at least one more conversion and interrupt will occur before `sample_buffer_full` gets cleared.  One unhandled conversion is enough to lock up the interrupt handler.  Here are some alternative approaches to consider:

• Use a circular buffer, and never stop filling it.  This is ok if you are only interested in the most recent data, rather than a complete waveform record.

• Set or reset `sample_buffer_full` as now; and remove the initial if test from the handler.  Instead, put an `if` before `sample_buffer_idx++;`, to not increment if the buffer is full.

• Turn off ADC's freerun mode.  This is a reasonable thing to do when not taking data.

• Turn off ADC's interrupt when not taking data.  Also reasonable.

• Use multiple buffers.  Reasonable, but by itself doesn't avoid the problem.

• Read the latest value every time the handler executes [for example, say `int datum = adc_get_latest_value(ADC);` as the first statement in the handler] and then only store that value in certain cases.  An easy and effective way to avoid problem.


body:
I'm new to electrical engineering and I am currently trying to make a motor turn on for one second, turn off for one second, and repeat.

I'm using an Arduino Uno's `digitalWrite()` feature to activate a transistor, allowing the external 9V battery to turn on the motor.

Although everything is responding, instead of the motor turning on and off like I want it to, it spins fast for a second, then spins slower for a second. I would like the motor to stop completely, but cannot figure out how to do that.

Here's the schematic of my circuit:

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

<!-- End schematic -->

**Code:**

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

    void loop(){
      digitalWrite(9, HIGH);
      delay(1000);
      digitalWrite(9, LOW);
      delay(1000);
    }

Why isn't the motor completely turning off?

title: Transistor slows motor instead of turning it off

Answers: 2

body:
There are multiple things wrong with your drawn schematic:

- The ground symbol is not wrong but really misleading.
- You forgot to add a flyback diode.
- You wired the load the wrong way: the load is placed between the collector and VCC, not between emitter and GND.
- The base resistor is way too high.

body:
I can't make much sense of your diagram-  but this is the correct way to do it:

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

<!-- End schematic -->

R1 is low enough that the base gets 10-15mA of drive, sufficient for a few hundred mA of motor current. D1 protects the transistor Q1 when it turns off (from the motor inductance). The emitter of the NPN transistor should be grounded and then the collector will either be near ground or at the 9V level depending on whether it is off or on.

You may have damaged the transistor you are using (due to breaking it down in reverse across the E-B junction) so I would suggest proceeding with a new one. You didn't mention it, but it probably got quite warm.


body:
I want to make a MP3 player with arduino. My problem is what board should I use? There is the SparkFun MP3 Player Shield, SparkFun Audio-Sound Breakout - WTV020SD. Then I want to attach a 2.8 TFT touch screen to control volume,change track etc. Can I attach it to for example on top of MP3 player shield?I'm thinking in this one https://www.adafruit.com/products/1651. And finally what speakers can I use with which board? I want some good small speakers, two to be exact.

I don't really need help with electronics and programming. Just need to know wich are the best components that can work with each other without spending a lot of money. Thank you.

Best Regards

title: Arduino MP3 Player

Answers: 2

body:
I would recommend you the [VS1003][1] chip ($2.30 on ebay) or module ($7 on ebay). It can play MP3, WMA, MIDI, WAV and can record and encode ADPCM. It's even programmable (own filters etc). See [this project][2].

  [1]: http://www.vlsi.fi/fileadmin/datasheets/vs1003.pdf
  [2]: http://arduino-cool.blogspot.com/2012/10/arduino-mp3-player-i.html

body:
I would recommend you do not use speakers but instead send the output to a 3.5mm stereo plug, so you can use headphones or speakers.

Is a 2.8" inch display really necessary?  You could probably get away with a 1" display and at a guess that would use less power.

Another idea may be to look at a Bluetooth interface for sending the sound to the headphones or speakers.

You could also look at a WIFI interface to provide additional control interface and to allow downloads straight to the device.  (ESP8266 would probably be the easiest interface).

Something you didn't mention was the power source.  Are you going to have internal batteries with a USB charging and power socket, so you can hook it to a PC or Batter Pack.


body:
    void GravaFicheiros(CONFERENCIA *co)
    {

     int i, ii, iii;

     FILE *fp;

     fp = fopen("grabameisso", "wt");

     fprintf (fp, "%s\n", co->nomeconf);

     int k = NSessoes(co);
     fprintf (fp, "%d\n", k);

     for (i = 0; i < k; i++)
     {

      fprintf (fp, "%s\n%d\n%d\n", co->sessoes[i].tema, co->sessoes[i].hora, co->sessoes[i].auditorio);

      int a = NArtigos(co, i);

      fprintf (fp, "%d\n", a);

      for (ii = 0; ii < a; ii++)
      {

       fprintf (fp, "%s\n", co->sessoes[i].artigos[ii].titulo);

       int aa = NAutores(co, i, ii);

       fprintf (fp, "%d\n", aa);

       for (iii = 0; iii < aa, iii++)
       {

        fprintf (fp, "%s\n%d\n", co->sessoes[i].artigos[ii].autores[iii].nome, co->sessoes[i].artigos[ii].autores[iii].idade);
       }
      }
     }

     fclose(fp);
     return;

title: c expected ; before ) token

Answers: 1

body:
Although you didn't ask a specific question I assume you want to know why there was an error in your code.

One of your for loops is missing a semi-colon.

>     for (iii = 0; iii < aa, iii++) //this line gives the error

Should be:

     for (iii = 0; iii < aa; iii++) //the comma should be a semi-colon

When it says ; expected before token ). It means quite literally that there is a ; missing before a ).


body:
Is it possible to connect more than one or to be specific 5 MPU9250 into 1 Arduino lilypad? How will I set the addresses, and where should I put the pins for SDA and SCL? I hope someone out there could help me on this project.

Cheers!

What if I have this working codes, how will I edit this to connect more than two MPU9250? Please guide me. Thanks.

     #include <Wire.h>
     #include <TimerOne.h>

     #define    MPU9250_ADDRESS            0x68

     #define    MAG_ADDRESS                0x0C

     #define    GYRO_FULL_SCALE_250_DPS    0x00
     #define    GYRO_FULL_SCALE_500_DPS    0x08
     #define    GYRO_FULL_SCALE_1000_DPS   0x10
     #define    GYRO_FULL_SCALE_2000_DPS   0x18

     #define    ACC_FULL_SCALE_2_G        0x00
     #define    ACC_FULL_SCALE_4_G        0x08
     #define    ACC_FULL_SCALE_8_G        0x10
     #define    ACC_FULL_SCALE_16_G       0x18

     // This function read Nbytes bytes from I2C device at address Address.
    // Put read bytes starting at register Register in the Data array.
    void I2Cread(uint8_t Address, uint8_t Register, uint8_t Nbytes, uint8_t*      Data)
    {
    // Set register address
    Wire.beginTransmission(Address);
    Wire.write(Register);
    Wire.endTransmission();

    // Read Nbytes
    Wire.requestFrom(Address, Nbytes);
    uint8_t index=0;
    while (Wire.available())
    Data[index++]=Wire.read();
    }

    // Write a byte (Data) in device (Address) at register (Register)
    void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data)
    {
    // Set register address
    Wire.beginTransmission(Address);
    Wire.write(Register);
    Wire.write(Data);
    Wire.endTransmission();
    }

    // Initial time
    long int ti;
    volatile bool intFlag=false;

    // Initializations
    void setup()
    {
    // Arduino initializations
    Wire.begin();
    Serial.begin(115200);

    // Set accelerometers low pass filter at 5Hz
    I2CwriteByte(MPU9250_ADDRESS,29,0x06);
    // Set gyroscope low pass filter at 5Hz
    I2CwriteByte(MPU9250_ADDRESS,26,0x06);

    // Configure gyroscope range
    I2CwriteByte(MPU9250_ADDRESS,27,GYRO_FULL_SCALE_1000_DPS);
    // Configure accelerometers range
     I2CwriteByte(MPU9250_ADDRESS,28,ACC_FULL_SCALE_4_G);
     // Set by pass mode for the magnetometers
     I2CwriteByte(MPU9250_ADDRESS,0x37,0x02);

     // Request continuous magnetometer measurements in 16 bits
     I2CwriteByte(MAG_ADDRESS,0x0A,0x16);

     pinMode(13, OUTPUT);
     Timer1.initialize(10000);         // initialize timer1, and set a 1/2   second period
     Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt

     // Store initial time
     ti=millis();
     }

     // Counter
     long int cpt=0;

     void callback()
      {
      intFlag=true;
      digitalWrite(13, digitalRead(13) ^ 1);
      }

      // Main loop, read and display data
      void loop()
      {
      while (!intFlag);
      intFlag=false;

      // Display time
      Serial.print (millis()-ti,DEC);
      Serial.print ("\t");

       // _______________
      // ::: Counter :::

       // Display data counter
      //  Serial.print (cpt++,DEC);
     //  Serial.print ("\t");

      // ____________________________________
      // :::  accelerometer and gyroscope :::

     // Read accelerometer and gyroscope
     uint8_t Buf[14];
     I2Cread(MPU9250_ADDRESS,0x3B,14,Buf);

     // Create 16 bits values from 8 bits data

    // Accelerometer
    int16_t ax=-(Buf[0]<<8 | Buf[1]);
    int16_t ay=-(Buf[2]<<8 | Buf[3]);
    int16_t az=Buf[4]<<8 | Buf[5];

    // Gyroscope
    int16_t gx=-(Buf[8]<<8 | Buf[9]);
    int16_t gy=-(Buf[10]<<8 | Buf[11]);
    int16_t gz=Buf[12]<<8 | Buf[13];

     // Display values

    // Accelerometer
    Serial.print (ax,DEC);
    Serial.print ("\t");
    Serial.print (ay,DEC);
    Serial.print ("\t");
    Serial.print (az,DEC);
    Serial.print ("\t");

    // Gyroscope
    Serial.print (gx,DEC);
    Serial.print ("\t");
    Serial.print (gy,DEC);
    Serial.print ("\t");
    Serial.print (gz,DEC);
    Serial.print ("\t");

    // _____________________
    // :::  Magnetometer :::

    // Read register Status 1 and wait for the DRDY: Data Ready

    uint8_t ST1;
    do
    {
     I2Cread(MAG_ADDRESS,0x02,1,&ST1);
    }
    while (!(ST1&0x01));

    // Read magnetometer data
    uint8_t Mag[7];
    I2Cread(MAG_ADDRESS,0x03,7,Mag);

    // Create 16 bits values from 8 bits data

    // Magnetometer
    int16_t mx=-(Mag[3]<<8 | Mag[2]);
    int16_t my=-(Mag[1]<<8 | Mag[0]);
    int16_t mz=-(Mag[5]<<8 | Mag[4]);

    // Magnetometer
    Serial.print (mx+200,DEC);
    Serial.print ("\t");
    Serial.print (my-70,DEC);
    Serial.print ("\t");
    Serial.print (mz-700,DEC);
    Serial.print ("\t");

    // End of line
    Serial.println("");
    //  delay(100);
     }

title: How to use Multiple MPU9250 to Arduino Lilypad

Answers: 4

body:
According to [the datasheet](https://moderndevice.com/wp-content/uploads/2014/09/PS-MPU-9250A-01.pdf) the MPU-9250 can work in either I2C or SPI mode.

When it is in SPI mode you can connect up as many MPU-9250s as you have spare IO pins.  With SPI the clock and data lines are all shared, and each slave device has its own Slave Select line.

In I2C mode it is possible to only use 2 devices at once - the AD0 pin configures which is which device (connect it to GND or VCC to identify the two devices).

Interestingly the MPU-9250 does include an I2C master module for connecting other sensors to it. Theoretically it should be possible to connect the master port of an MPU-9250 to two other MPU-9250s, and each of those could connect to a further two MPU-9250s each, and so on and so forth in a huge tree.  However the programming of such an environment would be an absolute nightmare and not something I would like to undertake.

So in summary: use SPI mode, it's simpler.

body:
> where should I put the pins for SDA and SCL?

Same as on a Uno:

* SDA is on pin A4
* SCL is on pin A5

> Can you suggest me some links that can help me learn more about SPI?

I have [an SPI page](http://www.gammon.com.au/spi) and also one about [I2C](http://www.gammon.com.au/i2c).

There is also a page about SPI on this site: https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino

If you want to use 5 devices, it sounds like Majenko's recommendation is good: Use SPI. You would share MOSI/MISO/SCK between all devices (D11/D12/D13), and give each one a separate SS (slave select) line.

body:
> Is it possible to connect more than one or to be specific 5 MPU9250 into 1 Arduino lilypad?

Yes, that is possible with both SPI and I2C. With SPI you will need MOSI(11), MISO(12), SCK(13), and CSn where CSn is CS0..CS4 are digital pins in output mode for chip select.

With I2C the following pins are needed SDA(A4), SCL(A5), and CSn. The chip select pin is connected to AD0 on the device. AD0 is used for the lowest bit in the I2C address. Addressing is achieved by connecting AD0 to CSn and keeping all high except the one that is addressed. The I2C address is the same for all access. The CSn pin defines which device will response.

The example code below uses the lower address and chip select is put low for the selected device.

    // Chip select pin device#0
    const int CS0 = 4;
    ...
    void setup()
    {
      ...
      // Initiate chip select pin for device#0
      pinMode(CS0, OUTPUT);
      digitalWrite(CS0, HIGH);
      ...
    }
    ...
    void loop()
    {
       ...
       // Select device#0
       digitalWrite(CS0, LOW);
       MPU9250_someFunction();
       digitalWrite(CS0, HIGH);
       ...
    }

> How will I set the addresses, and where should I put the pins for SDA and SCL?

SDA is connected to A4 and SCL to A5.

Using the above given example code (from the question) a rewrite of the I2Cread function could be:

    // This function read Nbytes bytes from MPU9250 device with chip select pin.
    // Put read bytes starting at register Register in the Data array.

    void MPU9250_read(uint8_t CS, uint8_t Register, uint8_t Nbytes, uint8_t* Data)
    {
      digitalWrite(CS, LOW);

      // Set register address
      Wire.beginTransmission(MPU9250_ADDRESS);
      Wire.write(Register);
      Wire.endTransmission();

      // Read Nbytes
      Wire.requestFrom(Address, Nbytes);
      uint8_t index = 0;
      while (Wire.available()) Data[index++] = Wire.read();

      digitalWrite(CS, HIGH);
    }
    ...
    // Read magnetometer data from device#3
    uint8_t Mag[7];
    MPU9250_read(CS3, 0x03, 7, Mag);

Cheers!

body:
If you use I2C, you can use an I2C multiplex chip to handle the arbitration to handle lots of MPU-9250s.  I had a setup with 6x of them going.  I did find however, that the amount of CPU time that it takes for I2C communication is high, so once you get in to that many 9250s, you don't have much CPU time left over for other things.  Using SPI is a bit trickier to get going, but it is wicked fast and also lets you take advantage of the FIFO buffer on the 9250s.

Majenko mentioned using the I2C master functionality on the 9250 to daisy chain - I had also tried that approach before I tried the I2C multiplexer.  I have to say it was a horrible experience.  When you use that I2C master function, you are actually programming the advanced functionality of the 9250 instead of using the Arduino coding in C.  Once it all starts working (if it does), it acts quite flaky.  That functionality on the chip was really designed to enable using an external magnetometer on the 6250 to get 9dof.  Any more complex use than that gets hairy with the interchip timing, and initializing on startup is also rough.

Final answer - put in the time to learn how to use the SPI bus as mentioned in some of the other answers.  Once you get through the learning curve, it can run at up to 20khz communication speed.  SPI is designed for high speed communication.  I2C is designed to be easier to use but for things with lower update rates.


body:
Could I get something like this, a 12v silicone heating pad, and vary its temperature with an arduino somehow?

http://www.banggood.com/Waterproof-Silicone-Flexible-Heating-Pad-6060MM-DC-12V-10W-p-972464.html

My grand plan is to put temperature sensors on it and make it hit a certain temperature, and make it hotter/cooler to try and reach a target temperature.

title: What could I use to vary the temperature of a Heating Pad?

Answers: 2

body:
In principle, I don't see any problems. Your heating pad uses 12V and 10W, which means it would be consuming slightly less than one amp of current. The MOSFET you linked can go up to 5A (needing a heat sink with over 1A).

You could use PWM (there are 6 pins on a Uno that can do that) to provide pulse-width modulation to control the amount of output you give to the heater.

You would, of course, need to measure the heat of the device to work out when to adjust the PWM output. You might look up using a PID algorithm to adjust the PWM output depending on the sensed heat input.

---

## References:

* [tag:pid]
* [tag:pwm]
* [tag:mosfet]
* [tag:sensors]

body:
If you want to control the temperature very accurately, try connecting a shunt resistor (value: <0.1 ohm) in series with the heater. Use an op-amp to amplify the voltage difference on its two terminals and read with Arduino the resulting value. You can calculate with it the actual current and therefore the actual resistance of the heating pad.

The value changes with temperature, you can use the resistance value to measure the surface temperature of the heating pad.


body: I'm currently working on a self-balancing robot with an Arduino Uno and a 10DOF ADXL345 sensor. Everything is going fine until I got to this PID tuning part. I've read about it several times but I'm unable to get the desired results. Can somebody give a detailed guide on PID tuning? Thank you.

title: PID tuning help

Answers: 2

body:
Maybe you can help yourself with this [tutorial][1] for PID line follower robot. I successfully tuned my PID for line following and had some success with PID for wall following with sonar.

  [1]: http://www.inpharmix.com/jps/PID_Controller_For_Lego_Mindstorms_Robots.html

body:
In real life there is no set equation to find the PID values. At best you'll get close with equations and then need to tune the parameters.

For anyone into PID loops have a read of [this][1].
I've found it to be excellent.

My advice is to:

 - only use P
 - set I & D to 0
 - get it and good as you can by trial and error
 - add I and trial it too

D is for experts really and may cause weird/undesirable jitter.

  [1]: http://controlguru.com/table-of-contents/


body:
I am trying to compile my project, but unfortunately get errors.

I created class and separated implementation and declaration (cpp file and h file)

Here they are

**sensor.h**

    #ifndef SENSOR_H
    #define SENSOR_H
    #include <stdint.h>
    #include "Arduino.h"
    // Sensor types
    enum SensorType {
      ANY_SENSOR,
      UNKNOWN_SENSOR,
      WATER_SENSOR,
      TEMPERATURE_SENSOR,
      VIBRATION_SENSOR,
      INTERCOM_SENSOR,
      HUMIDITY_SENSOR,
      PIR_SENSOR,
      SOUND_SENSOR,
      LIGHT_SENSOR
    };
    class Sensor {
      public:
      // Variables declaration
        uint32_t sensorId;
        SensorType sensorType;
        float currentValue;
        bool isEnabled;
        float criticalLowerLevel;
        float criticalUpperLevel;
       // Methods declaration
        Sensor();
        Sensor(uint32_t id,SensorType type,long currentValue,bool isEnabled,long lower,long upper);
        String toString();
        bool isCriticalLevelRised() {
          return (this->currentValue >= this->criticalUpperLevel || this->currentValue <= this->criticalLowerLevel);
        };
        void enable(bool enable);
        void toggle();
        static String convertSensorTypeToString(SensorType sensorType);
    };

    #endif

And cpp file

    #include "sensor.h"
    Sensor::Sensor()
    {
      this->sensorId = 0;
      this->sensorType = UNKNOWN_SENSOR;
      this->currentValue = 0;
      this->isEnabled = false;
      this->criticalLowerLevel = 0;
      this->criticalUpperLevel = 0;
    }
    Sensor::Sensor(uint32_t id,SensorType type,long currentValue,bool isEnabled,long lower,long upper) {
      this->sensorId = id;
      this->sensorType = type;
      this->currentValue = currentValue;
      this->isEnabled = isEnabled;
      this->criticalLowerLevel = lower;
      this->criticalUpperLevel = upper;
    }
    void Sensor::enable(bool enable) {
       this->isEnabled = enable;
    }
    void Sensor::toggle() {
      this->enable(!this->isEnabled);
    }
    String Sensor::toString()
    {
      String response = "";
      response += F("Sensor id is ");
      response += this->sensorId;
      response += '\n';
      response += F("Sensor type is ");
      response += convertSensorTypeToString(this->sensorType);
      response += '\n';
      response += F("Sensor current value is ");
      response += this->currentValue;
      response += '\n';
      response += F("Sensor isEnabled is ");
      response += this->isEnabled;
      response += '\n';
      response += F("Sensor criticalLowerLevel is ");
      response += this->criticalLowerLevel;
      response += '\n';
      response += F("Sensor criticalLowerLevel is ");
      response += this->criticalUpperLevel;
      response += '\n';
      return response;
    }
    String Sensor::convertSensorTypeToString(SensorType sensorType) {
      switch (sensorType) {
        case UNKNOWN_SENSOR:
          return F("UNKNOWN SENSOR");
        case ANY_SENSOR:
          return F("ANY_SENSOR");
        case WATER_SENSOR:
          return F("WATER_SENSOR");
        case TEMPERATURE_SENSOR:
          return F("TEMPERATURE_SENSOR");
        case VIBRATION_SENSOR:
          return F("VIBRATION_SENSOR");
        case HUMIDITY_SENSOR:
          return F("HUMIDITY_SENSOR");
        case PIR_SENSOR:
          return F("PIR_SENSOR");
        case SOUND_SENSOR:
          return F("SOUND_SENSOR");
        case LIGHT_SENSOR:
          return F("LIGHT_SENSOR");
        default:
          return F("UNKNOWN TYPE");
      }
    }

And I got following errors

    ketch/NodeIntercom.ino.cpp.o: In function `sendSensorMessageToMaster(RF24Mesh*, SensorDataMessage*, char, unsigned int, bool)':
    /home/iron/Arduino/What'sHappening/NetworkMaster/additional_functions.h:48: undefined reference to `Sensor::toString()'
    sketch/NodeIntercom.ino.cpp.o: In function `handleSetSensorDataRequest(RF24NetworkHeader*)':
    /home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:97: undefined reference to `Sensor::toggle()'
    /home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:89: undefined reference to `Sensor::enable(bool)'
    sketch/NodeIntercom.ino.cpp.o: In function `SensorDataMessage':
    /home/iron/Arduino/What'sHappening/NetworkMaster/common.h:40: undefined reference to `Sensor::Sensor()'
    sketch/NodeIntercom.ino.cpp.o: In function `__static_initialization_and_destruction_0':
    /home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:35: undefined reference to `Sensor::Sensor(unsigned long, SensorType, long, bool, long, long)'
    collect2: error: ld returned 1 exit status

What I am doing wrong ?
Please help.

**EDIT**

Yes main sketch compiles perfectly where this files are located.

But I don't want to duplicate common files in my all my arduino sketches withing the project, they are the same for whole project. Here my files location

    --ArduinoProjects
    ---NodeIntercom
    ----NodeIntercom.ino
    ---MasterNode
    ----MasterNode.ino
    ----sensor.h
    ----sensor.cpp
    ----common.h

So this files are only located in MasterNode directory

And I tried to include them like this

    #include "/home/iron/Arduino/What'sHappening/NetworkMaster/common.h"
    #include "/home/iron/Arduino/What'sHappening/NetworkMaster/additional_functions.h"

And in common.h I include sensor.h
Also tried to include directly, but still the same

But headers files included as above works perfectly.

What is the right way to solve this problem, I don't want to duplicate this class in each folder whenever I change it.

If there is no way, maybe create symbolic link (I am using linux) ?

**PARTIAL SOLUTION**

Just use symbolic links in the sketch directory and this works perfectly

title: Arduino declaring class in h and cpp file Undefined Reference

Answers: 2

body:
There is nothing wrong with that class and its code (as far as I can tell) - it compiles perfectly fine.

What is probably wrong is that the IDE isn't picking up the code and compiling it in to your project.

Is this class part of the sketch, or is it a separate library that you are writing?  If the latter you have to ensure that the IDE knows about it, and it can only look for it when you load the IDE, so if you haven't restarted the IDE since creating the library you must do that so it can find the new library.

body:
The Arduino build preprocessing cannot locate the sensor source and header files if they are located in another sketch directory. The files needs to be moved to separate directory if shared (as a library).

    --Sketchbook
    ---NodeIntercom
    ----NodeIntercom.ino
    ---MasterNode
    ----MasterNode.ino
    ---libraries
    ----Sensor
    -----Sensor.h
    -----Sensor.cpp

The Sensor header is included with

    #include <Sensor.h>

in the sketches that needs to use it.


body:
Probably something stupid, but I can't figure out how to work with these large numbers, then cast the result (which will be small) to an integer. I keep getting negative numbers, which I think means I'm overflowing somewhere.

    int freq = 440;
    int len = 256;
    long timer = 2000000.0 / (freq * len);
    int roundedTimer = int(timer);

I should get 18, but I'm getting -108...

title: Trouble with large numbers

Answers: 1

body:
`freq * long`, since they are both integers, are calculated as integers.

`440*256=112640` - in binary that is `1 1011 1000 0000 0000` and trimmed to 16 bits becomes `1011 1000 0000 0000` which is `-18432` and that is where the heart of your problem is.  Unless you explicitly say otherwise the Arduino's compiler does all calculations (except floating point) as 16-bit signed integers.

By casting the values to `long` it forces the compiler to 'overflow' the 16-bit limit and use a 32-bit limit instead:

    long timer = 2000000 / ((long)freq * (long)len);

Another alternative is to define `freq` and `len` to be `long` from the outset instead of `int`.


body:
I'm working on a Arduino-based synthesizer using [this tutorial](http://makezine.com/projects/make-35/advanced-arduino-sound-synthesis/), specifically using a wavetable and 1-bit DAC. I understand that the value for OCR2A register sets the frequency, but how do I calculate the value?

I've seen [this list of notes](http://cdn.makezine.com/make/35/OCR2A-frequency-table.pdf) which is great, but I want arbitrary frequencies in Hz...

Here's the code I'm working from:

    #include <avr/interrupt.h>

    // sinewave parameters
    #define FREQ 18
    #define PI2 6.283185    // 2*PI saves calculation later
    #define AMP 127         // scaling factor for sine wave
    #define OFFSET 128      // offset shifts wave to all >0 values

    #define LENGTH 256      // length of the wave lookup table
    byte wave[LENGTH];      // wavetable

    void setup() {

      // populate wavetable
      for (int i = 0; i < LENGTH; i++) {
        float v = (AMP * sin((PI2 / LENGTH) * i));
        wave[i] = int(v + OFFSET);
      }

      // set timer1 for 8-bit fast PWM output
      pinMode(9, OUTPUT);       // make timer’s PWM pin an output
      TCCR1B = (1 << CS10);     // set prescaler to full 16MHz
      TCCR1A |= (1 << COM1A1);  // pin low when TCNT1=OCR1A
      TCCR1A |= (1 << WGM10);   // use 8-bit fast PWM mode
      TCCR1B |= (1 << WGM12);

      // set up timer2 to call ISR
      TCCR2A = 0;             // no options in control register A
      TCCR2B = (1 << CS21);   // set prescaler to divide by 8
      TIMSK2 = (1 << OCIE2A); // call ISR when TCNT2 = OCRA2
      OCR2A = FREQ;           // set frequency of generated wave
      sei();                  // enable interrupts to generate waveform!
    }

    void loop() {
      // nothing to do here!
    }

    // called every time TCNT2 = OCR2A
    ISR (TIMER2_COMPA_vect) {   // called when TCNT2 == OCR2A
      static byte index = 0;    // points to each table entry
      OCR1AL = wave[index++];   // update the PWM output
      asm("NOP; NOP");          // fine tuning
      TCNT2 = 6;                // timing to compensate for ISR run time
    }

title: Calculate OCR2A from audio frequency

Answers: 1

body:
The equation to calculate it is given in the first article you linked:

[![From linked Makezine article "Advanced Arduino Sound Synthesis"][1]][1]

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

The 2MHz value comes from the factor of 8 prescale on the 16MHz clock and 256 is the size of the lookup table specified by your `LENGTH` define. If you start from a frequency you want to synthesize, just use the above equation to solve for the necessary value of OCR2A. Note that since you have to input integer values to OCR2A, you can't really achieve *arbitrary* frequencies, but you're certainly not locked in to the values given in the supplemental musical note PDF you reference.

So, to solve for OCR2A:

    OCR2A = TCNT2_rate / (desiredFreq * wavetableLength);


body:
As Arduino Uno has a 16 MHz oscillator but while running program it has less frequency because some of the processing power is used for running the program.
I have used the `delay(1)` but it is giving me around 500 Hz.

**My questions:**

1. Is there any way to achieve more than 500 Hz?
2. What would be the maximum frequency of digital signal for below program?

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

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

    void loop() {
      digitalWrite(13, HIGH);
      digitalWrite(13, LOW);
    }

title: Maximum frequency of digital signal in Arduino Uno?

Answers: 3

body:
1. Yes, use the hardware timers.

2. You can achieve 8 MHz.

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

Example sketch which outputs 8 MHz on pin 9 on a Uno:

    #ifdef __AVR_ATmega2560__
      const byte CLOCKOUT = 11;  // Mega 2560
    #else
      const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
    #endif

    void setup ()
      {
      // set up 8 MHz timer on CLOCKOUT (OC1A)
      pinMode (CLOCKOUT, OUTPUT);
      // set up Timer 1
      TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
      TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
      OCR1A =  0;       // output every cycle
      }  // end of setup

    void loop ()
      {
      // whatever
      }  // end of loop

If you change OCR1A you can get lower frequencies. If you change the prescaler you can get lower frequencies again.

See [my page about timers](http://www.gammon.com.au/timers) for more details.

body:
Also, don't forget that there are alternative methods of toggling outputs.

You can use PORTS to do the job.

Here's a good [example][1]. And another [here][2].

And this code is the idea behind it:

    void setup()
    {
      DDRD = B11111111; // set PORTD (digital 7~0) to outputs
    }

    void loop()
    {
      PORTD = B11111111; // set PORTD pins (digital 7~0) high
      PORTD = B00000000; // set PORTD pins (digital 7~0) low
    }

P.S. Don't forget that the port numbering is in reference to the chip pins and not the Arduino pins/legs.

  [1]: http://www.billporter.info/2010/08/18/ready-set-oscillate-the-fastest-way-to-change-arduino-pins/
  [2]: http://tronixstuff.com/2011/10/22/tutorial-arduino-port-manipulation/

body:
**Nick Gammon's** code worked fine for me. Here is an **oscilloscope picture** of the waveform I've got from **his code**:

[![Output of Arduino UNO pin 9, approximately 1 V peak-to-peak Amplitude with spikes][1]][1]

His code above (*from Nick Gammon, on Jan 25 '16 at 20:33*) worked excellent for me. I used his code on Arduino UNO and got about **7.9 MHz** of output frequency on an approximately **1 V amplitude** (peak-to-peak, with spikes making it go to about **2 V peak-to-peak amplitude**).

The image above was obtained with my 40 MHz Oscilloscope from *ICEL Manaus* (manufacturer) at pin 9 (I used the Arduino UNO), with a LED and a resistor as a load at pin 9:

 - a green LED of about 1.79 V voltage drop
 - and a 4.7 Ohms resistor with 5% tolerance

The oscilloscope probe (*Channel 2, with fall slope trigger detect*) is on the 4.7 Ohms resistor. It follows the connection order out of the pin 9 from Arduino UNO:
*PIN 9* > *green LED* > *4.7 Ohms resistor* >  *GROUND*.

The green LED keeps blinking at a normal luminescence, as compared when used at other output frequencies.

I used a external 5 V DC power supply, along with the USB connection on my PC.

If you have any questions just put them here. Thanks and thanks [Nick Gammon][2]

  [1]: https://i.stack.imgur.com/8NWfq.png
  [2]: https://arduino.stackexchange.com/users/10794/nick-gammon


body:
I'm looking for a limit switch to use with the Arduino. In my project I want to count how many times my [turntable][1] makes a full 360° rotation. An object (wheel, pipe, whatever) will be sticking out the side of the turntable and when it comes in contact with the limit switch that will be right next to the turntable, it should notify the Arduino.

Any suggestions on which limit switch I should get?

Thanks so much in advance!

  [1]: http://cdn.shopify.com/s/files/1/0220/4654/products/slider1_large.jpeg?v=1420208854

title: Recommendations for limit switches for Arduino

Answers: 2

body:
A $2 microswitch with a roller would be OK for a million revs or so.

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

You would put a little ramp on the diameter and use it to trigger the switch.

Non-contact magnetic or optical could be better for more cycles or faster operation.

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

body:
Instead of a limit switch a hall effect sensor with a moving magnet is an optimal soltuntion since it is contact less there will be no frictional side effects on your application.

But there is one more better way to it, try to use an rotary encoder, something like a 400/600 ppr should also be fine for this, doing this way you have more positional data of the turntable,

You can calculate no of turn, arcs etc.

For eg:

 1. A 400ppr would give you a resolution of 0.9 degree per pulse, and
 2. 600ppr would give you 0.6degree per pulse of accuracy.

Although you can go for even higher ppr encoders but you can get these at very low cost.

Pic from: https://m.ebay.co.uk/itm/400BM-Rotary-Encoder-Module-LPD3806-360-6mm-Shaft-Arduino-Pi-Flux-Workshop-/112607725039?_mwBanner=1

Note: Just an example, price may be different at other webites, haven't checked the price while writing this solution.
[![A 400ppr rotary encoder][1]][1]

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


body:
I am a beginner when it comes to electronics, coding and things like that (this is practically the first time I have done anything like this), so when building an application that is supposed to vibrate a vibration motor with a strength based on the distance measurement made by the ultrasonic rangefinder, I bumped up with a problem.

The MCP 41010 digital potentiometer seems to let electricity through only when it is given a SPI.transfer(128). Any other number stops the flow of electricity completely.

I have tried some addresses such as 00, 0x00, 0x01 and 0x04 to replace the 0 and the result was the same. With addresses 0x11 and 0x08 the digital potentiometer didn't react at all.

In addition to the code I have here I have tried just copy-pasting some of the tutorials I found from the internet, for example this one https://arduino.stackexchange.com/questions/4952/digital-potentiometer-not-fading-led without really understanding the commands formats thing all that well. With that code I got a vibration that didn't seem to fade in or fade out at all, so the problem remains (I lack a way to properly test that though).

So... what am I doing wrong and how to fix it?

Thank you!

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

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

Many tutorials were used when making the code.
<pre>
#include <SPI.h>

int vcc = 2; // attach pin 2 to vcc
int trig = 3; // attach pin 3 to Trig
int echo = 4; // attach pin 4 to Echo
int gnd = 5; // attach pin 5 to GND

int shortest = 250;
int longest = 12000;

int CS = 10; // for digi pot

void setup() {

  SPI.begin ();
  pinMode (vcc,OUTPUT);
  pinMode (gnd,OUTPUT);
  pinMode (CS, OUTPUT); // for digi pot
  // initialize serial communication:
  Serial.begin(9600);

}

void loop()
{
  digitalWrite(vcc, HIGH);
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(trig, OUTPUT);
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(5);
  digitalWrite(trig, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echo,INPUT);
  duration = pulseIn(echo, HIGH);

  if (duration > 200 && duration < 220)
  // Limiting out an unwanted, randomly appearing distance measurement
  // made useless by later code though
    {
     Serial.print("Error ");
     Serial.print(duration);
     Serial.print("\n");

     return;
    }

   // Compressing the result of the distance measurement into the scale of 0 - 128
  if (duration < shortest) duration = shortest;
  if (duration > longest) duration = longest;
  duration = (1.0f-((float)(duration - shortest) / (float)(longest - shortest))) * 128;

  digitalWrite(CS, LOW);
  SPI.transfer(0); // 0x01 and 0x04 seem to "work" too. With 0x11 and 0x08 no voltage goes through
  SPI.transfer(duration); // sending a number from 0 to 128 to the digital potentiometer
  digitalWrite(CS, HIGH);

  Serial.print(duration); // printing the result of the measurement and calculations
  Serial.print("\n");

  delay(100);
}
</pre>

title: Problem with a digital potentiometer application

Answers: 1

body:
Digital potentiometers are not a good choice for controlling the speed of a motor. They are designed only for very low current applications - things like setting offset points for op-amps and things like that - things where you would use a small trimmer pot rather than a large power *rheostat*.

Instead you should be controlling the motor using PWM and a transistor ([here is a good tutorial](http://www.circuitstoday.com/pwm-generation-and-control-using-arduino)).

But to help you understand the digital potentiometer and so you can work with it better:

Step one is always to read [the datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/11195c.pdf).  That details the SPI communication protocol for you so you can know what numbers mean what.

In this case the protocol is made up of two bytes - a command byte and a data byte.

The command byte is made up like this:

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

As you can see it's in two parts - a command and a potentiometer selector.  So to set the resistance of potentiometer 0 you would need to craft a command byte that had the write command and the code for potentiometer 0.  That would be `0b00010001` or 0x11 in hex.  So your transaction would look like:

    digitalWrite(CS, LOW);
    SPI.transfer(0x11);
    SPI.transfer(duration);
    digitalWrite(CS, HIGH);

Another important part of the datasheet is the electrical characteristics.  That is a table that tells you the minimum, typical and/or maximum values for different parameters.  One important one here is the *wiper current* which it states as being allowed between -1mA and +1mA.  That is the maximum current you are allowed to draw through the digital potentiometer before you risk damaging it.  That is why it's not good for powering things like motors, no matter how small.

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


body:
I'm trying to control a 4-digit 7 segment display with an Arduino Nano, but I'm getting something wrong. I'm using the ICSP header to interface with a 74HC595 Shift Register which is then connected to the display. I've tested and retested the connections and everything seems to be alright, however the shift register doesn't have the desired output, and I notice it only shifs one single bit when I press the reset button on the arduino board.

    74HC595   |    A. Nano
    DS     <-----> MOSI (ICSP)
    SH_CP  <-----> SCK (ICSP)
    ST_CP  <-----> D6
    MR     <-----> 5V (ICSP)
    OE     <-----> GND (ICSP)
    VDD    <-----> 5V (ICSP)
    GND    <-----> GND (ICSP)

My code:

    //pin connected to STCP
    const int latchPin = 6;
    //pin connected to SHCP
    const int clockPin = 17;
    //pin connected to DS (MOSI)
    const int dataPin = 11;

    byte val=0;

    void setup() {
      // put your setup code here, to run once:
      //SPI pins are output
      pinMode(latchPin,OUTPUT);
      pinMode(clockPin,OUTPUT);
      pinMode(dataPin,OUTPUT);

      pinMode(3,OUTPUT);
      updateRegister(0);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      digitalWrite(3,HIGH);
      for (int i=0; i<8; i++) {
        updateRegister();
        delay(500);
      }

    }

    void updateRegister() {
      //pull latch low to write new bits to the register
      digitalWrite(latchPin,LOW);
      //shift out the data
      shiftOut(dataPin,clockPin,LSBFIRST,val);
      //pull latch pin high so that the leds light up
      digitalWrite(latchPin,HIGH);
    }

title: Arduino Nano, ICSP header and 595 Shift register

Answers: 3

body: Do you need to add the _  to the shiftOut(dataPin,clockPin,LSBFIRST,val); ?

body:
<!-- language-all: lang-C++ -->

It is extremely confusing to have a variable `val` and then use `_val` in your function but then:

      shiftOut(dataPin,clockPin,LSBFIRST,val);

As James pointed out, you are not sending the value passed to the function, to the shift register.

Also this is just going to give you a boolean:

     updateRegister(!i);

Why take "not i" there?

---

I suggest you use SPI and not muck around with shiftOut. I have a [page about the 595 chip](http://www.gammon.com.au/forum/?id=11518) including example code. eg.

    #include <SPI.h>

    const byte LATCH = 10;

    void setup ()
    {
      SPI.begin ();
    }  // end of setup

    byte c;
    void loop ()
    {
      c++;
      digitalWrite (LATCH, LOW);
      SPI.transfer (c);
      digitalWrite (LATCH, HIGH);
      delay (20);
    }  // end of loop

body:
`const int clockPin = 17;`

I'm pretty sure that should be 13, not 17.


body: I used the example code AnalogReadSerial and tried it on all analog pins from A0 to A7. None of the analog pins were connected to anything so I expectedy to get 0 in the serial monitor. But as it turns out, I was wrong. Only pin A7 shows 0 to 19 values on the serial monitor. The rest have values ranging from 100 to 300 for pins A2, A3, A4, A5 and A6. The worst performers are A1 and A0 with values from 921 to 1023 showing on the serial monitor. What is the cause of this and how will I fix it?

title: Analog Pins are sensing Values

Answers: 2

body:
This is normal, as the unconnected pin may float from GND to VCC. You may  enable internal pull-up (to VCC). This is normal for all high-z inputs. If you read digital port you'll see that it floats too. Sometimes you can change digital I/O input value just by waving your hand above the board.

For that reason we always tie high-z inputs to something. You can leave it floating - it won't damage anything, but the value obtained from free-floating input is useless.

body:
The ADC is multiplexed across the pins, and will carry a small charge from pin to pin.  If you want them to be zero, tie them to ground.

This answer, https://arduino.stackexchange.com/a/575/6628 , suggests pulling them to ground for higher accuracy.


body:
This isn't strictly limited to Arduino but I spend a lot of time with serial devices on my Arduino and I'm sure that others do as well:

Here goes..

Let's say a device sends three characters [ABC] via serial at 9600 8N1.

And let's also say the device receiving the data only knows that it's serial stream and 8N1 but does not know the baud.

The receiving device would need to take a guess at the baud and so probably get it wrong. It would therefore receive weird characters.

Is there anyway/anything around that a user could paste the strange characters into that would reverse engineer (from the bit stream) to give the correct baud and hence correct ascii characters [ABC]?

title: Converting data between baud rates

Answers: 4

body:
I am not aware of anything like that, no.  The problem is what you are seeing as characters are a complete corruption of the data. Only some part of it may have been interpreted as a valid bit sequence, and even then you can't know what bit it was.

However, there is one magic character in UART communication: `U`

What is special about that character is its binary pattern.  It is ASCII character 85, which in HEX is 0x55, or binary it's 0b01010101.  Add to that the start and stop bits, and invert it for the UART logic (1 = LOW, 0 = HIGH) and the signal that gets sent out of the UART looks like:

    ____start_____     _____     _____     _____     _____
        |   |  0  | 1 |  0  | 1 |  0  | 1 |  0  | 1 | stop
        -----     -----     -----     -----     -----

And yes, that's a pretty good square wave.  The frequency of that square wave will be exactly half the baud rate - so a frequency of 4800Hz will be a baud rate of 9600 baud.

This effect is cleverly used for a system called [Automatic baud rate detection](https://en.wikipedia.org/wiki/Automatic_baud_rate_detection) whereby a receiver waits for a `U` character to determine the baud rate to use.  Most modern microcontrollers have this facility available.

If you can't get the frequency of a block of `U` characters you will have to examine the waveform with an oscilloscope.  It should be possible to identify the individual characters in the data stream as distinct blocks in the waveform.  From that you can then work out the width of one symbol and thus the baud rate.  It's best to use a DSO for this since you can then capture a short burst and use the markers to measure the time between different points in the waveform.  A logic analyser will also do the job quite well, and will most likely be able to decode the waveform and calculate the baud rate for you.

If you have neither of those it would be possible to program an Arduino to capture the time between transitions of an incoming signal and allow you to plot them in Excel to give you a waveform you can examine to determine the baud.

Another option is just to keep trying different baud rates (there's relatively few "standard" baud rates) until you see the right text coming in.

body:
My logic analyser has a "guess baud rate" feature, which usually is fairly accurate. If you analyse an incoming bit stream you can probably have a reasonably good guess. For example the shortest transition means the baud rate cannot be **slower** than that. For example, at 9600 baud sooner or later you will get a transition in 104 µs (ie. `1/9600`). Thus if you see that, the baud rate could not be 4800 baud.

Also, in general, there will be a gap between "packets", so in your case after the "ABC" there would be a longer gap (of all 1s). You would assume then that the active time represents an integral number of bytes (eg. 3 bytes, 8 bytes, but not 1.5 bytes).

Another thing is that baud rates are usually multiples of a power of 2 times 300 (ie. 300, 600, 1200, 2400, 4800). So this gives you a small range of possible baud rates to test. You could test (say for 9600) and see if you get reasonable results. A "reasonable result" would be a stop bit appearing 10 bits after a start bit.

See my post: https://arduino.stackexchange.com/questions/19756/how-does-serial-communications-work-on-the-arduino

body:
Try measuring pulse width and match shortest pulse against pre-defined widths corresponding to available baudrates. This way you can detect baudrate by analysing random binary stream.

Signal glitches, such as very short spikes, will be filtered out, as they will never match the list of baudrates.

Repeat the measurement few times to raise accuracy and choose the most probable value from all guessed values.

body:
In the days of dumb terminals and time sharing systems, setting the baud rate was accomplished by the terminal sending a pre-determined series of characters with gaps between them and the host changing its baud rate and looking for the expected data. It is best to start at a high baud rate and drop the rate between tries.

For example the terminal user would hit Enter repeadedly and the host would try decreasing baud rates until it saw the Carriage Return character. When it saw the CR, it would respond with "Login Please" and you would know you were good to go.


body:
I'd like the arduino to write to a file whenever an ajax call is made. The ajax works, but it doesn't write to the file. All other code inside the ajax handler does execute.

    void handle_ajax() {
     int startUrlIndex = HTTP_req.indexOf("button");
     int endUrlIndex = HTTP_req.indexOf(" HTTP");
     String url = HTTP_req.substring(startUrlIndex, endUrlIndex);
     int startButtonIndex = url.indexOf("device-") + 7;// 7 is length of device-, I really just want the number.
     int endButtonIndex = url.indexOf("&");
     String button = url.substring(startButtonIndex, endButtonIndex);
     int startStateIndex = url.indexOf("state=") + 6; // 6 is length of state=, I really just want the number.
     String state = url.substring(startStateIndex);
     int device = button.toInt();
     int newState = state.toInt();
     dim_light(device, newState * 12);
     write_config("", "text");
    }

    bool write_config(String line, String text) {
     configFile = SD.open("config.ini", FILE_WRITE);

     if (configFile) {
      configFile.write("Dipshit");
     }

     configFile.close();
     Serial.println("Works.");
     return true;
    }

title: Arduino uno not writing to file

Answers: 1

body: You have run out of RAM. Consider moving string literals into flash with thr `F()` macro.


body:
I'm planning to buy an ESP8266. Do I really need to learn Lua to play with it? I have seen some people using it with the standard Arduino IDE.

Do you need a custom firmware to use the Arduino IDE instead of Lua?

The Arduino IDE seems better for me because I already know the syntax. Is there any downside to using the Arduino IDE instead of NodeMCU with Lua?

title: ESP8266, Arduino IDE vs Lua?

Answers: 4

body:
Using the Arduino IDE *is* custom firmware. That's what you're writing. You don't *need* any new firmware because the new firmware is what you are writing.

I can't think of any downsides to using C++ to program the ESP8266 instead of Lua - in fact it can only be a benefit since you are not using an interpreted language which is going to be slower than natively compiled code.

body:
Lua, like many scripting languages, tends to make you a lot more
productive as a programmer: things become far easier as you work at a
higher abstraction level and do not worry about trivial things like
memory management. You achieve the same goals with far less lines of
code. On the other hand, whereas it makes development faster, it also
makes program execution slower. Whether this is a good trade-off or not
is very dependent on the particular application you want to write.

In your particular case, you also have to consider the fact that you do
not know Lua, and you already know both the C++ language and the Arduino
API. Then you may not rip the benefits of Lua on a single project,
because of the time needed to learn the language. You may consider
learning the language as an investment, probably worth it if you are
going to program a lot on this platform, probably _not_ worth it if it's
only for a single, simple enough project. If unsure, I suggest you take
a look at the API provided with Lua on this platform: how well does it
fit your project? Is it a significantly better fit than the Arduino API?

body:
I STRONGLY RECOMMEND TO STAY WITH THE ARDUINO IDE!

Despite programming in C++ not being as friendly and versatile as Lua (working with Esplorer is really a dream come true!), Lua is VERY UNSTABLE AND UNPREDICTABLE!!!

You can run a simple program of ten lines and it works ok for a day... two... and suddenly, on the 3rd day the chip hangs unexpectedly, and with no reason!
If you are lucky, the chip will reboot and program will start running again... that WAS NOT the case with me. I had to reload the program again! After 3 cycles like this, I decided to abandon Lua... FOREVER.

body:
Sorry for bumping, but this thread helped me to decide for Arduino IDE.

I started with Arduino IDE but couldn't get it to work with ESP-07.
Moved on to NodeMCU and Lua with Esplorer. Took me a while to get it working there also due to the odd bootloader baud rate. First it seemed so easy to set up a WEB-server, but problem was that all the examples found were based on an ancient FW 0.96, and trying with the latest 2.1 didn't work at all. So realising that people hadn't done much with newer FW gave me second thoughts.

Now with Arduino IDE things start to work the way they should! :)


body:
I have an Arduino Uno and a W5100 Ethernet Shield. I am trying to post some data from the Arduino board to the WAMP server running on my computer. I do not have a router so I have directly connected my Ethernet shield stacked onto the Arduino Uno to the laptop's Ethernet port via an Ethernet cable. I have also assigned the Ethernet connection a static IP address 192.168.0.1 and my localhost page opens when I put this address in my browser.

In my Arduino sketch I have assigned the Arduino shield an IP address 192.168.0.4, i.e. on the same IP segment. When I try to do client.connect to the server (192.168.0.1), i.e. localhost, I get "Connection failed".

    #include <SPI.h>
    #include <Ethernet.h>

    byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0x6F, 0xED };
    IPAddress ip(192,168,0,4);
    byte server[]={192,168,0,1};

    int value=9;
    EthernetClient client;

    void setup() {
      // Serial.begin starts the serial connection between computer and Arduino
      Serial.begin(9600);
      // start the Ethernet connection
      Ethernet.begin(mac,ip);
    }

    void loop() {
      // Connect to the server (your computer or web page)
      if (client.connect(server, 80)) {
        Serial.println("Connecting...");
        client.print("GET /Ethernet/getData.php?"); // This
        client.print("value="); // This
        client.print(value); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
        client.println(" HTTP/1.1"); // Part of the GET request
        client.println("Host: 192.168.0.1");
        client.println("Connection: close");
        client.println(); // Empty line
        client.println(); // Empty line
        client.stop();    // Closing connection to server
      }

      else {
        // If Arduino can't connect to the server (your computer or web page)
        Serial.println("--> connection failed\n");
      }
      delay(10000);
    }

Now when I upload the sketch onto the board and run the serial monitor, I get this output:

[![Serial monitor output][1]][1]

My Ethernet connection detail screenshot is as follows:

[![Ethernet connection details][2]][2]

Please tell me any changes that I must make and also are there any WAMP settings which I should change to allow the connection to get established?

Please consider the fact that I don't have a router anywhere in this connection - just my laptop and Ethernet shield connection.

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

title: Unable to connect Ethernet shield W5100 to localhost

Answers: 2

body:
After uploading the sketch from your laptop you should disconnect your Arduino and Ethernet shield setup from your laptop and then use a switch.

Connect the same setup to the switch at one end and the other end of the switch must be connected to your laptop then you can try to access your web page using IP address you specified in Ethernet sketch.

body: Well, the problem has been solved. The Ethernet shield was not properly stacked onto the Arduino board which caused connection to fail.


body:
I've connected ESP8266 to Arduino UNO. After a getting a huge trouble I successfully managed to run some AT commands. I have also tested AP mode.

Then I got some trouble with software serial communication with Arduino and decided to change baud-rate to 9600 (previously it was 115200).

I used `AT+IPR=9600` command to change it.

After that blue led of esp stays on and not taking AT commands any more, but output some gibberish to serial monitor with few ascii text like below:

 ets Jan  8 2013,rst cause:4, boot mode:(3,6)

 wdt reset
 load 0x40100000, len 1396, room 16
 tail 4
 chksum 0x89
 load 0x3ffe8000, len 776, room 4
 tail 4
 chksum 0xe8
 load 0x3ffe8308, len 540, room 4
 tail 8
 chksum 0xc0
 csum 0xc0

 2nd boot version : 1.4(b1)
 SPI Speed      : 40MHz
 SPI Mode       : DIO
 SPI Flash Size & Map: 8Mbit(512KB+512KB)
 jump to run user1 @ 1000

Note: I know it consumes a lot power tried external 3.3V power supply and voltage divider for rx pin.

Any help would be appreciated.

title: Both red and blue led of ESP8266 stays on

Answers: 1

body:
If you have too, you can find the firmware for the ESP8266 [here][1] and re-flash it.

There's some good info [here][2] about the instruction set.

With respect to your issue of the blue (traffic) light staying on, I can't imagine that the baud command would have caused an issue. Perhaps you need to double check your circuit and make sure that the Rx pin of the ESP8266 is not being held high.

What happens with only 3.3V and GND connected to the ESP8266?

Also the output you're getting is similar to the output from “AT+GMR”. Are you sending it that in a loop by chance?

  [1]: https://github.com/espressif/esp8266_at/tree/master/bin
  [2]: http://bbs.espressif.com/download/file.php?id=84


body:
I have a value I'm taking from a sensor module, which is 2500 when the sensor is facing a light source. This reads to my code and can be saved perfectly fine. When I try to find the weighted average of a set of values (2500*1000+2500*2000+2500*3000 etc), the Arduino comes out with very weird answers. For example

2500*1000=9632

If I just compute 2500*1000 on its own, the answer still comes out the same! The results come out negative if I use int so I switched to using double (just in case the values created were too big), this stops producing negatives as expected but the result is still like it is above.. I have no idea why.. any ideas?

title: Arduino can't multiply?

Answers: 1

body:
2500 * 1000 = 9632 is exactly what you expect with 16-bit integers. You
should use long integers instead:

    2500L * 1000L == 2500000L

Floats work also, but are more expensive:

    2500.0 * 1000.0 == 2500000.0

although I do not recommend testing for exact equality of floats (it
works here because these numbers are exactly representable).


body:
I am looking to setup a system where I have a master Arduino polling a number of sensors.

The way I am thinking is hooking the master TX line to the sensors RX line(and the opposite for the other line)

Questions

1. How long can the lines be?
2. Can the lines branch?

title: Branching Bus for Sensor

Answers: 2

body:
How many sensors and what kind are they?
What Arduino do you have?

Basically you could use 1 Arduino Output per sensor if you have enough, or you are going to need to use a multiplex technique via additional electronic components.

The only other solution would be to use communication (I2C/Serial/etc) to receiving nodes at the sensor.

body:
I have a page about [connecting Arduinos using RS485](http://www.gammon.com.au/forum/?id=11428). You can connect multiple devices up like this:

[![RS485 setup][1]][1]

That has a reasonable range, 20 metres or more.

---

On that page I describe a *Rolling-master system* where each device takes turns to be the master and transmit information to the other devices. It also manages some devices not responding.

This screenshot shows the various devices "talking" during their timeslot:

[![Rolling master demo][2]][2]

In that particular case there were 3 devices active out of 4 configured.

---

> I have a master ardunio polling a number of sensors.

I'm assuming in my answer that you have an Arduino at each sensor point (you could use a cheap ATtiny85 or something). That would be needed to run the rolling master code.

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


body:
I have seen it said over and over (in different places) that in order to achieve 640x480 resolution out to a DB15 VGA connection, the arduino would need to be clocked at 25Mhz or that at half resolution it would need to be clocked at 12.5Mhz.

What is the relation between resolution and internal clock? I would expect that so long we can feed the signal fast enough that would be enough.

title: What is the relation between Arduino's clock and possible VGA resolution?

Answers: 1

body:
<!-- language-all: lang-C++ -->

I doubt if that would be fast enough. See [my thread about connecting to a VGA monitor](http://www.gammon.com.au/forum/?id=11608).

Borrowing from that page, so as to not make a link-only answer ...

---

For 640x480 pixels of active video you have something like this:

[![Video timing diagram][1]][1]

---

## Vertical Sync

Let's start with the vertical sync pulses. In fact, we'll show how all the timing data can be derived from three figures:

*    The screen refresh rate (eg. 60 Hz)
*    The screen resolution (eg. 640 x 480)

So what is the refresh rate? It's the rate at which the entire screen is redrawn. If you ever looked at Windows screen resolution you probably saw something like this:

[![Refresh rate][2]][2]

That's the refresh rate: 60 Hz (60 times a second). This figure was probably originally chosen because it is the mains frequency in the USA, so that would minimize the artifact of mains hum bars appearing on the screen, in the days of CRT monitors.

The other figure of interest is the screen resolution.

In our case we are going for the minimum we can (640 x 480) and seeing where those figures lead us.

Starting with the refresh rate, a 60 Hz refresh rate will require a "vertical sync" pulse 60 times a second, or a period of 1/60 (16.66 ms).

---

## Generating vertical sync pulses

This code in my VGA output sketch generates the vertical sync pulses:

      // Timer 1 - vertical sync pulses
      pinMode (vSyncPin, OUTPUT);
      Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE);
      OCR1A = 259;  // 16666 / 64 uS = 260 (less one)
      OCR1B = 0;    // 64 / 64 uS = 1 (less one)

The clock period is 62.5 ns (1/16000000). By applying a prescaler of 1024 the timer counts up once every 64 µs. So to get a period of 1/60 of a second (16666 µs) we need to count up to 260 (16666 / 64 = 260). Since the timer counts are zero-relative we set OCR1A to count up to 259. This sets the frequency of Timer 1.

Then we need to set the pulse width by putting the correct value in OCR1B. We want a pulse width of two lines. One line is 1 / 60 / 525, namely 31.7 µs. So two lines would be 63.4 µs. This is close enough to exactly one timer count (64 µs). So OCR1B is set to zero (being zero-relative, making it zero gives a count of 1).

Timer 1 is configured to "clear B on compare" which effectively means that it toggles the output pin (D10 on the Uno) so it is high for the duty cycle width (64 µs) and low the rest of the time. If you wanted the opposite sync pulse polarity, change CLEAR_B_ON_COMPARE to SET_B_ON_COMPARE.

The timer is also set up to generate an interrupt, which is used to tell the code that we are starting another vertical cycle, by setting the line count to zero:

    ISR (TIMER1_OVF_vect)
      {
      vLine = 0;
      messageLine = 0;
      backPorchLinesToGo = verticalBackPorchLines;
      } // end of TIMER1_OVF_vect

---

## Horizontal sync

Horizontal sync pulses tell the monitor when to start drawing each line.

To calculate the horizontal sync frequency we need to divide the overall frame rate (60 Hz) by the number of total lines (525 if you count the sync pulse itself, and the front and back porches).

In other words:

     (1/60) / 525 * 1e6 = 31.74 µs

We also need to know the sync pulse width. That is documented to be 96 pixels, so we need to know the width of one pixel. That would be the figure above, divided by 800 (being the total screen width including the sync pulse, and front and back porches).

Thus that is:

    ((1/60) / 525 * 1e9) / 800 = 39.68  ns
    1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz

So our pixel width is 39.68 ns and the pixel clock is 25.2 mHz.

The horizontal sync pulse width is 96 pixels, so we want a pulse of:

    96 * 39.68 ns = 3.8 µs

---

## Generating horizontal sync pulses

Now we are ready to set up the timer for the horizontal sync pulses:

      // Timer 2 - horizontal sync pulses
      pinMode (hSyncPin, OUTPUT);
      Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE);
      OCR2A = 63;   // 32 / 0.5 µs = 64 (less one)
      OCR2B = 7;    // 4 / 0.5 µs = 8 (less one)

The clock period is 62.5 ns (1/16000000). By applying a prescaler of 8 the timer counts up once every 0.5 µs. So to get a period of 32 µs we need to count up to 64 (32 / 0.5 = 64). Since the timer counts are zero-relative we set OCR2A to count up to 63. This sets the frequency of Timer 2.

Then we need to set the pulse width by putting the correct value in OCR2B. We want a pulse width of 96 pixels (3.8 µs). So OCR2B is set to 7 (being zero-relative, making it 7 gives a count of 8, which is 4 / 0.5).

Again, if you wanted the opposite sync pulse polarity, change CLEAR_B_ON_COMPARE to SET_B_ON_COMPARE.

The timer is also set up to generate an interrupt, which has the sole purpose of waking the processor up from sleep, so it can draw each line with exactly the same delay after the pulse. If it wasn't asleep, there would be a variation of two to three clock cycles (since an interrupt cannot occur during a single instruction) and this gives very bad-looking "jitter" on the screen.

    ISR (TIMER2_OVF_vect)
      {
      } // end of TIMER2_OVF_vect

---

## Pixel data

Now things get tricky ...

Let's see how long we have to draw 640 pixels:

    ((1/60) / 525 * 1e9) / 800  * 640 = 25396.82 ns (25.39 µs)

It just can't be done on this processor. The clock period itself is only 62.5 ns, so there is no way we can output a pixel every 39.68 ns (that is: 25396.82 / 640 = 39.68).

The fastest way we can get bits "out the door" is using the SPI hardware. That can run at a maximum clock rate of twice the system clock, that is, one pixel every 125 ns. So we will have to settle for having the pixels 4 times as wide. A horizontal resolution therefore of 160 pixels. Since we will display 8-pixel characters, that gives us 20 characters per line.

---

## Summary

Even at 25 MHz processor speed (which exceeds its spec) you won't be able to clock out pixels fast enough for 640 pixel width (since the fastest SPI speed is half the processor clock speed).

---

>  I would expect that so long we can feed the signal fast enough that would be enough.

That's the tricky bit. To output data you have to do more than merely send it. You have to read it from memory, so it would take a least a couple of clock cycles to do that.

---

## Example of working at that resolution

A screen shot of my sketch in action (160 characters wide - 640 pixels and 30 characters high - 480 pixels, which is 16 pixels each as they were "doubled" in height to make them look in proportion). The font data was 8x8 pixels, and thus they appear as 16x16 on the screen.

[![Example VGA output][3]][3]

---

> So does that mean that there really isn't a direct relation between clock speed and resolution? Other than, the clock must be faster than this

To work even at that speed the processor speed needs to be a multiple of the VGA clock, or close enough for the monitor to accept. (Looking at my figures the pixel rate is not in fact a multiple of 39.68 ns, so I am guessing that my monitor was able to adjust).

You could get better results by having a system clock which was an exact multiple of 39.68 ns (around 25 MHz - precisely 25.201613 MHz) - which is what you suggested in the question. However that just gives more accurate timing, you would still get similar resolution to what I show here.

So yes, to work on more monitors you should have a direct relation between clock speed and resolution.

I seem to have a 25.175 MHz crystal in my parts drawer, so perhaps I experimented with this a while back. Of course, you have to recalculate the other timings if you use that, and the processor is running out of spec.

  [1]: https://i.stack.imgur.com/tGTx3.png
  [2]: https://i.stack.imgur.com/cxDIR.png
  [3]: https://i.stack.imgur.com/SC5PU.jpg