# Question
Title: Encoding an entire Byte for File Reading
I'm using an Arduino Yun to read from a data file, which will then populate a data structure. The `file.read()` function "*returns: The next byte (or character), or -1 if none is available.*"

This functionality is identical to the `SD.read()` function in the SD card library.

The data file will never have any value that exceeds 1 byte with all numbers in the range 0-255. If I print these numbers as a long string in the data file, each character is read as a byte. So I need to call `file.read()` 3 times to read in a single 0-255 value. And then do some additional processing to construct the final 8-bit value for storing.

I could reduce this to 2 calls by printing the Hex code in the data file, but this isn't much of an improvement.

**Is there a way to encode a full byte in a single character?**

**Effectively , is there a particular way I can format my data file so that I can read in an `8-bit unsigned` value in a single call to `file.read()`?**

# Answer
> 0 votes
There's two parts to what you want to do, writing the file in the right form, and reading that format file.

The format of file is known as *raw binary*. Every byte in the file can store a separate value between 0 and 255, or between -128 and 127, dependin on how you interpret the data. At the end of the day, every byte in a file is just a collection of 8 bits yielding 2^8 = 256 combinations. What those combinations actually mean is more of a human thing than a machine thing.

We, as humans, have decided upon three main representations of those bytes: *unsigned* numbers from 0 to 255, *signed* numbers from -128 to 127 (lookup two's complement) and finally ASCII characters.

ASCII characters are more of a lookup table placed over one of the other two representations. Some systems use unsigned bytes and some signed bytes for the basis of that lookup tabe.

Writing text into the file results in looking up the corresponding byte values for each character in that text and placing those values in the file. When you read the file the reverse is done - the byte values are read and you look them up in the ASCII table to find the corresponding letters.

To store just numbers between 0 and 255 it is far more efficient to bypass that ASCII table and store the values directly as bytes. How you do that is entirely dependent on what language you are writing your software in. Since you haven't mentioned what that language is I can't advise you on that front' only give some examples in languages I know.

Such as in C you would store your data in an array of *unsigned char* or *uint8\_t*. You then use the `write()` function to write raw data to the file.

In Perl you might use the `pack()` function to store your values as bytes in a string then write that string to a file.

When reading the data you are presented with a raw value. That may be given to you as a signed or an unsigned value depending on the underlying system. I don't know what the yun is off hand. Converting from whatever is handed to you by thr `file.read()` function to what you expect it to be though is a very simple matter, and is called *casting*.

```
int in = file.read();
uint8_t bval = (uint8_t)in;

```

The bit in brackets is the *cast* which converts the value in the integer *in* into a uint8\_t (Unsigned INTeger 8-bit Type) which corresponds to whatever you wrote as an unsigned char or uint8\_t at the other end.

# Answer
> 0 votes
This is a fragment (untested) of how you can do it:

```
char datafile[512];
int ch;
int index = 0;

while ((ch = file.read()) != -1) {
  datafile[i] = (char)ch;
  if (++i == 512)
    break;
}

```

---
Tags: arduino-yun, sd-card
---


# Question
Title: Can I make the Arduino ignore serial print
I like having serial communication for debugging and testing purposes but after a while it takes away too much speed from the sketch.

Is it possible to have the Arduino ignore serial.print and serial.println throughout my code, without turning it into a comment or placing every serial printing inside for example "if(debug == true)" statements?

Thanks in advance.

# Answer
> 15 votes
If you insist on top performance, the best thing would be to use a macro for that:

```
#define Sprintln(a) (Serial.println(a))

```

Then instead of

```
Serial.println(F("Hello world!"));

```

write

```
Sprintln(F("Hello world!"));

```

etc. To deactivate the `Serial` printing, define the macro empty:

```
#define Sprintln(a)

```

This will have the preprocessor remove all debugging code defined with `Sprintln` from your code.

(Of course, there's a huge number of variations on this theme.)

# Answer
> 7 votes
You could, for example, use the preprocessor to change all `Serial` in your code.

```
#ifndef ENABLE_PRINT
// disable Serial output
#define Serial SomeOtherwiseUnusedName
static class {
public:
    void begin(...) {}
    void print(...) {}
    void println(...) {}
} Serial;
#endif

```

# Answer
> 2 votes
Yet another solution is to implement a dummy Serial device. That would be a class that as HardwareSerial inherits from Stream and implements the necessary virtual member functions with dummy functions.

```
class NullSerial : public Stream {
public:
  virtual size_t write(uint8_t) { return (1); }
  virtual int available() { return (0); }
  virtual int read() { return (0); }
  virtual int peek() { return (0); }
  virtual void flush() {}
  ...
  void begin(unsigned long, uint8_t) {}
  void end() {}
  ...
};

NullSerial Serial;

```

As Serial is not defined as a weak symbol the application would need to use a Steam variable for output. And bind this to the HardwareSerial or the NullSerial.

```
#if defined(DEBUG)
Stream& trace = Serial;
#else
NullSerial noSerial;
Stream& trace = noSerial;
#else

#endif
...
trace.print(42);

```

This is not complete as all the HardwareSerial member functions (that the sketch uses) are needed but gives the general idea how to use OOP to solve the problem.

Cheers!

---
Tags: serial
---


title: Verify RGB Led Cube equipment

text:
# Question
Title: Verify RGB Led Cube equipment
I'm preparing this kit on eBay to create the following instructable - http://www.instructables.com/id/4x4x4-RGB-LED-Cube/ But I have doubts about 0.1uF and 22pF capacitors since the once on eBay are 50v. Also MOSFETs - instructable uses IRF9531 but the ones I found on eBay are IRF9540N. Is the equipment I added on eBay compatible with instructable?

# Answer
> 1 votes
Capacitor ratings don't really matter in your case, as you are using only 5 volt. Only their values (F) do.

Though the crystal you selected has an indication it needs 20pF load capacitors, not 22pF. 22pF is probably still fine. (Also note the ±20% accuracy, so between 17.6 and 26.4pF)

The IRF9531 and IRF9540N have the same pinout. They are also pretty similar in specs. The IRF9540N is slightly better even.

Note that the ATMega328p doesn't have the bootloader pre-installed. It's not that hard to do yourself though.

The EEPROM you selected is an SMD version. Kind of hard to work with if you are still a beginner. Better use a DIP version instead (that one is a bit more expensive, but 4 times the size)

I'd suggest you add an USB to Serials Adapter to the list, so you don't need the Arduino Uno every time you want to reprogram it, and use the Uno for something more useful.

# Answer
> 1 votes
For a crystal with 20pF load capacitance you need 40pF capacitors.

The formula used is:

* Cx1 = Cx2 = 2(CL - Cpara)

CL is 20pF and Cpara is the parasitic capacitance of the circuitry involved. Under most amateur circumstances that can be ignored.

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


# Question
Title: Can both the 3.3V and 5V pins on the Arduino be used at once for power?
I'm supplying power to Arduino via PC USB.

# Answer
> 5 votes
Yes.

Here's a block diagram of how the Arduino power is arranged:

As you can see the USB power is fed through a FET (P-channel MOSFET) to isolate it when there is external power applied (as decided by the comparator *COMP*). External power is fed through a 5V regulator and is fed to the same point as the USB power. Thus you get the same 5V at the same point regardless of if you have USB or Barrel Jack power. From there the 5V (wherever it comes from) is fed into a 3.3V regulator. The 5V pin on the Arduino is connected directly to the 5V point where the USB and the 5V regulated input are connected. The 3.3V pin is connected directly to the output of the 3.3V regulator.

So no matter what input power arrangement you use - barrel jack, USB power, battery connected to the V IN pin (not shown, but connects to the barrel jack), or regulated 5V into the 5V pin, you get access to the same 5V and 3.3V power on the 5V and 3.3V power pins.

---
Tags: arduino-uno, power, hardware
---


# Question
Title: Connect my arduino with ethernet shield to new router
I just changed the router for my webserver and I'm having trouble to connect my arduino with the LAN. I'm using a router which uses Zhone technology, and I've been working with NetGear for a while without problems. The procedure I've done so far is:

1. Connect the arduino with the ethernet and run the DhcpAdressPrinter example
2. Once I got the adress, in my case 192.168.1.125 I run the WebServer example, using the IP assigned by the DHCP.
3. In the serial monitor, I see it has started the program with the correct IP.

Problem: WHEN PUTTING THE IP INTO A BROWSER, NOTHING CHARGES

More info:

* In my router page (192.168.1.1) I can see that each ethernet port has assigned a MAC adress, I don't really understand why.
* I also can see that the arduino has been successfully added to the DHCP with the IP assigned and the MAC adress that I wrote on the code
* Finally, add that I've read in another website that sometimes the problem is due to the fact that the router just let the access to some specific MAC adress, but i'm not sure.

Any help will be apreciated! Thanks!

# Answer
Finally, I was capable to solve it by just creating a port forwarding with the IP that was assigned by the DCHP. It looks like my router for security reasons don't let you comunicate with other devices within the lan, so it's necessary to open a port and access the device through it!
> 0 votes

---
Tags: ethernet
---


title: safety for power electronics

text:
# Question
Title: safety for power electronics
I'm quite new to Arduino. I have build a number of projects successfully, like potentiometers, serial communication, DAC, sensors, motors etc.

I use a laptop to power my Arduino project and Atmel Studio to program and upload to the Arduino. I have created a project with 2 motors and I have successfully used a separate power supply (a transformer) to power the motors.

Now I want to continue my experiments but I'm afraid of the possibility to cause any problem to my laptop.

When I made the circuit with the 2 power sources (laptop for the Arduino, transformer for the motors) I had to connect the 2 grounds together.

So my question is that:

*Can someone explain me or point me to some information about power electronics so to be absolutely sure that I won't cause any problem to the laptop?*

Should I use optocouplers, or diodes etc? Is there a way to avoid the 2 grounds connection? What is the reason to connect both grounds (of the 2 power supplies) in the first place?

# Answer
> 3 votes
Connecting the grounds together is required since without that there would be no circuit for the current to flow through. Take this simple block diagram for instance:

In the top diagram there are two complete circuits - the green one (Arduino's 5V power) and the blue one (device's 12V power). The communication between the Arduino and the Device can't happen because there is no circuit (red).

In the bottom diagram the red circuit has been completed by joining the grounds together. That means that the current has some way to get back to where it came from (which current always *has* to do) so the signals you send can actually get through.

To avoid having to connect the grounds together you need something called *Galvanic Isolation*. This involves using some method that is not electricity to connect the two circuits together. That could be using light in the form of an opto-coupler, or magnetism in the form of a transformer, or even something even more physical like a relay. In that situation you have an arrangement like this:

The ground connection that was part of the red circuit above has now been sliced in half (red and orange now) and the isolation device is responsible for passing the signal from one side to the other.

Galvanic isolation is highly desirable when:

* You are controlling a different *type* of current (e.g., using DC to switch AC)
* You are working with voltages considerably higher than your drive voltage (e.g., switching mains)
* You have different ground potentials (e.g., you have a long distance connection)

---
Tags: power, hardware, electronics, system-design
---


title: Arduino Delivering less power

text:
# Question
Title: Arduino Delivering less power
I connected 4x716 Coreless DC Motors on pin 13,12,11,10 and 1xGY-521 to Arduino Pro Mini 328, 5v but speed of propellers is not enough to produce enough torque to lift the quad whereas when i connect then directly to 3.3v LiPo battery the quad has lift but because of no flight control it moves randomly.

I checked the voltage of pin 13,12... they have output as 0.5-0.6v, I think this is the reason quad is not lifting.

I am using following code

```
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

int p1 = 13;
int p2 = 12;
int p3 = 11;
int p4 = 10;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
    pinMode(p1, OUTPUT);
  pinMode(p2, OUTPUT);
  pinMode(p3, OUTPUT);
  pinMode(p4, OUTPUT);
  digitalWrite(p1, 0);
  analogWrite(p2, 0);
  analogWrite(p3, 0);
  analogWrite(p4, 0);

  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);

   digitalWrite(p1, HIGH);
  analogWrite(p2, 250);
  analogWrite(p3, 255);
  analogWrite(p4, 255);

  delay(333);
}

```

# Answer
Atmega328 output pins are rated at 40 mA absolute-maximum current, and the 328's total current through Vcc and ground pins is 200 mA absolute max. Eg, see table 29.1 in the Atmega328 specs.

Although some sources rate a high-speed 716 coreless dc motor at 40 mA, other sources rate it at 100 mA. In either case, it exceeds normal I/O pin capability. You should use FETs or other drivers between Arduino output pins and the motors rather than trying to drive the motors directly from digital output pins.

*Edit:* Regarding the comment, “But most projects i've seen don't use any drivers, Why so ?” I replied:

> Perhaps they are using slightly higher voltage to the Pro Mini, eg 3.7 V up to 5 V, which after accounting for voltage drop in the i/o pin circuits may deliver enough voltage to the motors. Note that a driverless circuit ie direct drive from the i/o pins operates the 328 out of its safe operating area (SOA), but it may be close enough to the safe area to usually work.

For example, some of the 716-based quadcopter pages I looked at say they used 4.2 V LiPo batteries. Also note, 716 seems to be a fairly generic motor designation; it refers to the motor's 7 mm diameter and 16 mm length. As a generic designation it has been used for several different motors, some of which produce less power. For example, in thread #1710948 on rcgroups.com, people refer to different RPMs, less lift, etc. for various motors, and the importance of shaving grams off of the copter's weight to allow it to fly.

Another item that matters when drawing high current from an Atmega328 is which ports are used; and for some devices, it matters whether drive is high-side or low-side, ie whether current is sourced or sunk. The Atmega328 spec sheet (Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P\_datasheet\_Complete.pdf) says “Each output buffer has symmetrical drive characteristics with both high sink and source capability”, but for several kinds of drivers less voltage is lost with low-side drive than with high-side. Ie, you could try connecting the motor's V+ lead to Vcc and its V- lead to the i/o pin, and inverting the on-off logic in the sketch. (I don't know if this will make any difference at all in how well things work.)

Regarding which ports are used, the footnotes to Table 30-1, “Common DC characteristics”, spell out various combinations of ports where total current draw must not exceed a limit (100 mA in some cases, 150 mA in others). On the Uno and Pro-Mini, digital outputs marked 10 through 13 (as used for motor control in the question's sketch) are port B Atmega pins, with a footnoted total-current limit for the group. If you move two of the motor drives to outputs marked 2...4 or D2...D4, then a different total-current limit will apply. (Again, I don't know if this will make any difference at all in how well things work.) Refer to Table 30-1 footnotes for details.

As noted in Gerben's comment, having flyback-diodes for the motor circuits is a good idea. This consists of placing power diodes across the motors, cathode to V+, anode to V-, to prevent energy stored in the motor's inductance from producing extreme i/o pin voltages each time the motor is turned off.

*Edit 2:* Regarding “which diode, FET to use and where \[to\] learn about them”, electronics-tutorials.ws is an accurate and helpful presentation about FET digital circuits. In particular, see the section called “An example of using the MOSFET as a switch”.

Which FETs to consider depends in part on your electronic-circuits fabrication skills. Note that surface mount devices (SMD parts) usually weigh less than other versions of parts, which is important for a lightweight quadcopter. However, some people find SMD parts difficult to work with. In my opinion, the main difficulty is holding parts in their proper places while soldering them, due to small size. (Eg, a SOT-23 SMD transistor package is on the order of 3mm x 2mm x 1mm, and a diode may be half as big.) If you have good soldering skills and a way to hold parts in place while soldering, you should be ok, either using a printed circuit board or air-wiring parts using wire-wrap wire (ie, 30 AWG wire, about 0.25mm diameter).

Some typical logic-level-input SMD FETs are shown in mouser.com's online catalog. Note that in that list, RDS\_on decreases a bunch as unit price increases slightly. For example, the FDN359BN would have under 0.1 ohm resistance when operated with Vcc = 3.7 V and currents \< 100 mA. Voltage drop running a 40 mA motor should be about 4 millivolts.

Some typical SMD Schottky diodes also are shown in mouser.com's online catalog. I think even the cheapest of these would work ok. Of course you'll need to adapt all these suggestions to your own skills, sources of parts supply, and budget.
> 2 votes

---
Tags: arduino-pro-mini
---


# Question
Title: How to loop over objects or pass object to function?
I'm not sure if this is more of an C++ question, but I've looked up both and still have no idea.

I have a sketch which controls 6 stepper motors using the AccelStepper library and in order to shorten the code, I would like to simply loop over them, or pass them to a function individually. They are all initialised with different parameters and then placed in an array.

However I get the error "conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested" or "conversion from ‘SomeClass (\*)()’ to non-scalar type ‘SomeClass’ requested" depending on what I try.

I've got experience with C and Java, not much C++ and I thought it would be a straightforward array of pointers, but I can't get the right combination.

I've made a cut down version that I try to compile with gcc to demonstrate either approach. I've removed all attempts at pointers with & or * to explain what I want:

```
SomeClass classA();
SomeClass classB();

// error: conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested
SomeClass things[2] = {classA, classB};

int init(class SomeClass thing) {
    std::cout << "Setting up thing ";
    thing.setFoo(100);
}

int main() {

    for (int i=0; i < 2; i++) {
        things[i].setFoo(100);
    }

    // could not convert ‘classA’ from ‘SomeClass (*)()’ to ‘SomeClass’
    init(classA);

    return 0;
}

```

And just for completeness my class files which are simplified versions of the AccelStepper class:

SomeClass.h:

```
#include <stdlib.h>

class SomeClass
{
public:
    SomeClass();

    void    setFoo(float foo);
};

```

SomeClass.cpp:

```
#include <stdlib.h>
#include <string>
#include <iostream>
#include "SomeClass.h"

SomeClass::SomeClass()
{
}

void SomeClass::setFoo(float foo)
{
    std::cout << "foo ";
}

```

I hope someone doesn't mind explaining what is probably really simple and obvious! :)

# Answer
There's a couple of fundamental errors in your sketch. Mainly your construction of your class instances:

```
SomeClass classA();
SomeClass classB();

```

Those are taken as functions that return a SomeClass object, not SomeClass constructors. Instead they should just read:

```
SomeClass classA;
SomeClass classB;

```

As for the rest, you are much better off using pointers to the classes - it makes passing them around so much easier. For instance, your array would look like this:

```
SomeClass *things[2] = {&classA, &classB};

```

That is an array of pointers to the objects. It just stores the addresses that they are at, rather than duplicating the objects into new objects within the array.

Your loop would then run like this:

```
for (int i=0; i < 2; i++) {
    things[i]->setFoo(100);
}

```

Note the use of `->` instead of `.` because you are using a pointer to the object.

Similarly your `init()` function would be like this:

```
int init(SomeClass *thing) {
    Serial.println("Setting up thing");
    thing->setFoo(100);
}

init(&classA);

```

However, if you're never going to use the contents of your array with it you could use a reference instead of a pointer:

```
int init(SomeClass &thing) {
    Serial.println("Setting up thing");
    thing.setFoo(100);
}

init(classA);

```

That performs the same job as a pointer but leaves you with what looks like a real object rather than a pointer to the object - in fact it's just aliased the object name to a new one at the same address so you can still access it the same using `.`
> 1 votes

---
Tags: c++, class, gcc
---


# Question
Title: How I can print several numbers via Serial with very few lines of code?
Could someone help me how to output the numbers from 1 to 10 via Serial, without having to write out each command by hand?

Below is my sketch - I need it concise instead of a long sketch:

```
#include <Streaming.h
//setup
void setup() {
 Serial. begin(9600);//The faster the better
}//Close the sertup

//main loop
void loop() {

  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(1) << endl;
  delay(1000);
  Serial<< _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(2) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(3) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(4) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(5) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(6) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(7) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(8) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(9) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(10) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(11) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(12) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(13) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(14) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(15) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(16) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(17) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(18) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(19) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(20) << endl;
   delay(1000);
  while(1){}//freeze the main loop

}

```

# Answer
> 3 votes
*\[This replaces my earlier answer, and addresses information added to the question.\]*

You apparently want a sketch that outputs 1, 2, 3 ... 100 to serial output, where each number string is embedded within a control sequence.

Here are two ways. The first program outputs the sequence once, using ordinary Arduino `Serial.write()`, `Serial.print()` and `Serial.println()` statements:

Program 1. Output 1, 2, 3 ... 100 once

```
void setup() {
  Serial.begin(9600);
  for (int j=1; j<=100; ++j) {
    Serial.write(27); // Send escape character
    Serial.print("[2J"); // Send erase-screen command
    Serial.print("\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t");
    Serial.println(j); // Send j in decimal format
    delay(1000);
  }
}
void loop() {}

```

The other program will output the sequence repeatedly. It uses the `Streaming.h` library, but in a rational manner; for example, instead of quoting every character separately like the program in the photo, it quotes character sequences in strings. Note, Esc \[2J is an ANSI escape code sequence that erases the screen it is directed to, if the screen device is ANSI compliant.

Program 2. Output 1, 2, 3 ... 100 repeatedly

```
#include <Streaming.h> // or "Streaming.h" if appropriate
byte j=0;
void setup() {
  Serial.begin(9600);
}
void loop() {
  ++j;
  // Send Esc [2J which will erase screen
  Serial << _BYTE(27) << "[2J";
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << j;
  if (j >= 100) j=0;
  delay(1000);
}

```

# Answer
> 3 votes
Ah, a challenge!

> I have to write from 1 to 100, and I don't want to repeat it all 100 times

Your question did not make that clear. Anyway:

```
int main () {
  Serial.begin (9600);
  for (int i = 1; i <= 100; i++)
    Serial.println (i);
  while (true);
  }

```

You can probably make it shorter at the expense of readability.

```
int main(){Serial.begin(9600);for(int i=1;i<=100;i++)Serial.println(i);while(1);}

```

# Answer
> 2 votes
Fixing the typos in your original code, so that it should probably read:

```
#include <Streaming.h>

//setup
void setup() {
 Serial.begin(9600);  //The faster the better
}   //Close the setup

//main loop
void loop() {
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(1) << endl;
  delay(1000);
  Serial<< _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(2) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(3) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(4) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(5) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(6) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(7) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(8) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(9) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(10) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(11) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(12) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(13) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(14) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(15) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(16) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(17) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(18) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(19) << endl;
  delay(1000);
  Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
  Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
  Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(20) << endl;
  delay(1000);
  while(1){} //freeze the main loop
}

```

Then condensing the *cursor positioning* lines, gives:

```
#include <Streaming.h>

//setup
void setup() {
 Serial.begin(9600);  //The faster the better
}   //Close the setup

//main loop
void loop() {
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(1) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(2) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(3) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(4) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(5) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(6) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(7) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(8) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(9) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(10) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(11) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(12) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(13) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(14) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(15) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(16) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(17) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(18) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(19) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
  Serial << "\t\t\t\t\t" << _DEC(20) << endl;
  delay(1000);
  while(1){} //freeze the main loop
}

```

Then joining the two *cursor positioning* lines, gives:

```
#include <Streaming.h>

//setup
void setup() {
 Serial.begin(9600);  //The faster the better
}   //Close the setup

//main loop
void loop() {
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(1) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(2) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(3) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(4) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(5) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(6) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(7) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(8) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(9) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(10) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(11) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(12) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(13) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(14) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(15) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(16) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(17) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(18) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(19) << endl;
  delay(1000);
  Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
  Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(20) << endl;
  delay(1000);
  while(1){} //freeze the main loop
}

```

Then putting each repeated line in a `for` loop, and adding a *Maximum Count* `const` variable, gives:

```
#include <Streaming.h>

const int MaxCount = 20;

//setup
void setup() {
 Serial.begin(9600);  //The faster the better
}   //Close the setup

//main loop
void loop() {
  for (int n = 1; n < 20; n++) {
    Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
    Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(n) << endl;
    delay(1000);
  }

  while(1){} //freeze the main loop
}

```

However, jwpat7's answer is much better, and Nick's answer is the shortest.

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


# Question
Title: make Arduino tell when the Python program stops reading from the Serial (crash, etc)
Here's the Arduino code:

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

  pinMode(7, INPUT_PULLUP);
}

void loop() {
    int val = digitalRead(7);
    if (val == HIGH) {
        Serial.print("1");
    } else {
        Serial.print("0");
    }
    Serial.println("");  // new line

}

```

Python code:

```
import time
import serial

# setup Arduino USB communication
try:
    arduinoSerialData = serial.Serial('com3', 9600)

except: # not connected/damaged
    pass

while True:
    if arduinoSerialData.inWaiting() > 0:
        datastr = arduinoSerialData.readline()
        print datastr
        time.sleep(1)

```

WHat I want to add is, if Python program exits, or crashes, let the Arduino know somehow. More specifically turn on a LED in pin 8.

# Answer
There is no way to know if the connection has closed or not, you can only know if the connection *was* working at some point in the past.

Your communication protocol as shown is only *half duplex* (i.e., it's only one way - the Arduino sends to Python but never the other way around) which simplifies things somewhat.

There are a number of strategies you can employ in your case, and any number of them can be combined to create a system as robust (and complex) as you like.

First you would need to make your protocol *full duplex*. This is, you need your Python program to be able to send information to the Arduino. Since you aren't doing that at the moment the implementation of it can be in any way you like.

One method you can use is called Keepalive. In this system the Python program will periodically send an "I am here" message to the Arduino. The Arduino receives these messages and remembers when the last one was (hint: use the `millis()` function). If a message hasn't been received for more than a pre-defined timeout period the link is assumed to be dead.

Another method which is good if you are sending data very regularly from the Arduino to the Python program is to use a system of *acknowledgements*. In this situation every bit of data sent to the Python program is followed by the Python replying with an "I got that" message. If the Arduino doesn't get that response after sending its data within a certain timeout period (can be much shorter than for a keepalive timeout) then the link is assumed to be dead.

Wrapped around both these methods you can add an "I have arrived" and an "I am leaving" message. These are sent by the Python program when it starts and just before it's about to exit so the Arduino knows when the link *should* be alive and when it *shouldn't*. If it gets an "I am leaving" message then it knows that it shouldn't care whether it gets any acknowledgement or keepalive messages, so it doesn't need to think about timeouts. Only after it has received an "I have arrived" message should it start caring.

So for instance your protocol, with all these things implemented, might look like this (`>>` = message from Arduino to Python, `<<` is message from Python to Arduino):

```
>> 1
>> 1
>> 1
>> 0
>> 0
>> 1
<< A    - I have arrived
>> 1
<< Y    - Yes, I got that
>> 1
<< Y    - Yes, I got that
>> 0
<< Y    - Yes, I got that
<< K    - keepalive - we know the link is alive and working.
>> 0
<< Y    - Yes, I got that
>> 1
<< Y    - Yes, I got that
(Program crashes now.)
>> 1
*no Y received - assume connection is closed*
>> 1
... etc ...

```

In this instance the 0 and 1 are what you are sending at the moment. A is an "I have **A**rrived" message, Y is a "**Y**es I got that" message, K is a "**K**eepalive" message, and if the program had exited cleanly an L would have been an "I am **L**eaving" message.

Keeping the messages simple (single characters) means it's really easy for the Arduino to parse those messages and work out what is going on.

There is a certain amount of balancing act to be performed when implementing your system between how often you are sending data and how long you are willing to wait for a valid response or message to flag the connection closed.

Expanding your existing example program to incorporate these messages might look like:

```
unsigned long lastKA = 0;
unsigned long lastSent = 0;
boolean isConnected = false;

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

  pinMode(7, INPUT_PULLUP);
}

