title: ESP8266 GET REPLY ERROR 501

text:
# Question
Title: 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

# Answer
> 0 votes
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?

# Answer
> 1 votes
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

```

---
Tags: esp8266
---


title: MQTT Callback function don't called

text:
# Question
Title: MQTT Callback function don't called
I'm doing a device to recongnize NFC cards with an Arduino UNO, a CC3000 wifi shield, and a PN532 NFC shield. That's ok.

So, I created a sketch with this library: https://github.com/nathanchantrell/pubsubclient

I subscribed a topic /ocean/nfc/porta. When I publish a message to it, the callback function isn't called. Moreover, when it takes a card ID it publishs to a topic sometimes then don\`t work more. How to solve it?

```
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_PN532.h>
#include <Adafruit_CC3000.h>
#include <cc3000_PubSubClient.h>

#define PN532_IRQ   (4)
#define PN532_RESET (3)  // Not connected by default on the NFC Shield

char cardID[ 16 ];

Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
// also change #define in Adafruit_PN532.cpp library file
   #define Serial SerialUSB
#endif

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   2  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  7
#define ADAFRUIT_CC3000_CS    10

// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER);

#define WLAN_SSID       "Ocean Convidado"
#define WLAN_PASS       "ocean2901"
//#define WLAN_SSID       "Ocean Lab"
//#define WLAN_PASS       "ocean3101"

// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

Adafruit_CC3000_Client client;

// We're going to set our broker IP and union it to something we can use
union ArrayToIp {
  byte array[4];
  uint32_t ip;
};

ArrayToIp server = { 25, 0, 25, 172 };

void callback (char* topic, byte* payload, unsigned int len) {

    Serial.println(F("CALLBACK"));
/*
    char payload_buffer[20];

    if (strcmp (topic,"/ocean/nfc/porta") == 0) {

        byteToChar(payload, payload_buffer, len);

        if (strcmp(payload_buffer, "permitir") == 0) {
          Serial.println(F("Abreeee!!!!!!"));
        } else {
          Serial.println(F("Não abre!!!!!!"));
        }

    }*/
}

cc3000_PubSubClient mqttclient(server.ip, 1883, callback, client, cc3000);

void setup(void) {

  #ifndef ESP8266
    while (!Serial); // for Leonardo/Micro/Zero
  #endif
  Serial.begin(115200);
  Serial.println(F("Hello OCEAN NFC Reader!"));

  Serial.println(F("Inicializando NFC Reader...."));

  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print(F("Didn't find PN53x board"));
    while (1); // halt
  }
  // Got ok data, print it out!
  Serial.print(F("Found chip PN5")); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print(F("Firmware ver. ")); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print(F(".")); Serial.println((versiondata>>8) & 0xFF, DEC);

  // configure board to read RFID tags
  nfc.SAMConfig();

  Serial.println(F("Waiting for an ISO14443A Card ...\n\n"));

  Serial.println(F("Inicializando Wifi CC3000"));

  displayDriverMode();

  Serial.println(F("\nInicializando o CC3000 ..."));
  if (!cc3000.begin()) {
    Serial.println(F("Nao foi possivel inicializar o CC3000! Os cabos estao conectados corretamente?"));
    for(;;);
  }
  else {
    Serial.println(F("Carregou"));
  }

  uint16_t firmware = checkFirmwareVersion();
  if ((firmware != 0x113) && (firmware != 0x118)) {
    Serial.println(F("Versao do firmware errada!"));
    for(;;);
  }

  displayMACAddress();

  Serial.println(F("\nDeletando perfis de conexoes antigas"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Falhou!"));
    while(1);
  }

  /* Attempt to connect to an access point */
  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nTentando conectar-se a(o) ")); Serial.println(ssid);

  /* NOTE: Secure connections are not available in 'Tiny' mode! */
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Falhou!"));
    while(1);
  }

  Serial.println(F("Conectado!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Requisitando DHCP"));
  while (!cc3000.checkDHCP()) {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /* Display the IP address DNS, Gateway, etc. */
  while (!displayConnectionDetails()) {
    delay(1000);
  }

   // connect to the broker
   if (!client.connected()) {
     client = cc3000.connectTCP(server.ip, 1883);
     Serial.println(F("Conectando em TCP"));
   }

   // did that last thing work? sweet, let's do something
   if(client.connected()) {
    if (mqttclient.connect("ArduinoUnoClient-CC3000-A2", "iotocean", "NZZOLd0O66oLS0vpajiA123")) {
      Serial.println(F("Publicando"));
      mqttclient.publish("/ocean/nfc/debug","A2 está online");
      mqttclient.subscribe("/ocean/nfc/porta");
    }
    else {
      Serial.println(F("Ouve um erro ao conectar-se ao broker"));
    }
   }

}

void loop(void) {

  delay(1000);

  Serial.println(F("Entrei no loop\n"));
  uint8_t success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

  // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
  // 'uid' will be populated with the UID, and uidLength will indicate
  // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

  if (success) {
    // Display some basic information about the card
    Serial.println(F("Found an ISO14443A card"));
    Serial.print(F("  UID Length: "));Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print(F("  UID Value: "));
    nfc.PrintHex(uid, uidLength);

    if (uidLength == 4)
    {
      // We probably have a Mifare Classic card ...
      uint32_t cardid = uid[0];
      cardid <<= 8;
      cardid |= uid[1];
      cardid <<= 8;
      cardid |= uid[2];
      cardid <<= 8;
      cardid |= uid[3];
      Serial.print(F("Seems to be a Mifare Classic card #"));
      Serial.println(cardid);

          // Testa se ainda esta conectado
          if (!client.connected()) {
            Serial.println(F("!client.connected()"));
             client = cc3000.connectTCP(server.ip, 1883);

             if(client.connected()) {
               if (mqttclient.connect("ArduinoUnoClient-Office-A2")) {
                  mqttclient.publish("/ocean/nfc/debug","A2 está novamente online");
               }
             }
          } else {
            Serial.println(F("else !client.connected()"));
            // as per comment from LS_dev, platform is int 16bits
            sprintf(cardID,"%lu", cardid);

            mqttclient.publish("/ocean/nfc/id", cardID); delay(1000);
          }
          //delay(1000);

    }
    Serial.println(F(""));
  }

  Serial.println(F("Sai do loop\n"));
}

