# Question
Title: Problem sending colors from an audio visualizer to Arduino
Sorry in advance for the length of my question; I want to provide proper context. I wrote an audio visualization program in Java that (in addition to making "pretty pictures" based off of the amplitudes of different frequencies being sent from the computer) sends a color to an Arduino Uno based off the sound it is "hearing."

I know the algorithm for generating this color is functional (in addition to sending that color to the Arduino, it also changes the color of an item on the DrawingCanvas). When the color is sent to the Arduino (as 3 bytes representing red, green, and blue), though, the physical LEDs don't respond correctly (they become a random color for a few seconds then switch to another random color for a bit – the behavior is hard to describe, but certainly not desired!).

I have been able to send colors to the Arduino using the same client program, but when the audio visualizer sends colors by the same method, this odd behavior occurs. My thought is that, because the audio visualizer sends color profiles dozens of times per second, the Arduino might be getting overloaded with data. Is that possible?

Here are the relevant pieces of code from the client, the audio visualizer, and the Arduino:

**Client:**

```
public class Client extends WindowController{
  //USB is a class I wrote that extends PApplet. Unless baud rates are the issue, I don't think we need to worry about this.
  static USB port = new USB("COM3", 9600);
  byte[] code = new byte[LENGTH];
  static byte killTerm = -100;
  private AudioVisualizer vis;

public void begin() {
  resize(1500,900);
  for (int k=0;k<LENGTH;k++){
    code[k]=killTerm;
  }
  vis = new AudioVisualizer(10,30,1200,300,canvas);
}

public void onMouseClick(Location point) {
  runVis = !runVis;
  if(runVis) {
    vis.start();
    code[0]=-22;
    sendCodeUSB(code);
  } else
    vis.stop();
}

public static void sendCodeUSB(byte[] code) {
  for (int k=0; k<code.length; k++) {
    port.writeProfile(code[k]);
  }
}

```

AudioVisualizer

```
public class AudioVisualizer implements Runnable {
  Thread thread = null;
  DrawingCanvas canvas;
  byte[] code = new byte[3];
  private int xPos;
  private int yPos;
  private int width;
  private int height;
  private int scale;
  private Location topLeft;
  private Location bottomRight;
  private FilledRect background;
  private int brightness=0;
  private boolean needOff = false;

  public AudioVisualizer(int x, int y, int w, int h, DrawingCanvas myCanvas) {
    canvas=myCanvas;
    xPos=x;
    yPos=y;
    topLeft = new Location (xPos,yPos);
    bottomRight = new Location (xPos+width, yPos+height);
    width=w;
    height=h;
    background = new FilledRect(topLeft,width,height,canvas);
    background.setColor(Color.BLACK);
    initiateMonitor();
    scale = height/30;
  }

  public void start() {
    if (thread == null) {
      thread = new Thread(this);
      thread.start();
    }
  }

  public void stop() {
    thread=null;
  }

  public void run() {
    while (thread != null) {
      try {
        Thread.sleep(40);
      } catch (InterruptedException e) {
      }
      graphAmps();
    }
    thread = null;
  }

  public void graphAmps() {
    //there is a whole bunch of stuff here that is unrelated that I removed.
    //basically, just know that graphAmps() calls avgColors()
    avgColors();
  }

  public void avgColors(){
    //there is stuff here that generates avgRed,avgGreen,and avgBlue (known to be working)
    Color c = new Color (avgRed,avgGreen,avgBlue);
    background.setColor(c);
    //so we don't spam the Arduino more than we need to
    if(avgRed>10 || avgGreen>10 || avgBlue>10) {
      sendArduinoColor(c);
      needOff = true;
    } else if (!(avgRed>10 || avgGreen>10 || avgBlue>10) && needOff) {
      sendArduinoColor(c);
    }
  }

  public void sendArduinoColor(Color c) {
    //takes the color and sets code = an array of 3 bytes with values from 0-100 (100 is the highest brightness I ever want the LEDs to be)
    //I am sure this is done correctly so I've left it out.
    constrainArduinoColor(c);
    //calls the static method from the client and passes in the byte array with the rgb values
    Client.sendCodeUSB(code);
  }
}

```

Arduino

```
#include <EEPROM.h>

int redPin = 11;
int bluePin = 10;
int greenPin = 9;
//declared here for debugging ease of access
int r;
int g;
int b;
//are we going through the Spectrum Cycle loop for the first time?
boolean sclFirstTime = true;
//temporary initialization
boolean waiting = true;
int index = 0;
const int LENGTH = 20;
byte profile[LENGTH];
byte avProfile[3];
byte killTerm = -100;
byte audioVisualizationCode = -22;

void setup() {
  //start the serial communication
  Serial.begin(9600);
  //initialize the profile to all -1 values
  clearProfile();
}

void loop() {
  //if there is nothing over serial and nothing is in the EPROM, we are waiting
  if (!eepromProfileAvailable() && Serial.available()==0){
    waiting = true;
  } else if (eepromProfileAvailable() && Serial.available()==0) {
    //if there is something in EEPROM and nothing over Serial, we aren't waiting and load the EEPROM profile
    waiting = false;
    loadEEPROMProfile();
    //load the EPROM color profile into the array
  } else if (Serial.available()>0) {
    //if something enters over Serial, we aren't waiting, clear the profile, and load the new profile with the serial info
    waiting = false;
    clearProfile();
    while (Serial.available()<LENGTH) {}
    // Wait until there are LENGTH number of Bytes waiting
    for(int n=0; n<LENGTH; n++) {
      profile[n] = Serial.read(); // place them in the profile.
    }
    Serial.flush();
    //clear out the serial to prep for next time
  }
  //if we have a profile (either from EEPROM or Serial), save it, check for special codes (if found, apply the effect),
  //and if there are no special codes, the profile is a static color profile, and set LEDS to that.
  if(!waiting) {
    saveEEPROMProfile(); //omitted but working
    if (profile[0]==101) {
      while (Serial.available()==0)
        spectrumCycle(); //omitted but working
    } else if (profile[0]==-22) {
      audioVis();
    } else {
      anodeSafteyOut(redPin,profile[0]);
      anodeSafteyOut(greenPin,profile[1]);
      anodeSafteyOut(bluePin,profile[2]);
    }
  }
}

//a bunch of preset color effects omitted
//we are using a common Anode LED, so low value is 255 instead of 0
void anodeSafteyOut(int pin, int c) {
  if(c>=0) {
    c = 255 - c;
    //as a safety measure because there are no resistors (yes, I know im breaking an intergalactic law by not using any), make sure we aren't writing something too bright
    if (c>=155) {
      analogWrite(pin,c);
    }
  }
}

//wait for 3 bytes to come in, assign them to the avProfile, set the colors to that, do it again
//THIS IS PROBABLY WHERE THE PROBLEM IS
void audioVis() {
  while (Serial.available()<3);
  for (int k=0;k<3;k++)
    avProfile[k]=Serial.read();
  anodeSafteyOut(redPin,avProfile[0]);
  anodeSafteyOut(greenPin,avProfile[1]);
  anodeSafteyOut(bluePin,avProfile[2]);
  audioVis();
}

```

So that's a lot, and I've left a lot out that I didn't think was necessary, though I'm happy to provide the full programs if needed. Thanks for your help!

Here is `constrainColorArduino`:

```
public void constrainArduinoColor(Color c) {
  int r = c.getRed();
  int b = c.getBlue();
  int g = c.getGreen();
  int r1 = (int)(r*0.4);
  int b1 = (int)(b*0.4);
  int g1 = (int)(g*0.4);
  byte r2=0;
  byte b2=0;
  byte g2=0;
  for (int k=0; k<r1; k++)
    r2++;
  for (int k=0; k<b1; k++)
    b2++;
  for (int k=0; k<g1; k++)
    g2++;
  System.out.println(r+" "+g+" "+b);
  System.out.println(r1+" "+g1+" "+b1);
  if (r2>100) r2=100;
  if (b2>100) b2=100;
  if (g2>100) g2=100;
  if (r2<0) r2=0;
  if (b2<0) b2=0;
  if (g2<0) g2=0;
  System.out.println(r2+" "+g2+" "+b2);
  code[0]=r2;
  code[1]=g2;
  code[2]=b2;
}

```

# Answer
> My thought is that, because the audio visualizer sends color profiles dozens of times per second, the Arduino might be getting overloaded with data. Is that possible?

Close, but the source of the problem is probably this line

```
  Serial.flush(); //clear out the serial to prep for next time

```

Because your audio visualizer keeps sending data, it's quite likely that by the time you get around to claiming a record, at least some part of another one (or more) has also arrived. When you discard that with flush(), you are probably most of the time *not* going to be discarding exactly a record's worth of bytes, but rather some arbitrary number more or less. This introduces a synchronization problem.

You've already had some advice on solving synchronization problems. There are a variety of workable methods, binary and otherwise. One simple one that works in a lot of situations is to encode bytes textually in hex and terminate the record with a newline. It does have just over a factor of two overhead, but it has the debug/test advantage of being human readable, and you can basically cover the overhead by switching from 9600 to 19200 baud.
> 1 votes

# Answer
Your idea that there's a synchronization issue seems plausible. Whenever any byte gets skipped, color assignments shift from RGB to GBR or BRG, etc.

While sending a start code before the color profile is a possible approach to fixing the problem, it may be that occasionally one of the RGB values matches the start code, which could result in temporary desynchronization.

For an alternative method that doesn't require a start code, consider encoding the data into four bytes. In the first byte, send the high two bits for RGB; in the second, the next two bits of each color; etc. Set the low two bits of each byte to 11, 10, 01, 00 for first, second, third, fourth.

That is, each byte you send would be encoded BBGGRRdd where the capital letters are appropriate bits from RGB brightness levels and dd indicates which pairs of bits are being sent.

Here's some (untested) code that implements the decode:

```
byte code = Serial.read();
byte shif = 2*(code & 3);
byte mask = ~(3<<shif);
code >>= 2;
for (byte i=0; i<3; ++i) {
  profile[i] = (profile[i] & mask) | ((code & 3)<<shif);
  code >>= 2;
}

```

The following shows a function `sendData3()` that encodes three bytes from an array of RGB data into four bytes to be sent to the Arduino. It also shows a convenience function `sendDataRGB()`. A call like `sendDataRGB(100, 0, 42);` puts three R, G, B values into a three-byte array and calls `sendData3()` to send it off. \[Substitute as appropriate in place of `Serial.write`\]

```
void sendData3 (byte *dataIn) { // dataIn[] has R,G,B levels
  byte code;
  byte mask=3;          // mask for low 2 bits of a byte
  for (int b=4; b; ) {
    --b;
    byte shif = 2*b;    // For moving bits to align with mask
    code = 0;
    for (int k=3; k; ) { // Loop to handle dIn[2], dIn[1], dIn[0]
      --k;
      code |= (dataIn[k]>>shif) & 3; // Pick off 2 color bits
      code <<= 2;            // Roll up
    }
    Serial.write (code | b);    // Send encoded bits
  }
}

void sendDataRGB (byte R, byte G, byte B) {
  byte dataEg[] = { R, G, B };
  sendData3(dataEg);
}

```
> 0 votes

---
Tags: serial, rgb-led, java
---