void loop() {

    // Check the timeouts if we are connected
    if (isConnected) {

        // First check to see if the Keepalive timeout has passed
        if (millis() - laskKA > 5000) { // 5 second keepalive timeout)
            isConnected = false;
        }

        // If we have sent data...
        if (lastSent > 0) {
            // ... check that we got a response in time
            if (millis() - lastSent > 100) { // 100ms Y timeout
                isConnected = false;
            }
        }

    }

    // If we are connected then send some data
    if (isConnected) {

        int val = digitalRead(7);
        if (val == HIGH) {
            Serial.print("1");
        } else {
            Serial.print("0");
        }
        Serial.println("");  // new line

        // and set the timer for the response
        lastSent = millis();
    }

    // Now process incoming messages.
    if (Serial.available()) {
        int c = Serial.read();

        // If the message is an A then turn on the connection and
        // treat it as a Keepalive as well.
        if (c == 'A') { // Arrived
            isConnected = true;
            lastKA = millis();

        // If it's a Leaving message then turn off the connection.
        } else if (c == 'L') { // Leaving
            isConnected = false;

        // If it's a Keepalive then reset the timer.
        } else if (c == 'K') { // Keepalive
            lastKA = millis();

        // A Y acknowledgement will disable the sent timer.
        } else if (c == 'Y') { // Yes
            lastSent = 0; // Cancel the sent timer
        }
    }
}