void displayDriverMode(void)
{
  #ifdef CC3000_TINY_DRIVER
    Serial.println(F("CC3000 is configure in 'Tiny' mode"));
  #else
    Serial.print(F("RX Buffer : "));
    Serial.print(CC3000_RX_BUFFER_SIZE);
    Serial.println(F(" bytes"));
    Serial.print(F("TX Buffer : "));
    Serial.print(CC3000_TX_BUFFER_SIZE);
    Serial.println(F(" bytes"));
  #endif
}

void charToByte(char* chars, byte* bytes, unsigned int count){
    for(unsigned int i = 0; i < count; i++)
      bytes[i] = (byte)chars[i];
}

void byteToChar(byte* bytes, char* chars, unsigned int count){
    for(unsigned int i = 0; i < count; i++)
       chars[i] = (char)bytes[i];
}

uint16_t checkFirmwareVersion(void)
{
  uint8_t major, minor;
  uint16_t version;

#ifndef CC3000_TINY_DRIVER
  if(!cc3000.getFirmwareVersion(&major, &minor))
  {
    Serial.println(F("Unable to retrieve the firmware version!\r\n"));
    version = 0;
  }
  else
  {
    Serial.print(F("Firmware V. : "));
    Serial.print(major); Serial.print(F(".")); Serial.println(minor);
    version = major; version <<= 8; version |= minor;
  }
#endif
  return version;
}

/**************************************************************************/
/*!
    @brief  Tries to read the 6-byte MAC address of the CC3000 module
*/
/**************************************************************************/
void displayMACAddress(void)
{
  uint8_t macAddress[6];

  if(!cc3000.getMacAddress(macAddress))
  {
    Serial.println(F("Unable to retrieve MAC Address!\r\n"));
  }
  else
  {
    Serial.print(F("MAC Address : "));
    cc3000.printHex((byte*)&macAddress, 6);
  }
}

/**************************************************************************/
/*!
    @brief  Tries to read the IP address and other connection details
*/
/**************************************************************************/
bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

  if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

```

Output of Arduino IDE:

> O sketch usa 28.438 bytes (88%) de espaço de armazenamento para programas. O máximo são 32.256 bytes. Variáveis globais usam 1.546 bytes (75%) de memória dinâmica, deixando 502 bytes para variáveis locais. O máximo são 2.048 bytes. Pouca memória disponível, problemas de estabilidade podem ocorrer.

# Answer
> -1 votes
I solved the problem. There is a bug on CC3000, so need to use WatchDog to reset for each while.

---
Tags: arduino-uno, rfid
---


title: SD card shield not working on 3.3v

text:
# Question
Title: 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. 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.

# Answer
I could not find any info on the full size SD card adaptor, but the microSD adaptor has a 3.3V (LM1117 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.
> 2 votes

---
Tags: esp8266
---


title: Sending uint16_t over I2C

text:
# Question
Title: 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?

# Answer
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);
}

```
> 2 votes

# Answer
The problem is that I'm using the wrong type of `write()` in my slave. As this blog 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);

}

```
> 2 votes

---
Tags: arduino-uno, i2c
---


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

text:
# Question
Title: 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?

# Answer
> 2 votes
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.
> 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.

---
Tags: arduino-uno, sketch-size
---


title: Identify connected PC per Arduino

text:
# Question
Title: Identify connected PC per Arduino
**Question:** Is there a way to collect any data (e.g. MAC addresses, installed devices, driver versions, etc.) from a PC by simply connecting an Arduino via USB to it, so that this PC can be clearly identified?

**Background:** Basically, I\`m using an Arduino to send some text to a computer by emulating a keyboard, but I don´t want the text to be sent to any computer I connect the Arduino with. That is why I want the PC to be identified first.

*To be clear: this should be done without having to install programs on the PC in the first place.*

# Answer
> 1 votes
No you cannot. Arduino communicates to pc via UART so there must be a host which can send or receive the data. You have to install software on the host computer which can send and receive data to the com port to which arduino is connected to.

---
Tags: serial, usb, communication, windows
---


title: Arduino Rubber ducky?

text:
# Question
Title: 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

# Answer
> 0 votes
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.

---
Tags: usb
---


# Question
Title: 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?

# Answer
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

```
> 3 votes

---
Tags: arduino-nano, spi, port-mapping
---


# Question
Title: 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)?

# Answer
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 votes

---
Tags: web-service
---


# Question
Title: 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.

# Answer
> 0 votes
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

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). Adafruit have a really good walkthrough for hooking up and controlling the LEDs in this fashion.
Controlling Analog RGB LED Strips

---
Tags: arduino-uno, arduino-ide, rgb-led
---


# Question
Title: 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.

# Answer
> 1 votes
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.

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.

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,

---
Tags: communication, wireless, rf
---


# Question
Title: 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 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);
}

```

# Answer
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.
> 1 votes

# Answer
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.
> 0 votes

# Answer
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);
}

```
> 0 votes

---
Tags: arduino-nano, lcd, sd-card, frequency, ds18b20
---


title: ISR halts in DUE

text:
# Question
Title: ISR halts in DUE
I am using the following simple code to test the interrupt functionality of due:

```
void aMillion(){
    for(int i = 0; i < 1000000; i++){
        if(i % 1000 == 0){
            Serial.print("m");
        }
    }
}

void setup(){
  Serial.begin(9600);
  pinMode(2, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), aMillion, CHANGE);
}
void loop()
{
}

```

obviously what we expect to see is a thousand "m" characters after each interrupt event. On Arduino Mega, this worked fine. But I have tested it on multiple Due boards.

Very odd news is that on the reset event of due, I do get a single "m" character printed.

# Answer
> 0 votes
An attempt to run long loops in the ISR for the DUE fails. This is the result of some sort of a run time monitoring system. An infinite loop like this one here, or even a loop with a thousand repetitions of a Serial Print will result in an early halt of ISR on the **DUE**.

On the **MEGA** however, This is not the case. ISRs can run much longer. (At least ten minutes as I tried)

---
Tags: arduino-due, interrupt, isr
---


# Question
Title: 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?