# Question
Title: Porting ATMega8 AVR based program to Intel Curie Processor
I'm currently trying to port a program called 'ArduinoUSBLinker' to work on my Arduino 101 (which has an Intel Curie CPU instead of the standard ATMega CPU).

The program is used to flash ESCs without the need of additional hardware. Arduino USB Linker

Unfortunately the code is mainly based on the ATMega's built in AVR timers, which uses several different predefined variables such as `TCCR0,TCCR1,TCTN2…`

These are not available (or are they?) in the Curie Module. Since the Arduino 101 has timer functionality, I was wondering if there is a way to translate those into the Curie Timer library.

# Answer
Those variables are the addresses of physical registers on the AVR that manipulate its timer/counters. Most other processors will have equivalent, but not likely identical, hardware. You'll need to port functionality, not the code.

You'll need to reverse-engineer (worst-case) the code you're trying to port (assuming you aren't intimately familiar with it, e.g., you designed it), develop a spec for it (at least in your head), and write to that spec for the Curie.

If the overall job is not (too heavily) processor-specific, you may be able to write it to be portable by writing the job-specific code in, e.g., in C, and call well-defined functions (in C or assembler) for the CPU-specific ones, that could easily be replicated on another processor.
> 0 votes

---
Tags: atmega328, avr
---


# Question
Title: How to upload one program into several Arduinos at once?
I am trying to upload a single program to a number of Arduinos one by one. But it is time consuming. So I would like to know if there is any way to upload the code at once to multiple Arduinos.

I have tried as follows:

3 Arduino with all the Rx, Reset, Vcc, Gnd line connected to each other. Only pin left is Tx line. So I just connect the Tx line of one arduino and program it and so on.

Is there any other way?

# Answer
Are you programming them for the first time or doing a update?

If is the first programming, I cant see another way.

Otherwise, If is a update and your Arduino have a Wifi module you could try something like an update on the air, where you put your new firmware in a server for example and all devices updates yourself automatically or by a command.

Google for Arduino OTA (on the air) you will get a lot of source code and examples of doing that.
> 2 votes

# Answer
Arduino uses a microcontroller from Atmel and uses a programming tool that is designed for development use and not for production programming.

What you are looking for are tools that are called "production programming tools". Atmel has a nice documentation which describes their different programming solutions: link.
> 1 votes

---
Tags: programming
---


title: Accepting strings and integers via UART

text:
# Question
Title: Accepting strings and integers via UART
My intention is to write a code that asks a user to enter the name and then the age. The code should then simply display the persons name and age. To do that, I have written a simple code. I find it difficult to get it to work.

```
char temp = 0;
char ArrayName [50];
int positionArray = 0;
int age =0;

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

void loop() {

    positionArray = 0;
    Serial.println ("What is your name?");

    do {

        while (Serial.available()==0);
        temp = Serial.read ();
        ArrayName [positionArray++] = temp;
    } while (temp != '\r');

    ArrayName [--positionArray] = '\0';

    Serial.print ("Your Name is: ");
    Serial.println (ArrayName);

    // clear the UART Buffer
    while (Serial.available()==1){
        temp = Serial.read();
    }

    Serial.println ("What is your age?");
    while (Serial.available()==0);
    temp = Serial.read ();
    age = temp;

    Serial.print ("You are ");
    Serial.print (age);
    Serial.println (" Years old.");

    while (Serial.available()==1){
        temp = Serial.read();
        delay (10);
    }

}

```

The error I receive is that the program already outputs age without me even typing it. Would it be possible to know the error? I use both NL and CR to send in characters to Arduino and the Arduino IDEs default UART terminal.

EDIT:

Listening to advice gotton from answers I got the code to work but in a very weird way. My new code works! but it proves the clearing of buffer **cannot be done** by just reading it. This is in contrast to Arduino documents. My new code is as follows.

```
char temp = 0;
char ArrayName [50];
int positionArray = 0;
int age =0;

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

void loop() {

    positionArray = 0;
    Serial.println ("What is your name?");

    do {

        while (Serial.available()==0);
        temp = Serial.read ();
        ArrayName [positionArray++] = temp;
    } while (temp != '\r');

    ArrayName [--positionArray] = '\0';

    Serial.print ("Your Name is: ");
    Serial.println (ArrayName);

    // clear the UART Buffer **WHY IS THIS CODE NOT EFFECTIVE?**
    while (Serial.available() >= 1){
        temp = Serial.read(); // performing dummy reads untill buffer empty.
    }

    temp = Serial.read();
    delay (1000);
    temp = Serial.read();
    temp = Serial.read();
    temp = Serial.read();

    Serial.println ("What is your age?");
    while (Serial.available()==0);
    temp = Serial.read ();
    temp = temp - 48;
    age = temp*10;
    delay (1000); // providing the user a day to enter next digit of age

    if (Serial.available()){
        temp =  Serial.read ();
        temp = temp - 48;
        age = (int) temp + age; //whatever that is added have to be of same type. Else they need to be cased to same type.
    }

    Serial.print ("You are ");
    Serial.print (age);
    Serial.println (" Years old.");

    while (Serial.available() >=1 ){
        temp = Serial.read();
        delay (10);
    }

}

```

# Answer
As we don't know what you are using as a terminal program we can't comment specifically on your choice of EOL characters.

It is likely you are receiving everything in ASCII code. That is, when you type the number 1 you are actually getting the ASCII equivalent (0x31) from your terminal.

This is fine when you are working with character strings. But when you want to work with numbers that are to be used in equations you need to 1) make sure that the user is only entering a number (check to make sure the values are from 0x30 to 0x39) and 2) subtract the ASCII value for '0' from the value you received from the terminal. That is, subtract 0x30.

It should now be obvious that you can only enter 1 digit at a time when using a terminal. That you will have to reconstruct the number as the user types each digit. For example the number 13 is a 1 and a 3 and you will have to multiply the 1 by 10 then add it to the 3.

Since this is such a common conversion, there are Arduino libraries that do this for you. Consider using ParseInt for this purpose.

Added later...

In the modified code, consider the possibility the terminal program is sending both a Carriage Return (aka: CR, 0x0D, \r) and Line Feed (aka: LF, 0x0A, \n) each time the Enter key is pressed. And that the code is only waiting for the CR.

The delays are necessary as UART communication, as most communications, takes a finite amount of time. And additional characters, if any, and even if autonomously sent, will take a finite amount of time to arrive.

Consider "looking" for the LF character after finding for the CR character and removing the added delays.
> 3 votes

---
Tags: c++, uart
---


# Question
Title: Problem with LCD keypad shield and Arduino Uno R3
I have a problem with powering my LCD Keypad Shield from a DC cable (4 AA batteries or 9V battery). Everything looks good, but the LCD screen doesn't display anything. When I used a USB cable, the screen works as it should.

What is the problem?

# Answer
> 1 votes
I do not have an answer... but it might be power consumption problem, ou voltage stability problem. I use a LCD shield with an RFID card reader (contactless card reader like you can find in the subway). When I plug the thing to a 9v battery the contrast is higher than when I connect it to an USB cable.

---
Tags: arduino-uno, power, lcd
---


# Question
Title: How to connect twenty different serial devices to an Arduino Mega?
I want to connect 20 serial devices to the same Arduino Mega.How to do this?I know that multiplexing is the way but how to do that

# Answer
> 2 votes
You can use the SoftwareSerial library and declare instances to communicate with your serial devices. I am not sure if you can declare 20 such different instances but if at all you do, use the function: listen() to switch between those serial devices. This, probably, is as close as it gets to multiplexing as you mentioned.

I've tried with 2 such SoftwareSerial instances for communicating with GPS module and GSM module and the listen() function worked flawlessly.

Cheers!

# Answer
> 1 votes
You say that they are working on RS232 - which is an electrical standard. You may mean that they use standard UART style asynchronous serial communications - perhaps at 0 to 5V electrical levels.

It depends on how fast you need to communicate, and how continuously you need to communicate. If you can choose when to communicate with each device, you may be able to use Soft Serial with multiple pins. Be aware that it cannot both transmit and receive at the same time (one or the other), and it can only communicate with one port at a time. So it might work for you if you can communicate with one device for a while, then ignore it while you check with other devices, one at a time.

Otherwise maybe not. For example, if you need to receive from many devices at times of their choosing so you need an always-on hardware UART for each device. There are 4 hardware UARTs in the MEGA, so 4 would be your limit.

There are things like external UART peripherals, but managing that would likely be very hard for you.

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


# Question
Title: Is it possible to run 2 functions, that communicate with 2 different serial devices, in parallel using FreeRtos library?
This might seem like a very broad question but that's what i want it to be for multiple ways of implementation.

I've an Arduino UNO communicating with 2 Serial devices interfaced using SoftwareSerial flawlessly. I've used \[SS\_Object\].listen() function to switch between the two. Right now, the entire code works sequentially meaning that, once it's work with the 1st Serial device is done, only then it will switch to the 2nd Serial device and work with it. Can i communicate with the 2 in parallel (Multitasking) using FreeRtos? I've heard that the scheduler switches between tasks when it encounters a delay. So may be a small useless delay is required, only for the scheduler, to switch between the two. May be! or May be things will be better if i use more advanced Arduino like Mega or Due.

Thanks for taking your time to read this. Please answer the question the way you've understood it as i am sure different people with different experiences will interpret this differently.

Thanks in advance!

# Answer
> 2 votes
It is unlikely that FreeRTOS will allow you to do that. SoftwareSerial uses busy loops with interrupts disabled, which means it cannot be interrupted or preempted by the RTOS (or by anything for that matter).

If you want two serial connections in parallel, at least one of them should be done in hardware.

---
Tags: arduino-uno, serial, arduino-mega, arduino-due, softwareserial
---


# Question
Title: CC3000 gets wrong address when connecting to wireless AP
I tried using both the SparkFun and Adafruit CC3000 libraries first with what I actually wanted as a program, but when that didn't work, the examples for those libraries, and I always seem to get the same problem.

The CC3000 will connect to my AP, which uses a private address in the range `172.24.1.1/24`, and somehow it will end up with the address `192.168.1.64`.

I know that it is connecting, since iw event lists the device MAC address as it connects.

The only changes I have made to the source code at this point are the ssid and password, and changing the interrupt and vbat pins to match the configuration of the tinyduino cc3000 board.

The device has firmware 1.34. Here is the code.

The specific output I get from the arduino is as follows (Note I commented out the disconnect at the bottom):

```
Connected at 115200

---------------------------------
SparkFun CC3000 - Connection Test
---------------------------------
CC3000 initialization complete
Connecting to: my_wifi_ap
Connected!

CC3000 MAC Address: 70:FF:76:04:B9:5B
IP Address: 192.168.1.62
Subnet Mask: 255.255.255.0
Default Gateway: 192.168.1.254
DHCP Server: 0.0.0.0
DNS Server: 192.168.1.254
SSID: my_wifi_ap

Finished connection test

```

running `iw event -f` on my AP before running a connection test gives me the following output:

```
wlan0: new station 70:ff:76:04:b9:5b

```

When another device, like my phone, connects to this AP, we get `172.24.1.xx`, where `xx` is whatever number between `50` and `150` that DHCP assigns us.