```
> 1 votes

---
Tags: serial, arduino-nano, python
---


title: AnalogWrite custom voltage

text:
# Question
Title: AnalogWrite custom voltage
I want to get a low voltage on output pin of Arduino mega. I have connected Pin 46 to A3, and wrote 120 value to 46 port. Expected was to get 2-3v on A3 input pin. Instead I always get 1023 values as input. Am I doing something wrong ?

```
void setup(){
  Serial.begin(9600);
  pinMode(46, OUTPUT);
  pinMode(A3,INPUT);
  }

void loop(){
  analogWrite(46,120);
  Serial.println(analogRead(A3));
  }

```

# Answer
> 1 votes
The analog outputs aren't real analog outputs, they are PWM.

That means that they rapidly switch from OFF to ON and back to OFF again. The analog value is the ration of OFF time to ON time, known as the *Duty Cycle*.

You can convert that rapid switching to a real voltage by passing the signal through a *low pass filter*. The simplest form is the RC filter:

---
Tags: arduino-mega, pwm, hardware, analogwrite
---


# Question
Title: To know the state of USB (Serial) connection (connected or not connected)
```
if (Serial.available()) {
        digitalWrite(7, HIGH);
} else {
        digitalWrite(7, LOW);
}

```

It doesn't seem to be so simple. My testing LED turns on when the USB connection with another program is established, but it doesn't turn off (LOW) when that program exits.

# Answer
> How about having the other program send data to Arduino and Arduino knowing the connection is lost when new data isn't received? I have no idea what Arduino code would do that but just an idea.

That sounds simple enough.

```
const unsigned long MESSAGE_TIMEOUT = 10UL * 1000;  // 10 seconds