# Answer
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.

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 votes

---
Tags: c, array, pointer
---


title: Need help with 2X3 matrix for braille

text:
# Question
Title: 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.

# Answer
> 5 votes
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!

# Answer
> 4 votes
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 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.

---
Tags: programming, led, sd-card, display, multiplexer
---


title: Arduino UNO Rx/Tx speaks to itself

text:
# Question
Title: Arduino UNO Rx/Tx speaks to itself
I'm trying to make my chinese arduino (which use a chinese CH340G chip) speaks to itself via serial. I have wired rx/tx together.

Then, I run the arduino IDE and go to the serial monitor.

When I write a message, the arduino should respond with the exact same message, right ? Actually, when I write a message, the arduino doesn't respond anything...

# Answer
As Mikael Patel pointed out in his answer, you have set up a voltage divider. Mikael has thoughtfully provided a schematic of the clone Uno, where the relevant part is here:

---

## Equivalent circuit

If you jumper together pins D0 and D1 (Rx and Tx) on the Uno effectively you have made this circuit:

---

## Testing

If I set up this with a function generator, I get this result:

You can see that for a square-wave input of 0 to 5V, we only get an output of 2.16 to 5V.

---

## What is LOW?

Now looking at the datasheet for the DC characteristics we see:

For an input to register as LOW it has to be no higher than `0.3 * Vcc = 0.3 * 5`. Thus the voltage cannot be higher than 1.5V. Since we are measuring 2.16V, that will not count as a LOW.

Now admittedly that is for the Atmega328P and not the CH340G, but it will probably have similar characteristics.

I found a datasheet for the CH340G, and that shows even stricter requirements for a LOW signal:

---

## Official Uno

Comparing to the official Uno circuit:

You will note there that the indicator LEDs are on a different circuit, and thus do not form a voltage divider.

---

## The Maths

The clone Uno circuit above can be re-arranged like this:

Given that the LEDs have a voltage drop of 1.86V (measured in practice, and about right for the red LEDs I am using) then effectively we have the resistors R1 and R2 connected to 3.14V.

Since they are in parallel they are effectively 500 ohms.

Now using the formula for voltage dividers:

```
1000 / (1000 + 500) * (5 - 1.86) = 2.09V

```

This is close enough to the observed result. I didn't check each resistor to make sure it was exactly in spec.

I don't think R4 affects the results because it is effectively "floating".
> 5 votes

# Answer
After some research I found the below schematics of an Arduino UNO with CH340G. A loop-back is not possible as there is a voltage divider (1K ohm, i.e. RX/TX LED) resistors on the RX and TX line.

Tested on a Chinese Arduino Uno clone (VISduino) with CH340G and just as you wrote a loop-back does not work. Tested also an Arduino Mega 2560 clone with CH340G and a Duemilanove clone with FTDI. Both these work just fine.

Cheers!
> 2 votes

# Answer
There is no problem doing a loopback on an Arduino Uno, but you cannot use the serial monitor at the same time. I wrote the following test program, which works as expected:

```
const int LED_PIN = 13;

void setup() {
    pinMode(LED_PIN, OUTPUT);
    Serial.begin(9600);
}

void loop() {
    uint8_t data = random();
    Serial.write(data);
    while (!Serial.available()) { /* wait */ }
    if (Serial.read() == data) {

        // Two short pulses = success
        digitalWrite(LED_PIN, HIGH);
        delay(100);
        digitalWrite(LED_PIN, LOW);
        delay(100);
        digitalWrite(LED_PIN, HIGH);
        delay(100);
        digitalWrite(LED_PIN, LOW);
        delay(700);
    } else {

        // One long pulse = failure
        digitalWrite(LED_PIN, HIGH);
        delay(500);
        digitalWrite(LED_PIN, LOW);
        delay(500);
    }
}

```

There are, however, two caveats with this naive program:

1. the loopback wire has to be removed before uploading
2. after connecting the wire, the Arduino has to be reset to get out of the while loop.
> 0 votes

# Answer
the capacitor on pin 4 is connected to GND not to +5V
> -1 votes

---
Tags: serial
---


# Question
Title: 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 !

# Answer
> 3 votes
All the IO pins contain a pair of clamping diodes to protect against over-voltage and negative-voltage situations:

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.

# Answer
> 1 votes
Current through the clamping diodes shouldn't be more than 1mA according to Atmel's Zero Cross Detection Application Note (AVR182).

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.

---
Tags: arduino-mega, voltage-level, voltage-protection
---


# Question
Title: Receive data from multiple wireless sensors simultaneously
I want to receive data from multiple (2/3) wireless sensors at the 512 Hz data rate simultaneously at a single receiver (bluetooth or any other wireless standard). Is it possible with one receiver or I need multiple receivers?

I am novice to wireless communication please guide me to any available resources. Thank you.

# Answer
> 1 votes
It is possible to do this with Zigbee. The API mode in the Xbee modules enables this.

Unlike the AT mode in Zigbee the API mode enables you to distinguish between the packets that you receive from different slaves.

In the API mode, you send each data packet with as a frame with a header which contains start delimiter byte, most significant byte (which tells where the start byte is at), least significant byte (which tells the end of the byte), an API identifier, the data that you want to send and a checksum byte.

This link provides a nice tutorial which shows how to setup Xbees on API mode with an Arduino and Python: http://serdmanczyk.github.io/XBeeAPI-PythonArduino-Tutorial/

I hope this helps.

---
Tags: sensors, bluetooth, wifi, xbee, accelerometer
---


title: Using 6 axis accelerometers

text:
# Question
Title: Using 6 axis accelerometers
I've been messing around with accelerometers for Arduino for a school project. I bought the SODIAL GY-521 accelerometer + gyroscope module for Arduino. It uses de Invensense MPU 6050. I managed to connect it onto my board and successfully detect it, but it returns values of -1 on all output ports. I was expecting there to be a port for every axis of acceleration and rotation but it seems that this isn't the case. How should I connect the module into my Arduino, and how should I program the Arduino to read my data?

I tried to follow the Arduino Playground example but the result was as explained above.

Thank you for all answers.