**Edit:** Also, if I comment out the disconnect at the end of the test, I can see the device is sending keepalives every three or four seconds using:

```
iw dev wlan0 station get 70:ff:76:04:b9:5b  //(inactive time never exceeds 4000ms).

```

I can't `ping 192.168.1.64` because that network is obviously unreachable, but trying to `ping 172.24.1.64` gives me a exception:

```
icmp open socket: Operation not permitted

```

Output from Adafruit Example:

```
RX Buffer : 131 bytes
TX Buffer : 131 bytes
Free RAM: 1221

Initialising the CC3000 ...
Firmware V. : 1.32
MAC Address : 0x70 0xFF 0x76 0x04 0xB9 0x5B
Started AP/SSID scan

Networks found: 20
================================================

...

SSID Name    : my_wifi_ap
RSSI         : 83
Security Mode: 3

SSID Name    : my_other_wifi_ap
RSSI         : 67
Security Mode: 3

...

================================================

Deleting old connection profiles

Attempting to connect to my_wifi_ap
Started AP/SSID scan

Connecting to my_wifi_ap...Waiting to connect...Connected!
Request DHCP

IP Addr: 192.168.1.62
Netmask: 255.255.255.0
Gateway: 192.168.1.254

```

The actual device being connected to is a Raspberry Pi AP, which was set up with DNSMASQ and hostapd. The configuration works, and has been proven to work with other embedded networking devices.

# Answer
I realized that I was using firmware v 1.34 on the board, which is what it was configured with when I got it, and decided I would try to downgrade it to one of the fir;ware sets supplied by adafruit to see if that would work.

The firmware modifying program didn't actually compile on the desktop version of the arduino ide, so I decided to use codebender instead.

I'm not sure whether or not I should be disappointed or relieved, but downgrading the firmware actually made it work. I used the file titled driverpath\_1\_11, which I believe the libraries refer to as firmware version 0x113 or 0x118, which identifies itself as firmware version 1.24, which somehow actually worked.

The solution is here: https://codebender.cc/sketch:318229

The pins have been changed to correspond with the fixed pings used by the tinyduino.
> 1 votes

# Answer
Welcome to the wonderful world of Adafruit software. Some genius decided that the CC3000 should save the first address it is ever given to nonvolatile storage, and use that ever since no matter what DHCP may subsequently tell it. Check the library source.
> 0 votes

---
Tags: wifi, adafruit
---


# Question
Title: Arduino original motor shield can not supply enough torque to the motor?
I am using original Arduino motor shield L298P with Arduino uno.

I disassembled an electric screw driver which came out with a 4.8 v battery pack and a 4.8v specified DC motor.

I connected battery pack to the Vin and Ground pins of the motor shield, and connected the DC motor to A channel of the shield.

The thing is when I run a test code with PWM 255, the torque of the motor is way too low compared to connecting the motor directly to the battery pack. I also changed the batteries to a common 1.2v rechargeable 4 batteries connected in parallel. The result is the same.

What might be going wrong?

I also paste the code I am using below. Thanks in advance.

```
const int motorPin = 3;
int Speed;
int flag;
void setup()
{
pinMode(motorPin, OUTPUT); //Set pin 3 as an OUTPUT
Serial.begin(9600); //Init serial communication
//Print a message:
Serial.println("Give a number from 50 to 255."); //Why minimun value 50?     Because with values below 50 the motor doesn't spin ;)
Serial.println(""); //Blank line
}

void loop()
{
//Check if incoming data is available:
if (Serial.available() > 0)
{
  // If it is, we'll use parseInt() to pull out only numbers:
  Speed = Serial.parseInt();
  flag=0;
}

//Valid range is from 50 to 255
if (Speed>=50 && Speed<=255){
    //Send PWM value with analogWrite to Arduino pin 3 and print a message to serial monitor
    analogWrite(motorPin, Speed);
    //Print message only once
    if (flag==0){
        //Print PWM value
        Serial.print("Motor spinning with ");
        Serial.print(Speed);
        Serial.println(" PWM");
        flag=1;
    }
}

delay(1000);
}

```

# Answer
According to the motor shield page:

> To avoid possible damage to the Arduino board on which the shield is mounted, we reccomend using an external power supply that provides a voltage between 7 and 12V. If your motor require more than 9V we recommend that you separate the power lines of the shield and the Arduino board on which the shield is mounted. This is possible by cutting the "Vin Connect" jumper placed on the back side of the shield. The absolute limit for the Vin at the screw terminals is 18V.

According to you:

> I disassembled an electric screw driver which came out with a 4.8 v battery pack and a 4.8v specified DC motor.
>
> I connected battery pack to the Vin and Ground pins of the motor shield, and connected the DC motor to A channel of the shield.

That's a lot less than 7V.

---

Also, from the motor shield page:

> Max current 2A per channel or 4A max (with external power supply)

How much current does your screwdriver use?
> 2 votes

# Answer
From the Arduino playground:

Arduino: What Adapter?

by djmatic

Ever since the dawn of Arduino, one question has been asked over and over again: "what kind of DC adapter can I use to power my Arduino?"

The short answer is: 9 to 12V DC, 250mA or more, 2.1mm plug, centre pin positive.

The long answer is that an off-the shelf Arduino adapter:

must be a DC adapter (i.e. it has to put out DC, not AC); should be between 9V and 12V DC (see note below); must be rated for a minimum of 250mA current output, although you will likely want something more like 500mA or 1A output, as it gives you the current necessary to power a servo or twenty LEDs if you want to. must have a 2.1mm power plug on the Arduino end, and the plug must be "centre positive", that is, the middle pin of the plug has to be the + connection. These important details are often contained right on the adapter.

Current rating: Since you'll probably be connecting other things to the Arduino (LEDs, LCDs, servos) you should get an adapter that can supply at least 500mA, or even 1000 mA (1 ampère). That way you can be sure you have enough juice to make each component of the circuit function reliably.

One final note. The Arduino's on-board regulator can actually handle up to 20V or more, so you can actually use an adapter that puts out 20V DC. The reasons you don't want to do that are twofold: you'll lose most of that voltage in heat, which is terribly inefficient. Secondly, the nice 9V pin on the Arduino board will actually be putting out 20V or so, which could lead to potential disaster when you connect something expensive to what you thought was the 9V pin. Our advice is to stick with the 9V or 12V DC adapter.

Electronicalifragilistic: I use a power supply from an old HP laptop that I scrapped. The plug is center positive and puts out 12V. Fits perfectly into Arduino connector. Packs a Wallop - most laptops draw 2-2.5 amps. That ought to run your screwdriver.
> 0 votes

---
Tags: arduino-motor-shield
---


title: rf24 change order of data

text:
# Question
Title: rf24 change order of data
I'm using two Arduinos with the rf24 modules.

I want to control a process with those, but for now I'm just checking the connection.

This is the code of the master:

```
#include  <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
unsigned char msg[4];
unsigned char serial_msg[1];

String mensaje = "ii";

int CE = 9;
int CSN = 10;

RF24 radio(9,10);

//const uint64_t pipe = 0xE8E8F0F0E1LL;
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

bool done;
int incomingByte = 0;

String stringOne  = "";

void setup(void){
    Serial.begin(9600);
    radio.begin();
    radio.setRetries(15,15);
    radio.openWritingPipe(pipes[1]);
}

void loop() {

    radio.stopListening();

    if (Serial.available() == 3) {

        while(Serial.available() > 0)
        {
            incomingByte= Serial.read();

            stringOne = String(stringOne + String((char)incomingByte));

        }
        Serial.println(mensaje);

        incomingByte = Serial.read();
        serial_msg[0] = incomingByte;

        radio.write(stringOne.c_str() ,2);

    }

    stringOne  = "";

    radio.startListening();    // Volvemos a la escucha para recibir mas paquetes
    delay(10); // necesario para activar el modo de esucha

    if (radio.available())
    done = false;
    {
        while (!done)
        {
            if (sizeof(msg)==4)
            {
                done = radio.read(msg,sizeof(msg) );
                Serial.print("Estado: ");
                Serial.println(msg[0]);
                Serial.print("Voltaje: ");
                Serial.print(msg[1]);
                Serial.print(msg[2]);
                Serial.println(msg[3]);
            }

        }

    }
    mensaje = "";
}

```

What t does is read data for the serial monitor, convert it to a string and them send the string.

The code of the receiver is this:

```
#include  <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

int CE = 6;
int CSN = 7;
RF24 radio(CE,CSN);  /// ()
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

bool done = false;

int voltaje = 141;
String string_vol= "789";
enum states {
    ESPERA,
    ENCENDIDO,
    PAUSA
};
enum states state = ESPERA;

unsigned char msg[2];
char incomingByte = '_';
unsigned long previousMillis = 0;
unsigned long currentMillis = 0;
unsigned long interval = 1000;

void setup() {

    Serial.begin(9600);
    radio.begin();
    radio.startListening();
    radio.openWritingPipe(pipes[1]);
    radio.openReadingPipe(1,pipes[0]);

}

void loop() {

    string_vol= "789";
    currentMillis = millis();
    if ((currentMillis-previousMillis)>interval)
    {
        previousMillis = currentMillis;
        msg[0] = char(state);
        radio.stopListening(); // Dejamos d escuchar para poder hablar
        string_vol = String(String((char)state)  + string_vol );
        radio.write(string_vol.c_str() ,4);
        radio.startListening();    // Volvemos a la escucha para recibir mas paquetes
        delay(10);
    }
    if (radio.available())
    done = false;
    {
        while (!done)
        {
            done = radio.read(msg,sizeof(msg));
        }
    }

    switch(state) {
    case ESPERA:

        if (msg[0] == 'i')
        {
            state =  ENCENDIDO;
        }

        break;
    case ENCENDIDO:

        currentMillis = millis();

        if (msg[0]=='r')

        {
            state =  ESPERA;
        }
        else if  (msg[0]=='d')
        {
            state =  PAUSA;
        }
        break;
    case PAUSA:
        if (msg[0]=='r')
        {
            state =  ESPERA;
        }
        else if  (msg[0]=='c')
        {
            state =  ENCENDIDO;
        }
        break;
    }
}

```

This one acts as a state machine, and sends a string in this case:

```
string_vol= "789";

```

plus the actual state of the Arduino:

```
string_vol = String(String((char)state)  + string_vol );

```

When this Arduino is in state one:

In the other side I got:

Estado: 1
Voltaje: 555657

When is in state II I got:

Estado: 2
Voltaje: 555657

But if it's in state zero, which is the initial one, I got:

Estado: 55
Voltaje: 56570

It change the position of the state for one of the chars of the string

EDIT.

The issue is when sending the '0' of the first state, I changed enum to:

```
enum states {
    foo, //  revisar, solo usada para comenzar en 1
    ESPERA,
    ENCENDIDO,
    PAUSA
};

```

Now it works fine because the first state is '1', still don't now why it doesn't work if I use the '0'

# Answer
> 2 votes
The problem you run into is that you are trying to insert the binary value of 0 into an Arduino `String`. That may actually be possible, but the way you attempt to to do it utilizes some C-style mechanisms, specifically representing a string as a pointer to some characters terminated by a null byte - which is to say 0.

Your code:

```
string_vol = String(String((char)state)  + string_vol );

```

Invokes this String constructor from WString.cpp

