message:
Help avoiding floating point math

I'm using a Texas Instruments DRV2605 haptic controller in my project to drive a LRA vibration motor. I would like to calculate the LRA rated voltage during run time using the formula below as provided in the datasheet:

[![LRA Rated Voltage formula][1]][1]

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

I'm successfully calculating the rated voltage, but the calculation requires floating point calculations and I would like to avoid that because I'm low on available flash space on my ATTiny85 micro controller. Here is how I'm currently calculating the rated voltage value:

    uint8_t LRA_closed_loop_rated_voltage( uint16_t voltage ) {
    float RatedVoltage;
    uint16_t SampleTime = 300;
    uint16_t frequency = 175;

    RatedVoltage = ( (float) voltage ) * sqrt( 1 - ( ( 4 * SampleTime + 300 ) * 0.000001 ) * frequency );
    RatedVoltage = ( RatedVoltage * 255 ) / 5300;

    return RatedVoltage;
    }

The function above is just a simplified version showing the calculation and the SampleTime and frequency variables are set to their defaults values here. The voltage argument is the actuator's rated voltage in millivolt.

EDIT: Even though SampleTime and frequency have fixed values in the function above, their values will be determined by reading the relevant registers in the final implementation. SampleTime may have one of the following values: 150, 200, 250, 300 and the frequency will depend on the manufacturers specifications for the actuator.

It was easy to overcome the floating point issue on the other calculations by simply scaling up the values by 1000 (fixed point arithmetic):

> ODClamp = ( Vpeak * 255) / 5.6 /* Vpeak in volts */

TO:

> ODClamp = ( Vpeak * 255) / 5600 /* Vpeak in millivolts */

How can I do the calculation in question without having to use floating point?

body:
As I said in my comment, it is all about computing an approximation of
`sqrt(1-x)`. Assuming [the typical resonance frequency is between 175
and 235 Hz][LRA frequency], then we have

> (4 × 150 µs + 300 µs) 175 Hz ≤ x ≤ (4 × 300 µs + 300 µs) 235 Hz

i.e.

> 0.1575 ≤ x ≤ 0.3525

This range is small enough to try a simple polynomial approximation. A
linear approximation is just a bit too crude for 8 bit resolution.
Playing with quadratic polynomials, I found this approximation which is
good to 3.1e-5 in the relevant range:

> √(1−x) ≈ 0.9983795 − x (0.480515 + x 0.1955)

This can be easily implemented in fixed point by scaling everything by a
factor 216 = 65536. One has to take care that any
product of two such fixed point numbers must be computed in
32 bits, and the result subsequently divided by 65536. Which gives
the following implementation:

    /*
     * Compute a fixed point approximation of f(x) = sqrt(1-x).
     * Valid for x in [.1575, .3525].
     * Argument and result scaled by 2^16.
     */
    uint16_t f(uint16_t x)
    {
        return 65430 - x * (31491 + x * 12812UL / 65536) / 65536;
    }

[LRA frequency]: https://www.precisionmicrodrives.com/vibration-motors/linear-resonant-actuators-lras


sender: user

message:
Arduino box stops working: Reading RFID tag and sending data over network

This is a simple Arduino program which reads RFID tag and sends the data over a network (lora).

The program works fine in as i run it, the arduino reads RFID and sends it over the network (lora)

but

after a few hours it stops responding it neither reads nor sends the data over network (lora network).

I am very new to arduino and have no idea what causes the box to stop responding, kindly help.

When i restart the boxes or upload the code to it again, it starts behaving normally for a few hours and then goes back to not responding.

        /*
       Typical pin layout used:
       -----------------------------------------------------------------------------------------
                   MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
                   Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
       Signal      Pin          Pin           Pin       Pin        Pin              Pin
       -----------------------------------------------------------------------------------------
       RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
       SPI SS      SDA(SS)      10            53        D10        10               10
       SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
       SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
       SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
       Red LED                  A0
       Green LED                A2
       Blue LED                 A3
    */
    /***********************************************************************************************/
    //#include <SPI.h>
    #include <MFRC522.h>
    //#include <HID.h>

    // Cooking API libraries
    //#include <arduinoUtils.h>
    //#include <arduinoUART.h>
    //#include <arduinoMultiprotocol.h>
    #include <arduinoLoRaWAN.h>

    #define RST_PIN         9          // Configurable, see typical pin layout above
    #define SS_PIN          10         // Configurable, see typical pin layout above
    #define MAX             10         // Maximum Buffer size
    #undef Debugg
    /******** RFID Reader initialization**********************************************/
    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
    //char rfid_old[MAX];
    byte *buffer;

    /******************************LoRa Initialization********************************/
    // Pin definition for LoRaWAN module error LED:
    const int error_led =  7;
    //////////////////////////////////////////////
    uint8_t socket = SOCKET0;
    //////////////////////////////////////////////

    // Device parameters for Back-End registration
    ////////////////////////////////////////////////////////////
    char DEVICE_EUI[] = "0000000097E471E1"; // 0000000097E471E1 / 00000000518AD184
    char DEVICE_ADDR[] = "97E471E1"; // 97E471E1 / 518AD184
    char NWK_SESSION_KEY[] = "00EBB4C1FCDFF52878B1725CBDFF0BA1"; // Configured for TTN
    char APP_SESSION_KEY[] = "4EDC3AB4F79C565685109ECD4AF4604C"; // Configured for TTN
    char APP_KEY[] = "70B3D57ED0000300"; //APP_EUI
    ////////////////////////////////////////////////////////////
    // Define port to use in Back-End: from 1 to 223
    uint8_t PORT = 1;

    // variable
    uint8_t error;
    uint32_t cFreq[] = { 867100000, 867300000, 867500000, 867700000, 867900000 };
    char rfid_arr[MAX];
    char stampleErrorChar[] = "4AD6A6A65784AEBA2B"; // this data is sent from the WService When Stample Error-> Error
    /* *******************************START Initialize Indication LEDs******************************* */
    int greenPin = 6;
    int redPin = 8;

    void setup()
    {
      Serial.begin(57600);
      //LoRaWAN example - Send Unconfirmed packets (no ACK)
      pinMode(error_led, OUTPUT);
      digitalWrite(error_led, LOW);

      LoRaSetup();
      RfidSetup();
    }

    //-----------------------------------------------------------------------------
    // Name.: RfidSetup
    // Descr:
    //
    // In...:
    // Out..:
    // Ret..:
    //-----------------------------------------------------------------------------
    void RfidSetup()
    {
      SPI.begin();                        // Init SPI bus
      mfrc522.PCD_Init();                 // Init MFRC522
      mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
    }
    void LoRaSetup()
    {
      LoRaWAN.ON(socket);
      LoRaWAN.factoryReset();

      // Channel parameters
      for (uint8_t i = 3; i < 8; i++) {
        LoRaWAN.setChannelStatus(i, (char*)"on");
        LoRaWAN.setChannelFreq(i, cFreq[i - 3]);
      }
      for (uint8_t i = 0; i < 3; i++) {
        LoRaWAN.setChannelDutyCycle(i, 302);
      }

      for (uint8_t i = 3; i < 8; i++) {
        LoRaWAN.setChannelDutyCycle(i, 99);
      }

      LoRaWAN.setPower(5); // [N/A, 14, 11, 8, 5, 2] dBm
      LoRaWAN.setADR((char*)"off"); // Adaptive data rate
      LoRaWAN.setDataRate(5); // [250, 440, 980, 1760, 3125, 5470, 11000];
      LoRaWAN.setDeviceEUI(DEVICE_EUI);
      //showErrorResult((char*)"2. Set Device EUI ", LoRaWAN.getDeviceEUI());
      LoRaWAN.setAppEUI(APP_KEY);
      //showErrorResult((char*)"3. Set APP EUI ", LoRaWAN.getAppEUI());
      LoRaWAN.setDeviceAddr(DEVICE_ADDR);

      LoRaWAN.setNwkSessionKey(NWK_SESSION_KEY);

      LoRaWAN.setAppSessionKey(APP_SESSION_KEY);
      //showErrorResult((char*)"6. Set App Session Key ",error);
      LoRaWAN.setRetries(3);
      LoRaWAN.saveConfig();
      LoRaWAN.joinABP();
    }

    void loop()
    {
      // Look for new cards
      if (! mfrc522.PICC_IsNewCardPresent()) {
        return;
      }

      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
      }
      else
      {
         error = LoRaWAN.joinABP();
         if (error == 0)
         {
           char* UId = GetUid(mfrc522);
           if(UId != NULL)
           {
              BlinkGreen(500);
              delay(100);
              // Send it!
              error = LoRaWAN.sendUnconfirmed(PORT, UId);
              Serial.println(error);
              delay(100);
              if(error == 0)
              {
                 Serial.println(LoRaWAN._dataReceived);
                 BlinkGreen(1000);
              }
              else
              {
                 BlinkRed(1000);
              }
            }
            delay(2000);
         }
      }
    }

    char* GetUid(MFRC522 mfrc522)
    {
        // Optional: Dump data about the cards
        //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
        buffer = mfrc522.uid.uidByte;

        for (int i = 0; i < mfrc522.uid.size; i++)
        {
          sprintf(&rfid_arr[i * 2], "X", mfrc522.uid.uidByte[i]);
        }
        mfrc522.PICC_HaltA(); //command the card into sleep mode
        return rfid_arr;
    }

    void BlinkGreen(int delayTime)
    {
      digitalWrite(greenPin, HIGH);
      delay(delayTime);
      digitalWrite(greenPin, LOW);
    }

    void BlinkRed(int delayTime)
    {
      digitalWrite(redPin, HIGH);
      delay(delayTime);
      digitalWrite(redPin, LOW);
    }
    void showErrorResult(char* errorMessage, uint8_t error)
    {
      if(error == 0)
      {
        Serial.print(errorMessage);
        Serial.println("OK!");
      }
      else
      {
        Serial.print(errorMessage);
        Serial.print(" Error: ");
        Serial.println(error);
      }
    }

sender: assistant

body:
The bad news is I can't see that much wrong with your code.

 1. You need to set the Red and Green pinModes().  You've set error, but then don't use it.  I'm guessing the green LED is a new feature.  similarly you _could_ refactor the blink green and blink red functions into one and pass in the pin number.
 2. Are you sure that the `mfrc522.uid.size` is always less than 5?  In `GetUid()` you assume that i*2 will fit into the buffer rfid_arr which is 10 bytes.  sprint() always attaches a null onto the end of what it rights to the buffer so this will overflow if you write elements 9 and 10.

I really doubt either of those are the problem you are looking for, so would it be possible to stick loads of `Serial.println()` statements in and see where abouts it is crashing?


body:
@Matt,

thanks guys. But if rfid_arr size was an issue, wouldn't the box be giving problem the first time we use it? because it works for few hours before it goes into not responding state. The rfid tag data looks like below
AEA00622
DE1CD403


message:
Is it possible to hookup two ultrasonic sensors to one Arduino Uno unit?

I found a couple of projects using Ultrasonic Distance sensor with Arduino Uno. Is there a way to connect two or more sensors on the same Arduino Uno?

body:
Yes, it is certainly possible.  There are a few things you need to be aware of:

1)  The Arduino UNO is 5V by design.  Many sensors (not all, but many) are 3.3V devices.  So connecting them to a 5V pin could damage them.  Since you seem to be just starting out, I'd recommend sticking with 5V tolerant sensors.