# Answer
> 1 votes
From the Arduino playground:
This sensor board has a voltage regulator. When using 3.3V to the VCC the resulting voltage (after the onboard voltage regulator) might be too low for a good working I2C bus. It is preferred to apply 5V to the VCC pin of the sensor board. The board has pull-up resistors on the I2C-bus. The value of those pull-up resistors are sometimes 10k and sometimes 2k2. The 2k2 is rather low. If it is combined with other sensor board which have also pull-up resistors, the total pull-up impedance might be too low.

# Answer
> 0 votes
I usually use the following connections for my MPU 6050: Vcc: 3.3V GND: Any arduino GND SDA: A4 SCL: A5 AD0: GND(for address 68)/ 3.3V(for address 69)

I do not usually connect any of the other pins. For the code I usually use a wonderful library written by Jeff Rowberg which can be found here(http://www.i2cdevlib.com/devices/mpu6050#source). This library enables you to also use the Digital Motion Processor on board the MPU 6050 to give you prefiltered rotation data. It also has example code which should make things easy.

You can connect at most 2 MPU 6050s to the I2C port of the arduino by using different addresses for it. If you need to hook up more, you will require a multiplexer.

Hope this helps.

---
Tags: arduino-uno, sensors, accelerometer, gyroscope
---


# Question
Title: 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.

# Answer
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,
"<html>"
  "<head>"
    "<meta http-equiv='refresh' content='5'/>"
    "<title>Circuits4You.com Temperature Monitoring Server Demo</title>"
    "<style>"
      "body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }"
    "</style>"
  "</head>"
  "<body>"
    "<p>Temperature: %04d</p>"
  "</body>"
"</html>", analog
  );

```
> 0 votes

# Answer
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.
> 0 votes

---
Tags: arduino-ide, esp8266, c, communication, web-server
---


# Question
Title: What is the maximum length an Interrupt Service Routine?
In general, what's the maximum length of instructions that can be included in an Interrupt Service Routine?

The docs say an ISR should be "as short and fast as possible", but that's bit vague.

For example, I have an ISR that gets called for each pulse on an motor's encoder.

```
void on_encoder_pulse(){
    encoder_change = true;
    count1 += 1;
    count2 += last_call;
    last_call = millis();
}

```

Will this run without interruption?

# Answer
> What is the maximum length an Interrupt Service Routine?

This depends on the max latency before servicing any other waiting Interrupt Service Routine (ISR).

An AVR ISR will execute with further interrupts disabled until the running ISR is completed. Any other interrupt(s) during the execution will be delayed. Data may be lost if the delay is too long. This depends on the interrupt source and frequency of interrupts.

In general an ISR (for incoming data) should only capture the data that could be lost and delay processing to the main loop function. A good example is the ISR for the Arduino Hardware Serial (USART) handling. Data sent and received are queued.

A traditional method (design pattern) is to have very short ISRs that capture data and push to an event queue. All processing is done in the main loop. This gives short latency and faster response, and reduces the risk of ISRs depending on each other, etc.

Cheers!
> 2 votes

# Answer
In general, on AVR devices, interrupts have been turned off (by hardware) when an ISR (interrupt service routine) begins execution.

Thus, if `on_encoder_pulse()` is an ISR and is invoked due to an interrupt, it will run uninterrupted.

An ISR that within itself turns the interrupt system back on before it's done runs the risk of other interrupts being serviced before it completes.

The suggestion that ISR's be “as short and fast as possible” is intended to avoid other interrupts being missed, as will happen if an interrupt source activates multiple times while the interrupt system is off. Most interrupt sources latch a bit and will be handled when the interrupt system is re-enabled; some don't latch a bit, and won't be seen if some ISR is long-winded.
> 2 votes

# Answer
As already explained by jwpat7, interrupts are, by default, not interruptible. Thus, if another interrupt fires while your ISR is running, it will no be serviced until your ISR completes. This delay you impose on other interrupts is called *latency*. So your question boils down to “*how much latency can the other interrupts tolerate*”.

There is no simple answer: it all depends on the timing requirements of whatever those interrupts are servicing. For example:

* The `millis()` counter is updated by interrupts. Any latency longer than 1024 µs (on the Uno) can make it loose tics.
* If you are using the serial port to receive data, a latency longer than one byte time (1040 µs at 9600 pbs, less at higher baud rates) will make you loose data.
* If you are using the Servo library, *any* interrupt latency will create jitter in the drive signal, and at some point this may become visible as mechanical jitter.

Then, if you really need a precise answer, you will have to check the timing requirements of *every* piece of hardware and *every* library you are using. And then check the latency already imposed by the ISRs in those libraries, as your latency can come in top of that.

If your program relies on `loop()` looping fast enough, you should also keep in mind that interrupts also slow that.
> 2 votes

---
Tags: interrupt, isr
---


title: Object Array using Inheritance

text:
# Question
Title: 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 `vector` class but also the same error

# Answer
> 3 votes
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();
    // ...
}

```

# Answer
> 1 votes
Based on the answer from @KIIV and the Vector class, 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();
    // ...
  }
}

```

---
Tags: arduino-mega, array, vector
---


# Question
Title: writing and uploading sketch as cpp file
I want to use only `*.cpp` files and no `*.ino` anymore. I read a lot of stuff about how to upload c++ instead of arduino sketches. But still I was not able to find a step by step guide how to do it.

Actually I am developing my sketch within Spacemacs (Emacs) and uploading it with Arduino-Makefile (https://github.com/sudar/Arduino-Makefile)

When I now want to start a new project with only `*.cpp` and `*.h` files to use classes etc. how would I start? Does anybody has the time to describe a rough step-by-step without the trivial stuff?

# Answer
See my post about How the IDE organizes things.

Also see my page about how to avoid the quirks of the IDE sketch file pre-preprocessing.

You can certainly manage without .ino files. As Edgar Bonet says, they are really C++ files with certain pre-processing (see link above).

> but what about these loop() and setup() functions

Effectively, the Arduino IDE supplies a main function that looks like this:

```
int main ()
  {
  init ();    // initialize hardware, including timers and timer interrupts
  setup ();   // user setup
  while (true)
    loop ();  // stuff to be done repeatedly
  return 0;   // this will never be executed
  }