```
String::String(char c)
{
    init();
    char buf[2];
    buf[0] = c;
    buf[1] = 0;
    *this = buf;
}

```

Which tries to turn the input `char` into a C-style string containing the input and then its own terminating null. But in the case where state=0, that ends up being a buffer of two 0's. A C-style string is terminated by the first 0, so when interpreted that way, the buffer is considered empty. The last line of this constructor uses the buffer to invoke yet another constructor, that treats the input as a C-style null terminated string:

```
String::String(const char *cstr)
{
    init();
    if (cstr) copy(cstr, strlen(cstr));
}

```

Since strlen() finds the input here in the state=0 case to be empty, it produces an empty String. You then append some other data, and that is all that you see, with no state included in the packet.

---

As this demonstrates, it is necessary to to be careful mixing binary and textual representations.

One thing you might do would be to add an offset to the state before transmitting, and subtract it out on the receiver. If you have 9 or fewer states, adding the character code of '0' (ie, 0x30) would transmit them as potentially printable digits. If you have more, you could add 'A' and transmit them as letters of the alphabet. In the end it doesn't really matter what you add, as long as any value you intend to transport can be represented in all the intermediate data formats it passes through.

Of course the nRF24L01 parts will transmit binary data just fine; if you want to go ahead and move binary data through them you can, you just have to avoid using anything with C-style `char *` mechanics that is going to see `0` in the data as a terminator, not a character.

---
Tags: serial, c++, nrf24l01+, rf
---


title: Router with arduino

text:
# Question
Title: Router with arduino
Is it possible to send and receive data from a normal router using arduino? I need to create a little device that uses a router to communicate with a remote. It's a close circuit.

# Answer
> 1 votes
If you have a network interface (wired or wireless), yes, of course it is.

Look into the ESP8266, and ESP-12E-based boards such as the Adafruit Huzzah; they can be programmed in an Arduino environment, and have built-in wifi.

# Answer
> -1 votes
Yes ,You CAN. Use ESP 8266-07.Its a very good Wi-Fi module.You juts need to install ESP8266 board file in Arduno IDE. For board file installation and some basic tutorial , just Click here

Its helpful I think.

---
Tags: communication, wireless
---


# Question
Title: I just bought a TFT screen is it still possible to use the serial port 1 and 0?
so I have a question regarding the TFT touch screen... I would like to use the serial ports 1 and 0 (on my UNO) to transmit data to my mega... however it take up those ports. on the back of it, it shows what each prong should occupy. However, nothing is noted to be required for those ports. is it possible to clip those prongs off and still have the screen be usable or are they important to keep?

# Answer
> 1 votes
Yes, you can use those pins. Just because there are physical pins on the shield doesn't mean they are actually used. If nothing is written next to them then yes you can use them.

Be warned though that those pins are used for communication with your PC - and that includes uploading sketches - so you may experience problems doing things like that while your Mega is connected to those pins.

---
Tags: serial, tft
---


title: LED Pin 13 Input or Output?

text:
# Question
Title: LED Pin 13 Input or Output?
It is not clear to me whether Pin 13, corresponding to the LED, should be driven by an external voltage or not.

From the documentation,

> LED: 13. There is a built-in LED driven by digital pin 13. When the pin is HIGH value, the LED is on, when the pin is LOW, it's off.

However, in the "Blink" example code I am running, the Pin 13 appears to be driven by the ATmega328:

```
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(2000);              // wait for a second
}

```

If I now attach a voltage source to Pin 13, will there be contention issues?

# Answer
Like any other I/O pin, there should be no problem driving this pin (and thus the builtin LED) from an external source, as long as you make sure it is in `INPUT` mode. If the pin is set to `OUTPUT` you will likely damage the Arduino.

**Warning**: If you have the Blink example already loaded in the Arduino, the pin is in output mode. Be sure to upload another program, that does not set pin 13 to output, **before** connecting anything that could drive pin 13.
> 1 votes

---
Tags: arduino-uno, led
---


# Question
Title: Arduino IDE/Visual Micro - Undefined reference to constructor
I am using Visual Studio Community 2015 with the newest version of the Visual Micro Arduino Plugin, however I also tried compiling my code in the Arduino IDE. When compiling my code, there is the following error:

```
Compiling debug version of 'Autonomous_Car' for 'Arduino/Genuino Uno'
Autonomous_Car.cpp.o:In function `setup
Autonomous_Car.ino:undefined reference to `List<UpdateAble>  List()
Autonomous_Car.ino:undefined reference to `List<UpdateAble>  ~List()
collect2.exe*:error: ld returned 1 exit status
Error creating .elf

```

**Some info**

* Adding `#include "List.cpp"` fixes the error, however this does not seem like valid C++.
* The files do not lay in any sub-directory
* In my Project Explorer both `List.h` and `List.cpp` are added to the project.
* I also removed both files from the project, deleted them and added them again
* I deleted the ´%AppData%\Local\Arduino15´ directory
* I am fairly new to C++ and Arduino, there might be something obvious, what I just can't find

**Autonomous\_Car.ino**

```
#include "List.h"
#include "UpdateAble.h"

void setup()
{
    List<UpdateAble>* myList = new List<UpdateAble>();
    myList->GetCount();

    delete myList;
}

```

**List.h**

```
#ifndef _LIST_h
#define _LIST_h

#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
#include "WProgram.h"
#endif

template <class T>
class List {
public:
    void Add(T &item);
    bool Contains(T &item);
    bool Remove(T &item);
    void Clear();
    int IndexOf(T &item);
    T* GetItem(int index);

    inline int GetCount() { return count; };
    inline int GetCapacity() { return capacity; };

    List();
    ~List();
private:
    void EnsureCapacity(int capacity);

    int count;
    int capacity;
    T** items;
};

#endif

```

**List.cpp**

```
#include "List.h"

// Constructor
template <class T>
List<T>::List() {
    List::capacity = 4;
    List::count = 0;

    List::items = new T*[List::capacity];
}

// Cleanup
template <class T>
List<T>::~List() {
    delete[] List::items;
}

template <class T>
void List<T>::EnsureCapacity(int capacity) {
    if (List::capacity < capacity) {
        // Kapazität verdoppeln
        List::capacity = List::capacity * 2;

        // Speicher für neues array reservieren
        T** newArray = new T*[List::capacity];

        // Array kopieren
        for (unsigned int i = 0; i < List::count; i++) {
            newArray[i] = List::items[i];
        }

        // Speicher von alten array freigeben und neues array zuweisen
        delete[] List::items;
        List::items = newArray;
    }
}

// Adds a new item to the list
template <class T>
void List<T>::Add(T &item) {
    List::EnsureCapacity(count + 1);

    List::items[count] = item;
    List::count++;
}

// Gets whether the list contains an item or not
template <class T>
bool List<T>::Contains(T &item) {
    return List::IndexOf(item) != -1;
}

template <class T>
bool List<T>::Remove(T &item) {
    int index = List::IndexOf(item);

    // If the item does not exist, we cannot remove it
    if (index == -1) return false;

    // Move every item behind our item one further
    for (int i = index + 1; i < List::count; i++) {
        List::items[i - 1] = List::items[i];
    }

    List::count--;
}

// Release the heap
template <class T>
void List<T>::Clear() {
    for (int i = 0; i < List::count; i++) {
        delete List::items[i];
    }

    delete[] List::items;
}

// Gets an index of an item, -1 if not found
template <class T>
int List<T>::IndexOf(T &item) {
    for (int i = 0; i < List::count; i++) {
        if (List::items[i] == item) {
            return i;
        }
    }

    return -1;
}

template <class T>
T* List<T>::GetItem(int index) {
    if (index < List::count && index >= 0) {
        return List::items[index];
    }

    return 0;
}

```

I'd be very glad, if we can find the solution.

# Answer
> 1 votes
You're using a *template class*. A *template class* is a special corner case that breaks the "code in .cpp and definitions in .h files" rule.

Because it's a template it can't be pre-compiled - it needs to be specially compiled each time it is used, so that it can get the right values compiled in to the template place-holders, which are provided by the CU that has the template class included with it.

Because of that it is one of the rare cases where the code has to be in the header file.

For a full example you can take a look at my Average library which is a fully templated class.

---
Tags: c++, arduino-ide, visualstudio
---


# Question
Title: Two-wire communication (I2C) between Arduino Micros
I am attempting to communicate data via I2C between two Arduino Micros, but can't seem to get the "slave" device to detect a Wire.onRecieve() event.