void setup ()
  {
  Serial.begin (115200);
  while (!Serial) ;  // wait for Serial to become active
  Serial.println ("Starting");

  }  // end of setup

unsigned long lastMessage;

void processInput ()
  {
  while (Serial.available ())
    {
    char c = Serial.read ();
    // do something with the data
    }  // end of while loop
  }  // end of processInput

void loop ()
  {
  if (Serial.available ())
    {
    lastMessage = millis ();  // remember when we last got input
    processInput ();  // now handle the input
    }

  if (millis () - lastMessage >= MESSAGE_TIMEOUT)
    {
    // we don't seem to be receiving data
    }

  }  // end of loop

```
> 1 votes

# Answer
The problem here is twofold.

Firstly, on Arduinos that don't have a direct USB connection, (i.e., boards like the Uno, Mega, etc that use a separate chip to manage the USB connection) you have no way of knowing if the USB is open or not. That information simply isn't there. The main chip just receives UART serial data (*not* USB data) as it arrives and that is that.

Secondly, even on the boards that have a direct USB connection (Leonardo, etc) there is no *proper* way to know if the port has been opened or not. The CDC/ACM protocol simply doesn't have that kind of information (a bit short sighted of them really). The closest you can do is monitor the DTR and/or RTS signals that are encapsulated in the USB data stream. It is down to the host operating system (and maybe even your own program) to exert those signals properly, so isn't foolproof even then.

To check the status of those lines in your sketch you can examine the *boolean operator* of the `Serial` object:

```
if (Serial) {
  // I am connected
} else {
  // I am not connected
}

```

But as I say that can only work on boards like the Leonard - the other indirect boards think they are always connected, since there is no such thing as a *connection* in UART terminology, only data.
> 2 votes

---
Tags: serial
---


title: Pyserial serial.write() doesn't work

text:
# Question
Title: Pyserial serial.write() doesn't work
I need to communicate with an Arduino. When I use `serial.readline()` to read what Arduino has to say it works fine. But when I use`serial.write('something')` doesn't seem to do anything.

Interesting thing is that if I write the same code in the console or command-line, it works as expected...

Using Python 2.7.

Python code:

```
import serial
import time

arduinoSerialData = serial.Serial('com6', 9600)
time.sleep(1)

while True:
    arduinoSerialData.write('AAA')
    arduinoSerialData.flush()
    sleep(0.5)

```

Arduino code:

```
void loop() {

if (Serial.readString().startsWith("AAA")) {
    digitalWrite(7, LOW);
} else {
    digitalWrite(7, HIGH);
}

delay(500);

```

Again, Python code runs fine from the console, so no idea why this happens.

# Answer
> 2 votes
Closely related to To know the state of USB (Serial) connection (connected or not connected)

---

I would not be using `Serial.readString()` personally. How do you know where the string starts and ends? Just check for three "A" in a row.

Like this:

```
const unsigned long MESSAGE_TIMEOUT = 10UL * 1000;  // 10 seconds
const byte LED = 7;

void setup ()
{
  Serial.begin (115200);
  while (!Serial) ;  // wait for Serial to become active
  Serial.println ("Starting");
  pinMode (LED, OUTPUT);
}  // end of setup

unsigned long lastMessage;
unsigned int countOfA;

void processInput ()
{
  while (Serial.available ())
  {
    char c = Serial.read ();
    if (c == 'A')
      countOfA++;
    else
      countOfA = 0;
    // do something with the data
  }  // end of while loop
}  // end of processInput

void loop ()
{
  if (Serial.available ())
  {
    lastMessage = millis ();  // remember when we last got input
    processInput ();  // now handle the input
  }

  if (millis () - lastMessage >= MESSAGE_TIMEOUT)
  {
    countOfA = 0;
  }

  // warn if no keepalive received
  if (countOfA >= 3)
    digitalWrite(LED, LOW);
  else
    digitalWrite(LED, HIGH);

}  // end of loop

```

Note that this will fail (ie. it will light the LED) if it gets something other than "A" which would include newlines, etc.

What it does it count the number of times it gets the letter "A". If it gets something else it resets the count. If 10 seconds elapse without receiving something, the count resets.

---
Tags: serial, python
---


title: How Add Piezo Buzz to Pong Sketch

text:
# Question
Title: How Add Piezo Buzz to Pong Sketch
I am junior high teacher teaching students how to program using Arduino. I know the basics of programing but the students wanted to program a game which is a little above my skill set. I am using the following sketch (http://www.itopen.it/arduino-pong-with-8x8-led-matrix-and-max7219/) to introduce them to programing games. Thanks to this site I understand most of the code. However I would like to add a line of code that will make a piezo buzzer buzz every time the "ball" hits the pad. I think the code should look something like the code bellow, but I am not sure if it is correct or where I would put it.

```
#define buz 8 // number of pin buzzer connected to
     if (HIT_CENTER || HIT_RIGHT || HIT_LEFT) {
        digitalWrite(buz, HIGH);
        delay(100);
        digiralWrite(buz, LOW);
        }

```

Any help would be appreciated.

# Answer
> 1 votes
The condition `HIT_CENTER || HIT_RIGHT || HIT_LEFT` will always be true. (All three of those `HIT_` values are non-zero constants.)

Instead, you need to test if `getHit()` is non-zero. (To see this, search the sketch for occurrences of `HIT_RIGHT` or `HIT_LEFT`.)

The sketch sets up an event timer (via `ball_timer = timer.every(BALL_DELAY, moveBall);` in `setup()`) so that ball position will update every 200 ms. The `loop()` sequence is: Use `timer.update()` to service timer events. Use `setPad()` to read the paddle position. Use `drawGame()` to update the game picture. Somehow use `checkLoose()` to see if game is over. Use `delay(GAME_DELAY)` to wait 10 ms.

Given that structure of `loop()`, throwing in a 100 ms delay to wait for a buzzer would mess up the game play. You could turn on the buzzer and set up a timer event for turning it off, each time the ball hits the paddle.

More straightforwardly, since a 10 ms beep is likely to be adequately long, you could test for a hit just before `delay(GAME_DELAY)`, and always turn the buzzer off just after that delay. In other words, before the delay say: `if (getHit()) digitalWrite(buz, HIGH);` and after the delay say `digitalWrite(buz, LOW);`.

This supposes that writing HIGH to `buz` turns on the buzzer and that writing LOW turns it off.

# Answer
> 0 votes
**Method 1:** here is what i would have done is use this code snippet we can get the state of HIT,,,if it is not equal to HIT\_NONE ,buzz it

```
 #define buz 8
 if(getHit()!=HIT_NONE){
    digitalWrite(buz, HIGH);
    delay(10);
    digitalWrite(buz, LOW);
    }

```

This is the simpler version where in delay is small,Beaware using delay will completely halt processor operation ,buttons ,joystick serial ports etc everything will be halted.

**Method 2:With Flexible Delay**

```
  #define buz 8
  unsigned long previousMillis = 0;
  const long interval = 200;   /////Specify the delay you want here
  void loop()
   {
     unsigned long currentMillis = millis();  //start timer
     /*
         Remaining Code Is Left As It Is
     */
   }

       ///////////Code Snippet Without Using Delay
   if(getHit()!=HIT_NONE){
   digitalWrite(buz, HIGH);
   if (currentMillis - previousMillis >= interval)
        {
            previousMillis = currentMillis;
            digitalWrite(buz, LOW);
        }
   }

```

But where to add these functions??? Use ***getHit()*** to implement ,,,just like below

```
  int getHit() {
  if(yball != 6 || xball < xpad || xball > xpad + PADSIZE){
    return HIT_NONE;          //returns in case of hit failure so no
                              // buzzer ring
     }
        digitalWrite(buz, HIGH);    //If it has not returned yet makes
        delay(10);                  //sure that it is a successful hit
        digitalWrite(buz, LOW);     //buzzer ring
  if(xball == xpad + PADSIZE / 2){
    return HIT_CENTER;
     }
   return xball < xpad + PADSIZE / 2 ? HIT_LEFT : HIT_RIGHT;
 }

```

yet again u can replace those 3 lines with below one to be more flexible

```
digitalWrite(buz, HIGH);
if (currentMillis - previousMillis >= interval)
     {
         previousMillis = currentMillis;
         digitalWrite(buz, LOW);
     }
}