```

(It's slightly more complex, to allow for USB where applicable, but that is the idea).

> But still I did not found the step by step guide how to do it.

I'm pretty sure there are a lot of example "make" files around which show the idea.

I have an example here.
> 4 votes

---
Tags: arduino-uno, uploading, build
---


title: Results for GP2Y1010AU0F Dust Sensor

text:
# Question
Title: Results for GP2Y1010AU0F Dust Sensor
I am using Dust Sensor GP2Y1010AU0F

I downloaded the code from the manufacturer here: http://www.waveshare.com/wiki/Dust\_Sensor

```
/*********************************************************************************************************
*
* File                : DustSensor
* Hardware Environment:
* Build Environment   : Arduino
* Version             : V1.0.5-r2
* By                  : WaveShare
*
*                                  (c) Copyright 2005-2011, WaveShare
*                                       http://www.waveshare.net
*                                       http://www.waveshare.com
*                                          All Rights Reserved
*
*********************************************************************************************************/
#define        COV_RATIO                       0.2            //ug/mmm / mv
#define        NO_DUST_VOLTAGE                 400            //mv
#define        SYS_VOLTAGE                     5000

/*
I/O define
*/
const int iled = 7;                                            //drive the led of sensor
const int vout = 0;                                            //analog input

/*
variable
*/
float density, voltage;
int   adcvalue;

/*
private function
*/
int Filter(int m)
{
  static int flag_first = 0, _buff[10], sum;
  const int _buff_max = 10;
  int i;

  if(flag_first == 0)
  {
    flag_first = 1;

    for(i = 0, sum = 0; i < _buff_max; i++)
    {
      _buff[i] = m;
      sum += _buff[i];
    }
    return m;
  }
  else
  {
    sum -= _buff[0];
    for(i = 0; i < (_buff_max - 1); i++)
    {
      _buff[i] = _buff[i + 1];
    }
    _buff[9] = m;
    sum += _buff[9];

    i = sum / 10.0;
    return i;
  }
}

void setup(void)
{
  pinMode(iled, OUTPUT);
  digitalWrite(iled, LOW);                                     //iled default closed

  Serial.begin(9600);                                         //send and receive at 9600 baud
  Serial.print("*********************************** WaveShare ***********************************\n");
}

void loop(void)
{
  /*
  get adcvalue
  */
  digitalWrite(iled, HIGH);
  delayMicroseconds(280);
  adcvalue = analogRead(vout);
  digitalWrite(iled, LOW);

  adcvalue = Filter(adcvalue);

  /*
  covert voltage (mv)
  */
  voltage = (SYS_VOLTAGE / 1024.0) * adcvalue * 11;

  /*
  voltage to density
  */
  if(voltage >= NO_DUST_VOLTAGE)
  {
    voltage -= NO_DUST_VOLTAGE;

    density = voltage * COV_RATIO;
  }
  else
    density = 0;

  /*
  display the result
  */
  Serial.print("The current dust concentration is: ");
  Serial.print(density);
  Serial.print(" ug/m3\n");

  delay(1000);
}

```

My results seems rounded or always returning in certain 'steps'.
(below are my results)
Is there a rounded error in the code or something else that could be going on?

```
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 124.10 ug/m3

```

# Answer
> 1 votes
Its because the resolution of the analog read is 10 bits or 1024 discrete values.

In your code the density is basically calculated as:

```
density = (((5000 / 1024.0) * analog_value * 11) - 400) * 0.2

```

You can calculate the resolution as:

```
(5000 / 1024.0) * 11 * 0.2

```

and you get `10.7421875`, which matches your observation.

If your filtering (calculating the average over last 10 values), would calculate and return a float, you would get smoother values.

---
Tags: sensors, code-optimization, code-review
---


title: Accelerometer fix values

text:
# Question
Title: Accelerometer fix values
I use Arduino Uno with an Accelerometer ADXL345-gy-291 (the full name of the ship) i did hook it up like this

Note I'm using SPI Communication, that was the right one to use in my case. when I plug in my Arduino here what does my serial monitor give me

as you can see, it sends back fixed values no matter the movement of the ship is. the code I use is :

```
#include <SparkFun_ADXL345.h>
ADXL345 adxl = ADXL345(10);

void setup(){

  Serial.begin(9600);
  Serial.println("SparkFun ADXL345 Accelerometer Hook Up Guide Example");
  Serial.println();
  adxl.powerOn();
  adxl.setRangeSetting(16);
  adxl.setSpiBit(0);
  adxl.setActivityXYZ(1, 0, 0);
  adxl.setActivityThreshold(75);
  adxl.setInactivityXYZ(1, 0, 0);
  adxl.setInactivityThreshold(75);
  adxl.setTimeInactivity(10);
  adxl.setTapDetectionOnXYZ(0, 0, 1);
  adxl.setTapThreshold(50);
  adxl.setTapDuration(15);
  adxl.setDoubleTapLatency(80);
  adxl.setDoubleTapWindow(200);
  adxl.setFreeFallThreshold(7);
  adxl.setFreeFallDuration(30);
  adxl.InactivityINT(1);
  adxl.ActivityINT(1);
  adxl.FreeFallINT(1);
  adxl.doubleTapINT(1);
  adxl.singleTapINT(1);
}
void loop(){
  int x,y,z;
  adxl.readAccel(&x, &y, &z);
  Serial.print(x);
  Serial.print(", ");
  Serial.print(y);
  Serial.print(", ");
  Serial.println(z);
  ADXL_ISR();
}
void ADXL_ISR() {
  byte interrupts = adxl.getInterruptSource();

  if(adxl.triggered(interrupts, ADXL345_FREE_FALL)){
    Serial.println("*** FREE FALL ***");
  }

  if(adxl.triggered(interrupts, ADXL345_INACTIVITY)){
    Serial.println("*** INACTIVITY ***");
  }

  if(adxl.triggered(interrupts, ADXL345_ACTIVITY)){
    Serial.println("*** ACTIVITY ***");
  }

  if(adxl.triggered(interrupts, ADXL345_DOUBLE_TAP)){
    Serial.println("*** DOUBLE TAP ***");
  }

  if(adxl.triggered(interrupts, ADXL345_SINGLE_TAP)){
    Serial.println("*** TAP ***");
  }
}

