# Question
Title: Hex String -> Byte Array -> Serial Write
I'm writing code that I discussed in a previous post. I now have a setup where I send my Arduino an ASCII-encoded Hex String that represents the bytes I want to write to my serial device. I think I've got most the code figured out other than the way to best convert the hex string for sending

This Code is working

```
void SendCTRL (String &input)
{
  const char *hin = input.c_str();    // Get character array
  int clen = input.length()/2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
  RS485Serial.write(cmd[i]);   // Send string someplace
  }
  delay(clen/4);
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
  Serial.println();

}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

```

From what I understand something along the lines of `char ISS = SubS.GetBytes()`, but guidance would be appreciated

# Answer
> 1 votes
What your code is aiming at isn't particularly clear to me, but I will assume that for some obscure reason you want to accept an input String containing a series of ASCII-encoded hex digits, and create an array of half that many bytes with reconstituted byte values.

First, here are several criticisms of the code shown.

It's likely `length(input)` won't compile but that `input.length()` will.

The expression `input.substring((2*i),(2*i)+1))` is a String of one character. If you want two characters, use `input.substring((2*i),(2*i)+2))`. And use `i += 2` instead of `i++` in the `for` loop.

I don't understand `String CMD = CMD+ISS`. I won't say it's invalid, as I don't know without more research. But it looks like it's declaring variable `CMD` and using `CMD` in the initialization of `CMD`. \[In the example code I give below, I assume `CMD` should begin as an empty string and be filled up with reconstituted bytes.\]

`RS485Serial.write(input); // Send byte to Remote Arduino` looks mis-commented; presumably it will write out all of the input, not just a byte.

Using a timed delay for holding RS485 Transmit open, as in `delay(10);
 digitalWrite(SSerialTxControl, RS485Receive); // Disable RS485 Transmit`
may cause problems. On the one hand, it may usually waste five to ten milliseconds of time; on the other, it might occasionally disable RS485 transmit before transmission finishes. Instead, look for a flag to test for transmission complete, or look for a buffer-fill count, or compute how long to wait, etc.

The next paragraph describes some reasons that Strings may perform badly in this sketch. For additional discussion of Arduino String objects, see arduino.cc's *String* page, and see Majenko's *The Evils of Arduino Strings* page.

Each of the String-object operations in the code creates a new String. New String objects `SubS` and `CMD` are created and destroyed in each pass of the `for` loop. The object headers (with type data and member variables, such as a buffer pointer and buffer size) can be stack-allocated, which is harmless (does not leak or fragment memory) but takes some time. Each String object's character-buffer is heap-allocated: see code in cores/arduino/ file `WString.cpp`. Heap fragmentation can and will occur. ... In brief: In this application where using String objects is clunky and in the way, you might as well use ordinary C strings instead of String objects.

---

Ok, with criticisms out of the way, here's some example code that converts ASCII-encoded hex digits into a command string. Note, as I don't know the specs for `RS485Serial.write()` or how it determines how much to send, for demonstration purposes I've supposed it can handle a C string.

```
// Function declaration for dehex()
byte dehex(char c); // Get nibble value 0...15 from character c

void SendCTRL (String input) {
  const char *hin = input.c_str();  // Get character array
  int clen = input.length/2;
  // Next line invalid in C++, ok in C99.  Probably need to
  // instead declare a fixed-length array, cmd[MAXCMDLEN], etc
  char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2) {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  RS485Serial.write(cmd);   // Send string someplace
  delay(clen/4);        // Wait for write to complete? What rate?
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

byte dehex(char c) { // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
  // Above assumes that c is a 'hex digit' in 0...9, A or a ... F or f.
  // It would make more sense to just use 16 consecutive characters,
  // like eg 0123456789:;<=>? or @ABCDEFGHIJKLMNO so the above
  // could just say `return c & 0xF;`
}

```

*Edit 2:*