```

hope this helps.

---
Tags: c++, sketch, piezo
---


# Question
Title: Loading Leonardo bootloader to Atmega32U4 running at 8 MHz
I am currently using ATMega32U4 running at 16MHz using Leonardo. I can only supply 3.7V (I use LiPo batteries) and everything seems fine but this is not as per specs.

To run at 16 MHz, I have to supply 5V but I can't. I do not want to do any step-up. I am thinking of of using 8 MHz crystal so the processor will require only 3.3V, but I need to use a Leonardo.

Has anyone been successful in doing this?

# Answer
> 1 votes
The bootloader does USB. I don't think you can do USB on the 32u4 on only 8mHz.

You can however set the system clock prescaler to divide the main clock by 2, making it run at 8mHz. The bootloader will however still run at 16mHz, but that's probably still fine (though out of spec).

> The AVR USB has a system clock prescaler, and the system clock can be divided by setting the “CLKPR – Clock Prescaler Register” on page 38. This feature can be used to decrease the sys- tem clock frequency and the power consumption when the requirement for processing power is low. This can be used with all clock source options, and it will affect the clock frequency of the CPU and all synchronous peripherals. clkI/O, clkADC, clkCPU, and clkFLASH are divided by a factor as shown in Table 6-10.

To divide the system clock by 2, set the CLKPS0 bit in the CLKPR register. The code for this would be something like this:

```
void setup()
{
  cli();
  CLKPR = _BV(CLKPCE);
  CLKPR = _BV(CLKPS0);
  sei();

  ...

```

just note that everything runs twice as slow. So `delay(1000)` will take 2 seconds. You'll have to update F\_CPU somehow to fix this if this causes a problem.

---
Tags: arduino-leonardo, atmega32u4
---


# Question
Title: Sending a value from one arduino to another
I wonder if it is possible to send a value from one arduino to another.

Basically, I have one arduino measuring let's say weight, but I want to display that value using an lcd in another arduino. Is it possible to send the value to a pin using analogwrite or digital write in the arduino doing the measurement and use analogread/digitalread at the other arduino making the display?

I do not know if this is possible but what is attractive is that one can have several arduino making weight measurements, all showing up in the display of just one central one...

# Answer
You could have the LCD Arduino be an I2C master and all the weighing Arduinos be slaves. There's an example of master/slave communication and wiring here: https://www.arduino.cc/en/Tutorial/MasterReader.

I2C supports up to 128 devices and the wiring is very simple.
> 4 votes

# Answer
Yes it is possible,The answer provides one of the basic methods to do so

Connections

```
   Arduino1          Arduino2
     TX--------------->RX
     RX--------------->TX

```

Arduino1 Sketch:

```
void setup(){
 Serial.begin(9600);
 delay(2000);
}

void loop() {
 ////read sensor data to a variable
 Serial.println(sensorDataVariable);
 delay(2000); //Not to flood serial port
}

```

Arduino2 Sketch :

```
int byteRead;
void setup(){
 Serial.begin(9600);
 delay(2000);
}

void loop() {
  /* check if data has been sent from the computer: */
  while (Serial.available()) {
    /* read the most recent byte */
    byteRead = Serial.read(); //now byteRead will have latest sensor
                              // data sent from Arduino1
  }
  //Write code to display the values to LCD
}

```

hope this helps
> 2 votes

# Answer
To tie multiple Arduinos together you need to come up with some kind of networking topology and some form of networking protocol.

Requirements are:

1. The Arduinos must not (electrically) interfere with each other
2. There must be some way to know which Arduino is sending what and where to

The two points could be addressed by having a separate connection for each Arduino but that ends up complicated, and there are only limited resources on an Arduino for creating such connections (you really need to use the hardware UART ports and the Uno has only 1. The Mega has 4).

A better solution is to use a *bus* system (also known as a *multi-drop network*). There are a number of existing and well supported methods for doing this. In the automotive system the CAN Bus is used. In industry the RS-485 system is heavily used.

Personally I prefer RS-485 since it is well established. There are a number of standard protocols that run on RS-485, such as MODBUS, but for the Arduino world I wrote my own light weight protocol specially which is far simpler to get going with. You can find out more here: https://github.com/MajenkoLibraries/ICSC
> 1 votes

---
Tags: arduino-uno, lcd, analogread, communication, analogwrite
---


title: Fog Machine - On Command

text:
# Question
Title: Fog Machine - On Command
I work with a marching band, and we want to use fog machines for a particular part of the show. I know how to code/program in Arduino, however I am not great in the electrical and technical end. I own two fog machines, and the issue is that we need them to start fogging on command without delay (at least not a long delay, just not early and not late). We cannot exactly stop the show in the middle of a competition to say "wait, the fog is coming soon." We also need them to stop fogging on command.

I have read this article, Motion Triggered Fog Machine and it seems simple enough, however, I do not need or want it to work with a motion sensor. I suppose the easiest way you could help me is to either point me to a tutorial or tell me how to modify that tutorial to my own needs.

# Answer
> 1 votes
Perhaps use a small wireless board like the NRF24L01 (available for around $1 each on eBay). Have one at the fogging machine, similar to the Instructable, but instead of a sensor, you turn the machine on and off when a command arrives. For example, send "0" to turn it off and "1" to turn it on. There are examples with the NRF24L01 library.

Then you have an Arduino in the wings nearby where you press a switch when you need to turn the fogging machine on (this would transmit the signal).

---
Tags: arduino-uno, hardware, system-design, wireless
---


# Question
Title: Why are MOSFETs only giving 8.1V for LEDs, not 12V?
I'm using three PWM outputs from an Arduino Mini Pro to drive the R/G/B parts of some strips of LEDs. The circuit is basically this:

I've got a single 12V power supply, rated at 200W, to light the LEDs and to power the Arduino via the RAW pin, and there are 5 metres of 60LEDs/m RGB LEDs, i.e. a total of 300 LEDs, which should be drawing ~72W according to the spec sheet (14.4W/m).

The problem is that even when the sketch says **`digitalWrite(9, 255); digitalWrite(10, 255); digitalWrite(11,255)`**, the LEDs are considerably dimmer than when connected directly to the 12V supply. My cheap, digital volt meter measures ~8.1V ~~between GND and the PWM pins~~ across the LEDs, not the 12V that the transformer is supplying.

Am I doing something wrong? Does the MOSFET really cause such a large drop in voltage? Is there anything I can do to mitigate it? (It's important to get as much brightness as possible from the LEDs for this project).

# Answer
> 2 votes
By my calculations you are sinking 6 amps:

```
72 W / 12 V = 6 A

```

I have some doubt that the Arduino board is designed to handle that amount of current through its ground plane. Try running a separate ground wire to the MOSFET sources.

I would also be concerned about the gauge of wire you are using, and whether the prototyping board can handle that amount of current.

# Answer
> 0 votes
Your MOSFETs may not be appropriate for driving from a 5V device. I had a similar problem and someone suggested I need to use a MOSFET with a low turn-on voltage, specifically IRLB8743 (http://www.irf.com/product-info/datasheets/data/irlb8743pbf.pdf) which is fully enabled at 4.5V. You might also find that your MOSFETS are getting warm because they are acting as resistors if not fully engaged. In the above datasheet it says "Very low RDS(on) at 4.5V" meaning low resistance when VGS (arduino output voltage) is at 4.5V or more.

Your datasheet is here http://pdf.datasheetcatalog.com/datasheet2/8/0iyt26iogeofcyaowtrx4z7iwiky.pdf and I'd love to be able to tell you how to compare but I'm not sure which values to look at :/

The breadboard itself may also be introducing resistance. If you wiggle the mosfets around and the lights change brightness this is likely.

LEDs have a set forward (turn on) voltage. You can expect to see that voltage drop over LEDs and not more, which does not indicate the problem (current).

---
Tags: led, voltage-level, mosfet
---


title: What is the I2C address of a sensor?

text:
# Question
Title: What is the I2C address of a sensor?
I have connected BMP180 sensor:

to Arduino and was able to read its values with appropriate samples (from `Adafruit BMP085 Library` and `Adafruit BMP085 Unified`).

Apparently, this sensor is sending information via I2C bus.

However, I2C protocol assumes addresses of connected devices.

What are addresses in my case? How to know and/or change them?

Is it possible to connect several BMP180 to a single Arduino?

# Answer
From the datasheet:

> **4.2 Device and register address**
>
> The BMP085 module address is shown below. The LSB of the device address distinguishes between read (1) and write (0) operation, corresponding to address 0xEF (read) and 0xEE (write).

With the Wire library you divide that by 2 (because it handles the read/write bit) so the address for using with Wire is:

```
0xEE / 2 = 0x77

```

Which is mentioned in the Adafruit library:

```
#define BMP085_I2CADDR 0x77

```

> Is it possible to connect several BMP180 to a single Arduio?

You can certainly connect **two** of them. From the datasheet:

> There is an easy way to connect two BMP085 to the same I2C bus: You can use the XCLR input of BMP085 to set one BMP085 part silent while you communicate with the other BMP085 part via I2C and vice versa. The signals can be provided by two digital outputs of the microcontroller, or one digital output and one inverter.

If you have access to the XCLR input (the Adafruit board broke it out, I can't tell with the board in your photo) you could use that method. Otherwise do what some of the other answers suggested, and use an I2C multiplexer.
> 1 votes

# Answer
Line 30 in Adafruit\_BMP085.h clearly give you the address of sensor. Looks like the address is fixed meaning the only way you can connect several of these sensors is using a i2c multiplexer
> 1 votes

---
Tags: i2c
---


# Question
Title: Is it possible to create an electromagnetic wave using PWM?
What would be the simplest way of making an Arduino emit EM waves using PWM (or without)? Theoretically, oscillating a current through a wire would result in an electromagnetic wave, but I don't know if this is possible using an Arduino and if so, how?

# Answer
> 5 votes
I had a toy project a while ago that generated AM radio.

---

## Code

Code for Uno or any Atmega328 based boards:

```
const byte ANTENNA = 9;

void setup()
  {
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)
  }  // end of setup