```

so I wonder what was the mistake I made there?

# Answer
> 1 votes
You need to level-shift the Arduino's 5V signals to the module's I/O range of 1.7 - 3.6 V if you want to use SPI; that is, if you haven't damaged it already. I suggest you follow the tutorial here though. It employs I2C instead of SPI but is specific to your particular module. There are no level-shifters needed in this case. Simply connect VCC and CS to 3.3 V, the I2C pins to 3.3 V through 4.7k pull-ups and the GNDs together.

---
Tags: arduino-uno, accelerometer
---


title: Serial communication with Python

text:
# Question
Title: Serial communication with Python
I am trying to send integer from my Python program to Arduino MEGA. If I send 1, the LED should turn on and If I send 0 the LED should turn off.

I was able to write Python code correctly as I think. I have configure the port and made `serialWrite(val)` function for send data to Arduino only if data is changed. This not a full program. It has while loop. So, it writes data to Arduino rapidly. I used `serialWrite(val)` function to prevent that.

But, the LED never turns off, if I send 0. It turns on only. What are the problems in my code?

```
import serial as ser

prt = ser.Serial(
port='COM3',
baudrate=9600,
parity=ser.PARITY_NONE,
stopbits=ser.STOPBITS_ONE,
bytesize=ser.EIGHTBITS
)

preSerVal=0
#function for send data..data will send only val is changed
def serialWrite(val):
    global preSerVal
    if(not preSerVal == val):
        prt.write(str(val)+'\r\n')
        preSerVal=val

```

This is my Arduino program.

```
void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}
byte incomingByte;

void loop()
{
  if (Serial.available() > 0) {
    incomingByte = Serial.read();
      if (incomingByte == '1') {
        digitalWrite(13, HIGH);
    } else if (incomingByte == '0') {
        digitalWrite(13, LOW);
    }
  }
}

```

**UPDATE 1**

I write testing program like this.

Python code:

```
import serial as ser
import time

preSerVal=0
prt = ser.Serial(
port='COM3',
baudrate=9600,
parity=ser.PARITY_NONE,
stopbits=ser.STOPBITS_ONE,
bytesize=ser.EIGHTBITS
)
def serialWrite(val):
    global preSerVal
    if(not preSerVal == val):
         prt.write(str(val)+'\r\n')
         preSerVal=val

while 1:
   for i in range(0,10):
        serialWrite(0)
   time.sleep(1)
   for i in range(0,10):
        serialWrite(1)

```

Arduino code:

```
void setup() {
 Serial.begin(9600);
 pinMode(13, OUTPUT);
 digitalWrite(13, LOW);
}
byte incomingByte;

void loop()
{
  if (Serial.available() > 0) {
    incomingByte = Serial.read();
  if (incomingByte == '1') {
    digitalWrite(13, HIGH);
  } else if (incomingByte == '0') {
    digitalWrite(13, LOW);
  }
 }
}

```

This code gives this result. see the video bellow:

https://www.youtube.com/watch?v=utC4vo8YDVU&list=PLM5AA5oFchgC25da44Q2X900pz0eojSQJ&index=1

**UPDATE 2**

This is a piece of code..it sends 0..i checked it.

```
try:
    circles = np.uint16(np.around(circles))
    for i in circles[0,:]:
        houghCenter=(i[0],i[1])
        cv2.circle(src,houghCenter,i[2],(0,255,0),2)
        cv2.circle(src,houghCenter,2,(0,255,255),1)
        cv2.circle(drawing,houghCenter,i[2],(0,255,0),2)
        cv2.circle(drawing,houghCenter,2,(0,255,255),1)
        #print (houghCenter,"   ",contourCenter)
        dx=math.fabs(houghCenter[0]-contourCenter[0])
        dy =math.fabs(houghCenter[1]-contourCenter[1])
        if (dx>diff and dy>diff):
            serialWrite(0)
        else:
            serialWrite(1)
except Exception:
    serialWrite(0)

```

# Answer
> 1 votes
You are missing a second time.sleep(1). That is why the first loop executes correctly and the the LED flashed faster. Without any time.sleep() at all, the LED is going OFF/ON so fast that you cannot see it happen (may be it's just not so bright as usually).

```
while 1:
   for i in range(0,10):
        serialWrite(0)
   time.sleep(1)
   for i in range(0,10):
        serialWrite(1)
   time.sleep(1)

```

---
Tags: serial, arduino-mega, python
---


# Question
Title: Interrupt and delay problems on Attiny 85
I wrote this code and uploaded it to attiny85:

```
 int hours = 2;
 int minutes = 4;
 static int MINUTES_COUNT_BIT = 5;
 static int HOURS_COUNT_BIT = 3;
 #define button 2
void setup() {
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(button,INPUT);

  attachInterrupt(0,pin_ISR,CHANGE);

}

void loop() {

  // put your main code here, to run repeatedly:

}

void pin_ISR(){
    if(digitalRead(button)==LOW){
      for(int i = HOURS_COUNT_BIT;i>=0;i--){
      byte act_bit = bitRead(hours,i);

      switch(act_bit){
        case 0:
          digitalWrite(3,HIGH);
          delay(1000);
          digitalWrite(3,LOW);
          delay(1000);
          break;
        case 1:
          digitalWrite(4,HIGH);
          delay(1000);
          digitalWrite(4,LOW);
          delay(1000);

          break;
        }

    }
  }

  }