Per the specification on this site \[http://www.takktile.com/tutorial:arduino\] (and verified against Arduino's own site) I am using pins 2 and 3 as SDA and SCL for I2C. I have pin2 of Arduino 1 (ARD1) connected to pin2 of Arduino 2 (ARD2), and pin3 of ARD1 connected to pin3 of ARD2.

ARD2 acts as slave, ARD1 acts as master.

I am reading in a text file from SD on ARD1. On ARD1, you then press a button to initiate transfer. ARD1 lights a red LED to indicate the transfer is underway. When I initiate the transfer, it remains solid (indicating it never gets past endTransmission to where the LED is supposed to be turned off).

Here is the code for ARD1:

```
// include the SD library:
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
// personal debugging routines
#include "debug.h"
/*
 *
 *  THIS IS THE SLAVE RECEIVING MODULE
 *  IT WILL WRITE DATA TO AN SD CARD
 */

// GLOBAL VARIABLES
const int chipSelect = 10; // 10 because this is an Adafruit SD module.
File data;
int buttonA; // the button
char c;

void sd_readstart() {
  unsigned char i = 0;
  // Open serial communications and wait for port to open:
  Serial.print("\nInitializing SD card...");
  if (!SD.begin(10)) {
    Serial.println("Card initialization failed.");
    errorblink();
    return;
  }
  Serial.println("Initialization successful.");

}

void setup() {
  pinMode(11, OUTPUT); // setup for blink
  pinMode(12, OUTPUT); // setup for blink
  pinMode(10, INPUT); // button
  Wire.begin(8); // intitalize this device as a slave on addr .
  Wire.onReceive(receiveEvent); // when data is recieved, run recieveEvent(int).
  Serial.begin(9600);
  sd_readstart();
}

void loop(void) {
  // short blink to confirm this is going down correctly
  buttonA = digitalRead(10);
  if (buttonA == HIGH) {
    // button open
    blink(100,1000);
  } else {
    // button pressed

  }

}

void receiveEvent(int howMany) {
  data = SD.open("testoutput.txt");
  digitalWrite(12,HIGH);
  while (Wire.available() > 0) { // loop through all but the last
    c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
    data.print(c);
  }
  data.close();
  digitalWrite(12,LOW);
}

```

Here is the code for ARD2:

```
// include the SD library:
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
// Software Serial library:
#include <SoftwareSerial.h>
// personal debugging routines
#include "debug.h"
/*
 *
 *  THIS IS THE SLAVE RECEIVING MODULE
 *  IT WILL WRITE DATA TO AN SD CARD
 */

// GLOBAL VARIABLES
const int chipSelect = 10; // 10 because this is an Adafruit SD module.
File data;
int buttonA; // the button
char c;

void sd_readstart() {
  unsigned char i = 0;
  // Open serial communications and wait for port to open:
  Serial.print("\nInitializing SD card...");
  if (!SD.begin(10)) {
    Serial.println("Card initialization failed.");
    errorblink();
    return;
  }
  Serial.println("Initialization successful.");

}

void setup() {
  pinMode(11, OUTPUT); // setup for blink
  pinMode(12, OUTPUT); // setup for blink
  pinMode(10, INPUT); // button
  Wire.begin(8); // intitalize this device as a slave on addr 8.
  Wire.onReceive(receiveEvent); // when data is recieved, run recieveEvent(int).
  Serial.begin(9600);
  sd_readstart();
}

void loop(void) {
  // short blink to confirm this is going down correctly
  buttonA = digitalRead(10);
  if (buttonA == HIGH) {
    // button open
    blink(100,1000);
  } else {
    // button pressed

  }

}

void receiveEvent(int howMany) {
  data = SD.open("testoutput.txt");
  digitalWrite(12,HIGH);
  while (Wire.available() > 0) { // loop through all but the last
    c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
    data.print(c);
  }
  data.close();
  digitalWrite(12,LOW);
}

```

For completeness, here is my debug.h:

```
void blink(int h, int l) {
    digitalWrite(11, HIGH);
    delay(h);
    digitalWrite(11, LOW);
    delay(l);
}

void errorblink() {
  unsigned char counter = 0;
  while (counter < 4 ) {
    digitalWrite(12, HIGH);
    delay(50);
    digitalWrite(12, LOW);
    delay(50);
    digitalWrite(12, HIGH);
    delay(50);
    digitalWrite(12, LOW);
    delay(50);
    digitalWrite(12, HIGH);
    delay(50);
    digitalWrite(12, LOW);
    delay(1000);
    counter++;
  }
}

void goodblink() {
  unsigned char counter = 0;
  while (counter < 4 ) {
    digitalWrite(11, HIGH);
    delay(50);
    digitalWrite(11, LOW);
    delay(50);
    digitalWrite(11, HIGH);
    delay(50);
    digitalWrite(11, LOW);
    delay(50);
    digitalWrite(11, HIGH);
    delay(50);
    digitalWrite(11, LOW);
    delay(1000);
    counter++;
  }
}

```

I did attempt to do the minimum working example of Wire from the examples in the Arduino IDE. That didn't work either, which is to say that I didn't see any text in the serial monitor on ARD2 when I uploaded the slave reciever sketch that comes with the IDE (with send master running on ARD1) which makes me wonder if I'm doing something horribly, fundamentally wrong in hardware rather than just in software.

I hope it's not inappropriate to post up the more advanced example in order to get feedback on the larger picture of what I'm trying to accomplish -- moving a text file from the SD card on one arduino to the SD card attached to another.

# Answer
> 3 votes
I2c is an open collector setup. The pins go low, or open/input/hi-z, and let the line/bus free. Without a pull up on each line to VCC, the line never goes high. Pull up resistors are required. 4.7k typical.

Op's crudely drawn diagram is the correct way for a 5V I2C bus:

Keep in mind both arduinos/power supplies must have their grounds connected, as a reference ground voltage.

# Answer
> 1 votes
The I2C protocol and hardware don't care how much data is transferred.

The time you have for the transfer, or the transfer rate is much more important; you might get bored waiting, but it won't.

You might get over 100k bits/second transfer (allowing time to write to the SD card) if that's enough then it's fine.

The significantly faster option, using Arduino's, is SPI to SPI, and you are likely using SPI for the SD card, so I2C is a reasonable alternative, and makes your hardware and software simpler.

The only faster interface on the Arduino, excluding SPI, is the UART. That might be a bit tricky to use while you are developing, testing and debugging your software.

---
Tags: i2c
---


# Question
Title: Using the Logging library, sometimes doesn't exit setup()
This has been a hard problem to diagnose, so I hope I'm giving enough info here. I'm trying to write a program for the Arduino (a lighting controller) using a bit of OO. There are several classes in my library, and some extend others. I'm a long-time programmer (mostly Java) but this is my first big Arduino project.

I'm using the Logging library at various points in the main program, as well as the objects, and that's where it get complicated. Depending on where I put calls to the logging library, or even Serial.print(), it either all works, or what gets sent to the serial port is a bit garbled, and the board never enters loop() (I'm not sure if that means that it's crashing in setup() or not). This library hasn't been touched in 4 years and there are pending merge requests, so I don't think I'll get answers from the developer.

I have a sneaking suspicion that the root of the problem is that Logging.h ends with instantiating the logger ("Logging Log = Logging();") so multiple instances of the logger may be created and the serial port is being reset several times, possibly at different port speeds. I thought it was bad form to initialize object, or even have any running code, in a .h file. Is this a possibility, and do I have any options to fix this?

Are there any good alternatives for printing outputs at different debug levels?

I would hate to have to pass the logger instance in as a parameter to my classes, or have to write setLogger() methods for all my classes.

Thanks.

# Answer
> 0 votes
> Logging.h ends with instantiating the logger ("Logging Log = Logging();") so multiple instances of the logger may be created and the serial port is being reset several times, possibly at different port speeds.

I think you are mistaken, or have done something wrong with the library files. `Logging.cpp` ends with the instantiation, not `Logging.h`. `Logging.h` only has an `extern` reference to the instantiated object.

So some guesswork:

If you try and do anything with logging or serial access (or indeed anything more than just setting a few variables) within the constructors of your objects, and you instantiate those in the global scope, you won't have full access to the serial port - if any access at all. You can only use the serial port once `Serial.begin(...)` has been executed in setup, and global constructors are executed *before* `setup()` is run.

It is for this precise reason that 99% of Arduino libraries have a `.begin()` method which does all the work a constructor would normally do. The constructor is only used (if at all) for storing some default settings (pin numbers, etc) that are used later on. That way you have full control over what gets executed and when.

# Answer
> 1 votes
The constructor (called in a rather weird way) doesn't do anything, so I don't think that is the issue.

**Logging.h**:

```
    /*!
     * default Constructor
     */
    Logging(){} ;

```

**Logging.cpp**:

```
 Logging Log = Logging();

```

---

You should be calling `Log.init(whatever)` **once** in your code (as in the example). Are you doing that?

Please post a Minimal, Complete, and Verifiable example.

Without any posted code, we can only guess at what you are doing.

---

> I thought it was bad form to initialize object, or even have any running code, in a .h file. Is this a possibility, and do I have any options to fix this?

That is not done in the library you linked to.

---
Tags: serial, library, printf
---


# Question
Title: MIDI controlled analog RGB LED strip (code problem)
I have a an Arduino Uno doing PWM on an RGB analog LED strip ala the Adafruit guide: https://learn.adafruit.com/rgb-led-strips?view=all. I've written a sketch that accepts MIDI data over USB and uses it to control the LEDs.

```
#include <MIDI.h>
#include <midi_Defs.h>
#include <midi_Message.h>
#include <midi_Namespace.h>
#include <midi_Settings.h>

#include <MIDI.h>

MIDI_CREATE_DEFAULT_INSTANCE();

#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

byte commandByte;
byte noteByte;
byte velocityByte;

byte noteOn = 144;
byte noteOff = 128;

int colorGroup;
int pColor;
int sColor;

void setup()
{
    pinMode(REDPIN, OUTPUT);
    pinMode(GREENPIN, OUTPUT);
    pinMode(BLUEPIN, OUTPUT);
    MIDI.begin(1);
    Serial.begin(115200);
}

void checkMIDI(){
  do{
    if (Serial.available()){
      commandByte = Serial.read();//read first byte
      noteByte = Serial.read();//read next byte
      velocityByte = Serial.read();//read final byte
      }
    }
  while (Serial.available() > 2);//when at least three bytes available
}

void updateLights(){
  colorGroup = noteByte/42;
  pColor = noteByte%41*127/41;
  sColor = 127 - pColor;
  pColor = pColor*velocityByte/127;
  sColor = sColor*velocityByte/127;
  if (commandByte == noteOn && velocityByte > 0){
    if (colorGroup == 1){
      analogWrite(REDPIN, pColor);
      analogWrite(GREENPIN, sColor);
      analogWrite(BLUEPIN, 0);
    }
    else if(colorGroup == 1){
      analogWrite(GREENPIN, pColor);
      analogWrite(BLUEPIN, sColor);
      analogWrite(REDPIN, 0);
    }
    else{
      analogWrite(BLUEPIN, pColor);
      analogWrite(REDPIN, sColor);
      analogWrite(GREENPIN, 0);
    }
  }
  else if(commandByte == noteOff || velocityByte == 0){
    analogWrite(REDPIN, 0);
    analogWrite(GREENPIN, 0);
    analogWrite(BLUEPIN, 0);
  }
}

void loop()
{
    checkMIDI();
    updateLights();
}

```

Currently this code will turn the lights on and off in accordance with noteOn and noteOff messages. However, the color doesn't seem responsive to the note value and the brightness doesn't seem responsive to the velocity value. I suspect that the problem has to do with my arithmetic combined with the data type (maybe a problem with the order of operations), but I haven't been successful in debugging this.

The idea behind the RGB control is that I take the possible note values (0–127) and map it onto three different combinations of colors: R+G, G+B, and B+R. That's three groups of 42 values: 0-41, 42-84, and 85-127. Then I rescale the 42 values onto 0-127 for the intensity values of the LEDs. Finally I scale the intensity of all the colors by the velocity value over its possible max value.

# Answer
> 1 votes
I suggest that you write separate test programs for MIDI input and LED control, before trying to combine them together. That is, write a sketch to report back on Serial what MIDI data was read, and a sketch to cycle the LEDs through obvious patterns.

For example, if you read 10,20,30 as the three MIDI bytes, output "Got 10,20,30" (or similar). If that appears to be working, then add your arithmetic and output the results of `colorGroup, pColor`, and `sColor` calculations.

Note, the comment after `do{ ...} while (Serial.available() > 2);` says `//when at least three bytes available`, which does not correctly represent what that `do` loop does. When one or more bytes are available, that loop immediately reads three bytes (getting a value of -1 for any not-available byte). To do the read only if three bytes are available, get rid of the `do{ ...} while` construct, and instead say `if (Serial.available() > 2) { <read 3 bytes> }`.

Note, use parentheses in expressions like `pColor*velocityByte/127`. IIRC the C spec allows evaluation of that as either `(pColor*velocityByte)/127` or as `pColor*(velocityByte/127)`. Since `velocityByte/127` can only evaluate to 0 or 1, the result of the latter form is either `pColor` or 0.

Note, your code shows `if (colorGroup == 1){` twice. Change 1 to some other number in the second instance.

To cycle the LEDs through obvious patterns, you could have three different sketches, one that gradually raises and lowers the PWM level on Red, one that does the same for Green, and another for Blue.

---
Tags: programming, rgb-led, midi
---


title: 80 Apple Homebuttons and a steppermotor

text:
# Question
Title: 80 Apple Homebuttons and a steppermotor
I am graduating in a month and I want to make an installation with 80 apple homebuttons which are connected to a stepper motor. The idea is that each button that is pressed, turns the stepper motor the same amount of degrees each time. Also, each button is connected to an LED which must stay on, even if the button is pressed again and the motor too must not react. Once all 80 buttons have been pressed, the installation should switch off after a minute or so.

I am not sure how to connect 80 inputs to the arduino. Does anyone have any idea?

# Answer
**Why Apple home buttons?**

Finding out how to get input/output from these things and wiring them in a reliable way may cost you some time (and quite some money). I don't see how they would have other features than regular buttons.

(You won't get the fingerprint-scanning thing working, I'm afraid.)

**Start small**

It'll be quite a project to do in one month (especially when you're new to Arduino).