void loop()
  {
  pinMode (ANTENNA, OUTPUT);
  delay (500);
  pinMode (ANTENNA, INPUT);
  delay (300);
  }  // end of loop

```

---

## Wiring

Plug a wire into digital pin 9:

---

## Theory

The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 kHz, since one toggle turns the output on, and second toggle turns it off.

Then by turning the output pin on and off slowly you effectively have "keyed" output.

Obviously this would not have a long range, but you could amplify the output signal.

---

> What does the timer code do?

It's a bit easier to understand if you look at the datasheet. I did a summary for Timer 1 (and the other two timers on the Atmega328) a while back.

## Timer 1

The lines assigning to TCCR1A and TCCR1B set various bits as per the chart / datasheet. Then OCR1A is the value that the timer counts to, zero-relative, so it counts to 10.

The prescaler is set to 1, so each "tick" is 1/16000000 of a second (62.5 ns). Count 10 of them and you have 625 ns per tick. The timer is configured to toggle an output pin automatically. Since it takes two toggles (on and off) for one frequency "cycle" the period is 1.250 µs. The inverse of that is 800000. Thus the output frequency is 800000 Hz (800 kHz).

---
Tags: arduino-uno, serial, bluetooth, wireless
---


title: how to detect 125khz tags with mfrc 522

text:
# Question
Title: how to detect 125khz tags with mfrc 522
I have just ordered MFRC 522 RFID reader from amzon, and I have also orders 5 RFID tags with keychains and a arduino uno board for my project, I have received RFID reader and tags and I have tested the tags with my Sony xperia NFC. The tags that I received with the readers are working fine but the key chain ones are not working. I think because of the frequency difference 13.56 MHz and 125 KHz. So, please tell will this key chain tags work with the Reader

# Answer
> 2 votes
You are correct NFC is 13.56MHz the key chain ones you are referring to are most likely 125kHz The reader you have will only read 13.56MHz this is the NFC and HID cards. If you want to read the Key Chain ones you will need a reader like this one. Weigand 26 Card Reader Most Phones will not read the 125kHz

# Answer
> 1 votes
You can buy a 125 kHz reader from eBay for around $7. I got one like this:

You can communicate with it (listen to it) with a single serial pin (plus ground and power of course). I have a post about that board which describes the connections.

---

> So, please tell will this key chain tags work with the Reader

No, the 125 kHz tags won't work with the 13.56 MHz reader. However you can work around this (if you want to) by using the 125 kHz tags with a different reader.

---
Tags: rfid
---


title: Can I Implement a PLL on an Arduino?

text:
# Question
Title: Can I Implement a PLL on an Arduino?
Is it possible to create a system like a PLL using an Arduino? I ask this because there are some parts in the PLL system, such as: phase detector, VCO, divider, and I don't know how to make for each part in Arduino board.

# Answer
A PLL is a very complex device which is not something that can easily be created purely in code.

Many microcontrollers include a PLL as part of their oscillator systemm which allows them to run internally at a higher speed than their external crystal. This is not a programmable peripheral that you can use for your own things, but an integral part of the workings of the microcontroller.

While it may be possible to write one in software the results would be very somewhat limited. The best you could hope for is to use timers to measure an incoming frequency and use the results to output another frequency through some means, maybe PWM.

To create a real PLL you would be best off using either a dedicated PLL chip (which you can buy off the shelf) or use some form of programmable logic like a CPLD that has a built in PLL block.

Some microcontrollers, most notably the Cypress PSoC range, have programmable logic blocks built in that may be more suited to your task than an Arduino.

A typical digital PLL looks something like this:

Implementing all that in code would be both tricky and somewhat slow on a little 8-bit MCU with no floating point support. However, the basic principal of what a PLL can be summarised in one simple sentence:

> The frequency coming in determines the frequency going out.

The PLL, or *Phase Locked Loop* is just one method of achieving that desired result.

Another method, which is *not* using any form of PLL, is purely algorithmic and consists of just three things:

Three simple blocks, all of which the Arduino is, to a certain extent, capable of performing.

The first block, the *Frequency Detector*, works out what the frequency of the incoming signal is. That could either be by counting the number of pulses that arrive over a certain time frame, or measuring the time between successive pulses. Which method you use (*Frequency Counting* or *Frequency Measuring*) is really down to what frequency ranges you are using. Frequency Counting is better for higher frequencies, whereas Frequency Measuring is better for low frequencies. There are many examples on the web of how to do both of those using timers on the Arduino.

The *Decision Making* is basically working out what your output frequency wants to be according to your input frequency. This could be as simple as "Output = input * 2", for instance, or something more complex like "Between these frequencies I want to output this frequency, between these frequencies this other frequency, etc". It's entirely up to you.

The third block just takes the decided-upon output frequency and generates it. That could be done using the hardware PWM generation of the Arduino.

All this, though, will be limited to relatively low frequencies (tens of kHz maximum really) though with clever coding you could push it up slightly higher.

One thing that really makes this method differ from a PLL is that you don't get the "PL" portion of it - that is, the phase of the incoming frequency is lost, and the output frequency is running entirely with its own phase. There is little or nothing you can do to synchronise the phases of the input and output like you get with a full PLL.
> 4 votes

# Answer
There are two types of PLLs, hardware PLLs and software PLLs. Majenko has already addressed hardware PLLs so I will leave you to his answer for that.

Software PLLs perform the same function as regular hardware PLLs, but with code, and as a result are constrained by the clock speed and sample rate of the controller they are running on. Usually this means you are limited to sub MHz frequencies. The math and computation necessary to perform this is quite complicated, and I do not expect you would get particularly good performance out of your standard Arduino controller, as all of them lack a floating point unit to perform these types of computations.

If you were to still try and attempt this you would have to do it using integer math only. The faster the CPU, the higher the frequency it will be able to lock on to. The fastest Arduino available today is the Arduino Due. Aside from being fast, the Due can perform 32-bit arithmetic in a single cycle, which should be handy. The frequency limit will be dictated by how many cycles all of your calculations take.
> 2 votes

# Answer
You can absolutely make a PLL using an ATMega microcontroller, and I have made one myself using a ATTiny45. The way I did it is by setting the clock source to the internal RC oscillator, and using that as my VCO (or in this case, Numerically Controlled Oscillator). The internal oscillator can be tuned between 50% and 200% of its nominal frequency by adjusting the OSCCAL register, which can safely be done without stopping the processor. I used the ADC to read the input signal. For the phase detector I programmed the MCU to alternatively add, then subtract the ADC registers from an accumulator register. This is mathematically equivalent to multiplying the incoming signal by a square wave from the local oscillator, and integrating the result. After a fixed number of cycles, I checked to see if the accumulator was negative or positive. If its negative, I set OSCCAL to a "high frequency" which is definitely higher than the input signal. If its positive, I set it to a "low frequency", which is definitely too low. Of course this is a form of Bang–bang control, so its never stable per se, but I found works perfectly. Its much better than my attempts at a PID controller. Looking on my oscilloscope, the is almost no jitter visible between the input system and the internal RC clock, which I outputted on the CLKO pin by setting the appropriate fuse bits.

Although I used GCC and USBTinyISP, I see no reason why my system can't be implemented on Arduino. Setting the fuse bits will require a bit of work though, you can read more here:

http://forum.arduino.cc/index.php?topic=124879.0

If there is enough interest, I can add more detailed information to my answer.
> 2 votes

---
Tags: arduino-uno, programming, arduino-due
---


# Question
Title: IR Receiver interrupt and arduino sleep mode
I need to put my arduino into the sleep mode in order to consume less power. My arduino receives IR data and do some work with it, but I need to make it sleep until there is no data. If the data has appeared it should wake up and do something with data and go back to sleep mode.
Is there any way to do this.
I would be grateful for any help.

# Answer
This is what I have managed to achieve ...

---

## Library

IRLib - GitHub

> Version 1.51 March 2015 Copyright 2013-2015 by Chris Young http://tech.cyborg5.com/irlib/
>
> This library is a major rewrite of IRemote by Ken Shirriff which was covered by GNU LESSER GENERAL PUBLIC LICENSE ...

---

## Code

Modified code (from the demo IRrecord example):

```
/* Example program for from IRLib – an Arduino library for infrared encoding and decoding
 * Version 1.5  June 2014
 * Copyright 2014 by Chris Young http://cyborg5.com
 * Based on original example sketch for IRremote library
 * Version 0.11 September, 2009
 * Copyright 2009 Ken Shirriff
 * http://www.righto.com/
 */