```

When I click button it lights up LEDs but it is so much faster than 500 milliseconds it looks like that: https://drive.google.com/open?id=0ByeWvrEgy2gRNUp3MDNxQTAxd2c Please help

# Answer
In short:

* Arduino `delay()` is relying on `millis()`.
* The `millis()` function is updated by timer `ISR`.
* `ISR` handler blocks all other ISRs by disabling global interrupts.
* No update for `millis` results into deadlock in `delay` if you use it in another `ISR`

And recommendation for ISRs? **Do it as short as possible!** Set some volatile flag and do the action later outside of ISR.
> 2 votes

---
Tags: arduino-ide, interrupt, attiny
---


# Question
Title: Prevent 5V output on Arduino Nano 5V pin
I just made an addressable RGB LED strip controller but im concerned about if I'm going to break the thing.

I know it sounds vague so let me elaborate: there is an external power supply connected to my 5V pin and the LED strips positive so it powers both the strip and Arduino, but I also have my Arduino connected to my PC at all times. So I'm concerned about IF my power supply is for some reason not connected the Arduino will supply power on its own.

Is there a way to prevent 5V pin from outputting 5V, so it only accepts 5V

EDIT: There are cases when the USB isn't connected so I need the 5V to be connected at all times, if its still vague then is there a way to only use data on USB and disregard the power?

# Answer
A simple diode is all you need. The USB power already goes through a diode, so another diode the same will create a "highest voltage wins" situation.

That is, if the voltage provided by the USB port is higher than the voltage you provide on the +5V pin (after the diode's forward voltage drop) then the USB port will power the nano. If the voltage on the +5V pin is higher (after the diode's voltage drop) than the USB then the voltage on the +5V pin will power the nano.

No power will flow out of the 5V pin to your LED strip because the diode is in the way.

Connect the 5V external power to the *anode* of the diode, and the 5V pin of the Arduino to the *cathode* of the diode. The cathode is generally the end of the diode with the stripe. Make sure the diode can pass enough current to power the Arduino when the USB is un-powered. The 1N4001 is a popular choice and very easy to get hold of.

That choice of diode also has a higher forward voltage drop than the on-board USB diode (0.7V as opposed to about 0.4V), so the USB will generally be chosen by default when connected and powered up, which is as it should be for a bus-powered device.
> 2 votes

---
Tags: arduino-nano, usb, rgb-led, input
---


title: Code Optimisation

text:
# Question
Title: Code Optimisation
I have tried fading the RGB Led with different colour format and sequence. Working of Code :-

* When value of number is 1, the Red LED fades gradually and glow up with the delay interval of 10ms with fade amount 5.
* When value of number is 2, the Green LED works as above.
* The change of state from Red to green takes 4 seconds.

Blue Led Code can also be added to this and various other colour combinations can be made, which will complex the code and add up difficulty is debugging and finding errors because every combination should have different name for fading so that it doesn't conflict with other combinations.

Here is my code. However, I need some suggestions regarding quality of my code. Is it the efficient way to do code. How can I improve the code. Any constructive suggestions would be of great help.

```
int RED_LED = 12;           // the PWM pin the LED is attached to
int BLUE_LED = 14;
int GREEN_LED = 15;

int RedLedBrightness = 0;    // how bright the LED is
int GreenLedBrightness = 0;    // how bright the LED is

int RedFadeAmount = 5;
int GreenFadeAmount = 5;

unsigned long previousMillis = 0;
const long interval = 10;

unsigned long previousMillis2 = 0;
const long interval2 = 4000;

int j = 0;

void setup()
{
  pinMode(RED_LED, OUTPUT);
  pinMode(BLUE_LED, OUTPUT);
  pinMode(GREEN_LED, OUTPUT);

  Serial.begin(115200)
}

void loop()
{
    if (millis() - previousMillis2 >= interval2)
    {
     previousMillis2 = millis();

    j += 1;
    if (j > 2)
    {
        j = 1;
    }
    Serial.print("\n");
    Serial.println(j);
   }
    SpecialFunction(j);
}

void SpecialFunction(int Number)
{
  if (millis() - previousMillis >= interval)
  {
    previousMillis = millis();

    if (Number == 1)
    {
      RedGradualChange();
    }

    else if (Number == 2)
    {
      GreenGradualChange();
    }
  }
}

void RedGradualChange(void)
{
  analogWrite(GREEN_LED, 0);

  GreenLedBrightness = 0;    // how bright the LED
  GreenFadeAmount = 5;

  analogWrite(RED_LED, RedLedBrightness);
  RedLedBrightness = RedLedBrightness + RedFadeAmount;

  if (RedLedBrightness <= 0 || RedLedBrightness >= 1020)
  {
    RedFadeAmount = -RedFadeAmount;
  }
}

void GreenGradualChange(void)
{
  analogWrite(RED_LED, 0);

  RedLedBrightness = 0;
  RedFadeAmount = 5;

  analogWrite(GREEN_LED, GreenLedBrightness);
  GreenLedBrightness = GreenLedBrightness + GreenFadeAmount;

  if (GreenLedBrightness <= 0 || GreenLedBrightness >= 1020)
  {
    GreenFadeAmount = -GreenFadeAmount;
  }
}

```

# Answer
> 1 votes
Without deciphering what all those functions are supposed to do, I can see a few fundamental flaws and inefficiencies:

1. Don't use string - especially if you're only then using it to convert into a char array. Just use the char array.
2. You're storing a number in a char array then comparing it to string constants. What is wrong with dealing with just numbers in the first place...?
3. This bit is wrong: `if (incomingByte = '#')` \- you have an assignment (`=`) instead of a comparison (`==`) so it will always be true.
4. If you fix point 3 the rest of the code won't work, since your string will now always have `#` at the end (`3#` for instance) and the comparison against `3` (for example) will fail.

You should learn more about how to input values through serial:

---

For your fading code there is a lot of redundancy in there. Personally I would use a *bitfield* indicating which LEDs are to fade and which aren't.

Basically you have a single value and OR together bits within it to indicate the enabled LEDs. For instance, assign the value `1` to red, `2` to green and `4` to blue. These correspond to `0b001`, `0b010` and `0b100` respectively.