If you start out with 80 buttons and stuff, it will probably end up in a mess, and you'll be unable to show your prof anything.

You should however, order the 80 push-buttons (I shouldn't order the Apple ones, if you don't already know how they work) and LED's. Since they might take some shipping time.

Get yourself a solder-less breadboard, maybe 3 buttons, some LED's and a stepper (if you don't have one already). Depending on your type of stepper, you may need something to drive it.

*Start project*

Use two buttons or so, if you press one, it would go clockwise, if you press the other, it would go counter clockwise.

Make sure you pull up or down the button inputs, to be sure that they are not floating when the button is not pressed.

Find a way to drive the steppers, you'll most likely use Arduino libraries for this.

Code will be something like:

```
if(digitalRead(button1))
  stepper.step(steps++);
if(digitalRead(button2))
  stepper.step(steps--);

```

**Scaling up - alternative**

You could use the 80 buttons for each angle of the stepper. But you could also use a keypad and LCD (or 3x 7segment display) to display a value typed in, and then send it to the motor.

**Scaling up**

In the case of the 80 buttons. You could use 10 outputs in combination with 8 inputs.

With each output, you can energize a row of buttons, and with each input you read the columns. This way you only need 18 pins to read all keys.

I'm not sure if you want to control all LED's at the same time, or individually.

Or use shift registers or I/O expanders (JayEye).
> 1 votes

# Answer
If you follow JayEye's approach (ie, use five MCP23017 units to connect 80 switches, and five more to connect 80 LEDs) the wiring and the software should be fairly simple. But dealing with all the wires will be a problem unless you use a custom printed circuit board to mount all the switches, LEDs, wiring traces, and connectors. If you have experience with and hands-on access to printed circuit manufacturing equipment, and fast access to the parts you need, that approach should be ok.