/*
 * IRrecord: records IR signals
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Record a value by pointing your remote at the device
 */

#include <IRLib.h>
#include <avr/sleep.h>
#include <avr/power.h>

const byte LED_PIN = 8;
const byte RECV_PIN = 11;
const unsigned long BAUD_RATE = 115200;
const unsigned long NO_ACTIVITY_TIMEOUT = 2000;  // milliseconds

IRrecv My_Receiver(RECV_PIN);
IRdecode My_Decoder;
IRsend My_Sender;
/*
 * Because this version of the library separated the receiver from the decoder,
 * technically you would not need to "store" the code outside the decoder object
 * for this overly simple example. All of the details would remain in the object.
 * However we are going to go ahead and store them just to show you how.
 */
// Storage for the recorded code
IRTYPES codeType;          // The type of code
unsigned long codeValue;   // The data bits if type is not raw
int codeBits;              // The length of the code in bits

// These values are only stored if it's an unknown type and we are going to use
// raw codes to resend the information.
unsigned int rawCodes[RAWBUF]; // The durations if raw
int rawCount;                   //The number of interval samples

bool GotOne, GotNew;

// added by Nick Gammon
EMPTY_INTERRUPT (PCINT0_vect);

void setup()
{
  GotOne=false; GotNew=false;
  codeType=UNKNOWN;
  codeValue=0;
  Serial.begin(BAUD_RATE);
  while(!Serial);//delay for Leonardo
  Serial.println(F("Send a code from your remote and we will record it."));
  Serial.println(F("Type any character and press enter. We will send the recorded code."));
  My_Receiver.enableIRIn(); // Start the receiver
}

// Stores the code for later playback
void storeCode(void) {

  // added by Nick Gammon
  pinMode (LED_PIN, OUTPUT);
  digitalWrite (LED_PIN, HIGH);

  GotNew=true;
  codeType = My_Decoder.decode_type;
  if (codeType == UNKNOWN) {
    Serial.println("Received unknown code, saving as raw");
    // To store raw codes:
    // Drop first value (gap)
    // As of v1.3 of IRLib global values are already in microseconds rather than ticks
    // They have also been adjusted for overreporting/underreporting of marks and spaces
    rawCount = My_Decoder.rawlen-1;
    for (int i = 1; i <=rawCount; i++) {
      rawCodes[i - 1] = My_Decoder.rawbuf[i];
    };
    My_Decoder.DumpResults();
    codeType=UNKNOWN;
  }
  else {
    Serial.print(F("Received "));
    Serial.print(Pnames(codeType));
    if (My_Decoder.value == REPEAT) {
      // Don't record a NEC repeat value as that's useless.
      Serial.println(F("repeat; ignoring."));
     }
     else {
       codeValue = My_Decoder.value;
       codeBits = My_Decoder.bits;
     }
     Serial.print(F(" Value:0x"));
     Serial.println(My_Decoder.value, HEX);
  }

  // added by Nick Gammon
  pinMode (LED_PIN, INPUT);
  digitalWrite (LED_PIN, LOW);

}

void loop() {

  // added by Nick Gammon
  static unsigned long lastActivity;  // when we last woke
  // sleep if no activity for a while
  if (millis () - lastActivity >= NO_ACTIVITY_TIMEOUT)
    {
    Serial.flush ();  // wait for Serial to finish outputting
    Serial.end ();    // shut down Serial
    noInterrupts ();  // timed sequence coming up

    // pin change interrupt for D11
    PCMSK0 |= bit (PCINT3);  // want pin 11
    PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
    PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13

    set_sleep_mode (SLEEP_MODE_STANDBY);
    sleep_enable();

    byte old_ADCSRA = ADCSRA;
    // disable ADC to save power
    ADCSRA = 0;
    power_all_disable ();  // turn off various modules
    interrupts ();
    sleep_cpu ();
    sleep_disable();
    power_all_enable ();   // enable modules again
    ADCSRA = old_ADCSRA;   // re-enable ADC conversion
    Serial.begin(BAUD_RATE);
    lastActivity = millis ();
    }  // end of no activity for a couple of seconds

 if (My_Receiver.GetResults(&My_Decoder)) {
    My_Decoder.decode();
    GotOne=true;
    storeCode();
    delay(500);
    My_Receiver.resume();
  }
}

```

---

## Explanation

Main changes are in `loop` (near the bottom) where it sleeps if there is no activity for two seconds. This "no activity" test gives it time to catch an incoming pulse stream.

Before sleeping it turns off Serial (to save power), and sets up to detect the pin-change interrupt. It also turns off the ADC, and calls `power_all_disable` to disable various internal modules.

Note that it uses pin-change interrupts on Arduino pin D11 (pin 17 on the chip). For a different processor than the Atmega328P, or a different input pin, you would have to change which pin-change interrupt is used.

I found that I had to use SLEEP\_MODE\_STANDBY rather than SLEEP\_MODE\_PWR\_DOWN, otherwise it seemed to take too long to wake up and handle the incoming pulse.

For testing, I flashed D8 pin to make sure it was working when hooked up in low-power configuration.

---

## Power consumption

I tested with an AX-1838T IR-receiver that I had to hand (same pin-outs as in the Adafruit article).

Measured stand-alone (ie. not connected to the Arduino) it consumed 630 µA, so therefore we could not expect lower power consumption than that.

Connected up to a "bare-bones" board (ie. just the Atmega328P chip, decoupling capacitors, etc.) I measured 1.158 mA when idle.

My tests on my page about power indicate that SLEEP\_MODE\_STANDBY uses 480 µA more power than SLEEP\_MODE\_PWR\_DOWN, so this sounds about right.

```
630 + 480 = 1110 µA