2)  The Arduino UNO only has so many pins available....obviously.  Different sensors require different amount of pins to 'work'.  For example, a temperature sensor might work with the SPI interface.  Another sensor might require 8 pins.  So if you start running out of pins, you need to think about other challenges like using shift registers, multiplexers, etc.

3)  Don't be afraid to experiment.  I suggest buying a genuine Arduino UNO to support the project.  Maybe buy some cheap Chinese ones to experiment on...in case you fry on of those.

In theory, the sky's the limit when it comes to "how many".  In real life, if you start going over a handful, dozen, etc. then you might want to rethink your design.


message:
Serial Communication Between 3 Arduinos Doesn't Work (Daisy-Chain)

In my project, I have to send a string from one arduino to a second arduino, and make it send the same string to a third arduino. I used UART and SoftwareSerial library, and connected the arduinos like that:

**In all the arduinos:**
Pin 10 - RX port, pin 11 - TX port
[![enter image description here][1]][1]
  [1]: https://i.stack.imgur.com/iV307.png

Arduino 1 pin 11    ---->  Arduino 2 pin 10
Arduino 2 pin 11    ---->  Arduino 3 pin 10
Arduino 3             ---->  PC (by hardware Serial)

**By theory**, Arduino 1 sends string "CA" to arduino 2, which resends that same string to arduino 3, that prints it back on Serial.

**The problem** is that I get the string "C�" instead of "CA" (that weird "C�" is equal to "067 255" on ASCII).
Does anyone knows why it happens? Maybe there's something wrong with my code?

Here's the code for all the three Arduinos:

*Arduino No. 1:*

    #include <SoftwareSerial.h>

    #define ADDR "CA"
    SoftwareSerial tiny(10, 11); //TBD

    void setup() {
      Serial.begin(9600); //debug only
      tiny.begin(9600);
      delay(2000);

      tiny.write(ADDR);
    }

    void loop() {
      //nothing here
    }

*Arduino No. 2:*

    #include <SoftwareSerial.h>
    SoftwareSerial tiny(10, 11); //TBD
    void setup() {
      Serial.begin(9600); //debug only
      tiny.begin(9600);
    }
    void loop() {
      if(tiny.available() > 0) {
        tiny.write(tiny.read());
      }
    }

*Arduino No. 3:*

    #include <SoftwareSerial.h>
    SoftwareSerial tiny(10, 11); //TBD
    void setup() {
      Serial.begin(9600); //debug only
      tiny.begin(9600);
    }
    void loop() {
      if(tiny.available() > 0) {
        Serial.write(tiny.read());
      }
    }

Any idea on what went wrong?

body:
Arduino #2 should have two SoftwareSerial instances, one to listen to Arduino #1 and another one to talk to Arduino #3:

 // In Arduino #2
 SoftwareSerial tiny1(10, 11); // Listen to Arduino #1 on pin 10
 SoftwareSerial tiny2(8, 9);   // Talk to Arduino #3 on pin 9

You may not need to wire unused signals (11 and 8).

There is an example here : https://www.arduino.cc/en/Tutorial/TwoPortReceive