When the state is changed, either by your loop or by an external serial signal, you reset all three colour brightnesses to 0 (to keep them synchronised) and set the right bits in the bitfield for the colours you want fading. For instance, for red you set the bitfield to 1. For cyan you set it to 6 (0b110). Then in your processing loop you just fade the colours that are enabled, and write all three values (the colour that isn't enabled will already be 0). This also has a side-effect that you now already have numbers assigned to the colours:

```
0 = 0b000 = All off
1 = 0b001 = Red
2 = 0b010 = Green
3 = 0b011 = Yellow
4 = 0b100 = Blue
5 = 0b101 = Magenta
6 = 0b110 = Cyan
7 = 0b111 = White

```

In fact, since all the colours are fading together, you don't even need separate values for each colour - just one global brightness value.

Some code (untested) for you:

```
#define RED   0b001
#define GREEN 0b010
#define BLUE  0b100

int brightness = 0;
uint8_t enabled = 1;
int fadeAmount = 5;

const uint8_t RED_LED = 12;
const uint8_t BLUE_LED = 14;
const uint8_t GREEN_LED = 15;

unsigned long previousMillis = 0;
const long interval = 10;

unsigned long previousMillis2 = 0;
const long interval2 = 4000;

void setup() {
  pinMode(RED_LED, OUTPUT);
  pinMode(BLUE_LED, OUTPUT);
  pinMode(GREEN_LED, OUTPUT);

  Serial.begin(115200);
}

void loop()
{
    if (millis() - previousMillis2 >= interval2) {
        previousMillis2 = millis();
        enabled ++;
        if (enabled >= 8) enabled = 1;
        Serial.println(enabled);
    }

    if (millis() - previousMillis >= interval) {
        previousMillis = millis();
        if (enabled & RED) {
            analogWrite(RED_LED, brightness);
        } else {
            analogWrite(RED_LED, 0);
        }
        if (enabled & GREEN) {
            analogWrite(GREEN_LED, brightness);
        } else {
            analogWrite(GREEN_LED, 0);
        }
        if (enabled & BLUE) {
            analogWrite(BLUE_LED, brightness);
        } else {
            analogWrite(BLUE_LED, 0);
        }
        brightness += fadeAmount;
        if (brightness > 1023) {
            brightness = 1023;
            fadeAmount = -fadeAmount;
        } else if (brightness < 0) {
            brightness = 0;
            fadeAmount = -fadeAmount;
        }
    }
}

```

---
Tags: arduino-uno, arduino-ide, pwm, code-optimization
---


title: How to Factory reset ESP8266?

text:
# Question
Title: How to Factory reset ESP8266?
I want to use ESP8266 to send emails. I tried twice flashing the Firmware to a particular firmware as suggested in a tutorial. Now both my ESP are unresponsive to AT commands. Let me know the way to RESET it. CH\_PD + VCC + RST (Tried this combination), No success there any thing i am missing?

# Answer
AT commands are executed by the AT interpreter firmware. If you've been attempting to flash other firmware to the ESP8266 module, there is no longer any code in it that interprets AT commands. If you want to it to respond to AT commands again, you'll need to re-flash it with that firmware.
> 2 votes

# Answer
You need to reflash the "AT Firmware" you probably overwrited. Just follow the instructions in the Espressif board to get the latest one using their "Flash Download Tool".
> 0 votes

---
Tags: arduino-mega, esp8266, wifi, reset
---


# Question
Title: Getting the highest value from analog reading?
I am doing a project using an FSR (Force Sensitive Resistor), I'm currently reading values with no problem every 100milis. I want to output via Serial.print the highest value, I've read.

I am having a hard time doing so. The project is use to "measure" the strength some projectiles hit the sensor. I want to get the highest value.

This is the code I have until now.

```
int fsrPin = 0;     // the FSR and 10K pulldown are connected to a0
int fsrReading;     // the analog reading from the FSR resistor divider
void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);

  Serial.print("Analog reading = ");
  Serial.println(fsrReading);     // the raw analog reading

  delay(100);
}

```

# Answer
> 2 votes
You don't want to delay ever. Instead you want to change your thinking to "X miliseconds have passed, time to print and reset":

```
int maxval = 0;
uint32_t lastSample = 0;

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

void loop() {
    if (millis() - lastSample > 100) { // Every 100ms:
        lastSample = millis();
        Serial.println(maxVal);
        maxVal = 0;
    }
    int reading = analogRead(0);
    if (reading > maxVal) {
        maxVal = reading;
    }
}

```

Every 100ms it will print the maximum analog value read during the past 100ms.

You can replace the 100ms with any other value you choose, or even with a check to see if a button has been pressed, in which case you get the maximum reading since the last time the button was pressed:

```
// global
bool lastButtonValue = HIGH;

// in loop()
if (digitalRead(3) != lastButtonValue) {
    lastButtonValue = digitalRead(3);
    if (lastButtonValue == LOW) {
        // ... do the print and reset
    }
}

```

---
Tags: analogread
---


title: Generating analog signals

text:
# Question
Title: Generating analog signals
is there a way to make the Arduino act as a voltage source, by generating sinusoidal, triangular and other kinds of signals? If so, can it be done using LabVIEW? (I've already managed reading analog signals using VISA)

Thank you!

# Answer
> 1 votes
The Due (and similar SAM based boards) have a DAC built in which can be set to different voltages (I forget the range off hand, maybe 0-Vcc at 12-bit resolution). Change that voltage fast enough, and you have a waveform.

Other Arduinos have PWM outputs which, when filtered through a low-pass filter, give a voltage proportional to the duty cycle of the PWM. Again, change the duty cycle fast enough and you have a waveform (limited by the *carrier frequency* of the PWM).

Can you do it from LabVIEW? Who knows? I have never used it.

---
Tags: arduino-uno, analogwrite
---


title: OnKeyPress in a arduino

text:
# Question
Title: OnKeyPress in a arduino
So, I have 3 buttons to a arduino. I want to detect the button press on the 3 of them.

For that, i've created a function:

```
int OnKeyPress (int port) {

  int  LastState, BeginState, r;
  r = 0;

  BeginState = digitalRead(port);

  if (BeginState != LastState) {
      if (BeginState == 1) r = 1 ;
  }

  delay(5);
  LastState = BeginState;
  return r;
}

```

I want to instantiate 3 instances of this code, separately and they have to retain this variables `int LastState, BeginState, r;` for each button, and the next time the function runs on the loop, the variables are the same of when they ran last time.

Just, how?

# Answer
This is an ordinary method (function) which can not be instantiated. It is necessary to write a class with 1 or more methods in it in order to instantiate multiple copies of that class and the method(s) with in that class.

The integers "LastState", "BeginState" and "r" only have scope within the method and will not survive after returning from the method. There are several approaches to preserve these variables from one call to the next. They can be declared as static integers. Or they can be defined globally.

It appears you are recreating the existing Bounce library. I encourage you to continue if you are learning. However, you may want to look at the Bounce library's code for guidance.
> 1 votes

---
Tags: button
---