1. The first statement, `byte dehex(char c);` is a function declaration for the `dehex()` function. It tells the C/C++ compiler the datatypes that the function accepts and returns. Note, instead of a function declaration at that point, one could instead put the function definition itself (which in the above follows `SendCTRL()`, a `dehex()` caller that needs to know `dehex()`'s datatypes). Some versions of the Arduino IDE appear to work ok without function declarations ahead of use, but almost all other C/C++ environments will not.
2. In this edit I added `const` before `char *hin = input.c_str();` because ATE-ENGE reports “`char *hin =input.c_str()` is giving me an invalid conversion error from const char\* to char\*”. That error indicates the left-hand-side variable has a datatype different from that of the right-hand-side expression and an automatic conversion isn't available. Note, unfortunately the arduino.cc `c_str()` webpage doesn't specify the return type of `c_str()`.

*Edit 3:* Changed `for (int i=0; i < clen; i+=2)` to `for (int i=0; i < 2*clen; i+=2)` per notes in another question's answer.

*Edit 4:* Changed `cmd[i/2] = dehex(hin[i])<<4 + dehex(hin[i+1])` to `cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1])` to avoid an operator precedence problem. The precedence of `+`, addition, is higher than that of `<<`, bitwise shift, which in turn is higher than that of `|`, bitwise OR. The unparenthesized expression with `+` adds 4 to `dehex(hin[i+1])` and uses the total as a shift count; not at all as desired. Note, one can of course use parentheses to control the problem, as in the expression `(dehex(hin[i])<<4) + dehex(hin[i+1])`

---
Tags: arduino-uno, serial, softwareserial, convert
---


# Question
Title: How can I identify, debug or fix a faulty IMU?
I have an LSM9DS1 breakout board by Sparkfun, and am communicating with it using a Mega 2560 over I2C. The board is given 3.3 V power as defined in the data sheet, though there seems to be confusion whether the SDA and SCL pins need level shifting for communicating with the 5 V Mega. In theory it shouldn't need to.

I am able to connect with the device and get its accelerometer and magnetometer data, however the gyro is just returning noise and no signal. I have dug in to all the registers I know of regarding high pass filters, logging rates, enabling and powering the sensor, but the only hints are that when the gyro is disabled and then polled, it returns a constant nonzero value on all three axes, as though a bit somewhere is stuck. With any other setting the results are unchanged: finite noise on a constant DC signal. Is this even possible? How can I dig deeper to understand and solve this problem?

# Answer
In theory you **must** use a level shifter for SDA and SCL. The Arduino Mega 2560 board has internal pullup resistors of about 50k for SDA and SCL and extra 10k pullup resistors of 10k to 5V and according to the datasheet the ATmega2560 requires 3.5V to detect a high level for the I2C bus.

Those pullup resistors might damage the LSM9DS1.
5V-3.3V / 50k//10k times two (both SDA and SCL) = 400nA that might be pushed into the sensor (I assume there are protection diodes, and the maximum voltage is 3.6V, therefor the 400nA is just an indication). I assume the 10k pullup resistors to 3.3V on the sensor module are enabled. They will take away some over-voltage.

The current by the pullup resistors (to 5V) is a very small current, and I don't know if the sensor is in sleep mode during startup.

To be sure you need to buy another LSM9DS1 and a level shifter. Or even better: buy a 3.3V Arduino board, like the Due or the Zero, M0, and so on.

Have to compared the raw sensor data with others ? Those sensors are very noisy. That is why there is so much to do about filter algoritms to get data that can actually be used. The LSM9DS1 does not do processing or smart filtering with the raw data. All you get is the raw data. Did you assume that the values would be zero ? They never will be, because such sensors are far too noisy and too sensitive for that.
> 1 votes

---
Tags: i2c, gyroscope
---


# Question
Title: Directly powering a single 32x16 RGB LED matrix (without external PSU)
All the guides I've found suggest to use an external PSU to power an RGB matrix like this.

However I know it is possible to blink the LEDs at high rates (eg. 2ms) and still give the impression to the eyes they are fully on. I've verified this myself on a small 4x4 matrix, but I am not sure if the same can be done with these bigger matrices.

In my case I could tolerate reduced brightness and color space, but I'd like to power the matrix with the Arduino's 5V pin directly.

# Answer
> 1 votes
I've received yesterday the 32x16 LED matrix I've ordered from AliExpress and I've done some measurements with a multimeter in series with the power wire.

LED multiplexing does not seem a good idea as the matrix is already doing that internally.

Instead I've found that using the **minimum color intensity** helps a lot reducing the current usage.

E.g. for blue use `matrix.Color333(0, 0, 1)` instead of `matrix.Color333(0, 0, 7)`; for white use `matrix.Color333(1, 1, 1)` instead of `matrix.Color333(7, 7, 7)`, etc.

With the minimum brightness I've measured:

* All blue LEDs lit = ~170mA
* All LEDs lit as white (red+blue+green) = ~400mA

In the average case (not all LEDs are lit) I am getting around **250mA**, so I should definitely be fine powering the matrix directly from the 5V pin if I keep the brightness as low as possible.

# Answer
> 4 votes
When powered through USB, the total current consumption is limited to 500mA by the USB interface. If you are using the power connector, the total current is limited by the on board 5V regulator to 1A.

The board will also require some current, so you can draw around **400mA**, if powered through USB or **900mA**, if powered through the connector; from the 5V pin.

While the matrix on average may not draw than 300 - 400mA, the voltage regulator can overheat and shut off temporarily, and you will never be able to reach 900mA. The regulator is linear, so any extra voltage you supply will result in waste heat.

It is best to get a buck converter or power the matrix externally. You won't be wasting as much power, and avoiding possible thermal shutoff.

---
Tags: power, rgb-led
---


# Question
Title: How to light up all LEDs of a 7x5 LED matrix?
I want to light up all the LEDs of a 7x5 matrix with arduino uno. How can i do so?

# Answer
> 0 votes
You don't need an Arduino for that, and one will give you no benefit.

Connect all anodes to power, and all cathodes to the appropriate resistors, then ground.

---
Tags: arduino-uno
---


title: How can I split data coming from JSON?

text:
# Question
Title: How can I split data coming from JSON?
In my recent project, I'm working with Arduino and JSON. Now, I get data from JSON and I can able to receive in Arduino side.

Below one is my Arduino code:

```
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

String response = "";
bool begin = false;

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

void loop()
{

  while(Serial.available() || !begin)
  {
    char in = Serial.read();

    if (in == '{')
    {
      begin = true;
    }

    if(begin) response += (in);

    if(in == '}')
    {
        break;
    }
    delay(1);
  }

  lcd.setCursor(0, 0);
  lcd.print(response);
}

```

Output :

```
{"TPS":"0.40","MAP":"1.05","LOAD":"14"}

```

Now, I want to split data means store `0.40` in one variable, `1.05` in another variable and `14` in another variable. I don't know how to split this.

# Answer
Finally, I got it. I have fixed length of data. So, I use a counter to calculate the how many characters are there in my data. Now using the index of this characters, I find out proper data and then store in a different variable.

Below is my code:

```
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

String responseOne = "";
String responseTwo = "";
String responseThree = "";
bool begin = false;

int counter = 0;

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

void loop()
{

  while(Serial.available() || !begin)
  {
    char in = Serial.read();

    if (in == '{')
    {
      begin = true;
    }

    if(begin)
    {
      counter++;

      if(counter >= 9 && counter <= 12)   // This gives 0.40
      {
        responseOne += (in);              // 0.40 store in responseOne variable
      }

      if(counter >= 22 && counter <= 25)  // This gives 1.05
      {
        responseTwo += (in);              // 1.05 store in responseTwo
      }

      if(counter >= 36 && counter <= 37)  // This gives 14
      {
        responseThree += (in);            // 14 store in responseThree
      }
    }

    if(in == '}')
    {
        break;
    }
    delay(1);
  }

  float newResponseOne = responseOne.toFloat();  // Convert string into Float
  float newResponseTwo = responseTwo.toFloat();  // Convert string into Float
  int newResponseThree = responseThree.toInt();  // Convert string into Integer

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

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

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

```
> 1 votes

---
Tags: arduino-uno, serial, json, data
---


# Question
Title: Passing user defined callback functions to a library method
I developed an Arduino library that have a method called "process". This method is a Void function and must be called inside the loop and most of the time the library handles everything by it self:

```
#include <HookNinja.h>

HookNinja hookninja;

void setup()
{}

void loop()
{
  hookninja.process();
}

```

The idea is to keep the user program a simple as possible. Sometimes "process" have some data to give back to the user so he can use it as he likes. A simple approach is not to make process void and make the user check for the return value of process:

```
void loop()
{
  someVariableType foo;
  foo = hookninja.process();
  if(foo) {
    //user defined things
  }
}

```

But the data returned by process could be anything, from an int to an array of Strings, only the user knows the return type, also this method seems not very elegant. Im not an expert of C++, for me the ideal solution will be an object oriented approach were the user pass a function to process that can be called from the library, but I have no idea how to do this in C++, something like:

```
void userFunction(type param) {
  //do something with param
}

void loop() {
  hookNinja.process(some how pass userFunction here)
}

```

# Answer
A common solution would be to have the user provide a callback which takes no arguments and returns nothing. This is how `attachInterrupt()` works, so it may be the least surprising approach for your users. The user function can then get data from the rest of the program using globals.

If you really prefer passing an argument to the user function, the problem is you do not know the data type. The usual approach in plain C is to give it a “generic” pointer, and let the user cast it into a pointer specific for his data type. This is how functions like `qsort()` work:

```
HookNinja hookninja;

void userFunction(void *param) {
    someVariableType foo = * (someVariableType *) param;
    //do something with foo
}

void setup()
{
    hookninja.attachCallback(userFunction);
}

void loop() {
    someVariableType foo = something;
    hookNinja.process((void *) &foo);
}

```

A cleaner C++ approach could be to make you class a template that is specialized for the type of the user data:

```
HookNinja<someVariableType> hookninja;

void userFunction(someVariableType param) {
    //do something with param
}

void setup()
{
    hookninja.attachCallback(userFunction);
}

void loop() {
    someVariableType foo = something;
    hookNinja.process(foo);
}

```

But keep in mind that many Arduino users may not be familiar with templates.
> 4 votes

---
Tags: arduino-uno, c++
---


title: "Hello World" program for nRF24L01+?

text:
# Question
Title: "Hello World" program for nRF24L01+?
Where is a simple program that demonstrates unidirectional data transmission over a pair of nRF24L01+ radios? It should have adequate output so that a beginner can determine that the transmission is working properly.

# Answer
> 1 votes
I found this site to have pretty strait forward instructions:

https://maniacbug.wordpress.com/2011/11/02/getting-started-rf24/

Main Library: https://github.com/maniacbug/RF24/

Example Sketch: https://github.com/maniacbug/RF24/blob/master/examples/pingpair/pingpair.pde

# Answer
> 1 votes
Here are several "getting started" articles that contain simple programs.

http://tmrh20.github.io/RF24

https://groups.google.com/forum/#!topic/nrf24-arduino/VaC2U5D1o\_s

http://arduino-for-beginners.blogspot.com/2013/02/setup-nordic-nrf24l01-rf-modules-to.html

# Answer
> 1 votes
TMRh20 RF24 library examples work well.

Install TMRh20 RF24 library in the Arduino IDE Library Manager (“Sketch/Include Library/Manage Libraries...” and search for “RF24”). Then open the Getting Started example (“File/Examples/RF24/GettingStarted”).

You’ll need to change the “radioNumber” variable to `0` or `1` on the sending and receiving Arduino (line 13 of the code).

For the hardware I prefer to use pins 9 and 10 instead of 7 and 8 (line 16 of the code), so that all pins are connected to port B.

The nRF24 is supposed to be 5V tolerant on the data lines, but not for the power supply, so you need to connect VCC to 3.3 V. In my experience, it works best if you use it with a full 3.3 V board (ESP8266 or Arduino Pro Mini).

You absolutely need to add a strong capacitor between VCC and ground. I use a 2200 µF capacitor, but 10 µF may be enough (http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo).

I also wrote a small article about the nRF24L01+.

---
Tags: nrf24l01+
---


title: SIM800L Arduino Pro Mini

text:
# Question
Title: SIM800L Arduino Pro Mini
I am trying to send an SMS using the Sim800L module and it seems to be unable to connect to the network. When I send the AT+COPS=? command it shows me a list of all the available networks along with the carrier of the sim card inserted but the module is unable to connect to the network. AT+CPIN returns an error as well. I read that changing the antenna will help but I don't think this can be the case as the networks are being detected. What could be going wrong?

# Answer
Make sure that you are giving it enough power, seaching and registering to a network needs a current peak of 2amps, if the model you are using has a built-in regulator plug it to a stable 5v 2amp source of power and try AT+COPS? again, it should work; you can try with the computer power supply it has a 5v 2amp source.
> 1 votes

---
Tags: gsm, arduino-pro-mini
---


title: serial write pixels of a bmp image

text:
# Question
Title: serial write pixels of a bmp image
I'm looking for a way to read a 24 bpp bmp file from a SD cart, and than convert it to text and write it to the serial monitor.

So the output should look something like this: R255,B255,G255

And that for each pixel

# Answer
To read the pixels, start with this:

```
int32_t readNbytesInt(File *p_file, int position, byte nBytes)
{
    if (nBytes > 4)
        return 0;

    p_file->seek(position);

    int32_t weight = 1;
    int32_t result = 0;
    for (; nBytes; nBytes--)
    {
        result += weight * p_file->read();
        weight <<= 8;
    }
    return result
}

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

    Serial.print("Initializing SD card...");
    if (!SD.begin(53)) {
        Serial.println("initialization failed!");
        while (1); // <- this is how you should block execution, not with returns
    }
    Serial.println("initialization done.");

    // Open
    bmpImage = SD.open("Circle.bmp", FILE_READ);
    textFile = SD.open("test.txt", FILE_WRITE);

    int32_t dataStartingOffset = readNbytesInt(&bmpImage, 0x0A, 4);

    // Change their types to int32_t (4byte)
    int32_t width = readNbytesInt(&bmpImage, 0x12, 4);
    int32_t height = readNbytesInt(&bmpImage, 0x16, 4);
    Serial.println(width);
    Serial.println(height);

    int16_t pixelsize = readNbytesInt(&bmpImage, 0x1C, 2);

    if (pixelsize != 24)
    {
        Serial.println("Image is not 24 bpp");
        while (1);
    }

    bmpImage.seek(dataStartingOffset);//skip bitmap header

    // 24bpp means you have three bytes per pixel, usually B G R

    byte R, G, B;

    for(int32_t i = 0; i < height; i ++) {
        for (int32_t j = 0; j < width; j ++) {
            B = bmpImage.read();
            G = bmpImage.read();
            R = bmpImage.read();
            textFile.print("R");
            textFile.print(R);
            textFile.print("G");
            textFile.print(G);
            textFile.print("B");
            textFile.print(B);
            textFile.print(" ");
        }
        textFile.print("\n");
    }

    bmpImage.close();
    textFile.close();

    Serial.println("done write");
}`

```

Source: Arduino StackExchange Question: How to read bitmap image on arduino

The text output of this should be a file with an array of strings like `R10G100B25`, where R is the red component of the pixel, G is the green component and B the blue one. Work out how to print these to the serial output.

Note this is only compatible with the 24bpp format.
> 2 votes

# Answer
There is no "command" to read BMP files. They're files like any other. If you know how to read files on an SD card with an Arduino, then you know how to read BMP files. *Interpreting* the bytes of the file you just read is another matter. If the details of the BMP (width, height, depth, array offset, etc.) are known already, you may *seek* to the pixel array directly and begin parsing it (in your case, 3 bytes at a time in BGR order), remembering that BMPs are typically arranged bottom-to-top unless the height field in the header is negative.
> 0 votes

---
Tags: string
---


# Question
Title: Ublox GPS with Arduino Mega 2560 not working
Recently I bought a GPS module (ublox neo-6M-0-001) for my Arduino Mega 2560. I connected Vcc and Gnd (LED at GPS module glows blue and sometimes blinking).

GPS module RX port is connected to the Arduino's TX3, Port 14. GPS module TX port is connected to the Arduino's RX3, Port 15.

As a first step I just want to print the serial data received from the GPS module:

```
#include "SoftwareSerial.h"

SoftwareSerial mySerial(15, 14); // RX, TX

void setup() {
  Serial.begin(9600);
  Serial.println("uBlox Neo 6M Test");
  mySerial.begin(9600);
}

void loop() {
   if (mySerial.available())
     Serial.write(mySerial.read());
}

```

Saldy, there is no data received from the GPS module. According to the datasheet the baud rate 9600 seems to be correct.

Do I need to configure the GPS module somehow before it delivers data? Do I need to buy an external antenna?

Thanks for your help.

# Answer
> 3 votes
The Arduino Mega 2560 has three additional hardware serial ports. Why not use one of them instead? Serial1 on pins 19 (RX) and 18 (TX).

```
void setup()
{
  Serial.begin(9600);
  Serial.println("uBlox Neo 6M Test");
  Serial1.begin(9600);
}

void loop() // run over and over
{
  if (Serial1.available())
     Serial.write(Serial1.read());
}

```

Cheers!

# Answer
> -1 votes
I am also using the sam setup i.e Arduino Mega and NEO6VM2. The GPS module works perfectly fine with a Arduino Uno but when using Mega there are no CharsRX received i.e the Mega is not receiving anything. Please I need help urgently.

---
Tags: arduino-mega, gps
---


title: Can't send Data to LCD1602 with I2C

text:
# Question
Title: Can't send Data to LCD1602 with I2C
I've been doing fine with my LCD1602 I2C configuration but I discovered that command and data functions are the same even though I change the RS command/data bit, but the result is the same.

This is really strange, I really can't do anything about it??!

```
#define E   2   // E  bit
#define RW  1   // RW bit
#define RS  0   // RS bit

#define LCDadd_WR  0x4E
#define LCDadd_RD  0x4F

uint8_t bitmask = 0x08;
uint8_t i, arr[]={0x48,0x65,0x6c,0x6c,0x6f ,0x10 ,0x3a,0x29 ,0x10 ,0x48,0x6f,0x77,0x10
,0x61,0x72,0x65,0x10,0x79,0x6f,0x75,0x65,0x76,0x65,0x72,0x79,0x10,0x6f,0x6e,0x65};

// LCD prototypes
void LCD_Init(void);
void sendCMD(uint8_t CMD);
void sendData(uint8_t data);
void LCD_string(uint8_t arr1[]);
void move_cursor (uint8_t row, uint8_t col);

// I2C prototypes
void I2C_init(void);
void I2C_start(uint8_t address);
void I2C_stop(void);
void I2C_tx(uint8_t data);
void I2C_TWSR_Check(void);

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

void loop() {
//sendData(0x0E); /* I commented this line because it has the same effect as sendCMD(0x0F); in sendCMD function */
}

///////////////////////////////////////////////////
///////////////////////////////////////////////////
void LCD_Init(void)
{
  sendCMD(0x33);
  sendCMD(0x32);
  sendCMD(0x28);
  sendCMD(0x0F);
  sendCMD(0x01);
}

void sendCMD(uint8_t CMD)
{
  bitmask = 0x08;
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask &= ~(1<<RS));
  Serial.println("CMD");
  Serial.println(bitmask, HEX);
  I2C_tx(bitmask &= ~(1<<RW));
  I2C_tx(bitmask = CMD & 0xF0 | 0x08);
  _delay_ms(5);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  _delay_ms(1);
  I2C_tx(bitmask = (CMD<<4) & 0xF0 | 0x08);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  I2C_stop();
}