Note that what you are trying to do is a bus. Serial in Arduino is RS232 based and that is not a bus but a [point to point protocol](https://en.wikipedia.org/wiki/Point-to-point_(telecommunications)). You should consider using I²C or SPI.


message:
Arduino mini pro as ISP for Atmega329P-PU serial monitor failing

After trying a lot of tutorials and manuals around the web including at least 20 solutions here on StackExchange, I don't know what to try anymore.

My goal is to write a message in the serial monitor window of the Arduino IDE from my ATMEGA328P-PU.

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

I have written the Arduino bootloader (tried 8 and 16MHz) to the ATMEGA and I use a 'blink' sketch as follows:

    void setup()  {
     Serial.begin(9600);
     delay(100);
     pinMode(9, OUTPUT);
    }

    void loop()
    {
     digitalWrite(9, HIGH);
     Serial.print("high");
     delay(1000);
     digitalWrite(9, LOW);
     Serial.print("low");
     delay(1000);
    }

The blinking works fine, the timing looks good, not overly fast or slow.

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

I connect PIN3 (PCINT17, PD1, TXD) directly to the RX on the Arduino (lower red wire) and the serial monitor responds by returning nonsense like `����������`.

I have checked the baud rate. I have also tested with all other baud rates in combination with and without 8Mhz and 16MHz.

I have tested the entire setup with another ATMEGA328P-PU and using an entirely other PC. Same results.

It is not possible to upload a sketch while leaving the TXD -> RX connected, so I disconnect this cable when I upload a sketch. I have also tested with only power and TXD -> RX connected.

I have also tried a few types of resistor between the TXD and RX, one of many tutorials recommended this.

This is what I am trying:
http://www.instructables.com/id/Attiny-serial-monitor-using-arduino-walkthrough/

And this is my boards.txt:

    ##############################################################

    atmega328bb.name=ATmega328 (8 MHz internal clock)

    atmega328bb.upload.protocol=arduino
    atmega328bb.upload.maximum_size=30720
    atmega328bb.upload.speed=57600

    atmega328bb.bootloader.low_fuses=0xE2
    atmega328bb.bootloader.high_fuses=0xDA
    atmega328bb.bootloader.extended_fuses=0x05

    atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex
    atmega328bb.bootloader.unlock_bits=0x3F
    atmega328bb.bootloader.lock_bits=0x0F

    atmega328bb.build.mcu=atmega328p
    atmega328bb.build.f_cpu=16000000L
    atmega328bb.build.core=arduino:arduino
    atmega328bb.build.variant=arduino:standard

    atmega328bb.bootloader.tool=arduino:avrdude
    atmega328bb.upload.tool=arduino:avrdude

body:
As you can see at image from linked instructables, they've connected `TX` pin from Tiny to `TX` pin on `UNO` through `220R` resistor. This is extremely lousy idea as `UNO` and `Tiny` are both driving `TX` pins.

On the other side you've connected `TX` Output pin from `Target CPU` into `RX` Input of the `Arduino ISP (pro mini)`. `Arduino ISP` returns some error responses from its `TXO` pin directly into the monitor. And it's at different speed I suppose, as default baud rate is `19200` in `Arduino ISP` sketch.

Also using internal `8MHz` oscillator and: `atmega328bb.build.f_cpu=16000000L` means you are running at half speed as compiler and everything else expects. All speeds will be at half rate. Delays twice as long and so on.

Anyway, you can disconnect your USB to Serial converter and connect it directly to the target CPU. Or use two of them. Or just upload bootloader and get rid of ISP.


body: The thing is that you have 2 ATmegas for 1 uploader. You can't really remove the ATmega on the Pro Mini so I suggest removing the ATmega of an UNO and using the UNO without the ATmega to program your seperate ATmega. Tx to Rx and vice versa. 16MHz will work.


message:
Errors in code, LM35 temperature logging to web server

trying to experiment with Wemos D1 and LM35. Need to have temperature reading on the ESP IP. Found the following project to be exactly matching my requirements but I am having certain errors in it. Since, I am not that expert with C programming, hence I am unable to resolve the issues and the website admins are also not replying. If you can please help get this program work or point me to some other source. (There are a lot which involve thingspeak.com but I do not want that. A simple WiFi connection to ESP through mobile and get the data on the esp server IP page which is 192.168.4.1 in Wemos.)

Here is the link,
http://blog.circuits4you.com/2016/03/web-server-data-logger.html

First error I get is "temp is not declared". If I declare temp as int then the compiler gives error on spnprintf statement saying "Invalid conversion from int to char*". Tried to read snprintf reference but could not understand the error. Perhaps there will be more errors after this line too. Kindly help.

body:
It seems like you haven't declared the variable 'temp' from the line

    server.send ( 200, "text/html", temp );

It should work fine if you declare it.


body:
It's expecting buffer to write all that data: `char temp[400];`. The snprintf writes at most 399 characters and termination character `'\0'`. And nobody cares that it generates ugly html:

      char temp[400];
      snprintf ( temp, 400,
    ""
      ""
        "<meta http-equiv='refresh' content='5'/>"
        "<title>Circuits4You.com Temperature Monitoring Server Demo</title>"
        ""
      ""
      ""
        "
Temperature: d
"
      ""
    "", analog
      );


message:
AVR (Arduino Uno) Serial.print and Serial.println only printing 1 or 2 chars

I first used the Arduino IDE but now I'm using PlatformIO which is awesome. But I have some big trouble with `Serial.print()` and `Serial.println()`. To show this error I have the following example code:

    #include <avr/io.h>
    #include <util/delay.h>
    #include "Arduino.h"
    #include "main.h"

    int main(int argc, char const *argv[]) {
      Serial.begin(9600);

      section5ex34();

      return 0;
    }

    void section5ex34() {
      // Initialization
      DDRC = 0b00000100; // Port C2 as output and the rest (including Port C3) as input. (Port C2 is used for a led that indicates when en bit is being read)

      uint8_t b = 0b00000000;

      // here the code reads bits from PORTC3
      for (int i = 0; i < 8; i++) {
        _delay_ms(1000);
        PORTC |= _BV(PORTC2); // Make Port C2 high (indicates a bit will be read)

        if ((PINC & (0b1 << 3)) != 0) {
          b |= (1 << i);
        }

        _delay_ms(100); // Wait for the user to prepare the next bit (because this is now done by hand)
        PORTC &= ~_BV(PORTC2); // Then make Port C2 low
      }

      Serial.println(b, HEX);
    }

When I have the code like this, it prints the right Hexadecimal value corresponding with the 8 read bits.

When I add `Serial.println("test");` after the print, it doesn't print that.

Or when I change `Serial.println(b, HEX);` to `Serial.println(b, BIN);` it prints `11`.

When I replace those 2 prints with `Serial.println("Hi test test.");` it prints `Hi`, so it seems like it can only print 2 characters.

When I add `Serial.println("Hello world . hello . hi");` _four times_ after `Serial.begin(9600);`, it prints `Hello world . h` and nothing more. So here it seems like it can print _more_ than 2 characters, but not all. If I wait a few seconds it adds `ello` to this, so it says `Hello world . hello`.

In the initial code, when I replace the `if`-statement with

    if ((PINC & (0b1 << 3)) != 0) {
      b |= (1 << i);
      Serial.println("1");
    } else {
      Serial.println("0");
    }

and when the input is connected to 5v (so high) it prints a `1` once and nothing else, not even a hexadecimal value when the reading is finished.

This problem drives me crazy.

I have an Arduino Uno and use a baudrate of 9600 , 8,N,1.

I hope someone can help me out with this.

body:
You have two issues here:

The first is that you are using the Arduino core library and failed to
initialize it. This is done automatically if you rely on the core's
supplied `main()`, i.e. you stick with the `setup()`/`loop()` style of
coding. If you write your own `main()`, you should start by calling
`init()` to initialize the core.

**Edit**: In this particular instance, you could get away by just enabling
interrupts with `sei()`. But I consider it good practice to initialize the
core if you are ever going to use it.

The second issue is the abrupt termination of main:
`Serial.print()` and `println()` do not really print to the serial port.
Instead, they put the characters to be printed in the output buffer, and
let an interrupt take care of actually sending them through the UART.

Your program ends with

    return 0;

This will stop it. It will stop the whole program, including
interrupt-driven tasks. So you will see whatever characters did make it
to the UART, and nothing more.

If you instead end the program with and endless loop

    for (;;) ;

it should work as expected.


body:
Arduino `main()` is not so simple as you think. If you use standard Arduino `loop()` and `setup()` functions it might be working much better.

But if you're not allowed to use Arduino libraries, you can use this:

**src/main.cpp**

    #include <avr/io.h>
    #include <util/delay.h>
    #include <stdio.h>

    void section5ex34();
    int uart_putchar(char c, FILE *stream);
    void uart_init (unsigned long int baud);

    int main(void) {
      uart_init(9600U);

      while(1) section5ex34();
      return 0;
    }

    void section5ex34() {
      // Initialization
      DDRC = 0b00000100; // Port C2 as output and the rest (including Port C3) as input. (Port C2 is used for a led that indicates when en bit is being read)
      PORTC = 0b11111011;

      uint8_t b = 0b00000000;

      // here the code reads bits from PORTC3
      for (int i = 0; i < 8; i++) {
        _delay_ms(100);
        PORTC |= _BV(PORTC2); // Make Port C2 high (indicates a bit will be read)

        if ((PINC & (0b1 << 3)) != 0) {
          b |= (1 << i);
        }

        _delay_ms(100); // Wait for the user to prepare the next bit (because this is now done by hand)
        PORTC &= ~_BV(PORTC2); // Then make Port C2 low
      }
      printf("0xX and something loooooooooooong\n",b);
    }

    int uart_putchar(char c, FILE *stream) {
      if (c == '\n') uart_putchar('\r', stream);
      loop_until_bit_is_set(UCSR0A, UDRE0);
      UDR0 = c;
      return 0;
    }

    // function to initialize UART
    void uart_init (unsigned long int baud) {
        unsigned int baudrate = F_CPU/(baud*16UL)-1;
        UBRR0H = (baudrate>>8);             // shift the register right by 8 bits
        UBRR0L = baudrate;                  // set baud rate
        UCSR0B|= (1<<TXEN0)|(1<<RXEN0);     // enable receiver and transmitter
        UCSR0C|= (1<<UCSZ00)|(1<<UCSZ01);   // 8bit data format

        //// with static FILE variable:
        // static FILE uart0fd;
        // fdev_setup_stream((&uart0fd), uart_putchar, NULL,  _FDEV_SETUP_WRITE);
        // stdout = &uart0fd;

        //// or directly by using dynamically allocated FILE struct:
        stdout = fdevopen(uart_putchar,NULL); // uses malloc/calloc, it might be inconvenient
    }


message:
Why is LED lid when pin is set low?

I made this simple piece of code, to make my LED flash.. Which it does when the pin is set low.. But how does that makes sense?

    #include "pins_arduino.h"

    void setup() {
      // put your setup code here, to run once:
      pinMode(BUILTIN_LED,OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      digitalWrite(BUILTIN_LED,LOW);
    }

I am using the Wemos d1 - http://www.wemos.cc/

body:
If the LED is ON when LOW and OFF when HIGH then chances are the LED is connected between +3.3V and the IO pin with a suitable resistor.

When HIGH the IO pin is at +3.3V, so the voltage across the LED is 0V (3.3 - 3.3 = 0) and it is turned off.  When LOW the IO pin is at (nearly) 0V and the voltage across the LED (and its resistor) is 3.3V (3.3 - 0 = 3.3), so it lights up.


message:
Use transistor to press button on external device

I have a small device with a simple push button. I'd like my Arduino to be able to make the device register button pushes. It seems like the best way to do this is to use a transistor to close the circuit for the button when my Arduino sends it a pulse from one of its pins. I've mapped out what I think the circuit should look like on a breadboard. I didn't include the device in this diagram, but it's powered by a CR2032 watch battery, which seems to give 220 mAh at 3Vs.

Basically, the two sides of the button would be connected to the transistor's collector/emitter leads. Then the digital pin on my Arduino would be connected via a resistor to the base lead on the transistor. When the pin sends some current to the base lead, the transistor will make current flow through it and the device will register a button press.

[![Example circuit][1]][1]

I made this by adapting the circuit [here][2], which looks like this:
[![Base circuit][3]][3]

Basically I got rid of the motor/load and flyback diode, and hooked the two ends of the device's button up to the collector/emitter leads of the transistor.

I'm concerned that I've screwed up this circuit somehow, and will fry either the device or the Arduino or something else when I try and run it, otherwise I'd just test it right away.

Could anyone give me feedback if I'm on the right track here? I couldn't find other answers which dealt with quite this setup, where you are pressing a button on another device, though [this question][4] seemed related.

  [1]: https://i.stack.imgur.com/L0U6R.png
  [2]: https://teachmetomake.wordpress.com/how-to-use-a-transistor-as-a-switch/
  [3]: https://i.stack.imgur.com/0j9rv.jpg
  [4]: https://arduino.stackexchange.com/questions/19447/controlling-an-led-using-a-transistor-tl188

body:
Yes, you have screwed the circuit up slightly.

You want to lose the red wire between the collector and +5V otherwise when you turn the output pin HIGH the transistor will explode.

Also you need to make sure that the ground of the Arduino (emitter of the transistor) is connected to the - of the target circuit and that the button you are "pressing" is an active-low system with internal pullup. If it's not then you will have to come up with another way.

An opto-isolator is a better choice than a transistor when you don't know the internal circuitry of the target device:

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

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


message:
Good voltage and resistor value for string of LEDs

I building multiple parallel strings of 4 LEDs in series.

Since the four LEDs in series have a combined forward voltage of 12.56V at 20mA, and it's powered by 2 AA batteries, I have added a voltage booster.

Now my question is, since I can both choose the output voltage of the boost converter, and the resistor added to each string of 4 LEDs, what would be a reasonable value for both?

I could set the voltage to exactly 12.56V and not use a resistor, but that would probably lead to uneven current spread between the sets of 4 LEDs, as their forward voltage can differ slightly due to manufacturing differences.

On the other hand, I don't want to set the voltage too high, and wast a lot of power.

So what would be an acceptable voltage drop over a current limiting resistor?

body:
Since the relation between voltage and power is quadratic, the obvious answer is "as little as possible".

Allowing for 3% variance in VF gives us just under 13V, so that is a reasonable starting point. Solving for R gives 22ohms, a E24 value. This will result in a 8.8mW loss, which even a 0201 resistor can handle.


body:
> I could set the voltage to exactly 12.56V and not use a resistor, but that would probably lead to uneven current spread between the sets of 4 leds, as their forward voltage can differ slightly due to manufacturing differences.

While that is a completely true statement, by having multiple LEDs in a chain you effectively average out the forward voltages. The more LEDs you have in your chain the more "average" each chain gets.

It's still not good to rely on the forward voltage to set the current, since it also varies with temperature (as the LEDs heat up the current will rise, leading to more heat and therefore more current, until you get thermal runaway).

As Ignacio says, the less the better when it comes to the resistance, and has recommended 22Ω and 13V, which I would recommend too.

Another option is to use a low-side *constant current sink* on each chain. This will guarantee that the current is exactly what you want (within reason) with no thermal drift in either the LEDs or the resistor.

You can find some example circuits here: http://www.radio-electronics.com/info/circuits/transistor/active-constant-current-source.php

Or you can use constant-current sink LED driver chips, which also often gives you the advantage of being able to control each chain of LEDs individually - either on/off, or PWM.


body:
Using a boost converter and a resistor to limit current seems rather inefficient. The resistor is used to approximate a constant current source, but it would be far more efficient to use a switch mode supply to generate a constant current.

There are dedicated LED controllers which do this, although usually used with higher power LED e.g. CREE LED.

It may be possible to modify the feedback circuit in the boost converter to regulate the current, monitored with a small series resistor.


message:
Object can't get the right value of its property

I'm doing a program for a robot and I got stuck at a weird problem:
I have classes defined for my robot's internals, for example for a `StepMotor`. I also defined a class for a `Controller`, which is going to control the speed of each `StepMotor`.

Here's a fragment of my code:

        #include <SPI.h>
        #include <Tone.h>
        #include <Wire.h>
        #include <LiquidCrystal_I2C.h>

        /SILNIKI KROKOWE:
        class StepMotor: public Device
        {
            public:
                int motorPin;
                int dirPin;
                int sleepPin;
                int ForwardState;
                volatile double Speed;
                volatile int ControlValue;  //the value sent to the motor
                int MaxControlValue = 4000; //maximum ControlValue
                String Name;

                void Init ( void )
                {
                    //init
                }

                void SetSpeed ( int speed )
                {
                  toneObject.play(speed);
                }

                void SetMode(bool IsOn)
                {
                  if (IsOn)
                    digitalWrite(sleepPin, HIGH);
                  else
                    digitalWrite(sleepPin, LOW);
                }

                void SetDirection ( Dir direction )
                {
        //code for setting direction
                }

            private:
              Tone toneObject;
        };

        StepMotor motor_right;
        StepMotor motor_left;

        class Controller
        {
          public:
            ControllerType controllerType;
            double Kp;
            double Ki;
            double Kd;
            double Tp; //czas próbkowania
            volatile double e;
            volatile double e_old;
            volatile double P_result;
            volatile double I_result;
            volatile double D_result;
            StepMotor Motor;

            int Calculate ()
            {
              int Result;
         //Serial.print(Motor.Speed); HERE's THE PROBLEM
        /********************************
        /********************************
        /*******************************
              e = MoveOrder::speed - Motor.Speed;  //Motor.Speed is always 0.00, although it's not true

                 //the rest is not important
            }

            void Reset()
            {
              //reset procedure
            }

        };

        Controller controller_right;
        Controller controller_left;

        setup()
        {
           controller_right.Motor = motor_right;
           controller_left.Motor = motor_left;
        }

        ISR(TIMER5_COMPA_vect)
        {
            motor_right.ControlValue = controller_right.Calculate();
            motor_left.ControlValue = controller_left.Calculate();
            motor_right.SetSpeed(motor_right.ControlValue);
            motor_left.SetSpeed(motor_left.ControlValue);

        }

I have cut the less important parts. The rest works properly, because my robot can drive when I use `SetSpeed(somevalue);` The only problem is that place where I need to read current speed of my motor.
In the `Controller` class, there's `Calculate()` method. In that method I want to calculate `e = MoveOrder::speed - Motor.Speed;` Unfortunately it can't be calculated properly, because Motor.Speed ALWAYS is `0.00` (when I display it with `Serial.print(Motor.Speed)` I see `0.00` all the time). It's very strange, because when I display speed of each motor (`Serial.print(right_motor.Speed)` or `Serial.print(left_motor.Speed)`) the value is correct (when the wheels are spinning, value is not 0.00).

The speed calculations are in a different function, which I didn't present here, because it would be too long - I'm sure it works, because, as I said, I can get speed values properly.

As you can see in `setup()`, I set each contorller's Motor porperty to the correct object.
I also used volatile keyword for the properties that are used in the interrupt.

What is wrong with my code?

If the code I provided isn't enough, here's the full version:
https://1drv.ms/t/s!Atl-jM_xUkz1hc1f-qYYotj-pJIgUw

I'm not sure if anyone would want to dive into it, because it's not so short.

body:
My guess: `controller_right.Motor = motor_right;` makes a copy of `motor_right`. So you don't have the same class instance.

Basically `Controller controller_right;` calls default constructor which includes also default constructor for the `StepMotor`. And later all variables are copied into it by using default assigment operator, but still, it's not the same instance.


message:
Arduino Due: multiple TCS sensors

I am trying to run 2 `TCS3200`’s from one `Arduino Due`. Next, I must increase to 4 sensors. I need to read the data from the 2 digital pins but how do I read both within the same loop rather than in series to save time. The code reading one sensor tasoOutPin1 (pin 10) works but why can’t I place the second read command `int detectColor(int taosOutPin2)` before the `{` symbol?

    int detectColor(int taosOutPin1) {

    float white1 = colorRead(taosOutPin1,0,1);
    float red1 = colorRead(taosOutPin1,1,1);
    float blue1 = colorRead(taosOutPin1,2,1);
    float green1 = colorRead(taosOutPin1,3,1);
    }

Thanks,

Scott

body:
Seems you have to run these serially, but not sure why it's an issue, a due is quick.

seems more programming related... 'detectColor' is a function, and this is run inside the loop i assume.

    int taosOutPin1 = 10; //color detector 1
    int taosOutPin2 = 2; //Pins are examples, change to actual pin...
    int taosOutPin3 = 3;
    int taosOutPin4 = 4; //color detector 4

    typedef struct {
       float white;
       float red;
       float blue;
       float green;

    } color;

    void setup() {
      // put your setup code here, to run once:

    }

    void loop() {

    color detectedColorForSensor1 = detectColor(taosOutPin1);
    color detectedColorForSensor2 = detectColor(taosOutPin2);
    color detectedColorForSensor3 = detectColor(taosOutPin3);
    color detectedColorForSensor4 = detectColor(taosOutPin4);

    Serial.print(detectedColorForSensor1.red);
    Serial.print(detectedColorForSensor1.green);
    Serial.print(detectedColorForSensor1.blue);
    Serial.print(detectedColorForSensor1.white);

    //etc for sensor 2,3,4............

    }

    color detectColor(int taosOutPin1) {

    color detectedColor;

    detectedColor.white = colorRead(taosOutPin1,0,1);
    detectedColor.red = colorRead(taosOutPin1,1,1);
    detectedColor.blue = colorRead(taosOutPin1,2,1);
    detectedColor.green = colorRead(taosOutPin1,3,1);

    return detectedColor;

    }


message:
Pinball - "All Lanes Lit" Bonus score is not behaving as expected

I'm trying to build a (very basic) pinball machine with an Arduino Uno. This part of the code will detect when a ball passes 3 lanes. When a lane is passed, it will activate the lane(laneState), reward a score(+10) and light up an LED.

**The Expected Result:**

 - When all 3 lanes are LIT, assign a score of the lane passage(+10), assign a bonus score(+100) and reset all laneStates to 0 and turn all leds to LOW.
 - 110 points are being added in total

**Actual Result:**

 - the last lane passed lights back up as active (while I set all of them to inactive)
 - 120 points are being added in total (**instead of 110?**)

Any hints on why I see this behaviour are very welcome!

---
The sketch and board can be found here: https://circuits.io/circuits/2739062-poc-lane-passage-001/
Turn on 'Code Editor' and enable the Serial Monitor to see the scores.

---
More info:
I looked into using interrupts, but that is not an option here (the Uno only has 2 pins for interrupts, I need 3)

Thanks!

EDIT: added the code here too:

    // Scores
    int totalScore = 0;
    const int lanePassageScore = 10; // 10 points for passing a lane
    const int allLaneActiveBonus = 100; // 100 points for activating ALL lanes

    // Digital pins to detect the state of the buttons
    const int laneButtonPin[] = {2,3,4};
    const int laneStateLedPin[] = {10,11,12};

    // all three lanes are 'inactive' at the start of the game
    int laneButtonState[] = {0,0,0};
    int lastLaneButtonState[] = {0,0,0};
    int laneState[] = {0,0,0};

    void setup() {
      Serial.begin(9600); // for debugging
    }

    void loop() {
      // detect if lanes 1 to 3 were activated
      detectLaneButtonPassage(0); // Lane 1
      checkAllLanesLit();
      detectLaneButtonPassage(1); // Lane 2
      checkAllLanesLit();
      detectLaneButtonPassage(2); // Lane 3
      checkAllLanesLit();

      Serial.println(totalScore); // for debugging

      delay(5);
    }

    void detectLaneButtonPassage(int laneId){
      // Check state of the button
      laneButtonState[laneId] = digitalRead(laneButtonPin[laneId]);
      if(laneButtonState[laneId] != lastLaneButtonState[laneId]){
        if(laneButtonState[laneId] == HIGH){
          // The lane button change to an ON position, toggle the lane state
          if(laneState[laneId] == 0){
            // lane was not yet active, it becomes active now
            laneState[laneId] = 1;
            digitalWrite(laneStateLedPin[laneId], HIGH);
            rewardScore(lanePassageScore);
          }else{
            // lane was already active, it becomes inactive now
            laneState[laneId] = 0;
            digitalWrite(laneStateLedPin[laneId], LOW);
            rewardScore(lanePassageScore/2);
          }
        }
      }
      lastLaneButtonState[laneId] = laneButtonState[laneId];
    }

    void rewardScore(int score){
      totalScore += score;
    }

    void checkAllLanesLit(){
      // Check if ALL lanes are activated
      if(laneState[0]==1 && laneState[1]==1 && laneState[2]==1){
        // reset all buttons and states
        for(int laneId=0; laneId<=2; laneId++){
          laneButtonState[laneId] = 0;
          lastLaneButtonState[laneId] = 0;
          laneState[laneId] = 0;
          digitalWrite(laneStateLedPin[laneId], LOW); //Turn off led
        }
        rewardScore(allLaneActiveBonus);
      }
    }

body:
Looks like a timing issue.

Which ever order you hit the buttons in the last one always `stays` lit (and you get an extra 10 points added).

I set a breakpoint at:

    rewardScore(allLaneActiveBonus);

...and just waited a sec and then continued and your code worked as expected.

So I think that you are setting all lines to LOW in `checkAllLanesLit()` and then only have a short delay (5mS) before looping round and checking again (at which point the button is still HIGH as you haven't taken your finger off it quickly enough) - resulting in the additional 10 points and that lane being lit again.


body:
There are 2 lines of code that need to be removed from the `checkAllLanesLit()` function in order for your code to work as desired:

      laneButtonState[laneId] = 0;
      lastLaneButtonState[laneId] = 0;

*Explanation:*
What is happening is that the `detectLaneButtonPassage()` is firing as normal. Then `checkAllLanesLit()` runs and clears the `lastLaneButtonState` flag.

The program loops around again and the lane button is still pressed. However, the `detectLaneButtonPassage()` fires again because `lastLaneButtonState` has been reset and it appears to the program as a rising edge. Hence the extra 10 points.

----------

On a side note, the following 2 lines could be reduced down to a single line:

    if(laneButtonState[laneId] != lastLaneButtonState[laneId]){
        if(laneButtonState[laneId] == HIGH){

The above lines of code are detecting a rising edge. They can be expressed as:

    if(laneButtonState[laneId] && !lastLaneButtonState[laneId]){

For the if statement to fire `laneButtonState` must be high and `lastLaneButtonState` must be low.


message:
Using an LM339 IC as a motor driver

I have an [LM339 IC][1] from Radioshack that I am hoping to use as a motor driver.

I read many resources on how the [L239D][2] can be used as one.  I don't have enough circuit experience to truly know the difference between the two and googling shows many wiki pages I couldn't fully understand.

Can the LM339 be used as a motor driver?

I did a quick comparison of the two circuits here [LM339][3]  and [L239D][4]

But I am still unsure.  I don't want to fry my board so I am asking first.

  [1]: https://www.radioshack.com/products/quad-comparator
  [2]: http://www.instructables.com/answers/L239D-Motor-Driver-IC/
  [3]: https://www.google.com/search?q=lm339 image&espv=2&biw=1745&bih=897&tbm=isch&imgil=K4apd3i1hol9zM%3A%3BeiYyjemhPFicUM%3Bhttp%253A%252F%252Fwww.engineersgarage.com%252Felectronic-components%252Flm339-datasheet&source=iu&pf=m&fir=K4apd3i1hol9zM%3A%2CeiYyjemhPFicUM%2C_&usg=__YQbVumHDi18mddou0YcyQbS4JSg=&ved=0ahUKEwjGif20tJzPAhUD4oMKHRMACF4QyjcINQ&ei=O13gV4aAJ4PEjwSTgKDwBQ#imgrc=K4apd3i1hol9zM:
  [4]: https://www.google.com/search?q=l239d image&espv=2&biw=1745&bih=897&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjg4uOvtJzPAhUB0YMKHYb5DpAQ_AUIBigB#imgrc=It8hKixaSelnRM:

body:
The LM339 is a comparator, not a motor driver. The L239D is a dual H-bridge motor driver.

They are completely different things. One is used for comparing two voltages (up to 4 times, it's a "quad"), the other is used for driving motors.

The LM339 can output an absolute maximum of 20mA. That's half what the Arduino itself can output on an IO pin!

You could use the LM339 as part of the control circuitry to *control* a H-bridge, but it cannot itself drive a motor in any way, shape, or form.


message:
Sending uint16_t over I2C

How do you transmit and read a uint16_t over I2C?

I'm trying to read two uint16_t values from a slave device, and I'm seeing nonsensical readings.

This is the code on my slave Arduino Uno:

    #include <Wire.h>

    void send_wire_int(uint16_t num){

        // Send low byte
        Wire.write((uint8_t)num);

        // Send high byte
        num >>= 8;
        Wire.write((uint8_t)num);
    }

    // This is called from the I2C host.
    void I2C_Send()
    {

        //  send_wire_int(acount_abs);// Send encoder A count.
        //  send_wire_int(bcount_abs);// Send encoder B count.

        send_wire_int(0);
        send_wire_int(0);

    }

    void setup(){

        Wire.begin(30);                                                        // initialize I²C library and set slave address
        Wire.onRequest(I2C_Send);                                                   // define I²C slave transmit ISR

        Wire.flush();
        Wire.setTimeout(1000L);

    }

    void loop(){
        //stuff
    }

All it does is wait for the master to request data. Originally, it was sending the values of two registers back, but these values were also garbled or non-changing, so I changed it to just send back 0s but I still get the identical garbled values.

This is the code on my master Arduino Uno:

    #include <Wire.h>

    uint16_t receive_wire_int(){

        while(Wire.available() < 1){}

        // Read low byte into rxnum
        uint16_t rxnum = Wire.read();

        while(Wire.available() < 1){}

        // Read high byte into rxnum
        rxnum += Wire.read() << 8;

        return rxnum;
    }

    void setup() {
     Wire.begin();        // join i2c bus (address optional for master)
        Wire.setTimeout(1000L);
     Serial.begin(9600);  // start serial for output
    }

    void loop() {
     Serial.println("Requesting data..."); Serial.flush();

     Wire.requestFrom(30, 4);

     uint16_t acount = receive_wire_int();
     uint16_t bcount = receive_wire_int();

     Serial.println(String("acount:")+String(acount)+String(" bcount:")+String(bcount));

     delay(500);
    }

As you can see, it simply requests the two uint16_t values in 4 bytes, and then prints them to the Serial (my laptop's terminal).

The output I'm seeing is:

    acount:65280 bcount:65535

when I would expect:

    acount:0 bcount:0

What I am I doing wrong?

body:
So I've just tested your code and apparently you have to send all data at once. After some research: it sends characters into the function `twi_transmit` and this function just fills the buffer and actual data are sent asynchronously. So, if you are fast enough, you will overwrite the buffer with another bytes and it's still like you have only 1 character to send.

For example this works (AVRs are little endian):

    #include <Wire.h>

    // This is called from the I2C host.
    void I2C_Send()
    {
        uint16_t   uints[2] = {0xDEAD,0xBEEF};

        Wire.write((uint8_t*) uints, 4);
    }

    void setup(){
        Wire.begin(30);  // initialize I²C library and set slave address
        Wire.onRequest(I2C_Send); // define I²C slave transmit ISR

        Wire.flush();
        Wire.setTimeout(1000L);
    }

    void loop(){
        //stuff
    }

And receiver with `HEX` prints:

    #include <Wire.h>

    uint16_t receive_wire_int(){

        while(Wire.available() < 1){}

        // Read low byte into rxnum
        uint16_t rxnum = Wire.read();

        while(Wire.available() < 1){}

        // Read high byte into rxnum
        rxnum += Wire.read() << 8;

        return rxnum;
    }

    void setup() {
        Wire.begin();        // join i2c bus (address optional for master)
        Wire.setTimeout(1000L);
        Serial.begin(9600);  // start serial for output
    }

    void loop() {
        Serial.println("Requesting data..."); Serial.flush();

        Wire.requestFrom(30, 4);

        uint16_t acount = receive_wire_int();
        uint16_t bcount = receive_wire_int();

        Serial.print("acount: 0x");
        Serial.print(acount,HEX);
        Serial.print("  bcount: 0x");
        Serial.println(bcount,HEX);

        delay(500);
    }


body:
The problem is that I'm using the wrong type of `write()` in my slave. As [this blog][1] explains, there are two overloaded `write()` methods in the Wire library. One that accepts a single byte, and another that accepts a byte array. I was sending each byte separately, which doesn't guarantee they'll be received together.

It works if I rewrite my slave's to:

    void I2C_Send()
    {
      byte myArray[4];

      myArray[0] = 0;
      myArray[1] = 0;
      myArray[2] = 0;
      myArray[3] = 0;

      Wire.write(myArray, 4);

    }

  [1]: https://thewanderingengineer.com/2015/05/02/1312/


message:
ESP8266 GET REPLY ERROR 501

I am trying to build a home automation system and i am unable to get data from a website using the arduino sketch, however i am able to get data from the website when i enter the AT commands into the serial monitor.Below is my sketch:

    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(4,5);

    void setup(){
      Serial.begin(9600);
      esp8266.begin(115200);
      esp8266.println("AT+CIPMUX=1\r\n");
      delay(2000);
      esp8266.println("AT+CIPSTART=0,\"TCP\",\"www.homeautomationserver.com\",80 \r\n");
      delay(2000);
      esp8266.println("AT+CIPSEND=0,75");
      esp8266.println("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
      esp8266.println("Host:www.homeautomationserver.com\r\n\r\n");
    }

    void loop(){

      if (esp8266.available()){
        Serial.write(esp8266.read());
      }
      if (Serial.available()){
        esp8266.write(Serial.read());
      }
    }

I get a 501 not Implemented error from the server.

Please Help.

Thanks

body:
Can you use you favourite web browser and retrieve the page http://www.homeautomationserver.com/f/pw9e1acqx7yb0gl.txt ?
If you can then the problem is with your client, if not its with the address you are requesting or the server.

The fact you are getting a 501 error indicates that GET is not supported for this resource.  So check that you are using the correct method?

Get yourself a REST console (there is an add-on for chrome and plenty of others) try typing the command in manually to see if you can identify the fault.

Look at Wikipedia for a list of error codes, it might give you a clue as to what is wrong.

And don't you need a AT+CIPSEND after you have printed the http packet?


body:
Your problem lies in these lines:

    esp8266.println("AT+CIPSEND=0,75");
    esp8266.println("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
    esp8266.println("Host:www.homeautomationserver.com\r\n\r\n");

You are mistakenly using `println()` instead of `print()` when sending the data. That imposes its own `<CR><LF>` sequence on the end of the lines, yet you are adding the `<CR><LF>` manually.  You are also incorrectly specifying 75 characters to send, so the result of all that is:

    GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n              37
    \r\n                                                  2
    Host:www.homeautomationserver.com\r\n                35
    \r                                                    1
                                                       ----
                                                         75

I.e., your request is garbled. You need to change the `println()` to `print()` for the data printing and make sure the character count is correct:

    esp8266.println("AT+CIPSEND=0,74");
    esp8266.print("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
    esp8266.print("Host:www.homeautomationserver.com\r\n\r\n");

    GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n              37
    Host:www.homeautomationserver.com\r\n                35
    \r\n                                                  2
                                                       ----
                                                         74

You should also include more detail and commands in your headers. Things like the length of the body (0 bytes) and the fact that the connection should be closed, and there really should be a space after the colon on the Host: header:

    esp8266.println("AT+CIPSEND=0,113");
    esp8266.print("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
    esp8266.print("Connection: close\r\n");
    esp8266.print("Content-Length: 0\r\n");
    esp8266.print("Host: www.homeautomationserver.com\r\n\r\n");

    GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n              37
    Connection: close\r\n                                19
    Content-Length: 0\r\n                                19
    Host: www.homeautomationserver.com\r\n               36
    \r\n                                                  2
                                                      -----
                                                        113


message:
SD card shield not working on 3.3v

My SD shield works nicely on 5v supply, but does not detect SD card on 3.3v. Could someone explain the possible reason behind this? Could you also provide a solution for this?

I've worked with it on Arduino Uno. Now I want to use SD card directly with ESP-12E to read its contents using SPI [by doing something like this][1]. Since ESP8266 operates olny on 3.3v, I need SD card to work on this voltage.

I've used two separate SD card shields without any luck! Photos of the two shields and micro-SD card are attached.

[![SDHC card shield-front][2]][2]

[![microSD card shield-front][3]][3]

[![microSD card shield-back][4]][4]

[![microSD card and adapter][5]][5]

  [1]: https://www.reddit.com/r/esp8266/comments/48ib9g/connecting_a_sd_card_to_my_esp8266/
  [2]: https://i.stack.imgur.com/buF9C.jpg
  [3]: https://i.stack.imgur.com/cRirB.jpg
  [4]: https://i.stack.imgur.com/ila5I.jpg
  [5]: https://i.stack.imgur.com/kPdiq.jpg

body:
I could not find any info on the full size SD card adaptor, but the microSD adaptor has a 3.3V ([LM1117][1] or equivalent) regulator on it. It, therefore, needs a minimum of 4.5V to operate.

To run the adaptor from 3.3V, you would have to remove the regulator and solder in a piece of wire in its place.

  [1]: http://www.ti.com/lit/ds/symlink/lm1117.pdf


message:
options for wireless data broadcasting to hundreds of nodes

I would like to build approx 100 arduino devices that can talk to each other, I have a set of constraints that I'm looking to get some insight on :

 - all devices would operate within a 300 meter proximity of each other

 - the devices each need to broadcast some data (their speed and
   orientation from a gyro) to the rest of the devices in the group for
   storage
 - They need to update each other roughly every 500ms/1s
 - Some of the devices need to be added and removed from the pool regularly
 - The devices need to start broadcasting their data to the rest of the
   devices in the pool immediately when added (<1s delay)
 - The spectrum needs to be public & unlicensed

Which method of communication would you recommend? For the range, it seems like a 433hz RF transceiver and receiver would be appropriate or wifi could work but I have concerns about overloading the channels. Bluetooth seems like it has too long a handshake period and the range is too low.

Are there any other options I'm missing? What would be the best way to implement this?

Many thanks for you answers

Update : Data estimation

So the data payload I estimate consists of :

Speed (km/ph) : ok so this will be max 3 decimal numbers, so one short int should be enough here (2 bytes)

bearing : so this will be a standard bearing, let's assume between 0-360 so another short int should be fine (2 bytes)

Velocity : ok, so also a short (2 bytes)

Long : well this needs to be a 32 bit float so it's going to take 4 bytes

Lat : same as above 4 bytes

It's possible with some hackery I could combine speed, volcity and bearing into one short to only take 2 bytes. But let's assume I'm probably going to need 14 bytes, in best case 9.

body:
In terms of Radio, the RFM69 is a good option for range, speed and reliability at low cost. A board like this one https://talk2.wisen.com.au/product-talk2-whisper-node-avr/ would have all ready to go, just add your sensors.

The link can run on 433MHz, 868MHz or 915MHz band, which cover 99% of unlicensed/open frequencies worldwide.

[![Whisper Node][1]][1]

For the protocol/software you need to reduce the message as much as possible. As you mentioned, you could have 9 bytes for the payload if you "share" some bytes, which is the correct approach in this tight network. Add some 2 extra bytes for "operation/command", "sender" and "receiver". Additional to that, you need to consider the bytes added by the radio itself, like Preamble, Sync-word, Network ID, Length, CRC, etc.

[![RFM69 Frame][2]][2]

The biggest challenge in my opinion would be to not have the RF network flooded with messages, causing multiple radios to transmit at the same time and messages being lost.

Let's suppose you have a total of **20 bytes** for all headers+payload per message. If your network is running at **80Kbits/sec (or 10KBytes/s)**, that would allow a maximum of 500 message/second (2ms per message) in a perfect scenario, without considering any kind of delay between messages.

Bring down to the real-world a 1/3 link utilization is a bit more realistic, giving you a bit over 150 messages of 20 bytes per second. In other words, if the network had an evenly message distribution a node would transmit a 2ms message followed by 6ms of silence.

Now, you can't count that 100 nodes would have perfect synchronization to send a 2ms message and stay quiet for exactly 998ms before sending a message again. There are so many variables which require you to have some sort of control.

One way of doing that is by using a **pooling mechanism**, where you have a "tick" or "clock" node, which is the only one allowed to talk without being asked. This node will be sending "pooling" requests, a small message with 1 or 2 bytes, containing a command and the destination address, for example: 0x99 0x0A, where 0x99 is the address of the node being polled and 0x0A is the command, like "send me the instrumentation readings, you have 2ms".

Now, instead of the node 0x99 start reading the sensors, it already have it all **stored in memory and ready to go**, sending the broadcast message to everyone interested. The node 0x99 will also start collecting the new sensor data and preparing the message, so as soon it'll be asked it's ready to go again.

This way you can control how noise the network is and also implement other commands to capture additional information if necessary, etc.

Another implementation would be similar to the old "Token-Ring", but I believe having a master would be more beneficial in this case.

**Notes:**

 - The RFM69 can go over 200Kbp/s, but only tests would tell the maximum reliable speed. I use 80Kbp/s to make maths easier.
 - Design your system so it would survive if a message is lost, like UDP packages, send it and "pray". Adding Ack and re-transmission is probably worst as it would slow down the whole cycle.
 - The radio also offers encryption, but it might take a few uS extra
 - If one node will be expected to receive every single message, bear in mind that it would have only a few milliseconds available to process the message and do whatever it needs to do before another message arrive. If you need to perform lots of processing/logs/control actuators you might need to delegate this task to other MCU(s)

Cheers,

  [1]: https://talk2blog.files.wordpress.com/2016/02/whispernode_0-3v.jpg?w=400
  [2]: https://i.stack.imgur.com/5iiJ4.png


message:
How can I tell how large my program is?

**Scenario**

When I upload my project via the Arduino ide I see this at the bottom:

    Writing | ################################################## | 100% 4.14s

    avrdude: 25698 bytes of flash written
    avrdude: verifying flash memory against /var/folders/r4/s_j4c02s3wvcx6wy41__rnwh0000gp/T/build5447a2e9a95ee46ba2ad71abe5de02d6.tmp/SwatBotSpine.ino.hex:
    avrdude: load data flash data from input file /var/folders/r4/s_j4c02s3wvcx6wy41__rnwh0000gp/T/build5447a2e9a95ee46ba2ad71abe5de02d6.tmp/SwatBotSpine.ino.hex:
    avrdude: input file /var/folders/r4/s_j4c02s3wvcx6wy41__rnwh0000gp/T/build5447a2e9a95ee46ba2ad71abe5de02d6.tmp/SwatBotSpine.ino.hex contains 25698 bytes

**Question**

I'm uploading to an `Arduino Uno`, does this mean I have 32256 - 25698 bytes left?

body:
Short answer: Yes.

At the end of a successful compilation (not upload), at least in ArduinoIDE 1.6.9, the final 2 messages look like:

> Sketch uses 23,442 bytes (72%) of program storage space. Maximum is
> 32,256 bytes. <br>Global variables use 1,093 bytes (53%) of dynamic
> memory, leaving 955 bytes for local variables. Maximum is 2,048 bytes.

In this case, 8814 bytes of flash remain unused, and 955 bytes remain for the use of the stack and the heap, combined.


message:
Object Array using Inheritance

I would like to create an array of a generic type so I can use multiple sensors and make my code as extensible as possible.

    /*
      Planning for good design. Agent library
      should be able to use more than one sensor.

      The agent's constructor will accept a vector
      of sensors.
    */
    class Sensor
    {
     public:
      Sensor(){};
    };

My implementation class

    #include "Arduino.h"

    class UltraSonicSensor: public Sensor {
     public:
      /*
        Constructors
       */
      UltraSonicSensor(){};
      UltraSonicSensor(int pin){
        pin_ = pin;
      };
      int Sense(){ return 20;};
      /*
        Measure Distance
       */
      float DistanceMeasure(void);
     private:
      /*
        Class only suppports Metric
       */
      float microseconds_to_centimeters(void);
      int pin_;
      long duration_;
    };

    #endif // SROBOT_SENSORS_ULTRASONIC_H_

I have tried many, many variations of this code but always the same error

    Sensor *sensors[2];

    UltraSonicSensor uSensor;
    sensors[0] = &uSensor;

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

    void loop(){
      Serial.println("starting...");
      delay(1000);
      Serial.println("ok");
    //  delay(2000);
    //  for (int i = 0; i < sensors.size(); i++) {
    ////    sensors[i].Sense();
    //  }
    }

The error is always a variation of

    main:10: error: 'sensors' does not name a type
     sensors[0] = &uSensor;
     ^
    exit status 1
    'sensors' does not name a type

I also used the code for a [small replacement][1] `vector` class but also the same error

  [1]: http://forum.arduino.cc/index.php?topic=45626.0

body:
You have to do it inside of function:

    Sensor *sensors[2];

    UltraSonicSensor uSensor;

    void setup(){
      Serial.begin(9600);
      sensors[0] = &uSensor;
    }

Or directly:

    UltraSonicSensor uSensor;

    Sensor *sensors[] = {&uSensor};

Don't forget to make method `Sense()` virtual in the base class and in the inherited classes. Otherwise you'll have to also find out the type of the object and typecast it to correct class pointer before it's use.

    class Sensor
    {
      public:
        virtual int Sense() = 0; // pure virtual base class
    };

    // and inherited class:

    class UltraSonicSensor: public Sensor {
      public:
        // ...

        // Prototype must be exactly the same, by using override
        // is ensured it actually overrides something from the parent class.
        virtual int Sense() override {
            // ...
        }
        // ...
    }

Also the last versions of `Arduino IDE` supports `C++11` standard so you can use range based `for` loop:

    for (Sensor * sensor : sensors) {
        int val = sensor->Sense();
        // ...
    }


body:
Based on the answer from @KIIV and the [Vector class][1], the below code compiles successfully

    #include "Vector.h"
    #include "Sensor.h"
    #include "UltraSonicSensor.h"
    #include "LaserSensor.h"

    Vector<Sensor*> sensors;
    UltraSonicSensor uSensor;
    LaserSensor lSensor;

    void setup(){
      sensors.push_back(&uSensor);
      sensors.push_back(&lSensor);
    }

    void loop(){
      Serial.println("starting...");
      delay(1000);
      for (int i = 0; i < sensors.size(); i++) {
        int val = sensors[i]->Sense();
        // ...
      }
    }

  [1]: http://forum.arduino.cc/index.php?topic=45626.0


message:
FreqMeasure.h uncompatible with my code problem

I have written code to read temperatures on a motor which also has pulse feedback to see speed, (one hall sensor) and my previous version of the code does work fine, however when i add example frequency code from [codebender][1] into my code it doesn't give feedback on the frequency. Standalone the frequency code works fine. Is there any obvious failure in the code or is there just some conflict between files in library?

Trying to return RPM into the SD card results in 0.00. And the temperature measurements goes into switching between 85C and -127C.

Equipment: Arduino Nano, DS18B20, 2x16 LCD, Homemade SD shield, motor with internal motordriver.

Here is my code:

    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <LiquidCrystal.h>
    #include <SD.h>
    #include <FreqMeasure.h>

    // Data wire is plugged into pin 9 on the Arduino
    #define ONE_WIRE_BUS 9

    // Setup a oneWire instance to communicate with any OneWire devices
    // (not just Maxim/Dallas temperature ICs)
    OneWire oneWire(ONE_WIRE_BUS);
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    // Pass our oneWire reference to Dallas Temperature.
    DallasTemperature sensors(&oneWire);

    float temperature1, temperature2, temperature3;
    double RPM;
    void setup(void)
    {
      // start serial port
      Serial.begin(57600);
      FreqMeasure.begin();
      Serial.println("Dallas Temperature IC Control Library Demo");
      // Start up the library
      lcd.begin(16, 2);
      sensors.begin();
      Serial.print("Initializing SD card...");      // Initialize SD card

      if (!SD.begin(10)) {
        Serial.println("initialization failed!");   // Initialize SD card failed
        return;
      }
      Serial.println("initialization done.");       // Initialize SD card done
    }

    double sum=0;
    int count=0;

    void loop(void)
    {
      if (FreqMeasure.available()) {
        // average several reading together
        sum = sum + FreqMeasure.read();
        count = count + 1;
        if (count > 30) {
          double frequency = F_CPU / (sum / count);
          RPM=frequency*60;
          sum = 0;
          count = 0;
        }
      }

      unsigned long curMillis = millis();
      unsigned long curSeconds = curMillis/1000;   // Get current seconds
      // call sensors.requestTemperatures() to issue a global temperature
      // request to all devices on the bus
      Serial.print(" Requesting temperatures...");
      sensors.requestTemperatures(); // Send the command to get temperatures
      Serial.println("DONE");
      temperature1=sensors.getTempCByIndex(0);
      temperature2=sensors.getTempCByIndex(1);
      temperature3=sensors.getTempCByIndex(2);
      logData();
      Serial.print("Temperature for Device 1 is: ");
      Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
      Serial.print("Temperature for Device 2 is: ");
      Serial.print(sensors.getTempCByIndex(1));
      Serial.print("Temperature for Device 3 is: ");
      Serial.println(sensors.getTempCByIndex(2));

      lcd.setCursor(0, 0);
      lcd.print("T1=");
      lcd.setCursor(3, 0);
      lcd.print(sensors.getTempCByIndex(0));
      lcd.setCursor(8, 0);
      lcd.print("T2=");
      lcd.setCursor(11, 0);
      lcd.print(sensors.getTempCByIndex(1));
      lcd.setCursor(0, 1);
      lcd.print("T3=");
      lcd.setCursor(3, 1);
      lcd.print(sensors.getTempCByIndex(2));
      lcd.setCursor(8, 1);
      lcd.print("S=");
      lcd.setCursor(10, 1);
      lcd.print(curSeconds);
        // You can have more than one IC on the same bus.
        // 0 refers to the first IC on the wire

    }

    void logData() {
      Serial.print("Temperature1 = ");   Serial.print(temperature1);    // Printing to serial communication
      Serial.print(" C, Temperature2 = ");  Serial.print(temperature2);       // Printing to serial communication
      Serial.print(" C, Temperature3 = ");  Serial.print(temperature3);       // Printing to serial communication
      Serial.println(" C");                                           // Printing to serial communication
      Serial.println(RPM);
      unsigned long curMillis = millis();          // Get current time
      unsigned long curSeconds = curMillis/1000;   // Get current seconds

      // open the file. note that only one file can be open at a time,
      // so you have to close this one before opening another.
      File myFile = SD.open("LOG.txt", FILE_WRITE);

      // if the file opened okay, write to it:
      if (myFile) {
        Serial.print("Writing to LOG.txt...");                        // Printing to serial communication
        myFile.print("Time = "); myFile.print(curSeconds);            // Printing to log file on sd card
        myFile.print(" Temperature1 = "); myFile.print(temperature1);   // Printing to log file on sd card
        myFile.print(" Temperature2 = "); myFile.print(temperature2);         // Printing to log file on sd card
        myFile.print(" Temperature3 = "); myFile.print(temperature3);       // Printing to log file on sd card
        myFile.print(" RPM = "); myFile.println(RPM);       // Printing to log file on sd card
        // close the file:
        myFile.close();
        Serial.println("done.");
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening LOG.txt");                      // Error either SD card not connected or not detected
      }
      delay(1000);
    }

  [1]: https://codebender.cc/example/FreqMeasure/LCD_Output#LCD_Output.ino

body:
I believe there is a conflict bewteen the code relative to the SD card, which uses `SPI` and the use of timer1 within `FreqMeasure`.

My advice is to temporarily remove the code for the SD card and write that data onto the serial console: if the data displays correctly on the serial monitor than you have an indication the issue is in there.

The problem with SPI and time based interrupts is the latter might prevent the SPI communication to properly complete.


body:
This is an explanation of the issue with the RPM variable in the code, its not an answer, but it needs formatting to explain it clearly.

    double RPM;
    ...
    if (FreqMeasure.available()) {
    ...
      RPM=frequency*60;
    ...
    }
    ...
    Serial.println(RPM);

It is _possible_ that RPM is going to be written to Serial.println() before it has a value set.

In this case it is very unlikely to cause anything more than 'garbage' to be printed, but it could be much worse.  So I think if you initialised the RPM variable to 0.0 when you declare it it would be good practice.


body:
From what i have tested myself towards then it seems that the problem with this code is that OneWire.h and DallasTemperature.h are the problem when combined with FreqMeasure.h, so i found a way to use the A0 as RPM reader. So the answer to the question is that those libraries are uncompatible, and with the following code it is possible to read RPM, temperature and write to SD.

My code works with the added A0 as RPM reader.

    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <LiquidCrystal.h>
    #include <SD.h>

    // Data wire is plugged into pin 9 on the Arduino
    #define ONE_WIRE_BUS 9

    // Setup a oneWire instance to communicate with any OneWire devices
    // (not just Maxim/Dallas temperature ICs)
    OneWire oneWire(ONE_WIRE_BUS);
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    // Pass our oneWire reference to Dallas Temperature.
    DallasTemperature sensors(&oneWire);

    float temperature1, temperature2, temperature3;
    double RPM=0.0;
    //storage variables
    byte newData = 0;
    byte prevData = 0;
    //freq variables
    unsigned int timer = 0;
    unsigned int period = 0;
    double frequency;

    void setup(void)
    {
      cli();  //disable interrupts
      ADCSRA = 0; //clear register
      ADCSRB = 0; //clear register

      ADMUX|=(1<<REFS0);  //Set reference voltage
      ADMUX|=(1<<ADLAR);  //left align the ADC value so we can read highest 8 bits from the ADCH register only
      ADCSRA|=(1<<ADPS2)|(1<<ADPS0);  //set ADC clock with 32 prescaler- 16mHz/32=500kHz
      ADCSRA|=(1<<ADATE); //enable auto trigger
      ADCSRA|=(1<<ADIE);  //enable interrupts when measurement is complete
      ADCSRA|=(1<<ADEN);  //enable ADC
      ADCSRA|=(1<<ADSC);  //start ADC measurement
      sei();  //enable interrupts

      // start serial port
      Serial.begin(57600);
      Serial.println("Dallas Temperature IC Control Library Demo");
      // Start up the library
      lcd.begin(16, 2);
      sensors.begin();
      Serial.print("Initializing SD card...");      // Initialize SD card

      if (!SD.begin(10)) {
        Serial.println("initialization failed!");   // Initialize SD card failed
        return;
      }
      Serial.println("initialization done.");       // Initialize SD card done
    }
    ISR(ADC_vect){  //when new ADC value ready
      prevData = newData; //store previous value
      newData = ADCH; //get value from A0
      if(prevData<127 && newData>=127){ //if increasing and crossing midpoint
        period = timer; //get period
        timer = 0;  //reset timer
      }
      timer++;  //increment timer at rate of 38,5kHz
    }

    void loop(void)
    {
      frequency = 38462/period; //timer rate/period
      RPM = frequency*60;
      unsigned long curMillis = millis();
      unsigned long curSeconds = curMillis/1000;   // Get current seconds
      // call sensors.requestTemperatures() to issue a global temperature
      // request to all devices on the bus
      Serial.print(" Requesting temperatures...");
      sensors.requestTemperatures(); // Send the command to get temperatures
      Serial.println("DONE");
      temperature1=sensors.getTempCByIndex(0);
      temperature2=sensors.getTempCByIndex(1);
      temperature3=sensors.getTempCByIndex(2);
      logData();

      lcd.setCursor(0, 0);
      lcd.print("T1=");
      lcd.setCursor(3, 0);
      lcd.print(temperature1);
      lcd.setCursor(8, 0);
      lcd.print("T2=");
      lcd.setCursor(11, 0);
      lcd.print(temperature2);
      lcd.setCursor(0, 1);
      lcd.print("T3=");
      lcd.setCursor(3, 1);
      lcd.print(temperature3);
      lcd.setCursor(8, 1);
      lcd.print("S=");
      lcd.setCursor(10, 1);
      lcd.print(curSeconds);
        // You can have more than one IC on the same bus.
        // 0 refers to the first IC on the wire

    }

    double sum=0.0;
    int count=0;

    void logData() {
      unsigned long curMillis = millis();          // Get current time
      unsigned long curSeconds = curMillis/1000;   // Get current seconds
      Serial.print("Time="); Serial.print(curSeconds);
      Serial.print(" Temperature1 = "); Serial.print(temperature1);
      Serial.print(" Temperature2 = "); Serial.print(temperature2);
      Serial.print(" Temperature3 = "); Serial.print(temperature3);
      Serial.print(" RPM = "); Serial.println(RPM);
      // open the file. note that only one file can be open at a time,
      // so you have to close this one before opening another.
      File myFile = SD.open("LOG.txt", FILE_WRITE);

      // if the file opened okay, write to it:
      if (myFile) {
        Serial.print("Writing to LOG.txt...");                        // Printing to serial communication
        myFile.print("Time = "); myFile.print(curSeconds);            // Printing to log file on sd card
        myFile.print(" Temperature1 = "); myFile.print(temperature1);   // Printing to log file on sd card
        myFile.print(" Temperature2 = "); myFile.print(temperature2);         // Printing to log file on sd card
        myFile.print(" Temperature3 = "); myFile.print(temperature3);       // Printing to log file on sd card
        myFile.print(" RPM = "); myFile.println(RPM);       // Printing to log file on sd card
        // close the file:
        myFile.close();
        Serial.println("done.");
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening LOG.txt");                      // Error either SD card not connected or not detected
      }
      delay(100);
    }


message:
Need help with 2X3 matrix for braille

I'm an intermediate Arduino progammer, and I'm making an electronic braille display for my friend. You can think of this display as an array of 28x3 LEDs(one braille character contains a maximum of six (2x3 for one letter) dots so there can be 14 characters displayed at a time, including spaces) but actually instead of LEDs, there will be electrical braille cells. This will be the algorithm:

1. Read string (English alphabet) files from SD card
2. Count the letters, including spaces, until it becomes 14. Convert them into braille (2x3 for one letter) and then display them (as we will be able to display only 14 letters at a time )
3. When the user presses the button for the next row/page do the same process(step 2) for the next string.

So this is the complete process I want to do.

I have 5 months deadline to make it. The main problem is how I can make the code to convert and then display it. I know there are already a lot of Arduino libraries out there for displaying stranded English characters, but this is different, because I'm new to Arduino and 'C'.

Instead of losing your mind and saying this site is not for fool people like you, please guide this 17yr old what should I learn in order to make this for my friend who lost his eyesight in an accident(consider I have time of 5 months).

Do I have to build entire new Library for converting alphabet and multiplexing braille? Or is there existing code that will work.

[![Braille][1]][1]

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

body:
Each character will be 6 bits (so let's use a byte to store it) and we'll use the following bit to LED mapping

    bit0   bit1
    bit2   bit3
    bit4   bit5

Now you just need an array of bytes where each byte signifies an ASCII character.
Your code will get the letters to display and for each one will do something like this:

    byte BrailleBytes[] = {0x01, 0x05, 0xD, etc etc}; // only done the first 3 chars

    byte getBrailleForCharacter(char c)
    {
        int index = asc(c) - asc('A');
        return BrailleBytes[index];
    }

The key to decoding it this way is to make sure you sequence your bytes in BrailleByte the same way the [ASCII table][1] does - so if you want punctuation/numbers etc then you'll have to start lower and adjust the `asc('A')` accordingly

Now you have the byte it is just a case of checking what bits are set and turning on the relavant LEDs.

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


body:
First of all, may I say "Thank you" for helping your friend like that? I cannot think of a better way to use an Arduino than as a driver for a Braille display like you describe!

As you know, Braille is a _representation_ of characters into a "shape" that many systems don't recognise. Most people only encounter Braille when they press a button on an elevator or an ATM and see raised dots. Nevertheless, this is MUCH easier than the system that deaf people use: they represent whole words with a hand gesture.

> I hereby challenge EVERY reader of this post to enter an elevator, or look at an ATM, and notice (and decode!) the Braille dots on the buttons. Elevators for some reason use the double coding "`#1`", "`#2`", "`#3`" etc. (as described in the question's graphic) when it is clearly unnecessary - of _course_ you want to press a floor number! ATM buttons just use the 'raw' number pattern.

Because in Braille each character is converted into its own representation, you can do a VERY simple conversion. If you think about it, it is happening in computers trillions of times a day: when a computer converts a keypress into a set of pixels that represent the character on a computer screen. Your "pixels" are just a _WHOLE_ lot simpler than the 5x7, 13x15 or font-specific conversion for the characters that normal-sighted people see.

The first thing that you need to do is define a system that converts the 2x3 array into an array of bits. Why? To make storage easier. I'm going to represent the Braille cell with a set of digits from `0` to `5`:

     0   1
     2   3
     4   5

Why? Because it is then possible to "compress" the representation into a single byte of data. If you know computing well enough, you know that it runs in binary, and each digit above can be represented in a single bit, numbered 0-5.

Thus `A` is represented by raising the top left pin, which is the same as bit `0`: which can be represented by the byte `B000001` or `0x01`:

    X .
    . .
    . .

Of course a space, with nothing raised, would be represented by `B000000` or `0x00`.

You may not know this, and most computing people wouldn't either: the next "obvious" encoding (for `B`) would be `B000010` or `0x02`:

    . X
    . .
    . .

But a blind person would have a serious difficulty in decoding this, since in isolation (no way of interpreting the "down" pins) it would look exactly like an 'A'. So the fact that 'B' is encoded as:

    X .
    X .
    . .

means that the binary encoding would be `B000101` or `0x05`.

As a further example, the character 'I' would be

    . X
    X .
    . .

or the byte `B000110` or `0x06`.

I'm not going to convert every character, but I hope that this explains things well enough for you. By giving every character its own bit pattern, you can then convert any possible string into a set of bytes for conversion by your library.

Only... there's a problem. With Braille, you need to convert numbers `0` to `9` into a special pattern. Because Braille only has 6 'bits' to choose from (and even then not every combination is "nice" for blind people to read), there is a special "flag" character to say "the following characters are digits!" (and a pattern to say "OK, back to normal letters again").

This means that there is not a one-to-one translation between an English string of characters, and the resultant string of bytes to represent those characters in Braille: you need to add extra "convert" bytes to the process. Of course these "convert" bytes can also be represented by the same bitmap as described above:

    . X
    . X
    X X

is equal to `B111010` or `0x3A`.

That means that it is possible to write a function to convert a series of ASCII characters into a series of Braille bytes: you just need to provide more bytes than the string converts! This also means that you may need to use less than 14 characters from the source before you run out of room on the display...

I would _love_ to give you my address for more help: I'm afraid that StackExchange won't let me post my e-mail address!


message:
Arduino Rubber ducky?

So there is this hacking tool called a rubber ducky , the concept is that the device looks like a flash drive but the computer thinks it's a keyboard . According to what i know , a usb port has 4 wires , VCC GND and 2 for data , so i thought if it was possible to take a usb cable , cut it and connect it to the arduino accordingly , and send the computer that data so that he would think i connected a keyboard , and basicly create a fake reprogrammable keyboard

body:
Most Arduinos can't be a USB keyboard (not without some really nasty bit-banging code and dodgy electronics).

Some can, though - such as the Arduino Leonardo or the Arduino Micro. And you don't need to cut any cables, you just plug it in.


message:
While condition with & bitwise of PINx read

I was looking into `ATmega32u4` datasheet to configure the `SPI`, and there is initialization snippet for data transmission.

    void SPI_MasterTransmit(char cData)
    {
        /* Start transmission */
        SPDR = cData;
        /* Wait for transmission complete */
        while(!(SPSR & (1<<SPIF)));
    }

What I didn't quite get is the last line of the snippet with the while condition to check the state of the `SPIF` bit in `SPSR` register.

What I think I understand that it means, if `SPIF` bit with the a conditional value of 1 which would be in the ALU for comparing it with the actual bit state in `SPSR`. If this is true with & bitwise operator which would be true if the actual bit in the `SPSR` is set with the given value (`1 << SPIF`).

My questions:

1. Am I understanding it right?
2. What this line actually means?
3. I have removed the semicolon at the end of the line and it compiled OK! Is what I did OK?

body:
SPI transmitt is started by writing one Byte into `SPDR`. And this code won't return from `SPI_MasterTransmit` function before it's complete. Transmitt completition is anounced by setting SPIF by hardware (and if SPI interrupt and global interrupts are enabled, it'll run also ISR and clear that flag).

If you write into `SPDR` before transmission is completed you'll corrupt current "transaction", so you have to wait until it's complete before another write.

Bitwise & is used for bit masking. Bits in the result are set if bits at corresponding positions in arguments are both set:

    0b00110011
             &
    0b00100001
            ==
    0b00100001

So if bit at position SPIF is not set, it will loop again and when it's set, it exits the loop, as there is inverted logic.

    ( SPSR     & (1<<SPIF))                    !(SPRS &(1<<SPIF))
    0b0xxxxxxx & 0b10000000 == 0b00000000  =>  !0b00000000 == true
    0b1xxxxxxx & 0b10000000 == 0b10000000  =>  !0b10000000 == false


message:
Is there a library to use Amazon IoT services on any Arduino?

I started to work with AWS IoT today, which offers a MQTT based connection to their web service. They officially only have a demo for the Arduino Yún, which is rather expensive. Has someone managed to get it running (e.g. with a NodeMCU with a ESP8266)?

body:
You can try the AWS IoT Embedded C SDK, that is for more general devices.
Other Arduinos requires a crypto library and a device powerful enough, maybe PI, to support the authentication process...
At this time they have no crypto library like the YUN SDK, for other Arduinos...

[Try it...][1]

  [1]: https://github.com/aws/aws-iot-device-sdk-embedded-C/blob/master/README.md


message:
How do I program my Arduino Yun Shield when I keep getting this AVRDUDE error message?

The error message is:

> avrdude: AVR device initialized and ready to accept instructions
avrdude: Device signature = 0x1e950f
avrdude: Expected signature for ATmega32U4 is 1E 95 87
Double check chip, or use -F to override this check.

This error message is thrown when I attempt to upload any program to the Yun shield through an Arduino Bridge between the Uno and Yun shield with the Uno’s ATMega32 shorted into reset mode.
Any advice on how to get this working? Thanks.

body:
Apparently there is no `ATMega32U4` on that board but `ATmega328P` according to the signature `0x1e950f`.

Anyway, you may have to change or add new board with correct MCU setting.

Now I can see the difference between Yun and Yun shield. Shield can be connected to any Arduino board and Yun is similar like Shield + Leonardo.

I've found board definition for Arduino UNO:

    unoyun.name=Arduino Uno -- Dragino Yún
    unoyun.upload.via_ssh=true

    unoyun.vid.0=0x2341
    unoyun.pid.0=0x0043
    unoyun.vid.1=0x2341
    unoyun.pid.1=0x0001
    unoyun.upload.tool=avrdude
    unoyun.upload.protocol=arduino
    unoyun.upload.maximum_size=32256
    unoyun.upload.maximum_data_size=2048
    unoyun.upload.speed=57600
    unoyun.upload.disable_flushing=true
    unoyun.upload.use_1200bps_touch=true
    unoyun.upload.wait_for_upload_port=true

    unoyun.bootloader.tool=avrdude
    unoyun.bootloader.low_fuses=0xff
    unoyun.bootloader.high_fuses=0xde
    unoyun.bootloader.extended_fuses=0x05
    unoyun.bootloader.file=optiboot/optiboot_atmega328.hex
    unoyun.bootloader.unlock_bits=0x3F
    unoyun.bootloader.lock_bits=0x0F

    unoyun.build.mcu=atmega328p
    unoyun.build.f_cpu=16000000L
    unoyun.build.board=AVR_YUN
    unoyun.build.core=arduino
    unoyun.build.variant=standard

More info about it here: [https://www.arduino.cc/en/Guide/ArduinoYunShield][1] or similar product [http://wiki.dragino.com/index.php?title=Yun_Shield][2]

  [1]: https://www.arduino.cc/en/Guide/ArduinoYunShield
  [2]: http://wiki.dragino.com/index.php?title=Yun_Shield


body:
Make sure the board selected in the *Yun Shield* is the correct one (in this case *Arduino UNO*).

Steps for selecting the board on the Yun Shield
------------------------------------------------

 1. In your web browser load the *Yun Shield* page and log in (how to do this is described in the [Quick Start Guide][2]).
 2. Click on the SENSORS menu button.
 3. Under *Arduino Board Type* select the correct one.
 4. Click on the *CONFIGURE & RESTART MCU* button to apply settings.
 5. Maybe manual restart of the board would be needed (power unplug).

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

  [1]: http://wiki.dragino.com/index.php?title=Yun_Shield#Connect_to_Arduino_Uno
  [2]: http://www.dragino.com/downloads/downloads/YunShield/YUN_SHIELD_QUICK_START_GUIDE_v1.0.pdf
  [3]: https://i.stack.imgur.com/vutkA.gif


message:
Unable to analogWrite to MOSFET properly (IRLB3034)

I've got a 5 meter LED strip connected to a breadboard as such

12V Supply
----------

(+) -> (+) on breadboard rail

(-) -> ground on breadboard rail

Arduino (Wemos D1, all pins w/ PWM)
----------

pin7 -> gate(1st MOSFET)

pin8 -> gate(2nd MOSFET)

pin9 -> gate(3rd MOSFET)

GND -> ground on breadboard rail

MOSFETs (IRLB3034 equivalent)
----------

Gates (already explained)

Drain(1st MOSFET) -> Red line on WS2812 strip

Drain(2nd MOSFET) -> Green line on WS2812 strip

Drain(3rd MOSFET) -> Blue line on WS2812 strip

Source(all MOSFETs) -> (-) on breadboard

And despite this, when I run an extremely simple program such as this, I get white light (all being lit up), and can never individually address a color. I can write all to 0 and will still have a white light, same with writing all to 255, and same again with writing one or two to 255 and the remainder to 0.

    int redPin = 7;
    int bluePin = 8;
    int greenPin = 9;

    void setup() {

    }

    void loop() {
      analogWrite(redPin, 255);
      analogWrite(bluePin, 0);
      analogWrite(greenPin, 0);

    }

I'm thinking my AliExpress board may just be faulty, advertising PWM on every pin when that is not the case, or I may have selected the wrong MOSFETs for this application. Using this identical setup (same breadboard, same MOSFETs) with my Raspberry Pi 2B I was able to change the color of the lights.

Hoping someone here has worked with the Wemos D1 and can help. The documentation on this board seems to indicate that everything should be working, but it is not. I have two boards (same seller) and can confirm that it works with neither.

body:
Unfortunately the WS2812 LEDs color is set by powering it up and sending data to it. This means that you don't need the FETs at all.

Sparkfun have a really good walkthrough for hooking up and controlling these LEDs:
[WS2812 Breakout Hookup Guide][1]

To achieve what you set out to do (ie controlling the color with the FETs) you will need a different analog LED strip (such as [this][2]). Adafruit have a really good walkthrough for hooking up and controlling the LEDs in this fashion.
[Controlling Analog RGB LED Strips][3]

  [1]: https://learn.sparkfun.com/tutorials/ws2812-breakout-hookup-guide/all
  [2]: https://www.adafruit.com/products/285?&main_page=product_info&cPath=37&products_id=285
  [3]: https://learn.adafruit.com/rgb-led-strips?view=all


message:
Pass custom element of an array from an inherited class to main sketch

I'm building a base class that creates color patterns using FastLed's CRGB structure. I use the base class as inheritance for another more specific class that modifies a vector of *colors* (`Pixels[]`) and at some point I want to pass the color of a specific element from my class to the main sketch. But i'm having some issues with it, since the content of **`Pixels[]`** doesn't seem to match what I actually write in there.

Pattern.h:

 class Pattern
 {
  public:
  CRGB PixelAt(int idx);
  CRGB Pixels[6];
 }

Pattern.cpp:

 CRGB Pattern::PixelAt(int idx)
 {
   // safety check
   if (idx >= 0 && idx < NumLeds)
   {
     return Pixels[idx];
   }
   else
   {
     Serial.print("Index out of bounds: "); Serial.println(idx);
     return CRGB::Black;
   }
 }

TestPattern.h:

 class TestPattern : public Pattern {
  void Tick(unsigned long millis);
 }

TestPattern.cpp:

 void TestPattern::Tick(unsigned long millis)
 {
     for (int p = 0 ; p < NumLeds ; p++)
     {
       Pixels[p]=CRGB::Blue;
     }
 }

Main Sketch:

 for (int p = 0; p < NUM_PATTERNS; p++)
    {
      // update pattern
      ledPatterns[p].Tick(millis());

      if (ledPatterns[p].Status == Enabled)
      {
        // sum the values of the pixels
        for (int l = 0; l < NUM_LEDS; l++) {
          leds[l] += ledPatterns[p].PixelAt(l);
        }
      }
    }

I'm skipping parts of the code to make it easier to read, but I think with this much you should be able to help me make it work. I'm still getting acquainted with C and pointers, which is where I think the problem lies.

So how should I declare and use **`Pixels[]`** so that the Main Sketch, the base class and the inherited class all have consistent information?

body:
After reading comments i got some more clues where to search and indeed the problem was somewhat in the inheritance and how i was calling the functions. This post helped me [find the problem][1].

I forgot to post the piece of code where i was creating the patterns in the Main Sketch, this is how it was initially:

    Pattern ledPatterns[NUM_PATTERNS];
    ledPatterns[0] = TestPattern(NUM_LEDS, "Test Pattern 1", TestPat, 0, 0);
    ledPatterns[1] = TestPattern(NUM_LEDS, "Test Pattern 2", TestPat, 0, 1);

    ...
    ledPatterns[p].Tick(millis());
    ...

When i later called `ledPatterns.Tick` (the function that modifies the values, the function actually being called was the parent and not the child. Thus the unexpected result.

This is how i should have been initializing the patterns, since they are inherited:

    Pattern* ledPatterns[NUM_PATTERNS];
    ledPatterns[0] = new TestPattern(NUM_LEDS, "Test Pattern 1", TestPat, 0, 0);
    ledPatterns[1] = new TestPattern(NUM_LEDS, "Test Pattern 2", TestPat, 0, 1);

    ...
    ledPatterns[p]->Tick(millis());
    ...

Sorry for the huge confusion, i thought the problem was in a completely different part of the code

  [1]: https://stackoverflow.com/questions/34681286/why-is-a-virtual-function-of-child-class-not-called


message:
Analog read negative voltage inbuilt protection

I'm trying to read a -10 to +10V analog signal on my Arduino Mega (2560). I've been using a voltage divider to obtain a -5V to +5V signal (with two 10kOhm resistors), which used to work just fine.
I'm wondering if this -5V signal can damage the Analog Input pins of the Mega ?

Thank you in advance for your time !

body:
All the IO pins contain a pair of clamping diodes to protect against over-voltage and negative-voltage situations:

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

As long as the current flowing through one of those diodes doesn't exceed its maximum forward current all will be well and the Arduino won't be damaged. If too much current flows then you will damage the pin.

Since you have 10KΩ resistors, at -5V the maximum current that could flow (assuming a 0.7V drop on the diode) would be (-5 + 0.7) / (10,000 / 2) = -860µA (negative because it's flowing backwards out of the pin from ground to your negative voltage source, not into the pin to ground).

Unfortunately the datasheet doesn't provide a current limit specification for those diodes, but I would expect such a small amount of current to be safe enough.

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


body:
Current through the clamping diodes shouldn't be more than 1mA according to Atmel's [Zero Cross Detection Application Note (AVR182)][1].

EDIT: As Edgar Bonet pointed out you have current about `(-5+0.5)/(10000/2) = 0.9mA` (tested) in the worst case, there is not much space for mistakes.

  [1]: http://www.atmel.com/images/doc2508.pdf