```

You might be able to save more power by operating at a lower voltage. This particular receiver can operate at a lower voltage. As an indication, I tried the setup at 3.3 V (which is out of spec for the processor, but whatever, I was just testing) and it consumed 978 µA when idle. This is a modest saving over the 5 V test.

---

## References
> 7 votes

# Answer
Connect the IR receiver to INT0 or INT1 (pins 2 or 3 respectively). You can use the attachInterrupt function. E.g. attachInterrupt(0, yourfunctionname, LOW). The function being called can be empty, if you only use it to wake up the MCU.

To wake from sleep you need to use the LOW trigger mode. Once waken up you probably want to remove the interrupt handler (`detachInterrupt`), or it will swamp the cpu with interrupts.

(Note that most IR receiver will still use something like 3mA.)
> -1 votes

---
Tags: interrupt, arduino-pro-mini, ir, sleep
---


title: What's wrong with my ESP8266?

text:
# Question
Title: What's wrong with my ESP8266?
After trying to upgrade firmware of ESP8266, it failed. I am not finding any response from it. It's just blinking a red LED.

What will I do now?

---

I had tried to upgrade the firmwire in different ways...but couldn't.The result is that i am not finding any wifi signal response in the network connection ...What's now?

# Answer
The upgrade firmware on the ESP8266 is hardcoded. Attempting to reflash it with known good firmware should restore functionality.
> 2 votes

# Answer
Make sure you have the correct firmware depending on the version of the board you have, the family seems quite big: esp8266 wiki

There's nothing stopping you from experimenting and flashing different versions until you find the one that works.
> 0 votes

# Answer
Make sure that GPIO0 is not shorted to ground. Otherwise, try to reflash the firmware and when finished, leave GPIO0 floating to get out of firmware upgrading mode.
> 0 votes

---
Tags: esp8266
---


title: Unable to Upload

text:
# Question
Title: Unable to Upload
Not able to upload sketches to standalone arduino on breadboard (with Atmega328 bootloaded with blink LED program). Searched on the internet but there is no solution. Help ?

error : avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 5 of 10: not in sync: resp=0x00

OS: Ubuntu 14.04 LTS

# Answer
Make sure the RX, TX pins are not connected to any other circuit when uploading sketches.
> 2 votes

# Answer
Make sure the board selected and port selected are correct. I face this problem many time but they disappear after I remove my other circuit connection and reconnect my arduino board to pc
> 0 votes

---
Tags: atmega328
---


# Question
Title: Is it possible to make an arbitrary lake bottom generator?
I'm trying to generate an arbitrary lake bottom sonar returns using my Arduino.

I would like to seed a function with a "depth." This would be the starting depth. I would then like to randomize a set of parameters each time the function is called. **The output would look something like a time-truncated sine wave. The parameters would include:**

1. Randomized Amplitude of waveform (which wouldn't vary too much)
2. Randomized Period (or frequency) of waveform (also wouldn't vary too much)
3. Randomized exit point. Say the period is 10 seconds but function ends at 7 seconds. This would allow for a changing in depth over time even if random.
4. If possible, I would like to low pass filter the output to smooth any hard transitions.

Any suggestions on where to get started?

# Answer
> 1 votes
A common method of generating realistic-ish 3d terrain is as follows:

Start with a square (as seen top-down), described by the lengths of it's side (all the same), and the height of each of the corners.

Divide each edge in half; for example, add a new point halfway between the north-west point and the north-east point; it's altitude will be the average of the altitude of the two existing points, plus or minus a random number.

Now add a point in the center of the existing square; it's altitude being the average of the north, east, west and south points you've just created, plus or minus a random number.

You now have 4 smaller squares. Repeat this process on the four smaller squares, then the smaller squares within that, and so forth.

You might want to manually do the first few points, tweaking it to get the shape you want, then leave the details to the algorithm. Your random number for the adjustments of the "middle point" heights should be proportionate to the length of the sides; for example, the random altitude adjustment might be a random number up to X% the length; then subtract half of X% of the length. Adjusting X% will give you an area that is more or less "pointy".

---
Tags: sensors, c++, system-design
---


# Question
Title: Two Leonardos on one USB hub - not working properly
I have two Arduino Leonardos here. They do different things, but basically they both emulate a keyboard. Here is an example:

```
const byte SWITCH = 12;

void setup ()
  {
  Keyboard.begin();
  pinMode (SWITCH, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  if (digitalRead (SWITCH) == LOW)
    {
    Keyboard.println ("foo");
    delay (2000);
    }
  }

```

Now I program a second Leonardo with the same code but send "bar" rather than "foo".

Now if I plug these into my PC (running Ubuntu 14.04) using different USB ports, everything works. When the switch is closed I see "foo" and "bar" being typed into whatever application is open.

However ...

If I plug them both into a D-Link 4-port USB hub (model DUB-1340) only the first one works. The other is ignored.

Doing `lsusb` shows this (along with other irrelevant devices):

```
$ lsusb
Bus 003 Device 040: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)
Bus 003 Device 039: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)

```

This happens in both cases (if they are both in the USB hub or not).

---

## My question

Is this proper behaviour that two Leonardos on a USB hub fail to both work? (Perhaps you aren't supposed to plug two identical USB devices in at once).

Or, is this a bug in either:

* The Leonardo USB interface?
* My USB hub?

---

## Update

Further testing revealed that the setup worked OK when plugged into my Mac running OS/X.

Then I went back to Ubuntu and it worked as well! However a mouse that I had plugged into the USB hub now stopped working!

Further investigation reveals that the fourth port on my USB hub is faulty in some way. If I swap the mouse and the Leonardo the Leonardo works but not the mouse.

Following Majenko's suggestion:

> You can try running usb-devices from the usbutils package (should be already installed since lsusb is in the same package) and look for the two Leonardo blocks.

First one:

```
T:  Bus=03 Lev=02 Prnt=50 Port=00 Cnt=01 Dev#= 66 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=02(commc) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=2341 ProdID=8036 Rev=01.00
S:  Manufacturer=Arduino LLC
S:  Product=Arduino Leonardo
C:  #Ifs= 3 Cfg#= 1 Atr=80 MxPwr=500mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=00 Driver=cdc_acm
I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
I:  If#= 2 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbhid

```

Second one:

```
T:  Bus=03 Lev=02 Prnt=50 Port=03 Cnt=04 Dev#= 72 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=02(commc) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=2341 ProdID=8036 Rev=01.00
S:  Manufacturer=Arduino LLC
S:  Product=Arduino Leonardo
C:  #Ifs= 0 Cfg#= 0 Atr= MxPwr=
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceNumber: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bAlternateSetting: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bNumEndpoints: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceClass: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceSubClass: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceProtocol: No such file or directory
/usr/bin/usb-devices: line 79: printf: (none): invalid number
I:  If#= 0 Alt= 0 #EPs= 0 Cls=() Sub= Prot= Driver=

```

---

## Tentative conclusion

Perhaps I somehow damaged that USB port by drawing too much current during testing at some earlier point.

Although ... now the mouse is working in the port where it was not working before, and the Leonardo has stopped working in the 3rd port, when it was previously not working in the 4th port.

Those error messages above must be relevant, but I don't know enough about it to say in what way.

# Answer
> 1 votes
There is no reason I can think of that would stop it working as it should.

`lsusb` is showing both the devices, so they are being detected by the kernel.

You can try running `usb-devices` from the *usbutils* package (should be already installed since `lsusb` is in the same package) and look for the two Leonardo blocks. You should get two blocks like this:

```
T:  Bus=01 Lev=03 Prnt=07 Port=00 Cnt=01 Dev#= 11 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=2341 ProdID=0036 Rev=01.00
S:  Manufacturer=Arduino LLC
S:  Product=USB IO Board
C:  #Ifs= 3 Cfg#= 1 Atr=80 MxPwr=500mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=00 Driver=cdc_acm
I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
I:  If#= 2 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbhid

```

The important bit is the `I:` lines - they show the individual USB interfaces and what kernel driver has been associated with them. For the keyboard, of course, it's the last entry, which is assigned to the `usbhid` driver.

Another good diagnostic is `dmesg -w`

Run that with both Leonardos disconnected. Plug one in and it should show it registering as a USB device. A few moments later you should get a pair of lines like:

```
[ 2106.937086] input: Arduino LLC USB IO Board     as /devices/pci0000:00/0000:00:1a.7/usb1/1-1/1-1.4/1-1.4.1/1-1.4.1:1.2/0003:2341:0036.0006/input/input21
[ 2106.990523] hid-generic 0003:2341:0036.0006: input,hidraw4: USB HID v1.01 Mouse [Arduino LLC USB IO Board    ] on usb-0000:00:1a.7-1.4.1/input2

```

That is the board being associated with an input device (in this case input 2).

Repeat it with the second Leonardo and see if the same appears, but this time with a higher input number (it would be 3 on mine if I had a second Leonardo).

The fact that the two Leonardos work together normally means that they should be working fine in any arrangement, so if the OS is seeing it all fine but the data isn't getting through, then my money is on the hub. It looks quite a new hub, so it may have a few bugs in it that are yet to be ironed out.

USB devices are identified to the drivers using the VID and PID, but to the kernel the USB device is just a chain of bus/port numbers. For instance my Leonardo above is identified as:

```
1-1.4.1

```

That's USB bus 1, downstream port 1 (root hub - normally only has 1 port), which connects to a hub (the one built into the computer to drive multiple ports) which then has downstream port 4 connecting to a hub (on my desk) which then has downstream port 1 connecting to the device. Nothing else can be connected to that same combination of downstream ports - it's physically impossible, so it's uniquely identified.

---
Tags: c++, arduino-leonardo, usb
---


title: TFT touch, 4bit data transfer

text:
# Question
Title: TFT touch, 4bit data transfer
I followed instructions to get my TFT to work.

I want to use other pins on the Arduino Uno for other I/O, so how can I use 4-bit data transfer for the TFT touchscreen?

# Answer
You read the datasheet for the chip that is on your TFT display (whatever that is) and find if it even supports a 4-bit mode. It probably doesn't. I have a large number of TFT screens here and I don't recall any of them using parallel 4-bit. It sounds like you actually want a TFT screen that works of SPI rather than a parallel interface. Those *are* available, but by using SPI the screen updates are considerably slower.
> 1 votes

---
Tags: 1-wire
---