A worthwhile alternative is to scale the project back slightly – say to 64 switches and LEDs instead of 80 – and use two Arduino Mega2650's, one to connect to switches, and another to connect to LEDs. Or you could use one Mega to handle the first 32 switch-and-LED pairs, and another, identically-wired, to handle the other 32. The two Mega's could communicate by I²C or via RxD-TxD connections (Arduino Mega's have four hardware serials ports, IIRC). If you plan to wire stuff up with jumpers and breadboards, this probably would be among the simpler, faster, and cheaper approaches. The modularity of building two identical units (except that only one of them will have the stepper driver attached) improves reliability and ease of debugging. You could also use four or five identically-wired Uno or Nano boards.

Note, however, that you are likely to have serious reliability problems if you connect up 80 switches and 80 LEDs via breadboards and jumper wires. As Chris Stratton suggested, start small. For example, wire up a dozen or two dozen switches and LEDs on a single Mega. This will let you see how much of a mess the wiring will be, and whether the original scale is practical. It will also allow tracking down software bugs on a hardware system that is small enough to allow some confidence that the hardware is working. If you build an 80-unit system before debugging the software, you are likely to run into problems where hours or days go by while you try to sort out whether the problem is due to a software error, a wiring error, or some combination of both.

Note that use of Charlieplexed connections or matrix connections would let you get by with about 10-20% as many IO lines as the direct-connect methods listed above. However, unless you have used Charlieplexed or multiplexed LED displays and matrix-connected switches successfully in previous projects, and have experience with building and driving circuit boards, the likelihood of getting the project done on time is rather lower than for the other methods mentioned above.
> 2 votes

# Answer
I have no idea what an apple homebutton is, but the easiest way to add more GPIO pins is to use something like an MCP23017; it connects over I2C and gives you 16 GPIO pins. Use five of them and you have your solution.
> 1 votes

---
Tags: led, button, stepper
---


title: How to rewrite code in millis?

text:
# Question
Title: How to rewrite code in millis?
I am currently working on a project that makes a plateua move back and forth using a stepper motor. On this plateau I have attached LEDs that create patterns. However, the plateau should be moving whilst the pattern is changing. With my current code this is not happening. I know that I have to work with millis, but when I am completely lost on how to do it. Could someone help me?

Here is my code:

```
#include <AccelStepper.h>

AccelStepper stepper(1, 42, 38);

int i;
int microStep = 46;

int currentAnimation = 0;
int count = 0;
int button = 13;

int state = LOW;
int lastState = LOW;

//bytes for patterns
byte a = B11110000;
byte b = B00010000;
byte c = B01000000;
byte e = B10100000;

//--------------------------------------------------------------------------------------------------------------------------------

void setup()
{
  DDRH = B1111000; // set PORT 6-9 of arduino mega high
  DDRB = B11110000; // set PORT 10-13 high

  stepper.setMaxSpeed(900.0);
  stepper.setAcceleration(400.0);

  pinMode(button, INPUT);
  state = digitalRead(button);

  pinMode(microStep, OUTPUT);
  digitalWrite(microStep, HIGH);
}

//--------------------------------------------------------------------------------------------------------------------------------

void loop()
{
  //This should happen constantly
  stepper.runToNewPosition(2000);
  delay(500);
  stepper.runToNewPosition(0);

  // These are the patterns, that should be played whilst the stepper is running. The patterns chaneg when you push the button
  if ( state == HIGH & lastState == LOW )
  {
    currentAnimation++;
  }

  if (currentAnimation % 3 == 0)
  {
    same();

  }
  if (currentAnimation % 3 == 1)
  {
    left();
  }
  if (currentAnimation % 3 == 2) {
    faster();
  }

  lastState = state;
  state = digitalRead(button);
}

//--------------------------------------------------------------------------------------------------------------------------------
//PATTERNS
void same() {
  for (int k = 0; k < 10; k++) //plays 10 times
  {
    PORTH = a;
    PORTB = a;
    delay(100);
    PORTH = 0;
    PORTB = 0;
    delay(100);
  }
}

void left() {
  for (int z = 0; z < 10; z++)
  {
    PORTH = e;
    PORTB = e;
    delay(100);
    PORTH = ~e;
    PORTB = ~e;
    delay(100);
  }

}

void faster() {
  for (int z = 0; z < 256; z++)
  {
    PORTH = z;
    PORTB = z;
    delay(100);
  }
  PORTH = 0;
  PORTB = 0;
}

```

# Answer
### The basic pattern goes like this:

when you start the timer, you essentially store the current millisecond. After this, in your loop code, among other things you should check if the time has passed by comparing current millisecond with the stored one. If their difference is equal or bigger of the desired delay interval, then the time has passed.

Make sure you use `unsigned long` variables to store times and check if time has passed with the condition used below (`if(millis() - mark >= interval ){...}`) so you will not have problem even after `millis()` rolls over.

If you need more help, do not hesitate to ask.

```
unsigned long interval=2000; //2000ms
unsigned long mark;
boolean enabled=true;

void setup() {
    Serial.begin(9600);
    Serial.println("starting timer");
    startTimer();

}

void loop() {
    check();
}

void startTimer(){
    mark=millis();
}

void check(){
    if(enabled){
        if(millis() - mark >= interval ){

            enabled=false;
            Serial.println("time elapsed");
        }

    }
}

```
> 2 votes

# Answer
You could try something along these lines, I haven't put all of the code in, but just how this could be done for the sweep timer using millis().

```
unsigned long sweepTime;
unsigned long animationTime;
int stepperPosition;

void setup()
{
    //... other setup code
    sweepTime = millis();       // initialise the variables for the sweep timer, and the animation timer
    animationTime = millis();
    stepperPosition = 2000;     // initialise the next stepper position
}

void loop()
{
    if (millis() - sweepTime > 500) //  check if more than 500 milliseconds have elapsed since last time we ran this.
    {
        stepper.runToNewPosition(stepperPosition);  // change stepper position
        sweepTime = millis();           // reset timer variable
        switch (stepperPosition) {      // need to change the value of the next position to set the stepper to
            case 0 :
                stepperPosition = 2000;
                break;
            case 2000 :
                stepperPosition = 0;
                break;
        }
    }
    //... continuation of loop code
}

```

Additionally, I don't have my arduino with me, so can't verify the correctness of the code.
> 2 votes

# Answer
Since microcontrollers typically only have one "core" or "thread" they can only do "one thing at a time".

A microcontroller will step through your code and do everything in order (if you don't call interrupts).

Basically, when you put in a `for-loop` (or any other type of loop) or a `delay`, it will only continue with the rest of your code when that is done.

To solve this, and "do two things at a time" (or actually rapidly switch between things) you'll need either interrupts or non-blocking code (or both).

**Interrupts**

I see you're doing some direct port manipulation, which is really nice. You're writing bytes directly to the control registers of the microcontroller.

You can leverage on that, to set up a timer (check the ATMega328P datasheet). You may make this timer give an interrupt each 100ms, and execute a "frame" of your animation at that point. And the next frame at the next interrupt. So that the time between each frames can be used for other code.

**Non-blocking code**

Arduino has built-in `millis();` which is basically an interrupt that fires every millisecond to keep track of the passed milliseconds. So you can use this instead of fiddling around with the timers (which may very well cause some of the Arduino's functions to fail (like millis() or the servo library).

To write non-blocking code, you'll not use delays, since they effectively throw away "processor time" by doing "nothing-instructions" all the time.

But if we take out the delays, the for-loops will run too fast. And a for-loop also doesn't really work without the delay. Because even if you use millis and wait for half a second, you can't do anything in between.

So we'll have to break up your code (specifically the animations) in chunks of code that can be executed withouth a delay. With only the need to delay in between these chunks.

**Frames**

Let's split up your animations in "frames". One of your animations `same()` works by PORTH&PORTB = A for 100msec and low for 100 msec.

```
void sameAnimation(unsigned char frame){//plays 20 times (1x on, 1x off) instead of 10x on-off.
  if(frame%2==0){//If even
    PORTH = a;
    PORTB = a;
  }else{//if not even.
    PORTH = 0;
    PORTB = 0;
  }
}

```

So based on the frame of the animation, the port will go high or low.

Now we look at the complete code, we have to change the motor every 500ms and have to change the animation frame every 100ms. And check a button.

We could put these in an interrupt that fires every 100ms, which would get reliable timing and minimum software overhead. Or use the millis(); (checked against the previous milis) to check if the last update was 100ms ago.

My go at the code is below, but you should be able to figure it out yourself.

```
void loop()
{
  unsigned char currentFrame = 0;

  //Could be done every round.

  lastState = state;
  state = digitalRead(button);
  if ( state == HIGH & lastState == LOW )
  {
    currentAnimation++;
    PORTH = 0;
    PORTB = 0;
  }

  // These are the patterns, that should be played whilst the stepper is running.

  if(millis() - previousMillis > 500){// Should change every 100ms
    previousMillis = millis();

    if (currentAnimation % 3 == 0)
    {
      sameAnimation(currentFrame++);
    }
    if (currentAnimation % 3 == 1)
    {
      leftAnimation(currentFrame++);
    }
    if (currentAnimation % 3 == 2) {
      fasterAnimation(currentFrame++);
    }

    if(currentFrame % 5){//Should change every 500ms, so every 5 frames.
      if(forward){
        stepper.runToNewPosition(0);
        forward = false;
      }else{
        stepper.runToNewPosition(2000);
        forward = true;
      }
    }
  }
}

//--------------------------------------------------------------------------------------------------------------------------------
//PATTERNS
void sameAnimation(unsigned char frame){//plays 20 times (1x on, 1x off) instead of 10x on-off.
  if(frame%2==0){//If even
    PORTH = a;
    PORTB = a;
  }else{//if not even.
    PORTH = 0;
    PORTB = 0;
  }
}

void leftAnimation(unsigned char frame) {
  if(frame%2==0){//If even
    PORTH = e;
    PORTB = e;
  }else{//if not even.
    PORTH = ~e;
    PORTB = ~e;
  }
}

void fasterAnimation(unsigned char frame){
  PORTH = frame;
  PORTB = frame;
}

```

**The button**

Checking the button every round isn't really needed. You can use an interrupt on that pin, so that the code to check it's state and go to the next frame only happens when the button is actually pressed. (interrupt triggered on rising edge?).
> 2 votes

---
Tags: millis, stepper
---


# Question
Title: How do I read from /dev/ttyACM0 in Linux without a terminal emulator?
I just bought an Arduino Due and I'm having trouble reading from a simple serial IO program.

I have a SparkFun RedBoard which is like an Uno. With that, I just ran a "`stty`" command to configure the baud rate and other terminal settings, and then I could do "`cat /dev/ttyUSB0`". Actually I have a C++ program which opens "`/dev/ttyUSB01`" and reads from it like a normal file.

Now, with the Due, the device is "`/dev/ttyACM0`" and there have been a few snags. One of them is that after programming the Due, and running `stty`, I have to open `/dev/ttyACM0` using the `screen` program:

```
screen /dev/ttyACM0 115200

```

and then kill screen, before `cat /dev/ttyACM0` will work. Otherwise, `cat` prints out one byte and exits; rarely it prints out 10 bytes or a line, or sometimes it prints nothing.

This is a bit annoying and I can't figure out what `screen` is doing to the device which I can't seem to accomplish using `stty`. My `stty` command is:

```
sudo stty -F /dev/ttyACM* 115200 -parenb -parodd -cmspar cs8 -hupcl -cstopb cread clocal -crtscts \
-ignbrk brkint ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl ixon -ixoff -iuclc \
-ixany -imaxbel -iutf8 \
-opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 \
-isig -icanon iexten -echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl \
echoke -flusho -extproc

```

I got this by running `stty -a < /dev/ttyACM0` after using `screen` to initialize as above.

I thought it might have something to do with serial auto-reset, so I tried using a resistor between `3.3V` and `RESET`, but this did not fix the problem.

I should note that `cu` from the `uucp` package is able to read continuously from `/dev/ttyACM0`, but unlike `screen` it does not leave the terminal set up in such a way that a subsequent `cat` command will work.

```
$ cu -l /dev/ttyACM0 -s 115200
<continuous stream of data>
$ killall cu             # (from another shell)
$ cat /dev/ttyACM0 | hexdump -c
<e.g. 7 bytes>
$

```

With `screen`, `cat` would have printed an infinite stream. Any ideas how to accomplish this setup without using `screen`?

# Answer
> 6 votes
I have had very similar problems with my yun(shields) and I found the stty command to be very crucial for a good working. I use following command and it works with mega and due on the yun

```
stty -F ${PortName}  ${SerialSpeed}  raw -clocal -echo icrnl

```

Since I call these I can redirect from and to /dev/ttyxxx without problems. As far as I can see you mis the raw.

---
Tags: serial, arduino-due, linux
---


# Question
Title: Trying to print text on LCD display from Arduino trinket
I'm trying to simply program an Arduino trinket to display some text on an LCD display.

I'm basically trying to follow this, except connect it to a Trinket rather than an Arduino Uno. The background color of the LCD display is changing as expected from the `loop` function in my Arduino code, but it's just displaying some o's and arrow's for text on the LCD display.

I'm new to Arduino's (and EE in general), but am a computer programmer.

What am I doing wrong that the sample code in the above link doesn't print text on my LCD display?

# Answer
> 1 votes
Operating this display should not be out of the range of the ATTiny85 abilities. I have one using a two-way serial connection for a setup routine, that modifies EEPROM values.

---

First off connect to the LCD Backpack using the USB connector and test it through there to rule out it being faulty.

At the bottom of that page:

> For more commands, check the github repository (see the Downloads tab) for a python script that will test all commands on the display.

---

**Testing Trinket Serial:**

What you can do is take your trinket and run a basic Serial connection program to test if the Trinket is sending the right info out.

Trinket:

```
#include <SoftwareSerial.h>
// Create a software serial port!
SoftwareSerial comm = SoftwareSerial(0, 1); //RX,TX
#define LEDPIN  PINB2
void setup() {
  //set baud
  comm.begin(9600);
  DDRB |= (1 << LEDPIN);  // set LED pin to output mode
}

void loop() {
  //print a specific character once a second

  comm.println('a');
  PORTB |= (1 << LEDPIN); // turn on LED
  delay(500);            // 0.5 second delay
  PORTB &= ~(1 << LEDPIN); // turn off LED
  delay(1000);
}

```

Then you need another Arduino, like an Uno, Leonardo:

```
// For leonardo use Serial1 for the connection to trinket
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Ready...");

  // set the data rate for the SoftwareSerial port
  Serial1.begin(9600);
}

void loop() { // run over and over
  if (Serial1.available()) {
    char incoming = Serial.read();
    Serial.println(incoming);
  }

}

```

Or the stock balnk sketch and connect the Trinket Serial out to Arduino `TX-> 1`.

If using an UNO you can set up a SoftwareSerial style of the above.

I recommend this rather, a USB-Serial converter as it will be quicker and cleaner.

Next you need to see what is coming out. If the received data is correct then there is an issue in the LCD display, try re-flashing the LCD board with new firmware.

If the data comes through correctly then move onto using the Adafruit code and still connecting it to the other Arduino boards serial connection, replacing the `Serial.println(Serial1.read());` with `Serial.println(Serial1.read(),HEX);`.

If the data still comes through correctly then the data is not being received properly by the LCD backpack.

---

**LCD Backpack**

You should test the display board with another Arduino, UNO or Leonardo (32u4).

Run the Adafruit tutorial code and see the results. If the code works then there is a problem with the Trinket and the SoftwareSerial library.

If there are again errors that happen with the LCD backpack when used with a 'normal' Arduino then it is the problem.

---

**Recomendations**

Download the ATTiny core from High-Low Tech and burn the 'bootloader' to reset the fuses to 8MHZ setting, also this is a good core to use if you want more space on the ATTiny.

Possibly re-flash the trinket bootloader and make sure the internal clock is 8MHz; the SoftwareSerial library is touchie I believe.

---

# Answer
> 0 votes
Warning: I do not have a ATtiny85 nor the lcd so this is purely based on what I found after some reading up on this mcu.

What I would do in your situation: As the trinket is using a ATtiny85 it does not have hardware serial. So a software variant is needed.
You opted for software serial (which is the most obvous in Arduino world) but which seems to be the hardest solution. According to this source Serial communication with the Tiny's is is possible (And I quote)

> you might have to tune the internal oscillator to get a stable connection.

Assuming your lcd does not need to send data back; I would try the TinyDebugSerial.

---
Tags: lcd
---


# Question
Title: RF 433 Module with VirtualWire: transmit and receive using the same Arduino board
**I was wondering if it was possible to work, in the same Arduino board, both Transmitter and Receiver RF 433 MHz modules. Is it feasible?**

Here is the schematics I tried:

1) a pushbutton toggles a state value (0 or 1) and triggers the RF transmitter to send it as a message to the receiver module

2) the RF receiver, whenever reading the message, turns on or off a LED according to the corresponding value (0 or 1)

Here is the source code I wrote:

```
#include <VirtualWire.h>

#define BTN_PIN A0    // pushbutton que aciona a transmissao
#define LED_PIN 13    // LED aceso ao receber o sinal
#define TX_PIN   4    // ligado ao pino DATA do transmissor RF
#define RX_PIN   7    // ligado ao pino DATA do receptor RF

#define SPEED  5000   // velocidade de comunicacao (bits por segundo)

int estado = 0;

void setup() {
  pinMode(BTN_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);

  vw_set_tx_pin(TX_PIN);  // transmissor
  vw_set_rx_pin(RX_PIN);  // receptor
  vw_setup(SPEED);
  vw_rx_start();

  Serial.begin(9600);
}

void loop() {
  int pressionado = !digitalRead(BTN_PIN);
  char msg[4];

  if (pressionado) {
    estado = !estado;
    itoa(estado, msg, 10);

    vw_send((uint8_t *) msg, strlen(msg));
    vw_wait_tx();

    Serial.print("Mensagem enviada: [");
    Serial.print(msg);
    Serial.println("]");

    delay(500);
  }

  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  int recebido = 0;

  memset(msg, 0, 4);
  if (vw_get_message(buf, &buflen)) {

    for (int i = 0; i < buflen; i++)
      msg[i] = char(buf[i]);
    msg[buflen] = '\0';

    Serial.print("Mensagem recebida: [");
    Serial.print(msg);
    Serial.println("]");

    recebido = atoi(msg);

    Serial.print("recebido = ");
    Serial.println(recebido);

    digitalWrite(LED_PIN, recebido);
  }
}

```

When I run it, according to Serial Monitor it sends the message. The problem is no message comes to the RF receiver.

**Does anyone have an idea of what could be wrong?**

# Answer
As said in the comment you definitely need an antenna on both modules.

It is also possible that you are not supplying enough power to the 433 Mhz modules. The Arduino is not capable of outputting much current and RF transmitters generally have large current spikes.

So I would recommend that you use a seperate power supply to power the modules (do not forget to keep common ground between the Arduino and the Transmitter.)

I have also heard that it is preferred to not maintain common ground between the transmitter and the receiver. So if all else fails then use two separate power supplies.
> 1 votes

# Answer
These lines in the ISR in VirtualWire.cpp

```
    if (vw_rx_enabled && !vw_tx_enabled)
        vw_rx_sample = vw_digitalRead_rx() ^ vw_rx_inverted;

```

and

```
    if (vw_rx_enabled && !vw_tx_enabled)
        vw_pll();

```

mean that the receive path code is just not executed while the transmitter is enabled.

It kind of seems from the comment as that might not have been true at some point in the past, though I'm not seeing a version history for an "official" version to check.

You could try to modify the code to implement both, but it is worth noting that VirtualWire has been deprecated in favor of the more versatile RadioHead, so you might want to evaluate that and perhaps make modifications there instead.
> 1 votes

---
Tags: arduino-uno, rf, virtualwire
---


# Question
Title: GikFun Arduino Nano locking up on serial I/O
I'm running into a problem with a GikFun Arduino Nano. The symptom appears when I'm reading the receive buffer to clear it after an operation completes. The unit just appears to stop somewhere in the loop function and never continues.

I know that this unit has a CH340 UART on it which seems to have issues.

Any suggestions on what I can do?

**OP Edits**

This code is more or less based on the code from this Make: article. I originally had this assembled through an Arduino Uno R3 with an HC-06 (Kootek BT2S) module. Everything connected via solderless bread-board.

This entire circuit works properly with the UNO, which I had it running on SoftwareSerial using pins 2, 3. After putting this on a perf-board in a project box using the GikFun Nano, it was not behaving. I had a number of wiring issues, which I resolved, but still had issues communicating on the HC-06/SoftwareSerial. I re-did the wiring using pins 0, 1 for the Serial and removed the SoftwareSerial references. The circuit worked as I expected with the HC-06 working as it had before. But if I issued more than 1-2 commands via Bluetooth the unit would just get stuck. I also tried this without the HC-06 connected and just used the Serial Monitor through the IDE same behavior. It would randomly lock up after clearing the receive buffer.

Code - as requested:

```
const int statusLED = 13; //the pin you connect your status LED to
const int desiredBaud = 4;//index of your desired baud rate 4 is 9600
char* myPin = "1234";//change to the pin of your choice

const int memRed=0;
const int memGreen=1;
const int memBlue=2;

const int redPin= 9;
const int greenPin= 10;
const int bluePin= 11;
const int cmdLed= 12;

// Max Red - 255
const int max_red = 255;
// Max Green - 90
const int max_green = 255;
// Max Green - 100
const int max_blue = 255;

int red= 255;
int green= 255;
int blue= 255;

unsigned int baudLookup[] =
{
  1200,  //code 1
  2400,  //code 2
  4800,  //code 3
  9600,  //code 4
  19200, //code 5
  38400, //code 6
  57600  //code 7
};

void setup()
{
  Serial.begin(9600);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(cmdLed, OUTPUT);
  pinMode(statusLED, OUTPUT);
  digitalWrite(statusLED, HIGH);

  Serial.begin(9600);
  delay(1500);//wait for reset to complete

  Serial.print("AT");
  delay(1500);//wait for reset to complete
  while(Serial.available()) {
    Serial.read();
  }
  delay(1500);//wait for reset to complete

  digitalWrite(statusLED, HIGH); //SUCCESS!

  digitalWrite(redPin, map( red, 0, 255, 0, max_red) );
  digitalWrite(greenPin, map( green, 0, 255, 0, max_green) );
  digitalWrite(bluePin, map( blue, 0, 255, 0, max_blue) );
}

void loop()
{
  digitalWrite(statusLED, LOW); //fast blink means success
  delay(200);
  digitalWrite(statusLED, HIGH);
  delay(200);

  String stat;
  char buffer[13];
  buffer[12]= 0;
  if( Serial.available() >= 3 ) {
    String stat = String("OK");

    Serial.readBytes(buffer, 3);
    buffer[3]= 0;
    String command= String(buffer);

    Serial.println(command);
    if( command == "GET" ) {
      char outBuffer[7];
      sprintf(outBuffer, " %02x%02x%02x", red, green, blue);
      stat += outBuffer;
    }
    else if( command == "SET" ) {
      if( Serial.available() >= 6 ) {
        Serial.readBytes(buffer, 6);

        int redVal= (getVal(buffer[0])<<4) | (getVal(buffer[1]));
        int greenVal= (getVal(buffer[2])<<4) | (getVal(buffer[3]));
        int blueVal= (getVal(buffer[4])<<4) | (getVal(buffer[5]));

        digitalWrite(redPin, map( redVal, 0, 255, 0, max_red) );
        digitalWrite(greenPin, map( greenVal, 0, 255, 0, max_green) );
        digitalWrite(bluePin, map( blueVal, 0, 255, 0, max_blue) );

        red= redVal;
        green= greenVal;
        blue= blueVal;

        char outBuffer[7];
        sprintf(outBuffer, " %02x%02x%02x", redVal, greenVal, blueVal);
        stat += outBuffer;
      } else {
        stat = "ERR";
      }
    }
    else {
      Serial.println("No Command");
    }
    Serial.println(stat);
    Serial.println("Clearing receive buffer");
    delay(1500);
    while(Serial.available()) {
      Serial.read();
      delay(100);
    }
    delay(1500);
  }
}

byte getVal(char c)
{
  if(c >= '0' && c <= '9') {
    return (byte)(c - '0');
  } else {
    return (byte)(c-'A'+10);
  }
}

```

# Answer
> 0 votes
The mix of delays and flushing in your code has a high chance of leading to unreliable operation. Consider for example:

```
Serial.println("Clearing receive buffer");
delay(1500);
while(Serial.available()) {
  Serial.read();
  delay(100);
}
delay(1500);

```

As the loop there can only consume about 10 characters per second, it would be quite easy for something on the far end to produce inputs faster than they are consumed, essentially making the loop infinite.

Time-based delineation of serial messages tends to be quite risky; better reliability is usually had by using a defined delimiting condition - for example, ending each message with a newline character and reading until that is seen.

USB-serial conversion also introduces added challenges for time-based schemes, as it introduces a sense of grouping into packets into a stream which in its native form does not have any.

---
Tags: arduino-nano, ch340
---


title: Why doesn't my LEDs turn on?

text:
# Question
Title: Why doesn't my LEDs turn on?
i have just started learning Arduino, so please be patient to me :)