void sendData(uint8_t data)
{
  bitmask = 0x08;
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask |= (1<<RS));
  Serial.println("data");
  Serial.println(bitmask, HEX);
  I2C_tx(bitmask &= ~(1<<RW));
  I2C_tx(bitmask = data & 0xF0 | 0x08);
  _delay_ms(5);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  _delay_ms(1);
  I2C_tx(bitmask = (data<<4) & 0xF0 | 0x08);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  I2C_stop();
}

uint8_t BF(void)
{
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask &= ~(1<<RS));
  I2C_tx(bitmask |= (1<<RW));
  I2C_stop();
  I2C_start(LCDadd_RD);
  I2C_rx();
  while (!(TWDR == (bitmask & (bitmask<<3))));
  I2C_stop();
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask |= (1<<RS));
  _delay_ms(500);
  I2C_tx(bitmask &= ~(1<<RS));
  _delay_ms(500);
  I2C_stop();
}

void move_cursor (uint8_t row, uint8_t col)
{
  if (row==1)
  sendCMD(0x80+col);
  if (row==2)
  sendCMD(0xC0+col);
}

void LCD_string(uint8_t arr1[])
{
uint8_t cnt=0;
  for (i=0;i<29;i++)
  {
    sendData(arr1[i]);
    _delay_ms(500);
    cnt++;
    if (cnt==16)
    sendCMD(0xC0);
  }
  sendData(0x10);
}

///////////////////////////////////////////////////
///////////////////////////////////////////////////

void I2C_init(void)
{
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1<<TWEN);
}

void I2C_start(uint8_t address)
{
  TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while (!(TWCR & (1<<TWINT)));
  TWDR = address;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
}

void I2C_stop(void)
{
  TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t data)
{
  TWDR = data;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
}