Why doesnt my circuit below doesn't work?

Here's the code:

```
#define led_green 2
#define led_yellow 8
#define led_red 13

void setup() {
  pinMode(led_green, OUTPUT);
  pinMode(led_yellow, OUTPUT);
  pinMode(led_red, OUTPUT);

  // Strarting all turned off
  digitalWrite(led_green, LOW);
  digitalWrite(led_yellow, LOW);
  digitalWrite(led_red, LOW);
}

void loop() {
digitalWrite(led_red, HIGH);

delay(1000);

digitalWrite(led_red, LOW);
digitalWrite(led_green, HIGH);

delay(1000);

digitalWrite(led_green, LOW);
digitalWrite(led_yellow, HIGH);

delay(1000);

digitalWrite(led_yellow, LOW);

}

```

I'm trying to reproduce this circuit that I saw in a tutorial:

Thank you.

# Answer
> 5 votes
If you are doing what is in the first picture then you're doing it wrong.

You have to make sure the led is horizontal, not vertical. The signal is going through the led and not making it into ground. And your ground is in the same lane as your signal.

I think you should learn how breadboards work and then move on from there. Its pretty simple and I think you'll learn it quickly.

For your code part, instead of defining the variables, you could just use `int`.
Refer to this as a starter tutorial, https://www.arduino.cc/en/Tutorial/.

This is how your wiring should look like if you followed the tutorial,

---
Tags: arduino-uno, led
---


# Question
Title: I feel like an idiot, why can't I make a servo move with the boilerplate code?
So I was working on a far more grand project, until I discovered that I couldn't get any of my servos to move.

I've gone back to basics, and am trying to just get the boilerplate code found here, working.

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

```

Here are pictures of my setup.

# Answer
> 1 votes
The only thing I see that could be the problem is with your servo wiring. It seems that most servos use this kind of wiring
Which is the way that you seem to wire it, but depending on how Radioshack servos are made the signal wire could correspond with a different wire. I imagine this could possibly be on the packaging so I would start by looking there to confirm your wiring.

---
Tags: arduino-nano, servo, arduino-micro
---


# Question
Title: message received from GSM contains parenthesis instead of curly braces
the GSM code i have been working out is up and running, I use JSON format in sending the data obtained by my sensors, but the JSON message I have been receiving contains parenthesis instead of curly braces.

# Answer
> 0 votes
One or both of your GSM endpoints is incapable of handling ESC prefixes according to GSM 03.38. The only difference between "{" and "}" and "(" and ")" is that the former are signified by a preceding ESC which either is not being generated by the sender or is not being interpreted by the receiver.

---
Tags: arduino-mega, gsm
---


# Question
Title: Circumventing overflow error by pushing data into computer?
It seems in certain applications, for example signal processing, Arduino and other micro-controllers in general run into the overflow error when they're trying to store even moderate amounts of data. It would seem the obvious answer would be to simply take this data, push it onto the computer, and deal with it there instead, where you have much more available computing power. Is this possible with Arduino, or am I missing something that makes it not feasible?

# Answer
> 1 votes
One of the "features" of most microcontrollers/microprocessors is that they don't have a whole heap of RAM - this keeps costs down, and lets the manufacturers keep everything on one chip (unlike your PC).

However to "push" data to somewhere that can process it, you need to have a fast communications channel. SPI is quite fast, but you don't generally talk to PCs using SPI. Serial communication is slower, but if it gets converted into a USB interface (such as on a Uno) you can get respectable speeds talking to a PC. Something like 115200 baud is usually reliable, which lets you transmit 11520 bytes per second.

However it depends on what you want to send (ie. how many bytes), how you are going to indicate where one piece of data ends and the next one starts, maybe allow for error detection or correction, and so on.

Say, for example, it takes 5 bytes to send one piece of data (eg. 4 digits plus a delimiter). Now you are down to 11520/5 = 2304 pieces of data per second.

This may or may not be adequate for whatever-it-is you are trying to do.

---
Tags: arduino-mega, arduino-ide, usb
---


# Question
Title: IF, ELSE IF functions not working with analogRead
not sure what is going wrong in the code below, but it's a simplified code of a larger piece I'm trying to debug. I notice that the code seems to skip to the else statement even though the if statement is valid. Potential is set to analogRead(A0)

```
while (potential < 1023) {
Serial.println(analogRead(A0));
if (potential < 1023) {
  if (potential > 200) {
    Serial.println("cool");
  } else {
    Serial.println("low");
    lcd.print("hello");
    delay(1000);
  }
}

```

Results in serial monitor show

```
235
low
324
low

```

I've also tried if (potential \< 1023 && potential \> 200) and if ((potential \< 1023) && (potential \>200)) to no avail.

Can anyone help, let me know what's going wrong or suggest a fix to this?

# Answer
If in while loop, analogRead needs to be reassigned so it is constantly read.

```
int potential = analogRead(A0);

void setup() {
  while (potential < 1023) {
    potential = analogRead(A0);
    ...
    }
}

```

Thanks guys for the help!
> 0 votes

# Answer
I'm not sure what you're trying to achieve with that `while`. But this will result in none of your other code being executed until potential is above 1022, which sound rather weird. (Unless it's for some kind of safety mechanism).

The problem is that you do send the new value over serial. But you do not assign that new value to the variable 'potential'.

Basically, you see something completely different as what is actually happening. You should do `Serial.println(potential);` to be sure that you print the value of 'potential'.

And you should assign the `analogRead(A0);` to your variable `potential`.

I've also taken away the `while` since I think it would be misplaced. And I worked around it, so it doesn't block your complete sketch.

```
void loop() {
  potential = analogRead(A0));
  Serial.println(potential);

  if (potential < 1023) {
    if (potential > 200) {
      Serial.println("cool");
    } else {
      Serial.println("low");
      lcd.print("hello");
      delay(1000);
    }
  }else{
    //Code that won't run if potential < 1023
  }

  //Other code that can run "simultaniously".
}

```
> 1 votes

---
Tags: arduino-uno, programming, arduino-ide, analogread, ide
---