uint8_t I2C_rx(void)
{
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

```

# Answer
> 1 votes
```
I2C_tx(bitmask |= (1<<RS));
I2C_tx(bitmask &= ~(1<<RW));
I2C_tx(bitmask = data & 0xF0 | 0x08);

```

RS is overridden in the third line, so the solution is:

```
I2C_tx(bitmask = data & 0xF0 | 0x08 | (1<<RS));

```

And delete the first two lines :)

---
Tags: arduino-nano, i2c, lcd, c, avr
---


# Question
Title: Arduino Due and BNO055 address in i2c mode
I have a project where I need to have several IMUs, the BNO055 shuttle board (I explained my project here), I manage to get the Euler angles from one BNO055 sensor, which have the address 0x29, because I linked the I2C\_MODE\_ADR\_SEL to a HIGH level.

I would like to have another sensor with the address 0x28. As the datasheet says, I must link the I2C\_MODE\_ADR\_SEL to a LOW level (to the GND) the i2c Scanner from the Arduino Playground does not recognize any i2c device.

I don't know how to change my sensor address, can anyone help me with this issue ?

# Answer
I've built MotioSuit, a mocap suit based on the BNO055 which currently has 9 sensors but could go up to 18.

https://hackaday.io/project/9266-motiosuit

The sensor board and library are open-source and documented in the link, I hope it helps!
> 2 votes

# Answer
According to Table 4-7 on page 90 of the BNO055 datasheet at adafruit.com, the BNO055 supports three I2C addresses: 0x28 or 0x29 in slave mode (selected by COM3 being low or high, respectively), or 0x40 in the HID-I2C configuration.

According to the diagram on page 2 in file BNO055\_Shuttleboard\_Flyer.pdf (Bosch's description of the BNO055 Shuttle Board), COM3 on pin 17 of the BNO055 (or, PSERCOM3) is wired via 0Ω jumper R106 to the middle pin of J102.

If you plan to get data from five different BNO055's, you may need to use a multiplexer (or several I/O's) to set COM3 on one BNO055 board to a different level than on the other four, to select one of the five boards for access. For example, you could use a 7438 (eg, an MM74HC138 or DM74LS138). When you set the 7438's address input to `j`, line Yⱼ (from among Y₀ to Y₇) will go low while the the other Yᵢ remain high. The BNO055 with COM3 attached to Yⱼ then would be the only BNO055 that would respond to I2C address 0x28.

For testing, you could set up several BNO055's and use several separate I/O lines to control several COM3 inputs. Using separate I/O lines takes five I/O lines for five COM3's, vs three I/O lines using a 7438 multiplexer; saving two lines might not be worth the extra effort of obtaining and using a multiplexer.

Another approach is to use two more Arduino (eg Pro Mini or Micro) units to support separate I2C busses for additional BNO055's. These auxiliary Arduinos could do some data reduction before sending data (via serial or I2C) to the principal Arduino.

Note, it is not clear to me that using more than one or two BNO055's makes sense. If the assemblage of BNO055's moves through space more or less as a unit, but with attitudes, roll rates, etc differing between BNO055's, then 3/4 or so of the data from different BNO055's will be the same. Possibly less-general sensors (eg, without magnetometer) with different I2C addresses could be used instead.
> 1 votes

# Answer
Although this is an older question, I believe there may be people still looking for a solution to this problem. Documentation for the BNO055 Shuttle board is pretty thin. I've added a bit of the schematic below.

BNO055 Com3 (pin 17) is presented on pin 22 of the shuttle board (12C\_MODE\_ADR\_SEL). This pin must be connected through a resistor either to shuttleboard pin 4 (SD0, GND) or to shuttleboard pin 5 (SD1). The datasheet makes mention of 2-position jumper J102 which should accomplish this, but there are versions of the Shuttle board that do not include this jumper or any place to mount it. In the photo of the OP's setup (pasted at bottom in case his link goes away) the jumper header would be installed across the three holes adjacent to pin 3 (GND), and jumping the center pin to the left or right-side pin would set the address to 0x028 or 0x029.

If you don't have the jumper, just connect the pins directly: when I connect pin 17 to pin 4 through a 10K resistor, the Arduino "example" scanner does see it at I2C address 0x28.

Personally I like the Adafruit BNO055 board a lot better than the Shuttle -- it has a voltage regulator and a lot of other additions, and it uses 0x028 as its default I2C address.

For those working in the Arduino code environment and wishing to incorporate more than two BNO055 devices and who do not wish to use a multiplexer, I might suggest looking at the Teensy family of 32-bit ARM cortex CPU boards. These are completely code-compatible with Arduino, but offer more than one I2C bus. In fact the Teensy 3.6 (180 MHz!! with 1M Flash, 256K Ram, 4K eeprom, an FPU) offers four\* separate I2C Wire interfaces on different ports, which would permit 8 of the BNO055 devices to be used.

I've personally been very happy with the performance and functionality of the Teensy boards when used with multiple BNO055 devices.
> 1 votes

---
Tags: sensors, arduino-due, i2c
---


# Question
Title: ESP8266 problem with recieved data trasmission via TCP
I am having small project where I want to read couple of analog inputs from Arduino UNO, send it via software serial to ESP8266-01 and from that to python server using TCP.

Data is sent to ESP using this code on Arduino UNO

```
#include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX
    int pin = 5;

    void setup() {
      mySerial.begin(9600);
      delay(20000);
    }
    void loop() {
      delay(1000);
      int data = analogRead(pin);
      mySerial.println(data);
    }

```

Code on ESP is bellow

```
void loop() {
    while(Serial.available()>0){
    char data = Serial.read();
    client.print(data);
    }
}

```

When data is sent to Python server, it prints it out but data is sent in two seperate parts, so it always looks like this

```
9
59

```

, but number sent from arduino is just 959!

Python server code snipet:

```
while True:

        #Receiving from client
        data = conn.recv(1024)

        print data

        #send data to database
        post.create(
            current = str(data)
        )

         if not data:
            break

```

So the question is, why data sent to server is separated in two parts? Maybe it have to do something with how data is reading from serial on esp?

# Answer
You assume all 5 bytes of `959\r\n` are received by the server at the same time. The data is sent byte after byte, based on the `client.print(data)` in the ESP code and assuming the underlying library doesn't buffer bytes before transmitting, so there's no way they'll arrive at the server simultaneously. Most likely, your first pass with `conn.recv(1024)` grabs the first byte `9` and times out. And then on the second pass, the others (at least 2) arrive and are read. The newline between the packets is typical Python 2 `print` behaviour.

What you need to do is parse the data at the server. Basically read data till you get CRLF i.e. `\r\n`, which is a good enough delimiter and you're sending it already anyways, and then use that to know when to write to your database.
> 0 votes

---
Tags: esp8266, softwareserial, python, tcpip
---


# Question
Title: POV using ATmega328 powered with cr2032 cell
I am planning to make a POV (persistence of vision) display using ATmega328 with 5 red LEDs for display.
Below are my aims:

* I want to power it with cr2032 coin cell, so power consumption has to be taken care, I am ready to keep single or 2 coin cell in parallel to meet current requirement.

1. Using 8MHz clock instead of 16MHz can help
        + Does it require separate boot-loader to be installed?
        + During boot-loading do I require to put external 16MHz clock?
        + How to ask controller to use the internal 8MHz clock?
    2. Supply voltage of 3V instead of 5V can also help, and cr2032 gives out 3V
        + What care should I take while using it at 3V?
        + Any mechanism to set the threshold for controller to stop working?
* To reduce the weight of whole circuit so I can rotate the board using small toy motor (I don't have a gear box).
I am planning to control the speed of motor using LM317 voltage regulator as a constant current source.
I will mount the LEDs on straw, keep the controller and the coin cells at the center. (Guessing that will reduce the torque required by the motor as `torque=Force*radius` and weight being at center reduced the radius)
* I am okay, if this circuit works for just few hours OR days.

# Answer
Not exactly an answer, but too big to place into the "comments" area.

**Clock** For the 8MHz vs 16MHz, you should be able to run your project at 1MHz. Just use a bare AVR MCU with the Internal 8MHz oscillator divided by 8 - search for AVR Fuses. You can program it using an ISP (or and Arduino as ISP)

**Battery** About the CR2032 or coin-cells in general are not designed to constantly supply current. You can use it for very low currents, up to 2-4mA or in pulses. Otherwise you damage the cell, reducing it's total usable capacity. Maybe have a look on sub AAA batteries instead of coin-cells.

**Motor** For the motor, have a look on the micro coreless dc motors. They are really tiny and should offer an excellent efficiency. Motor example

**Motor Driver** Not sure about the LM317. You don't want any kind of regulation as it would waste energy. To drive the motor a small Mosfet should do the trick. You can control the Mosfet using PWM, which will define the motor speed. Don't forget to implement some kind of rotary encoder to count the motor RPM so you can precise speed control - a tiny magnet and a hall-sensor should be enough.
> 2 votes

# Answer
**1.** You said you wanted to use your Atmega328 at minimal power usage so you asked how can I use my Atmega at 8mhz. So for doing that first you need to bootloader your Atmega with a 8mhz Bootloader so that it could work with its internal 8mhz source.

**2.** You said you wanted to use coin cells. But coin cells provide a very low amount of power and they are used for small projects. So instead you could use Lithium Ion batteries or AAA batteries.

**3.** You said you will probably look forward to use LM317 as motor controller and a small toy DC motor. Well if you would use LM317 i.e. Voltage regulator you would ended up with a lot of power consumed by it. So I would probably say you to use a MOSFET as Talk said. Now for the motor it's ok upto when you are okay with it. Now I can't say you specifically which motor you looking for as there are many motors with many shapes and features. And that could be done by just searching on Google.
> 1 votes

---
Tags: led, atmega328
---


title: Turn LEDs on in binary sequence

text:
# Question
Title: Turn LEDs on in binary sequence
Could I have some help getting the following code work?

My purpose is to turn on 4(or N) LEDs in a binary sequence with 4 (or N) bits, A,B,C,D. When bit=1, LED on, otherwise LED off,...

I will have 16 combinations, 2^4=16, so:

* 0000 =\> All leds off
* 0001 =\> All leds off except the one on the right
* ...

Here's the code I came up with:

```
int LEDblu=4;
int LEDgiallo=2;
int LEDrosso=5;
int LEDverde=7;
int num_led;
String numeri="";
String output;
int i=0;
int p;

void setup() {
    // put your setup code here, to run once:
    pinMode(LEDblu,OUTPUT);
    pinMode(LEDgiallo,OUTPUT);
    pinMode(LEDrosso,OUTPUT);
    pinMode(LEDverde,OUTPUT);

    Serial.begin(9600);

    if(Serial.available())                //Dimmi numero LED
    {
        num_led=Serial.readString().toInt();
        Serial.print(num_led);
    }
}

void loop() {
    // put your main code here, to run repeatedly:
    int vect[num_led];
    for(int i=num_led-1, c=0; i>=0; i--, c++)
    {
        int num=2^i;
        vect[c]=num;
    }

    output="";

    if(i<2^num_led)
    {
        p=i;

        for(int c=0; c<num_led; c++)     //Convert binary to decimal
        {
            if(p>=vect[c])
            {
                output+="1";
                int d=vect[c];
                p-=d;
            }
            else
                output+="0";
        }

        Serial.println(output);

        if(output[0]=="1")
            digitalWrite(LEDrosso,HIGH);
        else
            digitalWrite(LEDrosso,LOW);

        if(output[1]=="1")
            digitalWrite(LEDverde,HIGH);
        else
            digitalWrite(LEDverde,LOW);

        if(output[2]=="1")
            digitalWrite(LEDgiallo,HIGH);
        else
            digitalWrite(LEDgiallo,LOW);

        if(output[3]=="1")
            digitalWrite(LEDblu,HIGH);
        else
            digitalWrite(LEDblu,LOW);
    }

    delay(1000);
    i++;
}

```

# Answer
> 1 votes
I don't see any specific initialization of `num_led`; it should be set to some appropriate value, like 4.

As noted in some comments, the `^` operator is bitwise exclusive-Or. For example, 2^2 is 0, 2^4 is 6, 2^7 is 5, etc.

To compute the nth power of 2, say `1<<n`.

Your convert-binary-to-decimal code is clunky and unnecessary. Instead, do something like the following, which repeatedly strips off the least significant bit of `t`:

```
t = p;
digitalWrite(LEDrosso,t&1);   t>>=1;
digitalWrite(LEDverde,t&1);   t>>=1;
digitalWrite(LEDgiallo,t&1);  t>>=1;
digitalWrite(LEDblu,t&1);

```

If you want the blue LED instead of the red one to represent the least significant bit, reverse the order of color names in the `digitalWrite` statements from rosso, verde, giallo, blu to blu, giallo, verde, rosso.

To print data out in binary, use the `Streaming.h` library, and say, for example,

```
Serial << _BIN(p) << endl;

```

# Answer
> 1 votes
Note that this is one of those situations where direct port access just makes things easier. You did not specify what board you are using, and I will assume you have some AVR-based board. On those boards, I/O pins come in groups called *ports*, with up to eight pins per port. You can update all the pins of a port at once by writing a number to the port output register. And guess what? The number you write comes out the pins in binary, jut like everything works in binary inside the microcontroller.

For example, on an Arduino Uno, you could wire your LEDs to the first four pins of port B: i.e. pins 8 (lest significant bit) through 11 (most significant bit). Then you can output a number to the LEDs just by writing `PORTB = number`, and your loop would become:

```
void loop()
{
    static uint8_t number;
    PORTB = number;              // output to pins 8..11
    Serial.println(number, 2);   // print the value in binary
    number = (number + 1) % 16;  // increment modulo 16
    delay(1000);
}

```

---
Tags: serial
---


title: Why is the SPI response mis-ordered?

text:
# Question
Title: Why is the SPI response mis-ordered?
I have a Raspberry Pi and an Arduino Micro. The two are connected by a SPI bus, the RPi is the master; the Arduino the slave.

I need to send 5 bytes to the Arduino and get 5 bytes as an answer. The answer is pre-calculated so when the Arduino receives the first byte, it already knows what to answer.

I don't understand why the response I get is mis-ordered. I get the right bytes (value), but they seem shifted in time.

Arduino code:

```
// Data received
volatile unsigned char rx_buffer[5];

// Data to be sent
volatile unsigned char tx_buffer[5];

// Triggered to true by the interruption when message is complete
volatile bool message_ready(false);

// Useful to keep trace of where we are in the message
unsigned char bytes_received = 0;

// SPI interrupt routine
// Message consists of 5 bytes: never less, never more
ISR (SPI_STC_vect)
{
  SPDR = tx_buffer[bytes_received];
  rx_buffer[bytes_received] = SPDR;

  if (++bytes_received == 5) // Reached the end of the buffer
  {
    bytes_received = 0;
    message_ready = true;
  }
}

void setup (void)
{
  pinMode(MISO, OUTPUT); // Set Slave Output as output
  SPCR |= _BV(SPE); // Slave mode
  SPCR |= _BV(SPIE); // Turn on interrupts

  // Reponse to be sent
  tx_buffer[0] = 'a';
  tx_buffer[1] = 'b';
  tx_buffer[2] = 'c';
  tx_buffer[3] = 'd';
  tx_buffer[4] = 'e';
}

void loop (void)
{
  // When message is ready, print it on serial port
  if (message_ready)
  {
    message_ready = false;
    Serial.print((char) rx_buffer[0]);
    Serial.print((char) rx_buffer[1]);
    Serial.print((char) rx_buffer[2]);
    Serial.print((char) rx_buffer[3]);
    Serial.println((char) rx_buffer[4]);
  }
}

```

The RPi uses a C++ program and WiringPi 2.39 to communicate (I also made a similar program with Unix spidev/ioctl calls, same results)

```
#include <iostream>
#include <thread>
#include <chrono>

#include <wiringPi.h>
#include <wiringPiSPI.h>

using std::cout;
using std::cerr;
using std::endl;

int main(void)
{
  // Initialize wiringPi
  if (!wiringPiSPISetup(0, 150000))
  {
    cerr << "Could not initialize SPI!" << endl;
    return 1;
  }

  // Create message and response arrays
  uint8_t message[5], response[5];
  message[0] = 'z';
  message[1] = 'u';
  message[2] = 't';
  message[3] = ' ';
  message[4] = '!';

  std::chrono::steady_clock::time_point begin, end;
  unsigned count(0);
  while (1)
  {
    // Change the number at the end of the message: "zut 0", "zut 1" etc..
    message[4] = *std::to_string(count++).c_str();
    if (count == 10)
      count = 0;

    // Copy the message into response because reponse is going to be overwritten
    for (unsigned i(0); i < 5; ++i)
      response[i] = message[i];

    // Count time and transfer the message (and get the reponse at the same time)
    begin = std::chrono::steady_clock::now();
    if (!wiringPiSPIDataRW (0, response, 5))
      cerr << "Could not send message!" << endl;
    end = std::chrono::steady_clock::now();

    // Inform user
    cout << "Sent: " << message << endl;
    cout << "Received: " << response << endl;
    cout << "Duration: " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << " microseconds" << endl;

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  }

  return 0;
}

```

The outputs are the following,

Arduino (read over serial):

```
zut 0
zut 1
zut 2
zut 3
zut 4
zut 5
zut 6
zut 7
zut 8
zut 9
zut 0
zut 1
zut 2
zut 3

```

Everything looks good on the Arduino receive side!

RPi output (std::cout/cerr):

```
Sent: zut 0
Received: eabcd
Duration: 374 microseconds

Sent: zut 1
Received: eabcd
Duration: 359 microseconds

Sent: zut 2
Received: eabcd
Duration: 357 microseconds

Sent: zut 3
Received: eabcd
Duration: 384 microseconds

Sent: zut 4
Received: eabcd
Duration: 389 microseconds

Sent: zut 5
Received: eabcd
Duration: 384 microseconds

Sent: zut 6
Received: eabcd
Duration: 386 microseconds

Sent: zut 7
Received: eabcd
Duration: 391 microseconds

Sent: zut 8
Received: eabcd
Duration: 385 microseconds

Sent: zut 9
Received: eabcd
Duration: 387 microseconds

Sent: zut 0
Received: eabcd
Duration: 387 microseconds

Sent: zut 1
Received: eabcd
Duration: 387 microseconds

Sent: zut 2
Received: eabcd
Duration: 390 microseconds

Sent: zut 3
Received: eabcd
Duration: 386 microseconds

```

I get the bytes `eabcd` but I expected `abcde`.

Why isn't the RPi receiving the bytes in the correct order? Don't hesitate to ask for additional information.

# Answer
> 1 votes
@KIIV gave me the answer:

> Anyway to not be shifted, you'll have to fill the data register in slave device BEFORE master even starts the transfer.

What happens is that when an SPI transfer is complete, we enter the `ISR (SPI_STC_vect)`, this means that 1 byte (8 bits) has been received. This also means that the response has been sent, because SPI is full duplex!

So the `SPDR` must be filled with the next byte to be sent before entering the ISR. If you modify the `SPDR` inside the ISR, this will set the next byte to be sent; it will not be sent until a byte is received.

---

# Fixed Arduino code

```
// Data received
volatile unsigned char rx_buffer[5];

// Data to be sent
volatile unsigned char tx_buffer[5];

// Triggered to true by the interruption when message is complete
volatile bool message_ready(false);

// Useful to keep trace of where we are in the message
unsigned char bytes_received = 0;

// SPI interrupt routine
// Message consists of 5 bytes: never less, never more
ISR (SPI_STC_vect)
{
  // Store incoming byte
  rx_buffer[bytes_received] = SPDR;

  if (++bytes_received == 5) // Reached the end of the message/buffer
  {
    bytes_received = 0;
    message_ready = true;

    // Let's send another message next time!
    changeTxMessage();
  }

  // When next byte is received, this will be the response
  SPDR = tx_buffer[bytes_received];
}

// This changes the response message sent by the Arduino to the RPi
unsigned count(0);
void changeTxMessage()
{
  // Update message
  switch (count++)
  {
    case 0:
      tx_buffer[0] = 'c';
      tx_buffer[1] = 'r';
      tx_buffer[2] = 'a';
      tx_buffer[3] = 'z';
      tx_buffer[4] = 'y';
      break;
    case 1:
      tx_buffer[0] = 'k';
      tx_buffer[1] = 'a';
      tx_buffer[2] = 'n';
      tx_buffer[3] = 'j';
      tx_buffer[4] = 'i';
      break;
    case 2:
      tx_buffer[0] = 'b';
      tx_buffer[1] = 'u';
      tx_buffer[2] = 'x';
      tx_buffer[3] = 'o';
      tx_buffer[4] = 'm';
      break;
  }

  if (count > 2)
    count = 0;
}

void setup (void)
{
  pinMode(MISO, OUTPUT); // Set Slave Output as output
  SPCR |= _BV(SPE); // Slave mode
  SPCR |= _BV(SPIE); // Turn on interrupts

  // Reponse to be sent
  tx_buffer[0] = 'a';
  tx_buffer[1] = 'b';
  tx_buffer[2] = 'c';
  tx_buffer[3] = 'd';
  tx_buffer[4] = 'e';

  // Prepare first byte to be sent as a response
  SPDR = tx_buffer[0];
}

void loop (void)
{
  // When message is ready, print it on serial port
  if (message_ready)
  {
    message_ready = false;
    Serial.print((char) rx_buffer[0]);
    Serial.print((char) rx_buffer[1]);
    Serial.print((char) rx_buffer[2]);
    Serial.print((char) rx_buffer[3]);
    Serial.println((char) rx_buffer[4]);
  }
}

```

Changes done:

* On setup(), `SPDR` is filled with the first response byte
* Added a new function `void changeTxMessage()` that changes the response message sent by the Arduino for demo purposes.

Arduino output:

```
zut 0
zut 1
zut 2
zut 3
zut 4
zut 5

```

RPi output:

```
Sent: zut 0
Received: abcde
Duration: 241 microseconds
Sent: zut 1
Received: crazy
Duration: 231 microseconds
Sent: zut 2
Received: kanji
Duration: 232 microseconds
Sent: zut 3
Received: buxom
Duration: 249 microseconds
Sent: zut 4
Received: crazy
Duration: 254 microseconds
Sent: zut 5
Received: kanji
Duration: 254 microseconds

```

Everything looks good!

---

# Further thoughts

One thing I don't understand with the old code: why did I receive `eabcd` the first time I get an answer, the first byte should be random because I did not set the SPDR?! Maybe it's kept in memory during Arduino upload.

---

# Performance

I cannot achieve high bit rates with this code. 250 000 Hz is the maximum I can reach (`wiringPiSPISetup(0, 250000)`) before getting problems in the communication. Example at 0.5 Mhz:

Arduino log:

```
zut 0
zut 1
zut 2
zut 3
zut 4
zut 5
zut 6
zut 7

```

RPi log:

```
Sent: zut 0
Received: bzut
Duration: 143 microseconds
Sent: zut 1
Received: czut
Duration: 136 microseconds
Sent: zut 2
Received: kzut
Duration: 135 microseconds

```

I expected to reach at least 2 Mhz, I think I'll open a new question for that.

---
Tags: spi, arduino-micro, raspberrypi
---


# Question
Title: ATmega AVR frequency measurement with timer/counter
I've been rehashing some existing libraries I found on some obscure forums to measure a frequency on digital pin 5, using the ATmega328P/ATmega2560 Timer/Counter modules and an interrupt based approach in order to be able to measure frequencies up to 4MHz(-ish). However, using the code described below, the results are off by a factor of exactly 100. I used a frequency generator to accomplish these readouts. Here is an example of what I've been getting back when generating a 5000Hz square wave (50% duty cycle):

Can someone please point out what might be wrong. I've read the ATmega328P datasheet multiple times by now and it should just work! This is very strange.

> **Edit:** As it turns out the AWG I use has a blantant software bug which causes it to generate a wave with a period that's 100 times too long (see picture below). Nevertheless as Edgar pointed out I made some pretty big mistakes by not taking into account race conditions. Therefore the code below has been updated. Also, the test program has been updated to generate a 50% duty cycle square wave @5000Hz for testing purposes as suggested by Edgar.

This is the header file:

```
#ifndef FreqCounter_h
#define FreqCounter_h

#include <avr/interrupt.h>
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
namespace FreqCounter
{
    extern volatile unsigned long f_freq;
    extern volatile unsigned char f_ready;
    extern volatile unsigned char f_mlt;
    extern volatile unsigned int f_tics;
    extern volatile unsigned int f_period;

    void start(int ms);
}
#endif

```

This is the source file:

```
#include <FreqCounter.h>

volatile unsigned long FreqCounter::f_freq;
volatile unsigned char FreqCounter::f_ready;
volatile unsigned char FreqCounter::f_mlt;
volatile unsigned int FreqCounter::f_tics;
volatile unsigned int FreqCounter::f_period;

void FreqCounter::start(int ms) {
    f_period = ms;
    GTCCR = (1<<TSM) | (1<<PSRASY) | (1<<PSRSYNC); //halt all timers

    //set TC1 to normal mode => TOV1 flag set at TOP = 0xFFFF
    TCCR1A &= 0x00; //reset TC1 control register A
    TCCR1B &= 0x00; //reset TC1 control register B

    //set TC1 to use external clock source, clocked on rising edge
    TCCR1B |= (1<<CS10);
    TCCR1B |= (1<<CS11);
    TCCR1B |= (1<<CS12);

    //reset TC2
    TCCR2A &= 0x00; //reset TC2 control register A
    TCCR2B &= 0x00; //reset TC2 control register B

    //set TC2 to CTC Mode with TOP = OCR2A => counter cleared on reaching TOP
    TCCR2A |= (1<<WGM21);

    //TC2 is in CTC mode => set value of OCR2A = TOP
    OCR2A = 124; //TOP is reached every 125 counts (starting from 0)

    //set TC2 to use a prescaler of 1 => 16MHz / 128 = 125kHz
    TCCR2B |= (1<<CS20);
    TCCR2B |= (1<<CS22);

    f_ready = 0; //reset ready flag
    f_tics = 0; //reset TC2 interrupt counter

    //synchronize the value of both timers
    TCNT2 = 0;
    TCNT1 = 0;

    //clear interrupt flags
    TIFR2 |= (1<<OCF2A);
    TIFR1 |= (1<<TOV1);

    TIMSK2 |= (1<<OCIE2A); //enable TC2 Output Compare A interrupt => triggered on reaching TOP = OCR2A
    TIMSK1 |= (1<<TOIE1); //enable TC1 overflow interrupt => triggered on reaching TOP = MAX = 0xFFFF

    GTCCR &= 0x00; //restart all timers => start counting
}

/*
 * This ISR is triggered by TC2 every 1ms because
 * TC2 increments with a frequency of 16MHz / 128 = 125KHz
 * and reaches TOP every 125 counts
 * => trigger frequency = 1kHz
 * => trigger period = 1ms
 *
 * This ISR handles the Gate Time generation
 */
ISR(TIMER2_COMPA_vect)
{
    //increment number of TC2 interrupts (triggers when reaching TOP = OCR2A)
    FreqCounter::f_tics++;

    /*
     * If branch evaluates as true if given gate time (f_period) equals
     * amount of milliseconds TC2 has counted (= f_tics)
     */
    if (FreqCounter::f_tics >= FreqCounter::f_period)
    {
        //end of gate time => measurement ready
        TCCR1B &= ~0x07; //set TC1 to no clk source => TC1 stops counting
        TIMSK2 &= ~(1<<OCIE2A); //disable TC2 Output Compare A interrupt
        TIMSK1 &= ~(1<<TOIE1); //disable TC1 overflow interrupt
        FreqCounter::f_ready = 1; //set software flag for end of gating period

        //increment on overflow of TCNT1
        if (bit_is_set(TIFR1, TOV1))
            FreqCounter::f_mlt++;

        //calculate frequency
        FreqCounter::f_freq = 65536 * FreqCounter::f_mlt;
        FreqCounter::f_freq += TCNT1; //add value of TC1
        FreqCounter::f_freq = (long)(FreqCounter::f_freq * 1000.0 / (double)FreqCounter::f_tics);
        FreqCounter::f_mlt = 0;
    }
}

ISR(TIMER1_OVF_vect)
{
    FreqCounter::f_mlt++;
}

```

This is the test program:

```
#include <FreqCounter.h>

long frq;

void setup()
{
    //generate a 5 kHz square wave on OC0B = digital pin 5 = T1
    DDRD |= _BV(PD5); //PD5 = OC0B as output
    TCCR0B = 0; //stop timer
    TIMSK0 = 0; //disable overflow interrupt
    OCR0A = 50 - 1; //period = 50 * 64 cycles
    OCR0B = 50 / 2 - 1; //50% duty cycle
    TCCR0A = _BV(COM0B1) //non-inverting PWM on OC0B
        | _BV(WGM00) //fast PWM, TOP = OCR0A
        | _BV(WGM01); //...ditto
    TCCR0B = _BV(WGM02) //...ditto
        | _BV(CS00) //clock at F_CPU / 64
        | _BV(CS01); //...ditto
    Serial.begin(57600);
    Serial.println("Frequency Counter");
}

void loop()
{
    FreqCounter::start(1000);
    while (FreqCounter::f_ready == 0);
    frq = FreqCounter::f_freq;
    Serial.println(frq);
}

```

PS: This is my first ever post on this forum. Feel free to comment on the contents of my question. Tips as to how I might improve future questions are always welcome. Have a great day!

# Answer
I am posting this as an answer, just because it doesn't fit as a comment. But more than an answer it is intended to be a debugging help.

First, I would like to point out that you can use the same Arduino to both generate the test signal and read it. This can be done by configuring Timer 0 (the last one you have left...) to output the 5 kHz square wave on OC0B (digital pin 5), and wire this signal to pin T1 which is... also digital 5. No wiring needed then! You can do this by adding the following to your test program's `setup()`:

```
// Generate a 5 kHz square wave on OC0B = digital pin 5.
DDRD  |= _BV(PD5);    // PD5 = OC0B as output
TCCR0B = 0;           // stop timer
TIMSK0 = 0;           // disable overflow interrupt
OCR0A  = 50 - 1;      // period = 50 * 64 cycles
OCR0B  = 50/2 - 1;    // 50% duty cycle
TCCR0A = _BV(COM0B1)  // non-inverting PWM on OC0B
       | _BV(WGM00)   // fast PWM, TOP = OCR0A
       | _BV(WGM01);  // ...ditto
TCCR0B = _BV(WGM02)   // ...ditto
       | _BV(CS00)    // clock at F_CPU / 64
       | _BV(CS01);   // ...ditto

```

Then I would like to point out a couple of bugs in the library you are using. First, there is an off-by-one error: the program is counting one millisecond too much. This can be fixed by moving the lines

```
//increment number of TC2 interrupts (triggers when reaching TOP = OCR2A)
FreqCounter::f_tics++;

```

from the bottom to the top if `ISR(TIMER2_COMPA_vect)`.

Next, there is a race condition between the ISRs. Race conditions are nasty bugs because they are hard to reproduce and most of the time you don't see them. And then the program just fails at a random time after many tests showed it works fine.

Here it works as follows: let's say that after the required time has elapsed, `TIMER2_COMPA` fires and *right after that* `TIMER1_OVF` fires also. This second interrupt is put on hold (it's a *pending interrupt*) while `TIMER2_COMPA_vect` runs through its prologue. Then you compute the frequency based on `FreqCounter::f_mlt` (which has not been updated to account for the overflow) and `TCNT1` (which has already overflown to zero). Thus you get an incorrect result. Not only that, the overflow flag remains set, so the ISR will run *right away* as soon as the interrupt is enabled again by your next call to `FreqCounter::start()`. And again you get an incorrect result.

The fix is two fold: first you have to detect the pending interrupt condition in `ISR(TIMER2_COMPA_vect)`: after stopping the timers and before computing `FreqCounter::f_freq`, you need this:

```
// Did we miss an overflow?
if (bit_is_set(TIFR1, TOV1))
    FreqCounter::f_mlt++;

```

Next, you have to clear the interrupt flag. This is customarily done right before enabling the interrupt, and just to be safe you do it for every interrupt you enable. Thus, in `FreqCounter::start()`, right before touching `TIMSK2` and `TIMSK1`, you would:

```
// Clear interrupt flags.
TIFR2 = _BV(OCF2A);
TIFR1 = _BV(TOV1);

```

There are a couple of other minor issues, like the statement `TCCR2A &= ~(1<<WGM22);` which makes no sense (the bit belongs to another register). But given that this, like a few other statements, has no effect whatsoever, it should not affect the working of the program. It does reveal sloppy programming though.
> 1 votes

---
Tags: arduino-uno, arduino-mega, interrupt, timers, frequency
---


# Question
Title: Why can't I define the constant A0 (some pin) to something?
What I'm doing wrong or why is it not working:

```
#define Uin A0;

void setup() {
}

void loop() {
  analogRead(Uin);
}

```

Results in a `Error (expected ')' before ; token.`

I thought `#define` just exists as a place holder.

# Answer
> 17 votes
Because you have a `;` at the end of your #define.

```
#define Uin A0;
analogRead(Uin);

```

becomes:

```
analogRead(A0;);

```

The Arduino website mentions this in their reference. For more in-depth detail about the C pre-processor you can read the (rather large) manual here.

---
Tags: programming, c++
---


title: Write array to serial port

text:
# Question
Title: Write array to serial port
The Code Below now works:

```
void SendCTRL (String &input)
{
  const char *hin = input.c_str();    // Get character array
  int clen = input.length()/2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
  RS485Serial.write(cmd[i]);   // Send string someplace
  //Serial.write(cmd[i]);
  }
  delay(clen/4);
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
  Serial.println();

}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

```

Input is a series of ASCII-encoded hex digits and getting the output to print the byte values of the hex.

# Answer
> 2 votes
There's some logic slightly askew with your length calculations:

```
int clen = input.length()/2;

```

Ok, so for a (say) 20 character string you have `clen=10`.

```
for (int i=0; i < clen; i+=2)

```

Ok, so for the first 10 characters of your 20 character string you take alternate ones (0, 2, 4, 6, 8)

What about the last 10 characters? `clen` is 10, not 20, since you divided it by 2 at the start.

Decide if you want clen to be half the string length, then count *double*, or is the whole string length, and you divide it by 2 where you want the final string length. Or have two variables - one before and one after dividing by 2.

Oh, and you should pass your String parameter *by reference* so you don't duplicate the object and end up fragmenting your heap.

```
void SendCTRL (String &input)

```

I haven't gone into depth about the working of your `dehex` function, but this is the function I always use and works well:

```
unsigned char h2d(char hex)
{
    if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
    return(hex & 0xf);
}

```

Also you should *or* your values together, not *add* them:

```
cmd[i/2] = (dehex(hin[i])<<4) | dehex(hin[i+1]);

```

This would go some way to fixing your current issue, since `|` has a different precedence to `+`. At the moment you have effectively:

```
cmd[i/2] = dehex(hin[i]) << (4 + dehex(hin[i+1]));

```

since the `+` happens before the `<<`, whereas what you want is:

```
cmd[i/2] = (dehex(hin[i]) << 4) + dehex(hin[i+1]);

```

However with `|` instead you get

```
cmd[i/2] = (dehex(hin[i]) << 4) | dehex(hin[i+1]);

```

because the `<<` happens before the `|`

Here is your code written in pure C to run on a PC (faster to debug and test than an Arduino when you're on Linux):

```
#include <stdio.h>
#include <string.h>

unsigned char dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

void SendCTRL (const char *hin)
{
  int ilen = strlen(hin);
  int clen = ilen / 2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < ilen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
    printf("%02x\n", cmd[i/2]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  for (int i = 0; i < clen; i++) {
    printf("%c", cmd[i]);
  }
}

void main() {
    SendCTRL("010307E40001C549");
}

```

---
Tags: arduino-uno, c++, communication, code-review
---


title: Multiple arduino Wireless communication

text:
# Question
Title: Multiple arduino Wireless communication
I would like to know what device and model to use for an application where I will have `1 arduino as a master` micro controller waiting to receive data from `5 slave arduino` microcontrollers.

The `Master` arduino will be connected to local network via Ethernet cable so once it receive data from a `Slave` controller it needs to post to server the information, get a response back and in case the response is a "true" value then the `Master` need to talk back to the `Slave` in order to turn a LED on.

There will be cases when maybe 3 of the `Slaves` will send data at the same time, this doesn't mean at exactly the same millisecond. So I don't know if there will be data lost.

I was reading that `Xbee` maybe is the best device because it has a feature that will hold the data until there is a success communication with slave.

> Is this a doable and "easy" task using `Xbee`? Anyone that already try to do something like this that can guide me?
>
> > I was reading that there is a device `nRF24l01` that is very cheap and can do exactly what I need. Just that I don't really know how to start.

Appreciate any advice or help.

# Answer
It really depends on the communication range and context required.

If your *slaves* are within 10-20 meters from the *master* device and the environment is not polluted (in terms of magnetic field) you can achieve good results with very inexpensive nRF24L01+ modules which operate in the 2.4GHz.

If you need to cover greater distances (in the order of 100 meters) or a polluted environment then you have to resort to shorter wavelengths or more powerful devices, but that brings in the question on how are you powering your *slaves*: on battery power those ranges get pretty power hungry.

Generally speaking I would say this question should be rejected as it's going to start a debate rather than provide a solution.

You can get some introductions on how to use nRF24L01+ modules simply searching online:
> 1 votes

---
Tags: xbee, nrf24l01+, wireless
---


title: What if I have burnt my atmega328p?

text:
# Question
Title: What if I have burnt my atmega328p?
Actually I am facing a big problem while programming my atmega328p using an arduino uno as ISP. I followed a video on youtube "Arduino as ISP" by Notes and Volts. Which look doing the same steps that the majority followed. For the blinking LED sketch the µC worked very well and it did not show any troubles. So I decided to carry on , and at this point I needed to upload a new program but this i wanted to upload my program using "avrdude" command line because my code was written with MikroC pro for avr, and here is the command line :

`"avrdude -p atmega328p -b 19200 -C arduino -P COM7 -U lfuse:w:0xf7:m -U
 hfuse:w:0xc9:m -U efuse:w:0xff:m -U flash:w:LED.hex:i "`

But unfortunately it did not work well and I have got the following error :

`avrdude : invalid byte value <ff> specified for immediate mode
 avrdude : write to file 'ff' failed
 avrdude : safemode : Fuses OK`

Seeing that error paniced me , that's why I decided to retry the programmation with an arduino sketch and then happened the big issue when the arduino generate an error message about finding a bad microcontroller \[error about the device signature\] \[\]. My last try to find out if I ruined my µC is with switching the µCs; the arduino original and the one that I had to program and unfortunately It was not a good result : "avrdude : stk500\_recv() : programmer is not responding avrdude : stk500\_getsync() attempt 1 of 10 : not in sync : resp=0x85"  Looking for more than day on the internet and I could not find a valid solution , except the possibility that I really BURNT my µC and I have to buy another one. And this is specifically why I am asking for your help; I need to know if SO could figure this trouble out.Otherwise, could somebode confirm to me that there is no hope with my µC and it's gone and I have to stop trying to make it works . Thank you Regards

# Answer
Trying your fuse settings on an AVR fuse calculator shows that you have selected an “external full-swing crystal” as the clock source. Now your ATmega won't work unless you connect it to an external crystal. Or you could try just sending a square wave into the XTAL1 pin. *Then* you can try to reprogram it.
> 2 votes

# Answer
after two days of searching on internet, I decided to just reburn the bootloader again on my target µC to discover if it's really burned or not. SO, I guess it was not damaged because I was able to burn the bootloader and upload the blink led sketch successfully.
> 2 votes

# Answer
> What if I have burnt my atmega328p?

get a new one.

> Otherwise, could somebode confirm to me that there is no hope with my µC and it's gone and I have to stop trying to make it works .

based on the information you have provided, no one can tell definitively. you could have changed the fuse settings, or your 2nd chip didn't have the bootloader, or bad connection, ....

a better approach is to get a separate programmer - usbasp for low prices, or dragon (older debugger with hv programming capability) and go from there.
> 1 votes

---
Tags: avrdude, isp
---


# Question
Title: How to code multiple conditions inside if statement?
I have a system that checks the value of a moisture sensor and will also check the time

```
if (t.hour == 7 && t.min == 00 && moistureOneSensorValue >= 700) {
  RelayOne();
  RelayTwo();
}

```

When `moistureOneSensorValue` is greater than or equal to 700 it means the soil is `DRY`, so when all conditions inside the if statement are true the `relayOne` and `relayTwo` functions will be called.

My problem is that when `moistureOneSensorValue` is still `moist` the above if statement will result in `false` and the `relayOne` and `relayTwo` functions will not be called. I want Arduino to execute and call the `relayOne` and `relayTwo` functions and disregard the `time`. I use time so that the system will only call the `relayOne` and `relayTwo` functions in the morning at exactly 7 AM every day, but it needs to check/make sure that the soil is `DRY`...

**Example**

First thing in the morning the system will check the time and sensor value; if the `if statement` results in `false` the system will keep monitoring and try the if statement until the soil is `DRY`. But I think when that happens it will be over 7 AM.

Sorry for the messy explanation.

# Answer
> 1 votes
I'm not sure how quickly you soil could get dry, but I suspect what you want to do is to periodically check the dryness throughout the day. Say like every two hours:

```
// Check every 2 hrs (when hr is even)
if ( t.hour % 2 == 0 && moistureOneSensorValue >= 700 ) {...}

```

You could also bound it to only during the day time:

```
if ( t.hour >= 7 // after 7a
  && t.hour <= 19 // before 7p
  && t.hour % 2 == 1 // every 2 hrs (when hr is odd)
  && moistureOneSensorValue >= 700 // soil is dry
) {...}

```

# Answer
> 0 votes
If the event is to be time independent then it follows you can not check the time. If the event is to be both time independent and dependent then you need to add the code to handle the logic.

Consider checking if it is between 7am and, say, 7pm. If true then test if the moisture detector is dry. If true then close (watering) relays.

*(This is only a code example and has not been tested.)*

```
if(t.hour >= 7 && t.hour <= 19)
{
  while(moistureOneSensorValue >= 700)
  {
   RelayOne();
   RelayTwo();
  }
}

```

Consider adding a state machine to mitigate possible problems by monitoring minimum times between events and maximum times of events. For example, do not water more than once per 5 minutes. Do not water more than 30 seconds at a time. Do not water more then a total of 1 minute per hour. Do not water more than 5 minutes per 24 hours.

---
Tags: arduino-uno
---


# Question
Title: How to make 4 digits 7 segments common cathode thermometer
I'm new to Arduino and I have this problem: The common cathode 4 digits 7-segments keep on blinking even the code and my connection is correct (in my opition). I have used an LM35 IC to read the temperature I've just followed this pattern: and I used this code:

```
const int digitPins[4] = {5,4,3,2}; //4 common CATHODE pins of the display (inverted the pins order)
const int clockPin = 7;    //74HC595 Pin 11
const int latchPin = 8;    //74HC595 Pin 12
const int dataPin = 12;     //74HC595 Pin 14
const int tempPin = A0;     //temperature sensor pin
const byte digit[10] =      //seven segment digits in bits
{
  B00111111, //0
  B00000110, //1
  B01011011, //2
  B01001111, //3
  B01100110, //4
  B01101101, //5
  B01111101, //6
  B00000111, //7
  B01111111, //8
  B01101111  //9
};
int digitBuffer[4] = {0};
int digitScan = 0;
float tempC; //Deleted kelvin and farenheit

void setup(){
  for(int i=0;i<4;i++)
  {
    pinMode(digitPins[i],OUTPUT);
  }
  pinMode(tempPin, INPUT);
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(tempPin, INPUT);
  //Serial.begin(9600);
}

//writes the temperature on display
void updateDisp(){

  for(byte j=0; j<4; j++) {digitalWrite(digitPins[j], HIGH);} // Turns the display off. Changed to HIGH
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, B00000000);
  digitalWrite(latchPin, HIGH);

  delayMicroseconds(2);

  digitalWrite(digitPins[digitScan], LOW); //Changed to LOW for turning the leds on.

  digitalWrite(latchPin, LOW);
  if(digitScan==2)
    shiftOut(dataPin, clockPin, MSBFIRST, (digit[digitBuffer[digitScan]] | B10000000)); //print the decimal point on the 3rd digit
  else
    shiftOut(dataPin, clockPin, MSBFIRST, digit[digitBuffer[digitScan]]);

  digitalWrite(latchPin, HIGH);

  digitScan++;
  if(digitScan>3) digitScan=0;
}

void loop(){
  tempC = analogRead(tempPin)*0.00488;  //multiplied for this conversion constant
  tempC = tempC*10000;
  digitBuffer[3] = int(tempC)/1000;
  digitBuffer[2] = (int(tempC)%1000)/100;
  digitBuffer[1] = (int(tempC)%100)/10;
  digitBuffer[0] = (int(tempC)%100)%10;

  if (digitBuffer[0]>=5) {
    digitBuffer[0] = 5;
  }
  else {
    digitBuffer[0] = 0;
  }

  delay(5);
  updateDisp();
}

```

# Answer
> 1 votes
First thing to check is that you have the IC and the 7-segment display module connected the correct way around. As a reference, the green wire is attached to Pin 14 of the 74HC595 IC, so pin 1 would be the top right pin. The 7-segment display should have the the dot points towards the bottom.

Check that you have a common cathode display. You can do this by applying a voltage, through a 220 ohm resistor, verifying that it lights up when positive is on pins A-G and Gnd connected to the common cathode pin.

Check the code by removing the temperature section of the code and just writing '0's to all 4 digits. In fact it would be worth testing the digits one by one. The below code should do just that (unverified):

```
const int clockPin = 7;    //74HC595 Pin 11
const int latchPin = 8;    //74HC595 Pin 12
const int dataPin = 12;    //74HC595 Pin 14
const int digitPins[4] = {5,4,3,2};

void setup(){
  for(int i=0;i<4;i++)
  {
    pinMode(digitPins[i],OUTPUT);
    digitalWrite(digitPins[i], HIGH);
  }
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  for(int i=0;i<4;i++)
  {
    //select the digit by enabling the common cathode (sink)
    digitalWrite(digitPins[i], LOW);

    // write '0'
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, 63);
    digitalWrite(latchPin, HIGH);
    delay(1000);
  }
}

```

This code will display a '0' one digit at a time, each for 1 second. If this code works then I suspect the problem lies in the `updateDisp()` function.

NB: In your code, tempPin is setup twice as an input.

---
Tags: arduino-uno
---


# Question
Title: Arduino Nano + (2* tlc5940) + 34 LEDs = Power Questions
This is an adapted layout for two tlc5940 hooked up to an Arduino nano. The original project can be found here. I am a little unsure about the capacitors and resistors as that project had it hooked up to a 5v wall plug.

My Design will be running a pattern of PWM, blinking and chasing lights. The two red lights are off of the TLC5940s circuits because reds need a different resistance. If i am wrong, please let me know as that would simplify things.

Also as is the way of the stack community, any other red flags you can point out would be greatly appreciated as i am new to this game.

# Answer
> 0 votes
As Ignacio has mentioned the TLC5940 is a *constant current* driver. The 2kΩ resistor sets the current for the LEDs regardless of the forward voltage (or colour) or the supply voltage.

Also as Gerben says, move the 0.1µF (100nF) capacitor close to the TLC5940 as you can. There should be one for each TLC5940 since they are *decoupling capacitors*.

You might like to increase the capacitance of the electrolytic too. The purpose of that capacitor is to provide a low impedance energy source to supply the circuit (batteries are actually quite high impedance by comparison). Since you have lots of LEDs being controlled by PWM the current draw will be fluctuating wildly all the time, and lots of energy over brief periods will be wanted.

Another thing to watch, mentioned again by Ignacio, is the supply voltage for the TLC5940 is 5.5V *absolute maximum*. I wouldn't go much above 5V. Depending on what your batteries actually are you may be better running from 3 of them (4.5V alkaline AA - Ni-MH would be ~3.6V, so 4 of them, giving 4.8V, would be better in that situation).

I would also question your use of the TLC5940. They are not the easiest chips to drive requiring quite a strange protocol. Personally I prefer the TLC59116 which is the I2C variant of the same chip. Much easier to control from an Arduino, and requiring just 2 pins. Not so easy for bread-boarding though as they're SMD only.

---
Tags: led, arduino-nano, tlc5940
---


title: how to drive 500W of leds

text:
# Question
Title: how to drive 500W of leds
I am currently developing a project that needs 9 led stripes, each led stripe has 5 meters, 300 leds, it consumes 60W per stripe in a total of 540W...

This are the led stripes - 5M 12W/M 24V SMD 2835

This led stripes use a 24V power supply.

The thing is I want to drive them with an arduino and PWM. What would I need to do it. I was looking for something like CAT4101 but I never dealt with so much power before and I would like your advice.

Thanks

# Answer
The led strips will have their own current limiting / drivers. A couple of quick calculations:

* 24V at 12W is (I=P/V) 12/24 = 0.5A per meter
* 5 meters = 0.5\*5 = 2.5A

So each strip takes 2.5A. The CAT4101 is a 1A max driver, but since it is a *constant current* driver it's not suitable for a strip that has its own current control built in.

I suspect each meter consists of 10 chains of 6 LEDs with a current limiting resistor or two. Out of interest, calculations:

* 6 LEDs at (say) 3V forward voltage would be 18V.
* 24 - 18 = 6 volts to drop
* 500mA divided by 10 chains = 50mA
* R=V/I = 6 / 0.05 = 120Ω current limiting resistors.
* P=I²R = 0.05²×6 = 300mW dissipated from the resistors.

Instead all you need is an N-channel MOSFET as a low-side switch that can operate with that much current and not dissipate too much heat while switching. The more you derate the MOSFET the less heatsinking it would need.

A quick look on Digikey gave a possible match of PSMN022-30PL \- 30V, 30A, 27mΩ (typ) at 4.5V gate voltage.

simulate this circuit – Schematic created using CircuitLab
> 2 votes

---
Tags: led
---


# Question
Title: Programmatically Change Arduino Com Port Name
I have some devices that, when I plug in, will display a unique name, usually a serial number, as opposed to "COM #" is there any way I can have my Arduino Uno (or Mega) give itself a different name in my program's set up structure?

Edit: My purpose here is that I'm writing a program on the computer side that needs to find the Arduino among multiple possible COM ports. I'm deploying this program over multiple computers that I don't have admin access to so changing the registry is likely a non-starter.

Right now, I'm going through each port and sending a *`idn?\n` (which my program responds to with a specific string). For another device I have, I can search the possible connections for a port named \[device serial number\] and test that one first.

# Answer
1. If you read this So it says:

You'll have to change the software on the Arduino USB chip itself, and you may need to modify the drivers for the Arduino USB interface on the computer side. It's not trivial, and probably not worth it.

Then according to this you need to toggle and tinker with the Driver software

2. Wait that means it is not the correct answer. So according to your plan you need to maybe toggle with IDE that is instead of manually changing the ports you want the software to identify on its own. So for that purpose you have to tweak with Arduino board bootloader, and say it send a message to the Arduino IDE on startup . After that you have to tweak with Arduino ide source codes and then tweak it to Search for that message and then it reads down the address that is its COM
> 2 votes

# Answer
On Windows you can change the "Friendly names" assigned to devices and COM ports are devices. The process is basically open the device manager, open the device properties, find the 'Device Key' and then locate that in the registry and change the 'Friendly Name' value.

See this page for more details: https://www.eightforums.com/customization/15321-tutorial-how-change-device-names-device-manager.html
> 3 votes

---
Tags: arduino-uno, communication
---


title: Any good way to inverse a function?

text:
# Question
Title: Any good way to inverse a function?
I'm guessing that the answer to this is "no," but I'm curious if there is any way to save writing some code by specifying a function to do the opposite of whatever another function does. For example the inverse of:

```
int FW (int in)
{
  int out=2+in;
  Return out
}

```

would be

```
int RV (int in)
{
  int out=in-2;
  Return out
}

```

However, would there be any way to call the inverse of `FW()` if it was a more complicated function that still had one and only one input for each output?

# Answer
> 3 votes
No. A function does what it does and that is all. No other function can know what some other function does.

You could write a function that does different things depending on what parameters you pass to it, but that's the closest you can get, and is pretty pointless when you can just write different functions anyway.

---
Tags: arduino-uno, programming, sketch
---


title: float not a float

text:
# Question
Title: float not a float
I am trying to read a SDM220 meter on my solar setup. I've been reading it using Modbus SCADA, so know it all works ok. But I want to read it with my Arduino Mega 256. My problem is that when I run the code below the final value MtrKWh , is not float value. it's actual value is printed. Here is a copy of the output.

17241 MtrKWh1 1129906176 MtrKWh1\<\<16 57737 MtrKWh2 1129963913 MtrKWh3 11299639.00 MtrKWh 2

the value '1129963913' MtrKWh3,

if I turn it into Binary is 01000011010110011110000110001001,

if I convert this to binary using https://www.h-schmidt.net/FloatConverter/ it gives me the value

217.881,

the very value I expect. Am I missing some brackets somewhere? So how do I get MtrKWh to print its float value? I have left a lot of commented out bits to show the several things I have tried. Sorry if it appears messy, I will tidy it up once I solve this problem. I'm sure it is something simple, but, I haven't been able to see it so far. Any sugestions would be appreciated.

```
    // MtrV, MtrC, MtrW, MtrKWh
    //void AddressRegistry_0()
    result = sdm220_modbus.readInputRegisters(0x48, 2);
    //while (!result == 0) {
    // delay(10);
    // result = sdm220_modbus.readInputRegisters(0x156,4);
    //}
   if (result == sdm220_modbus.ku8MBSuccess)
   {
    // 1 Serial.println((node.getResponseBuffer(0x0D) + node.getResponseBuffer(0x0E) << 16)/100.0f);
    // 2 pvpower = ((long)node.getResponseBuffer(0x03) << 16 | node.getResponseBuffer(0x02)) / 100.0f;
    // 3 long pressure = ((pressure_data_high << 16) | pressure_data_low) / 4;
    // 1 working ?? MtrKWh1 = (((long)sdm220_modbus.getResponseBuffer(0x0) + sdm220_modbus.getResponseBuffer(0x1) << 16)/6.f);
    // 2 working ?? MtrKWh1 = ((long)sdm220_modbus.getResponseBuffer(0x0) << 16 | sdm220_modbus.getResponseBuffer(0x1)) / 100.3f;
    // 3 working MtrKWh1 = (( sdm220_modbus.getResponseBuffer(0x0)  << 16) |  sdm220_modbus.getResponseBuffer(0x1))  / 16.3f;
    //
   // float MtrKWh0 =((float)(sdm220_modbus.getResponseBuffer( 0) << 16 | sdm220_modbus.getResponseBuffer( 1)));
    //      Serial.print(MtrKWh0);
    //    Serial.print(" MtrKWh0     ");

signed long MtrKWh1 = sdm220_modbus.getResponseBuffer(0x0);
Serial.print(" ");
Serial.print(MtrKWh1);
Serial.print(" MtrKWh1");

MtrKWh1 = MtrKWh1 << 16;
Serial.print(" ");
Serial.print(MtrKWh1);
Serial.print(" MtrKWh1<<16");

word MtrKWh2 = sdm220_modbus.getResponseBuffer(0x1);
Serial.print(" ");
Serial.print(MtrKWh2);
Serial.print(" MtrKWh2");

signed long MtrKWh3 = MtrKWh1 | MtrKWh2;
Serial.print(" ");
Serial.print(MtrKWh3);
Serial.print(" MtrKWh3");

float (MtrKWh) = float (MtrKWh3) / 10000.0;
Serial.print(" ");
Serial.print(MtrKWh);
Serial.print(" MtrKWh     ");

//uint32_t x = 0x3f322e3f;
//float y = *(float*)&x;
//Serial.print (y, 6);
// Serial.print(" MtrKWhxxx ");

   }
   else
   {
    rs485DataReceived = false;
    Serial.println("Fail sdm220_modbus.readInputRegisters(0x0, 1) ");
   }

```

# Answer
> 1 votes
You need to convert the format by overlaying one type on top of the other, rather than casting from one type to another.

1000 as an integer cast to a floating point value is still 1000.

You have an example of how it can be done in comments:

```
//float y = *(float*)&x;

```

However this method is called *type punning* and is frowned upon (there are compiler options that can prevent it being used). Instead using a *union* is a better option:

```
union ifloat {
    uint8_t bytes[4];
    float val;
};

void setup() {
    ifloat f;
    Serial.begin(115200);
    f.bytes[3] = 0x43;
    f.bytes[2] = 0x59;
    f.bytes[1] = 0xE1;
    f.bytes[0] = 0x89;
    Serial.println(f.val, 4);

}

void loop() {
}

```

So you can get the byte order right your current numeric value of 1129963913 is 0x4359E189 in hexadecimal. Byte 3 is therefore the most significant byte and byte 0 the least significant. Note that it can change from system to system depending on the *endianness* of the chip.

How it works is quite simple. You have 4 bytes in memory, and the union just gives you different views of those 4 bytes.

You can either see them as four individual bytes (f.bytes\[0-3\]) or as a floating point value (f.val).

You can understand more about how the four bytes describe the floating point number by understanding more about the IEEE 754 Single Precision Floating Point Format.

---

You can achieve the same thing using `reinterpret_cast`, but that has to be done using *pointers*, not the values, which makes it a little more complex to understand:

```
// Your incoming 32-bit value
uint32_t l = 1129963913;

// A pointer to the same memory with a different type
float *f = reinterpret_cast<float *>(&l);

// Print the *content* of the pointer interpreted as a float.
Serial.println(*f, 3);

```

# Answer
> 1 votes
OK. So I never got the reinterpret\_cast, thing to work. Went with Majenko's solution. This code goes above Setup

```
// UNION, used to re-jig float
union ifloat {
uint8_t bytes[4];
float val;
};
// END UNION

```

And this is the modified code, with all the comments and bug print statements removed.

```
  // MtrV, MtrC, MtrW, MtrKWh
 //void AddressRegistry_0()
 result = sdm220_modbus.readInputRegisters(0x48, 2);
 if (result == sdm220_modbus.ku8MBSuccess)
 {
signed long MtrKWh1 = sdm220_modbus.getResponseBuffer(0x0);
word MtrKWh2 = sdm220_modbus.getResponseBuffer(0x1);
byte msb3 = MtrKWh1;
byte msb4 = MtrKWh1 >> 8;
byte msb1 = MtrKWh2;
byte msb2 = MtrKWh2 >> 8;
ifloat f;
f.bytes[3] = msb4;
f.bytes[2] = msb3;
f.bytes[1] = msb2;
f.bytes[0] = msb1;
Serial.println(f.val,3 );
  }
 else
 {
rs485DataReceived = false;
Serial.println("Fail sdm220_modbus.readInputRegisters(0x0, 1) ");
 }

```

And it is giving me the right numbers! Thanks for input to all who did, it helps some times to be show which door to walk through. Majenko, if you have time, and inclination, it would really help my understanding if you could describe your code. I am using it, but not sure how it works,or what most of it is doing. If you have the time.

---
Tags: float, modbus
---


title: RFID reader for unknown tag 125kHz

text:
# Question
Title: RFID reader for unknown tag 125kHz
I have an unknown RFID tag and tried to read its value. I bought two readers, RDM6300 125KHZ and RC522 13.56MHz. Each of the readers connected to Arduino works well with the purchased corresponding tags, but not with this tag. According to my information, the tag should be 125kHz tag, but RDM6300 foes not read it. The tag is simply not detected. I am sure that the tag works, I use it to open the door.

So my question is: Is there any other RFID reader for Arduino, which is different than the two that I have, and could work?

Thank you.

# Answer
> 2 votes
It could be something else (in the RFID low freq ~ 125khz) like a HID card. Also it could be an NFC (high freq 13.56Mhz) that its not compatible with the RC522.

Do you have access to a phone with NFC, to start ruling out what could it be?

---
Tags: rfid
---


title: RasPi GPIO into Arduino Digital Inputs

text:
# Question
Title: RasPi GPIO into Arduino Digital Inputs
So I'm making a Robot for my AP Comp Sci Class, and I'm borrowing an Arduino, as well as a Pi from the school. What I plan to do is have my Pi output from the normal GPIO pins and into the Arduino's digital inputs to "Tell" the Arduino what servos to run. The reason I'm doing it this way is so I don't have to screw with interfacing and all that crap. Is it safe for the Arduino? If so, what would I need for resistors and such?

# Answer
I think you are talking about writing to a GPIO and that being received by the Arduino if so the Pi is 3.3v and the Arduino is 5V so you will need a "Level Shifter" to boost the voltage to 5V so the Arduino can read the signals.

Other than that there is no problem with doing what you are doing, apart from its a lazy solution and you won't score very highly. I know you don't want to mess with protocols but if you can use I2C from the Pi then use that to send messages to the Arduino. Your protocol could be as simple as 1 byte saying which pin you want to light up, you'll get better marks.

Edit

To use I2C is really quite simple because someone has done almost all the work for you in Wire.h, so just include that file and then to send a byteits simply a case of:

```
Wire.beginTransmission(device_address);
Wire.write(data_byte);
Wire.endTransmission();

```

Reading data sheets for devices makes it look a lot harder with all the transmission sequence diagrams, but you don't need to worry about that its all done for you. The hardest bit to remember is the pull up resistors on the data lines.

Have a look at these links for more information:
> 0 votes

---
Tags: arduino-uno, pins, raspberrypi, digital-in
---


# Question
Title: What is the meaning of [type]* for arrays?
I've seen * used with arrays in some programs but not in others. The page on arrays doesn't mention it at all, but I often see it near functions when values are being passed.

Where would I find more information on this?

# Answer
> 1 votes
You are asking about Pointers - https://www.tutorialspoint.com/cprogramming/c\_pointers.htm.

---
Tags: programming
---


# Question
Title: Create an a message from two inputs[Programming Help]
I'm a bit new to this and I have the following function that I'm having trouble getting it to compile. The intent is to create a message to write out to a software serial port. Inputs are two int values of Function address and the data passed to the device while the output is a series of char characters

```
void Create_Message(int Address, int Data)
{
  byte S1Add = 1;
  byte FuCode = 2;
  byte AddHi = Address>>8;
  byte AddLo = Address;
  byte DatHi = Data>>8;
  byte DatLo = Data;
  byte AdDa[] = {AddHi,AddLo,DatHi,DatLo};
  unsigned int crc=CRC(AdDa,4);
  byte CrcHi = crc >> 8;
  byte CRCLo = crc & 0xFF;
 /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
 * to
 *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
 */
 unsigned char cmd[]={S1Add,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CRCLo};

  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
    RS485Serial.write(cmd[i]);   // Send string someplace
    Serial.write(cmd[i]); //echo back
  }
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

byte CRC(byte AdDa, int Size )
{
unsigned int crc16 = 0xFFFF;
int pos = 0;
int i = 0;

/*Write CRC*/
  for (pos = 0; pos < Size; pos++) {
    crc16 ^= AdDa[pos];          // XOR byte into least sig. byte of crc

    for (i = 8; i != 0; i--) {    // Loop over each bit
      if ((crc16 & 0x0001) != 0) {      // If the LSB is set
        crc16 >>= 1;                    // Shift right and XOR 0xA001
        crc16 ^= 0xA001;
      }
      else                            // Else LSB is not set
        crc16 >>= 1;                    // Just shift right
    }
  }
  /*Note, this number has low and high bytes swapped,
  so use it accordingly (or swap bytes)*/
  byte crc[]={crc16>>8,crc16};
  return crc;
}

```

Any help with optomizition would also be greatly appreciated :)

# Answer
> 2 votes
If you want help with optimisation then "Code Review" would be the better forum.

Its very difficult to optimise code that's hard to read. You have used an inconsistent formatting style (which might be because of the post but your failure to fix it indicates a lack of interest in the answers.

You passed all you function arguments by value, you should pass them by constant reference.

You are doing a number of implicit casts, because you have mismatched types.

You are sending a byte to serial.write, what happens if the value is outside of the printable range, it would be better to print this as a hex number.

I assume someone has already pointed out CRC should return a byte\*.

As for the algorithm, the code isn't readable enough to comment on that.

---
Tags: arduino-uno, serial, softwareserial, code-optimization, convert
---


# Question
Title: How to run my IDUINO Yun Shields stand-alone?
Experts,

How can I power and communicate with the IDUINO shield *stand-alone*? In other words, without any additional uC for it to plug into.

Failing in that, can a Nano (cheaper, smaller) be wired to give the Yun what it needs?

# Answer
> 1 votes
Yes, you can. All you need do is provide it with a regulated 5V supply on the 5V pin and it should power up and boot.

There's not a lot of IO on it though, so connecting to sensors and such would be hard, which is where the Arduino comes in handy. You communicate using the UART, so any microcontroller with a UART can be connected to it.

---
Tags: arduino-yun
---


# Question
Title: NRF24L01 integrated antenna exposed out of the box
I'm going to try my hand at making a few sensors that are to report status to a central server. To make them wireless, I'm going with nRF24L01 modules. I intend to enclose the sensors (Arduino Mini Pro + nRF24L01 + battery pack + a couple of other small components) in a simple PVC box.

A couple of the sensors would be about 10 meters away from the server, which, as far as specifications go, is about the maximum range of the radio modules. Especially the ones with the integrated antenna that I'm using. I thought that maybe I could squeeze some radio performance by exposing the antenna, so that the radio signal isn't attenuated by the PVC case. I could carve a small opening in the lid and have the nRF24L01 stick out, so that the electronics would be protected inside but the antenna strip would enjoy open air.

I would like some thoughts on this idea. I'm especially trying to understand if I just had the most novel idea ever, since I can't seem to find anything about it on the net. Has anyone ever tried this in real life? Does it make sense? Is it worth the trouble? I'm not looking for a theoretical analysis (I get that fine), only for actual experience. Thank you.

# Answer
> 2 votes
In general no, this would make little or no difference. PVC has very little effect on RF signals.

After all, the antenna on your typical WiFi router is inside a PVC tube and it doesn't suffer from it.

Instead you would do better constructing a *dipole antenna* from a couple of pieces of carefully measured wire.

For instance this instructable tells you how.

---
Tags: nrf24l01+
---