title: Simple Multiple RX/TX SoftwareSerial?

text:
# Question
Title: Simple Multiple RX/TX SoftwareSerial?
In this project I will be using multiple ESP8266 WiFi modules (4) connected by software serial to an Arduino Leonardo Micro (1 UART). I plan to rotate between all 4 (starting with 2): Open port, write, read response, close port, move on....

This is a very barebones version of my code to address this one issue. Works flawlessly with a single (always open) connection, but it does not work when I close Ser1 (even if I don't start Ser2!!!) Is the xxxx.end(); command broken or something? Or am I doing something wrong? :/

Note: This code sends "AT" to the module, it responds with "OK"

When adding Ser2, LED flashes on Arduino periodically indicating it is writing to serial monitor, but nothing appears...

Code:

```
#include <SoftwareSerial.h>

SoftwareSerial Ser1(10, 8);
SoftwareSerial Ser2(16, 7);
SoftwareSerial Ser3(14, 4);
SoftwareSerial Ser4(15, 2);
//Set up (RX, TX) pins^

void setup() {

  pinMode(10, INPUT);
  pinMode(16, INPUT);
  pinMode(14, INPUT);
  pinMode(15, INPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(2, OUTPUT);
  Serial.begin(9600);
  //Set up Serial Monitor on host computer

}

void loop()
{

  delay(1000);

  Ser1.begin(9600); // open Ser1

  Ser1.write( 'A' );
  Ser1.write( 'T' );
  Ser1.write( '\r' );
  Ser1.write( '\n' );   // sends the line: "AT" with appropriate format

  Ser1.listen(); // make sure it's listening

  while ((Ser1.available() > 0)) { //Read entire string
    Serial.write(Ser1.read()); //Dump it to serial monitor
  }

  //Should Respond with "OK"

  Ser1.end(); //close Ser1 port
  //This breaks the code for some reason....

  Serial.println(); // Extra line in Serial Monitor for neatness

  Ser2.begin(9600); // open Ser2

  Ser2.write( 'A' );
  Ser2.write( 'T' );
  Ser2.write( '\r' );
  Ser2.write( '\n' );

  Ser2.listen();

  while ((Ser2.available() > 0)) {
    Serial.write(Ser2.read());
  }

  Ser2.end();

}

```

# Answer
> 2 votes
As Ignacio mentions, you should not be stopping and starting the serial ports. Instead just switch between them with `.listen()`:

> Enables the selected software serial port to listen. Only one software serial port can listen at a time; data that arrives for other ports will be discarded. Any data already received is discarded during the call to listen() (unless the given instance is already listening).
>
> SoftwareSerial::listen() Manual Page

So your code would be written as:

```
#include <SoftwareSerial.h>

SoftwareSerial Ser1(10, 8);
SoftwareSerial Ser2(16, 7);
SoftwareSerial Ser3(14, 4);
SoftwareSerial Ser4(15, 2);
//Set up (RX, TX) pins^

void setup() {
  Serial.begin(9600);
  Ser1.begin(9600); // open Ser1
  Ser2.begin(9600); // open Ser2
}

void loop()
{

  delay(1000);

  Ser1.listen(); // Select Ser1 for receiving
  Ser1.print(F("AT\r\n"));

  delay(1000); // Give it time to send a response or you'll get nothing!

  while ((Ser1.available() > 0)) { //Read entire string
    Serial.write(Ser1.read()); //Dump it to serial monitor
  }

  //Should Respond with "OK"

  Serial.println(); // Extra line in Serial Monitor for neatness

  Ser2.listen(); // Select Ser2 for receiving
  Ser2.print(F("AT\r\n"));

  delay(1000); // Give it time to send a response or you'll get nothing!

  while ((Ser2.available() > 0)) {
    Serial.write(Ser2.read());
  }
}

```

---
Tags: serial, esp8266, softwareserial, arduino-leonardo, uart
---


title: Logic Gates Identifier

text:
# Question
Title: Logic Gates Identifier
I want to build a program which identifies logic gates connected to Arduino, by testing the output with changing the input voltage...

Here is the code:

```
int output1 = 0;   //Change output pins HERE
int output2 = 1;   //and HERE
int input = 2;     //Change the input pin HERE, where we will read the data (0 or 1)

void setup() {
  pinMode(output1, OUTPUT);
  pinMode(output2, OUTPUT);
  pinMode(input, INPUT);
  Serial.begin(9600);  // Start serial communication at 9600 bps
}

void loop() {
  int result[12];
  for(int i = 0; i < 2; i++) // For failure test, it runs 3 times
  {
    digitalWrite(output1, LOW);
    digitalWrite(output2, LOW);
    delay(1000);             //Wait for 1sec
    result[i * 4] = digitalRead(input);
    digitalWrite(output1, LOW);
    digitalWrite(output2, HIGH);
    delay(1000);             //Wait for 1sec
    result[i * 4 + 1] = digitalRead(input);
    digitalWrite(output1, HIGH);
    digitalWrite(output2, LOW);
    delay(1000);             //Wait for 1sec
    result[i * 4 + 2] = digitalRead(input);
    digitalWrite(output1, HIGH);
    digitalWrite(output2, HIGH);
    delay(1000);             //Wait for 1sec
    result[i * 4 + 3] = digitalRead(input);
  }
  if(result[0] != result[4] && result[0] != result[8] && result[1] != result[5] && result[1] != result[9] && result[2] != result[6] && result[2] != result[10] && result[3] != result[7] && result[3] != result[11]) // See if the results don't matches...
  {
    Serial.println("Input read error, please try again!");
  }
  if(result[0] == 0 && result[1] == 0 && result[2] == 0 && result[3] == 1) // AND gate
  {
    Serial.println("This is an AND gate");
  }
  else if(result[0] == 0 && result[1] == 1 && result[2] == 1 && result[3] == 1) // OR gate
  {
    Serial.println("This is an OR gate");
  }
  else if(result[0] == 1 && result[1] == 1 && result[2] == 1 && result[3] == 0) // NAND gate
  {
    Serial.println("This is a NAND gate");
  }
   else if(result[0] == 1 && result[1] == 0 && result[2] == 0 && result[3] == 0) // NOR gate
  {
    Serial.println("This is an NOR gate");
  }
  else if(result[0] == 0 && result[1] == 1 && result[2] == 1 && result[3] == 0) // EXOR gate
  {
    Serial.println("This is an EXOR gate");
  }
  else if(result[0] == 1 && result[1] == 0 && result[2] == 0 && result[3] == 1) // EXNOR gate
  {
    Serial.println("This is an EXNOR gate");
  }
  else // If there is no match...
  {
    Serial.println("This is not even a gate");
  }
}

```

It always gives back 1s... I have tested with leds, it works perfectly by changing the input, but as soon as serial.begin is declared in setup, it fails to work, the just stays on and I said, the program just gives back 1s.

What I'm missing?

Thanks!

# Answer
> 1 votes
Arduino uses pins 0 and 1 for Serial. Use other pins in your sketch

---
Tags: arduino-uno
---


title: Serial speed for debugging/logging

text:
# Question
Title: Serial speed for debugging/logging
I have a sketch where I want to check my nRF24L01's and they work great.

However, due to Serial.print(ln) statements I noticed there is a lot of delay. Is this normal?

I mean, is it better not to user Serial.print at all during speed checks? (probably not).

What other options would be best? Some I can think off:

1. Put all debugging info in an array and print it later (downside: more programming needed, probably special logging class)
2. Print less (bad solution I think, also makes logging more difficult to read)
3. Use another Arduino (so sending it by other means, via Wire or so? Never tried this, but I think this might be the best solutions.
4. I couldn't find any print that does not wait until ready sending (which would cause minimal 'downtime' for the running sketch.

I did not try the third option but I think that would be ideal (but cost another Arduino). Since in my project I eventually use multiple AVRs (mostly Arduino's), I was thinking about sending all logging info to one Arduino and let that Arduino print out everything, that means, only one serial monitor, and no delays (or barely) for all others (where it matters).

Do you think this is the best for logging/debugging? Or are there better methods for use with an Arduino?

# Answer
> 1 votes
I use a couple of techniques to measure code timing or to instrument it with mimimally disturbing time-critical code:

* Run the code-under-test in a loop of N times, taking the difference in the system clock before and after the loop. If the code-under-test is short enough that the loop housekeeping timing might significantly affect the measurement, I'll unroll part of the loop - cut and paste several repetitions of the code-under-test into the loop - to reduce the relative effect.
* Toggle an output pin at entry and exit of the code segment-under-test. Measure the pulse width with an oscilloscope, or with a DVM that includes frequency and duty-cycle measurement and calculate the pulse-width from that. I write directly to the I/O port to keep the influence of the software probes (added code) to a minimum.
* If I'm trying to collect debugging data without disturbing the code timing, then as you suggest, I store the raw data in an array (raw, to keep it small), dump the raw data in hex to the terminal after the test-run, and expand/interpret it on my PC (to address your point 1., more programming needed). You'll still need some extra programming but it will be in a separate domain (your PC), it can be big, dirty, and slow, and requires less disturbance to your embedded source-code.

---
Tags: serial, debugging, logging
---


title: Bluno + PS3 controller?

text:
# Question
Title: Bluno + PS3 controller?
I'm seeking information about connecting a PS3 controller using Bluetooth to an Arduino.

Bluno cards could be an integrated solution for that, but can it work?

Also, I've seen some tutorials using a USB shield + a Bluetooth dongle: in this case, at some setup steps a USB connection is needed between the PS3 controller and the Arduino. It is still the case with a Bluno card?

# Answer
> 0 votes
While not strictly impossible, using a PS3 controller with the Bluno (ATmega + CC254x) is essentially impractical.

The PS3 controller is either a USB device, or a *classic* Bluetooth device.

* A USB device can only communicate with a USB host. Neither the ATmega nor the CC254x on the Bluno is capable of being a USB host. An add-on USB host shield would cost more than simply buying a platform suitable for fulfilling the *entire* requirement natively.
* The CC254x only speaks Bluetooth Low Energy. It is not compatible with classic Bluetooth devices. To communicate with the PS3 via Bluetooth you would need to add a Bluetooth classic radio to the system.

If you wish to use a PS3 controller you should pick a non-Arduino platform having native USB Host capability or native classic Bluetooth capability.

Otherwise, if you wish to use an Arduino-like platform, pick an earlier generation controller with either a very old wire-per-function interface or a simple synchronous serial interface, for example a PS2 controller.

---
Tags: bluetooth, bluno
---


title: Arduino timer ctc mode 4 vs 14

text:
# Question
Title: Arduino timer ctc mode 4 vs 14
I'm trying to gain an understanding of the Arduino timer and interrupts, particularly the CTC-modes 4 and 12. I wrote a small example in which I generate interrupts while the mainloop sleeps for 1 second and the display how many interrupts occured. It can toggle between mode 4 and 12 with the #if 1.

This works fine for mode 12 ( 50 interrupts/sec ) but in mode 4 it gives -12k interrupts / seconds... unless when I set OCR1A to 39999 again inside the ISR then it does give the expected 50 interrupts/sec, but I'd like to know why.

I think my confusion might be related to not understanding the table-header explaining the modes where it says "Update of OCR1x at". What is meant with that ( who updates it, and to what value? or do I need to update it in the ISR ) ? Why would OCR1x be updated in mode 12 ( the table seems to state that it is) ? And it seems to work, even if I don't update it...?

Also, the only difference between mode 4 and 12 seems to be the register used for comparing to the timervalue (OCR1A vs ICR1)... but what is so fundamentally different between those? Why are there 2 options and what is the argument to choose for either mode 4 or 12 ?

Update: The issue seems to be related to initialization-order. If OCR1A is set to 39999 at the current location it gets reset to 0 a few lines further. When moving it after TCCR1A = TCCR1B = 0; then OCR1A keeps the value. So it's not necessary to set it on every interrupt. This also explains why we get -12k counts on mode 4 (because we are comparing OCR1A in that mode, comparing to 0 and generating loads of interrupts)...

Any insight into why the initialization-order matters in this case would be appreciated.

Thanks in advance!

```
volatile int isr1 = 0;

ISR(TIMER1_COMPA_vect)
{
  // this is called every time our timer-compare matches to ICR1 or OCR1A
  isr1++;

  // when using the #if part below, we need to do this, or we end up with weird values for isr1 ( around -12.000 )
  // If we set it to the original value then we get 50 interrupts per second...
  OCR1A= 39999;
}

void setup() {

  Serial.begin(115200);
  delay(50);

  ICR1 = 39999;                   // 50Hz signal @ 16MHz clock
  OCR1A= 39999;

//TIMSK1 |= 1 << ICIE;            // bit 5: Input Capture Interrupt Enable (execute interrupt when TIFR1.ICF flag is set)
  TIMSK1 |= 1 << OCIE1A;          // bit 4 : Enable the Timer-Output-CompareA-Match Interrupt

  TCCR1A = TCCR1B = 0;            // reset timer-config flags
   // An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCF1A or ICF1 Flag,
   // depending on the actual CTC mode. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value.
#if 1
  // Arduino Datasheet 20.12.2. : The counter value (TCNT1) increases until a compare match occurs with OCR1A, and then TCNT1 is cleared.
  TCCR1B |= 1<<WGM12;             // code 4 (CTC, compare with OCR1A, Immediate update of OCR1x, overflow on MAX)
#else
  // Arduino Datasheet 20.12.2. : The counter value (TCNT1) increases until a compare match occurs with ICR1, and then TCNT1 is cleared.
  TCCR1B |= 1<<WGM13 | 1<<WGM12;  // code 12 (CTC, compare with ICR1, Immediate update of OCR1x(?), overflow on MAX)
#endif

  // using a prescaler of 8, which "slows down" the clockticks by factor 8.
  // 1 clocktick takes 0.5 microseconds, so 39999 clockticks need 19999,5 microseconds
  // 1 second = 1.000.000 microseconds, so we get 50 interrupts per second
  TCCR1B |= 1<<CS11;   // timer CS11 = clki/o/8, 1 tick per 0.5 microseconds
}

void loop()
{
  delay(1000);            // wait 1 second
  Serial.println(isr1);   // print how many interrupts we had in that second
  isr1 = 0;               // and reset for the next second.
}

```

# Answer
As described in the operation part of the datasheet section, `OC1x` is *double-buffered*; the code sets a shadow buffer to a given value and then at some point the hardware copies the shadow buffer to the register that controls operation. "Immediate" means that the buffer is completely transparent since the value is copied immediately.

The difference between modes 4 and 12 is that mode 4 allows the use of ICP1 for input capture and mode 12 allows the use of OC1A for waveform generation.
> 1 votes

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


title: Arduino 3.3V Conversion

text:
# Question
Title: Arduino 3.3V Conversion
I am fairly new to Arduino. As far I know all official Arduinos run on 5 volts. Or there is Arduino versions that run from 3.3V? I need use Arduino with devices which chipsets all use 3.3V logic level. Do I need modify Arduino to make it 3.3V powered, like described in this Tips, or there is another way? I plan get Arduino UNO R3 ATmega328P board (comes with bootloader for Arduino UNO ZT).

# Answer
Arduino Pro Mini comes in 3.3v and 5v versions.
> 1 votes

# Answer
You can use different possibilities:

1. Use Arduinos which are already 3.3V by default (like Pro Mini, Due if I recall right)
2. (removed after valid comment of minto below)
3. Use 5-\>3.3V adapters, most general devices have adapters which can be bought separately (for under 1$) to convert 5 to 3.3V (including logic level converters)
> 0 votes

# Answer
What about just getting the bare chip so you can run it at whatever rail you want? Seems like the simplest and easiest solution.
> -1 votes

---
Tags: arduino-uno, atmega328, voltage-level, digital-analog-conversion
---


# Question
Title: Which component is described as a "jumper" (NOT jumper wire) when working with a motor shield?
In this video I'm watching then instructor talks about using "jumpers". He's got a motor controller shield and at first he says that "during the making of this video we only had 1 jumper, thus only Pin 4 is working", and that as a result he could only move a motor/wheel in 1 direction.

He proceeds to find another jumper, uses it to make Pin 5 work, and then he can reverse polarity and change the direction the the wheel spins.

At first I thought that he must mean header pins, but when he holds the tiny component up, it looks like it's something else:

I read about a "power jumper" on an Adafruit page, but it only applied to one version of the Arduino and sounded like it was to do with Power joining (using the same power source for the motor and controller), so I really don't know if that's the same thing.

# Answer
It's one of these (or similar). It connects two adjacent male header pins.
> 2 votes

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


# Question
Title: Arduino MotorShield code running but not motors
I have a motor shield V2 on my Arduino, i compile the codes just fine and i'm trying to just run the example dc motor test. The code compiles the serial is printing out the "tick tock ...." but the motors are not running. They ran once before on my mac though.

Using a 9v battery to power a basic Dc motor.

I'm using the right ports on pc. Same exact port for motor as the code tells. I'm not sure where i am wrong. TYIA

# Answer
Turns out the pins connecting the shield to the Arduino are quite loose and didn't "touch" the Arduino.
> 1 votes

# Answer
> Using a 9v battery to power a basic Dc motor.

Don't do that. These were designed for early transistorized radios, which needed a moderately high voltage but very low current.

There are very few motors with suitable low-current coil characteristics to be driven by such a battery. Others might work at best briefly before killing the battery.

If you need around 9 volts for a motor project, you should probably use 6 or so AA cells.
> 0 votes

---
Tags: arduino-uno, shields, arduino-motor-shield
---


title: Wake up Arduino Uno by RTC

text:
# Question
Title: Wake up Arduino Uno by RTC
I intend to make the device runs about couple hours a day(let say 2hrs) -\> go to deep sleep -\> wake up in next 7 days -\> repeat the process.

I got the code from one of member here (DotPi) which I can able to make the device wake up every 10 seconds and then back to sleep. When it wakes up, the LED is flashing.

My question is how to make the LED flashes for certain amount of time. For example from 7pm to 8 pm. After that the device should go to sleep again and wait for the next alarm triggered.

I was trying to use the while loop for that but the LED always flash and never go back to sleep :(

# Answer
In your while loop, you never check the time again, so when the while loops hits, you will never leave it. You need to request the time again. Something like:

```
while ( now.minute()>0 && now.minute() < 30)
{
   digitalWrite(ledPin, HIGH);
   delay(100);
   digitalWrite(ledPin, LOW);
   delay(1000);
   now = rtc.now(); // check time again
}

```
> 0 votes

---
Tags: arduino-uno, sleep
---


# Question
Title: How to understand the "power economy" of a voltage up-converter (boost converter)?
My online video Arduino instructor makes use of various devices to amplify signals, currents, and voltages. This seems like magic to me.

For instance, he has 4 AA batteries with 1.2V each. He says "that's not going to be enough for Arduino" so he then passes the power through a voltage up-converter and increases it to 9V.

I'm going to assume there must be some tradeoff here, because otherwise we can just use a giant string of these up-converters to give the world infinite energy from a single AA battery. I found the Wikipedia articles on this topic a little hard to understand, but basically gathered that if Voltage is boosted then it's at the expense of current. My questions are:

1. Is my understanding correct (higher voltage = lower current)?
2. If the current decreased then why was this still an adequate power source for Arduino? Does current not matter?
3. What are the practical limits of this type of conversion?

I would appreciate a plain-language (easy to understand) answer. I'm also kind of curious how the conversion works, but I assume that will be highly technical.

# Answer
He is describing a boost converter which steps up voltage at the expense of current. To quote from the Wikipedia page on that subject:

> A boost converter (step-up converter) is a DC-to-DC power converter that steps up voltage (while stepping down current) from its input (supply) to its output (load). It is a class of switched-mode power supply (SMPS) containing at least two semiconductors (a diode and a transistor) and at least one energy storage element: a capacitor, inductor, or the two in combination.

As an example, an Arduino Uno consumes around 50 mA from the power jack (at 9V) running a "do nothing" sketch like this:

```
void setup () {}
void loop () {}

```

You could say that this is consuming 450 mW of power.

```
9V * 0.050A = 0.450W

```

To run from a lower voltage the boost converter (say, 3V) you still need to get 450 mW of power, so therefore it will consume a higher current:

```
0.450w / 3V = 0.150A

```

In other words, we now need 150 mA (3 times the current) since we have 1/3 of the voltage.

Also, these converters are not 100% efficient. Say a particular converter is 90% efficient, that means it requires even more current (150mA / 0.9 in this case, being 166 mA).

The efficiency is not linear anyway. It varies somewhat depending on the input voltage and the load. There is a question and answer on Electronics Stack Exchange (Boost Converter Efficiency goes down as Duty Cycle goes up?) which discusses this.

---

> Is my understanding correct (higher voltage = lower current)?

Yes - in the sense that the device consumes *power*. Thus a higher voltage requires a lower current to deliver the same power. Conversely, if you drop the voltage you need to increase the current to get the same power.

> If the current decreased then why was this still an adequate power source for Arduino? Does current not matter?

Yes it matters. You need a certain voltage, with the *capability* of providing enough current. In this particular case if your batteries can supply 166 mA then the Arduino can still run.

> What are the practical limits of this type of conversion?

You will eventually exceed the capacity of your battery to supply enough current. A more elaborate Arduino circuit may involve LEDs and motors. The higher current drain may exceed what the battery can supply, or possibly it will just be drained quickly.

Another factor is that batteries are less efficient when supplying higher current (the quoted mAh figure for a battery is usually for quite a low current). In other words, if you double the current drawn from a battery, the time the battery lasts is not half the time, it is *less* than half the time. One of the reasons for this is that batteries have an equivalent series resistance (ESR). At higher current drains there is a larger voltage drop over that resistance (some power gets turned into heat, in other words). Thus it isn't practical to try to get 10 amps from an AA battery. The battery will just get very hot.

---

> For instance, he has 4 AA batteries with 1.2V each. He says "that's not going to be enough for Arduino" so he then passes the power through a voltage up-converter and increases it to 9V.

This is actually quite inefficient in the first place. The Arduino nominally can run from 5V (if sent directly to the 5V pin on the board) and 4 * 1.2V is 4.8V which should be close enough for practical purposes.

His idea is to step up the 4.8V using a boost converter to 9V (which in itself has some inefficiency) and then use the voltage regulator on the Arduino to drop the 9V back to 5V which is also inefficient because some power is now being dissipated as heat.
> 3 votes

---
Tags: power, voltage-level, voltage, convert
---


# Question
Title: Can an Arduino be used to read data from a serial port?
People often use Arduinos to send data over serial to other peripherals (flashing firmware onto modules, etc) by pulling RES to ground, connecting the TX and RX pins to the device being programmed, and then sending data to the Arduino over serial. As an alternative, one could also remove the ATmega instead of grounding RES.

That being said, there should be no reason why one could not receive data from a connected device in the same way. However, no matter what I try, I never succeed in using an Arduino to relay serial input from another device over USB.

I have even tried setting up a simple echo to no avail (even though the TX and RX LEDs flash):

Is it even possible?

# Answer
> 1 votes
Yes, it can, and the wiring diagram you have drawn works perfectly for me using `minicom` in Ubuntu.

The majority of serial communication is bi-directional anyway - especially when using it to program a device.

There is absolutely no difference between interfacing the built-in USB-\>UART adaptor to an external device of your choice and interfacing it with the ATMega328P chip. Just because the ATMega328P chip is on the same board doesn't make it in any way special - it is just a UART interfaced device.

If your setup is not working you can try:

1. Physically remove the ATMega328P chip to see if that is interfering even when held in reset
2. Check for software that may be interfering with your communication, such as the notorious ModemManager.

---
Tags: arduino-uno, serial, arduino-nano, usb, softwareserial
---


# Question
Title: Arduino: Digitally Muti-Switch - What is the proper term for hardware?
I have recently purchased a RoboMower. Like most of the automated mowers these use electric-fence wiring to mark the borders of the property and keep a small charge on those wires so that the mower can tell where the borders are. The RoboMower I purchased is rated for 3/4 of an acre and I have 2.25 acres to mow.

As a result I was thinking of breaking my yard into multiple 3/4 or less acre zones and using an Arduino to shift which zone is active/has current in it so that the mower would follow those boundaries. The base station would be in a place where all zones overlapped slightly. Based on what day of the week it was, the Arduino would activate the proper zone, and the mower would go out and mow in that zone because it was active. I'd clearly have to schedule this so that the switch did not happen when the RoboMower was actively mowing or it would cause all sorts of issues.

In any case, my question is: What is the hardware called that I would need in order to activate one zone or the other? Is that called a digital switch or something else? Is there such a thing of one switch that would be able to switch multiple zones, or would I basically need a bunch of switches to individually control each zone?

Each zone is a loop of wire and therefore there would not be any shared wires between the zones.

# Answer
The technical term of what you're looking for is **demultiplexer**. Note that the demux itself will not be enough to activate the zone, it will simply allow you to choose between different zones based on its input. It is still up to you to provide any further electronics required to enable the appropriate zone.
> 1 votes

---
Tags: arduino-uno, hardware, switch
---


# Question
Title: How to declare and use "Variabled arrays" inside arrays
Good day folks. I'm new here and have been starting to be enthusiast in Arduino. I have a problem and I don't know what I should do, or whether I did something wrong regarding an array of arrays. Surfed on the internet to find a bunch of examples but the only difference is that they don't use arrays that have been declared to have a name inside array.

Every array inside array I see that works is like this:

```
byte array[2][4] = { {1,2,3,4}, {5,6,7,8} };
Serial.println(array[0][2]); is equal to '3'.

```

But mine is like this:

```
byte arrayX[4] = {1,2,3,4};
byte arrayY[4] = {5,6,7,8};

byte arrayZ[2][4] = { arrayX[4], arrayY[4] };

Serial.println(arrayX[2]); is equals to '3'.
Serial.println(arrayZ[0][2]); is equal to '0'.

```

Why?

Below is what in reality I am experiencing. I hope someone can try this out too.

```
softAddr = cycle * 2;

```

is an expression I used for looping where cycle is the iterated variable

```
for (byte cycle = 0; cycle < 7; cycle++) {}

```

I did a simple simulation and I guess the way I initialize the parent array, it initializes a new array in the name same from the declared variables but separate.

```
byte arrayX[4] = {1,2,3,4};
byte arrayY[4] = {5,6,7,8};

void setup() {
  Serial.begin(9600);
  byte glass[2][4] = {arrayX[4], arrayY[4]};
  Serial.print(F("OLD 1: ")); Serial.println(arrayX[0]);
  Serial.print(F("OLD 2: ")); Serial.println(arrayX[1]);
  Serial.print(F("NEW 1: ")); Serial.println(`glass[0][0]`);
  Serial.print(F("NEW 2: ")); Serial.println(`glass[0][1]`);
}

```

output:

> OLD 1: 1
>
> OLD 2: 2
>
> NEW 1: 0
>
> NEW 2: 0

//answered realized

I forgot that the array I put inside the array already had its data based on its index and the `[4]` resulted to nothing or 0 since there is no value at index `[4]` (knowing, indexes where 0, 1, 2, 3 on a 4 sized array). I realized this after I made a simple loop declaration not instantly like this:

```
byte arrayZ[2][4] = { arrayX[1], arrayY[1] };

```

But like this:

```
byte arrayX[4] = {10,11,12,13};
byte arrayY[4] = {20,21,22,23};
byte arrayZ[2][4];
void setup() {
  Serial.begin(9600);
  for (byte parent = 0; parent < 2; parent++) {
    for (byte child = 0; child < 4; child++) {
      if (parent == 0) {
        arrayZ[parent][child] = arrayX[child];
      } else {
        arrayZ[parent][child] = arrayY[child];
      }
    }
  }
  for (byte parent = 0; parent < 2; parent++) {
    for (byte child = 0; child < 4; child++) {
      Serial.print(F("value: ")); Serial.println(arrayZ[parent][child]);
    }
  }
}

```

Output:

> value: 10
>
> value: 11
>
> value: 12
>
> value: 13
>
> value: 20
>
> value: 21
>
> value: 22
>
> value: 23

Resulting in simply like this:

```
byte arrayZ[2][4] = {
  {arrayX[0],arrayX[1],arrayX[2],arrayX[3]},
  {arrayY[0],arrayY[1],arrayY[2],arrayY[3]}
};

```

# Answer
Something is wrong with your type description:

```
byte arrayX[4] = {1,2,3,4}; byte arrayY[4] = {5,6,7,8};

byte arrayZ[2][4] = { arrayX[4], arrayY[4] };

```

Serial.println(arrayX\[2\]); is equals to '3'.

This is normal ... arrayX\[0\] = 1, arrayX\[1\] = 2, arrayX\[2\] = 3

However, the next one is not good:

```
byte arrayZ[2][4] = { arrayX[4], arrayY[4] };

```

You are declaring a byte array, but you add arrayX\[4\] and arrayY\[4\] which, where arrayX\[4\] is the 5th elements of arrayX but it has only 4 elements, so it points to memory outside the array (probably into the next array.

```
byte arrayX[4] = { 1, 2, 3, 4 };
byte arrayY[4] = { 5, 6, 7, 8 };

byte* arrayZ[2] = { arrayX, arrayY };

Serial.print(arrayZ[0][2]);

```

This should print 3 (not tested).
> 3 votes

---
Tags: array
---


title: MQTT client on Arduino + SIM900

text:
# Question
Title: MQTT client on Arduino + SIM900
I have used the pubsubclient library for Arduino for communicating with an MQTT broker in the past, however the library works only with Ethernet connecction. I need to use GSM in my application and am using the SIM900 at the moment. However, I cannot seem to find any library for MQTT communication using an Arduino as MQTT client and SIM900 as gateway. I found this to be surprising as there must surely be many instances where one would want to upload data from Arduino to a MQTT broker in a mobile scenario where cellular network is the only option (in place of Ethernet). So my questions are:

1. Is it possible to use the Arduino as MQTT client and SIM900 as gateway for communicating with an MQTT broker? Are there any libraries for the same?
2. What is the current standard way (gateway / communication protocol) of uploading some sensor data from Arduino to an internet server in a mobile scenario (i.e., where Ethernet is not an option)?

# Answer
> 4 votes
MQTT Library for SIM800 GSM Modem is available at ElementzTechBlog, ElementzGithubRepository

**Functionalities:**

**Auto connect**

```
   Automatically connect to TCP and to MQTT server.

```

**connect function**

```
   This function can be used to connect your client to MQTT broker.
   Use only if you do not use Auto connect functionality.
   Optionally  you can use username, password, WILL topic and WILL Message.

```

**OnConnect CallBack function**

```
   This call back function is called when MQTT connection is established.
   You can call subscription and publish functions inside it (according to your need).

```

**publish function**

```
   This function can be used to publish messages to different topics.
   You can select  QoS levels and RETAIN flag according to your need.

```

**subscribe function**

```
   This function can be used to subscribe messages from different topics.

```

**OnMessage CallBack function**

```
   This callback function is called when messages are received from  subscribed topics
   Topic, TopicLength, Message, MessageLength are the arguments of  OnMessage callback function.
   Inside this, you can write your custom code.

```

**unsubscribe function**

```
   This function can be used to unsubscribe from a previously subscribed topic.

```

**disconnect function**

```
   This function can be used to disconnect your client from MQTT broker.

```

**Keep Alive**

```
   You can specify your KeepAlive duration while initializing.
   Ping requests are sent and received automatically.

```

**Update**

Nowadays the easiest solution is to use SIM7600 4G/3G/2G modem. It supports MQTT using AT commands !. For more details the following link can be useful to get started.

https://www.elementzonline.com/blog/using-mqtt-at-commands-with-sim7600-and-arduino-for-gsm-iot-projects

# Answer
> 2 votes
The SIM900 allows creation of TCP sockets through an AT style command language, so this addresses point #1 of the previous comments concern.

This is only half the story though, you'll still need to learn how to create the requests, and handle the responses of the MQTT protocol using the SIM900's protocol.

There may be usable examples to start from in the ESP8266 community, as their style of TCP API looks similar to the SIM900.

# Answer
> 1 votes
1. MQTT by definition is a TCP/IP protocol, so if you don't have a TCP/IP stack, then it is a no go.
2. A common pattern/infrastructure in the IoT is to have your "things" connect to a hub of some kind (via BLE, XBee, or ... etc.) and then the hub will connect to the network and post the data. Another option would be to get a cellular device that provides a data connection (i.e. 2G/3G) and therefore a TCP/IP stack. It looks like the SIM900 only supports calls and texts, and as of this moment I am not aware of such a device that has libraries for Arduino.

# Answer
> 1 votes
Take a look at the FONA library from Adafruit.

https://github.com/adafruit/Adafruit\_MQTT\_Library/blob/master/examples/mqtt\_fona/

The FONA Library uses SIM800 which is a newer version of SIM900. You will find MQTT and FONA within the same library. They also run an MQTT Broker service in adafruit.io

# Answer
> 0 votes
These tutorials should help on getting started with MQTT on SIM900 or SIM800.

MQTT Protocol tutorial - LIVE DEMO using Mosquitto and CloudMQTT https://youtu.be/Oh3ZYAQBTko

This video explains about the main important control packets of MQTT protocol by explaining what each byte in a MQTT packet means and also shows how to send and receive data using TCP and Websockets UI of CloudMQTT.com Control panel. We also learn on how to use the Mosquitto Open source broker on Windows machine to Publish and subscribe to MQTT message and topics on localhost and to cloud servers with and without Authentication.

MQTT Protocol tutorial using SIM900/SIM800 modules - LIVE DEMO https://youtu.be/dcpMa2UwEeA

This video demonstrates how you can use the light weight MQTT protocol on the SIM900 or SIM800 GSM modules using TCP over the GPRS connection. Here you will learn, how you can use the SIM900/SIM800 TCP commands to send and receive messages as a publisher and a subscriber in almost realtime.

---
Tags: arduino-uno, gsm, ethernet, communication
---


# Question
Title: How to extract latitude and longitude from GPS
I want to extract longitude and latitude from GSM/GPS module and then upload it to thingspeak. I am using sim808 GSM/GPS module and AT+CGPSINF=0 to get GPS location information sentence (CGPSINF: 0,6.823375,80.001038,36.300000,20170705124133.000,0,10,0.037040,47.410000 ). I want to extract longitude and latitude from it. Does anyone know how to do it? I am not an expert in programming. someone told me to use strtok. But I don't know how to do it. Does anyone have any Arduino code to do this?

I tried DFRobot SIM808 library to collect GPS data. it works like charm. But the problem was, my upload code didn't work when i was using the library to collect longitude and latitude in the same code.

This is my web upload code.

```
#include <SoftwareSerial.h>
#include <String.h>

SoftwareSerial mySerial(10, 11);//(2,3)

void setup()
{
  mySerial.begin(2400);   // the GPRS baud rate 9600
  Serial.begin(2400);    // the GPRS baud rate 9600

  delay(1000);

  ShowSerialData();

}

void loop()
{
      Send2Pachube();
  if (mySerial.available())
    Serial.write(mySerial.read());
}
void Send2Pachube()
{
  mySerial.println("AT");//start with attention
  delay(1000);

  mySerial.println("AT+CPIN?");//check for the sim card
  delay(1000);

  mySerial.println("AT+CREG?");//check for registration and access technology of cell
  delay(1000);

  mySerial.println("AT+CGATT?");//check whether the device is attached to GPRS.0Detch,1Attch
  delay(1000);

  mySerial.println("AT+CIPSHUT");//shut packet data protocol context
  delay(1000);

  mySerial.println("AT+CIPSTATUS");// returns the current connection status
  delay(2000);

  mySerial.println("AT+CIPMUX=0"); //create multi-IP connection(0=single connection)
  delay(2000);

  ShowSerialData();

  mySerial.println("AT+CSTT=\"hutch3g\"");//start task and setting the APN,
  delay(1000);

  ShowSerialData();

  mySerial.println("AT+CIICR");//bring up wireless connection
  delay(3000);
  ShowSerialData();

  mySerial.println("AT+CIFSR");//get local IP adress
  delay(2000);
  ShowSerialData();

  mySerial.println("AT+CGPSINF=0");//get GPS
  delay(2000);
  ShowSerialData();

  mySerial.println("AT+CIPSPRT=0");//starts a TCP or UDP connection
  delay(3000);

  ShowSerialData();

  mySerial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//start up the connection
  delay(6000);

  ShowSerialData();

  mySerial.println("AT+CIPSEND");//begin send data to remote server
  delay(4000);
  ShowSerialData();

  String str="GET https://api.thingspeak.com/update?api_key=FF19NVWMPZEWX0XK&field1=100";
  mySerial.println(str);//begin send data to remote server
  delay(4000);
  ShowSerialData();

  mySerial.println((char)26);//sending
  delay(5000);//waitting for reply, important! the time is base on the condition of internet
  mySerial.println();

  ShowSerialData();

  mySerial.println("AT+CIPSHUT");//close the connection
  delay(100);
  ShowSerialData();
}
void ShowSerialData()
{
  while(mySerial.available()!=0)
    Serial.write(mySerial.read());
}

```

# Answer
First rather than just dumping it to the screen store the data in a char array

```
char dataBuffer[64];
int dataCount=0;

while ( (mySerial.available()!=0) && (dataCount<63) ) {
    dataBuffer[dataCount] = mySerial.read());
    dataCount++;
}
dataBuffer[dataCount] = 0;

```

then use strtok to split the string on the : and , characters

```
char *output;
output = strtok(dataBuffer,":");
// output will now point to everything up to the first : so "CGPSINF" for gps
int field = 0;
while (output != null) {
  field++;
  output = strtok(null,",");
// output will now point to each value in turn
// for CGPSINF:0,6.823375,80.001038,36.300000,
// when field == 1 output=="0"
// when field == 2 output=="6.823375" etc...
}

```
> 1 votes

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


title: Writing int/long on Sd card

text:
# Question
Title: Writing int/long on Sd card
I'm working on a project with SDcard, and I would like to write int and long in a file.

If I try to write 0x1954 I had 0x5419 on my file with file.write() so I did a circular shifting like:

```
  data=(data<<8)|(data >> (16-8)); //circular shift
  file.write((char*)&data,sizeof(data));

```

But with a long, I have 0x54195521 on my file instead of 0x19542155. So I don't know how to fix this. If you have any idea, I would like to read it ! (Or another way to do it)

Thanks !

# Answer
(Its not circular shifting, its bit shifting, the bits don't go round in a circle they disappear off the end and are lost forever.)

So in the library you are using you are writing bytes to the SD Card. If you write the data 0x1954 on the card you get 0x5419.
So what is happening is you are writing the least significant byte followed by the most significant. This is because you have take your int `0x1954` and cast it to a char\[2\] which contains `c[0] = 0x54` and `c[1] = 0x19` and then you write that out in the order c\[0\]c\[1\] et voila you have reversed you number.

The solution is to reverse the buffer before you write it:

```
char tmp = buf[0];
buf[0] = buf[1];
buf[1] = tmp;

```

HOWEVER - If you are only reading and writing from this code, who cares. As long as you read it in backwards does it matter how it is stored on the SD Card?
> 1 votes

---
Tags: sd-card
---


title: 24LC1025 Arduino - Data Writing Problem

text:
# Question
Title: 24LC1025 Arduino - Data Writing Problem
I have a very big problem by writing a list of strings to an eeprom (24LC1025) Your help with my problem highly appericiated.

I have a data matrix, PageData\[111\]\[96\] and I want to write all them at once, line by line to the eeprom. I am using arduino for coding.

the code is :

```
{

#include <Wire.h>

#define EEPROM_ADDR 0xA0;

void setup()
{

  Wire.begin();

  Serial.begin(9600);
int PageData[111][96]={ my data is here ... }

 for (t=0; t<111; t++){
  for (unsigned long i=0; i<96; i++){
    m=i*2;
    value[m] = highByte(PageData[t][i]);
    value[m+1] = lowByte(PageData[t][i]);   }

  at=((t*192));

 for (unsigned long i=0; i< 192; i++) {
    i2c_eeprom_write_byte(EEPROM_ADDR,(at+i),value[i]);
    delay(5);                             }
      }

void i2c_eeprom_write_byte( int deviceaddress, unsigned long eeaddress, byte data )
{
if( eeaddress > 65535 )
    deviceaddress = deviceaddress | B00001000;

    deviceaddress = deviceaddress >> 1;

  byte rdata = data;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));    // Address High Byte
  Wire.write((int)(eeaddress & 0xFF));  // Address Low Byte
  Wire.write(rdata);
  Wire.endTransmission();
}

```

My problem in this code: when I want to read the eeprom for the checking the strings, I realize, it does not write the eeprom the whole 111 line. It just writes randomly sometimes half of this sometimes less than this amount.

I tried several ways to solve the problem. but now I am desperate , please check this and tell me where i miss a point. Please let me know, if any information you need for the answer.

# Answer
Writing a single byte is really bad. You are causing a page write with each bye, and each page has a limited lifetime (100,000 - 1,000,000 cycles) so use block instead.

> When writing any amount of data, including a single byte using this function, the EEPROM will refresh the entire page (128 bytes) of data. EEPROMs have a limited write endurance (often 1 million cycles per page). Therefore, if you write one byte at a time, instead of writing a full block at once, you are *wasting the chip's lifetime* (doing so is also MUCH slower). ONLY use this if you really only need to write ONE byte, and avoid it when you can. Using a block write (below), you can write 128 bytes and only use a single page write (or *at most* two, if the write is not aligned to a page boundary).

This library should do the trick for you: https://github.com/exscape/electronics/tree/master/Arduino/Libraries/EEPROM/EEPROM\_24XX1025
> 1 votes

---
Tags: programming, eeprom
---


title: Arduino and big servo

text:
# Question
Title: Arduino and big servo
My dad told me, if i can mount some servo (to control 4 way ventil of heating) to his arduino-controlled home. But there is a problem... The servo does not have a normal 3 cables but 6 and I have no idea how to control. So i start some research about it and i found web site of manufacturer. There was also a Datasheet, but i dont understand it :D. So here is a link to the Manufacture´s web: http://www.mutmeccanica.com/prodottomutmeccanica.php?p=207 And link to datasheet: http://www.mutmeccanica.com/download\_file.php?file=downloads/scheda\_V70.pdf

And I have a question: Is any hope to connect this to arduino? Is there some shield for it?

# Answer
In the Arduino world, a servo motor is a RC servo motor. It runs at 5V or 6V and most of them can rotate 180°.

In an industrial environment or with the central heating in a house, the valves are often 24V AC. The most common voltages are 12V and 24V, and most of them with work with DC as well.
Sometimes the term "servo" is used for them, that is for example for a controller for valves with multiple positions.
To control them with an Arduino, the easiest way is with a number of relais.

Some intelligent valve controllers have an input signal. That is the one that you have.
The link to that datasheet is for a valve controller for 24V or 230V AC mains voltage. It has inputs to control it. Depending on the type, the input signal can be 0...5V, to 10V or to 20mA. Which one do you have ?

When that valve is in a central heating, it is possible to cause damage. First of all the central heating is tuned to the house. The valves work together with the pump, and not every system has a automatic overpressure-loop-valve.
> 1 votes

---
Tags: servo, home-automation
---


# Question
Title: Is this assignment valid or needs casting?
I have this assignment and while i don't get any error not even warning from the compiler.

```
uint16_t Buffer[40000];

for (int n=0; n<40000 ; n++){
Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n);
}

```

The Buffer is an unsigned short but as you can see inside there are float values inside.

The program does not work as expected.

Also i have another case where i am not sure if i need casting as this time, the final value is a float value.

```
int intVal;
float floatVal;

floatVal = intVal - intVal*Buffer[intVal];

```

Is this valid? Does it need casting? Or there is not reason to declare floatVal as float?

# Answer
> 1 votes
First part:

```
uint16_t Buffer[40000];

for (int n=0; n<40000 ; n++){
  Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n);
}

```

Buffer\[n\] will be filled with an uint16\_t and implicit casting to an uint16\_t will be used. I suggest you do such implicit castings explicitly (so add (uint16\_t) ... if you want).

However, if you do not want this, either define the Buffer as float, or at least add + 0.5 to give better roundings (if that is improving, depends on your situation, but mathematically it is better).

thus:

```
static const uint8_t BUFFER_SIZE = 40000;
uint16_t Buffer[BUFFER_SIZE];

for (int n=0; n<BUFFER_SIZE; n++)
{
  Buffer[n] = (int) (0.99 * cos(((2.0*PI)/BUFFER_SIZE)*n));
}

```

The next one:

```
int intVal;
float floatVal;

floatVal = intVal - intVal*Buffer[intVal];

```

This is also 'compiler-correct', and an int value can be more easier converted to a float. You will not lose digits. However, to make it clear an explicit cast with (int) ... is better.

Thus:

```
int intVal;
float floatVal = (float) (intVal - intVal*Buffer[intVal]);

```

# Answer
> 1 votes
c will perform implied casts for standard data types, normally without issuing any warnings.

This can catch you out at times.

So if you try to store a float into an int then it will be rounded down to the next integer. Since floats sometimes have rounding errors this can result in the value being 1 less than expected. e.g. 5 / 2.5 should give 2.0 but due to rounding may result in 1.99999999999. When saved as an int that would then give a value of 1.

If you want to round to the nearest integer then first add 0.5.

While the casts are implied and so not technically needed it can sometimes be a good idea to still include them explicitly just to make it clearer in the code that values are going to get rounded down.

The other thing to keep in mind is how variable types are promoted by the implied casts.

e.g. consider the following two lines:

float x = 3 + 2/4.0;
float x = 3.0 + 2/4;

In the first the calculation it is: int + int / double = int + double = double
In the second it is: double + int / int = double + int = double

So both result in a double that is then converted to a float (arduino is a little non-standard here, doubles are just floats anyway).

However the resulting values will be different. The first one will give the expected 3.5 while the second one will give 3.0 because 2/4 is an integer calculation and will have a value of 0. In order to get the correct value either the 2 or the 4 must be cast to a float or double before the division operation takes place.

For your specific questions:
`Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n);` is perfectly valid, all calculations will be performed as doubles and the end result cast to an int however you may get rounding issues as mentioned above. Changing the line to `Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n) + 0.5);` will round to the nearest integer which is probably what you want.
For the second question, `floatVal = intVal - intVal*Buffer[intVal];` there is no need for a cast, the value will be calculated as an int and then there is an implied cast to a float. However I'm not sure what the point of using a float is here since the result is always going to be an integer, using a float will only slow things down.

---
Tags: variables, data-type, float
---


# Question
Title: Connect Arduino Uno RX/TX to 3.3v NEO-M8N gps module
I'd like to connect an M8N gps module to an Arduino Uno. From what I understand

* the Arduino pins 0-RX/1-TX work on 5V
* the M8N RX/TX work on 3.3v
* the sensor-TX sending to the Arduino-RX should work (3.3v is “good enough” to drive the Arduino-RX-pin)
* the Arduino-TX sending to the sensor-RX is problematic because of the 5v (could break the sensor)
* During USB-programming, the Arduino-RX sensor can be at 5v (so suddenly the current flows in the "wrong direction"- which could break the sensor)
* A level-converter could be used to “translate” the voltages in each direction.

Assuming we don’t use a level-convertor

* Could we use a schottky-diode (which as I understand blocks current in 1 direction) to block the 5V from the ArduinoRX going into the sensor?
* But then the 3.3V from the sensor-TX would pass (correct direction ), but the diode will drop the voltage "a bit more"… is this still enough to drive the arduino RX-pin?
* And it works, why not also use a schottky-diode to also protect the Arduino-TX to sensor-RX connection ( just to be safe, since some people were saying one some Arduino they needed to connect RX-RX and TX-TX to get the communication to work.. ? ).

As an alternative to the schottky ( or maybe in addition to it) \- Could we simply take 2 voltage dividers (for one for both RX-TX and TX-RX) ?

We can use a “resistive voltage divider” to lower the Arduino-TX 5v to 3.3 V \- I understand to get from 5V to 3.3V we need “x” and “2 * x” resistors-values, so e.g 1K Ohm and 2K Ohm… but how do I know which values would be appropriate ( I mean, we could also take 10K Ohm and 20K Ohm, would also lead to 5V to 3.3v) but at a different current (Amps)… ?

Please be patient, electronics-beginner here trying to make sense of this…

# Answer
Buy some of these, it's a simple hardware solution to your problem then.

https://www.amazon.co.uk/gp/product/B0148BLZGE/ref=oh\_aui\_detailpage\_o01\_s00?ie=UTF8&psc=1

I know you said you don't want to use a level converter but it's the simplest way around the problem. You stated that you're an electronics beginner AS AM I, which is exactly why when I came up against the same problem i just spent the money. It was only £3.99 for 5 of them and as far as I'm aware you should be able to buy single ones off amazon too, haven't searched but i'd have thought you'd be able to.

Or if you need to do it with resistors you can use this calculator here

http://www.ohmslawcalculator.com/voltage-divider-calculator
> 1 votes

# Answer
You can use something along the lines of this:

simulate this circuit – Schematic created using CircuitLab

When the 5V Rx is driven to 5V D1 protects the 3.3V Tx pin.
When the 5V Rx is driven to 0V R1 protects the 3.3V Tx pin from excessive current draw.

When the 5V Tx is driven to 5V D2 protects the 3.3V Rx pin and R2 pulls the pin to 3.3V.
When the 5V Tx is driven to 0V D2 pulls the 3.3V Rx pin to ~0.2 V

Resistor values are rough guidelines, lower values will put more strain on the parts and increase power draw but will also increase the maximum UART speed that will work reliably.
> 1 votes

---
Tags: voltage-level, gps, voltage-protection, convert
---


title: 5 inch TFT LCD for Arduino

text:
# Question
Title: 5 inch TFT LCD for Arduino
I want to use a 5 inch 800x480 TFT display (touch not needed) with an Arduino (mega, uno or due). I'm thinking of buying this display: link (buydisplay.com). How can I connect this ?

I have also seen some pricier screens with serial i2c connection., but I don't understand the difference between this and using a shield?

Do anyone have any advice for displays to order and/or shields for Arduino ? Preferably a solution that I can reproduce by my self later for mass-production by doing be own circuit board.

Thanks in advance!

# Answer
> 1 votes
You need a driver board to run it. SSD1963 based ones are popular and are often included on the screen, especially the 7" ones on eBay.

Arduinos cannot drive a display directly. Small TFT screens often include the driver chip on them in the form of a Chip On Glass (CoG). That can't be done with the larger screens due to the sheer amount of memory needed to store the frame buffer. So an external chip has to be used, or a microcontroller with built in TFT interface.

Note that even with an SSD1963 (or equivalent - see the ones BuyDisplay sell are based on the RA8875) interfacing the Arduino to the TFT screen results will most likely be somewhat disappointing. Especially if you are interfacing using SPI or I2C which will create a bottleneck. Best is to interface with a 16-bit "8080" interface (16 data bits, read, write, chip select, reset and D/C), however that takes a lot of IO pins, and ideally a proper parallel interface to drive it quickly. And you want a lot of RAM for manipulating the data you want to display...

---
Tags: i2c, lcd, shields, tft
---


# Question
Title: Suddenly I can't compile any sketch. Not even a blink sketch that I compiled earlier
I use visual Micro for Visual Studio. Out of nowhere, I can't compile for any board. I tried a blink sketch for the nano, and I get intelisense red underlines for simple things like pinMode, digitalWrite, and Serial.print. Here's what I get for an output:

```
Compiling debug version of 'Nano_Trials' for 'Arduino Nano w/ ATmega328'
Build folder: file:///C:/Users/jf051e/AppData/Local/V.Micro/Arduino/Builds/Nano_Trials/nano_atmega328
Additional Defines: VM_DEBUG;VM_DEBUG_ENABLE 1;VM_DEBUG_BANDWIDTH_THROTTLE_MS 50;VM_DEBUGGER_TYPE_HARDWARESERIAL 0;VM_DEBUGGER_TYPE_SOFTWARESERIAL 1;VM_DEBUGGER_TYPE_FASTSERIAL 2;VM_DEBUGGER_TYPE_USB 3;VM_DEBUGGER_TYPE_TEENSY 4;VM_DEBUGGER_TYPE_UART 5;VM_DEBUGGER_TYPE_USART 6;VM_DEBUGGER_TYPE_USBSERIAL 7;VM_DEBUGGER_TYPE_TTYUART 8;VM_DEBUGGER_TYPE_NET_CONSOLE 9;VM_DEBUGGER_TYPE_Uart 10;VM_DEBUGGER_TYPE_COSA 11;VM_DEBUGGER_TYPE_CDCSerialClass 12;VM_DEBUGGER_TYPE VM_DEBUGGER_TYPE_HARDWARESERIAL;VM_DEBUG_BREAKPAUSE;
Architecture Tools: {runtime.tools.avr-gcc.path}/bin/
Sketchbook: file:\\\C:\Users\jf051e\Documents\Arduino
Sketch Include Paths
Include Path 'C:\Users\jf051e\Documents\Arduino\Nano_Trials'
Core Include Paths
Include Path 'C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino'
Include Path 'C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs'
Library Include Paths (1)
"{runtime.tools.avr-gcc.path}\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=106011 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers" "C:\Users\jf051e\AppData\Local\V.Micro\Arduino\Builds\Nano_Trials\nano_atmega328\Nano_Trials.cpp" -o "nul"
The system cannot find the file specified
    Preprocess: "{runtime.tools.avr-gcc.path}\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=106011 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers" "C:\Users\jf051e\AppData\Local\V.Micro\Arduino\Builds\Nano_Trials\nano_atmega328\Nano_Trials.cpp" -o "nul"
Unknown error during deep search source code for includes. Attempting alternative regex exploration
System.NullReferenceException: Object reference not set to an instance of an object.
   at Visual.Micro.MiroAppAPI.SketchCompilerArduino._TryRunPreProcessIncludesDiscoveryUntilDone(String sourceFilePath, Board brd, List`1 includePaths, Boolean isTopLevel)
   at Visual.Micro.MiroAppAPI.SketchCompilerArduino.TryRunPreProcessIncludesDiscoveryUntilDone(String sourceFilePath, Board brd, List`1 includePaths, SketchLibraryList knownLibs)
   at Visual.Micro.MiroAppAPI.SketchCompilerArduino._compile(SketchBuilder lsketch, String primaryClassName, Boolean verbose, Boolean isDebug)
Library Include Paths (1)
Build Core Paths: C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino
Using library VM_DBG version 0.0.0 in folder C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG
"{runtime.tools.avr-gcc.path}/bin/avr-g++" -c -g -Os -Wall -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=106011 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Arduino\libraries" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries" -I"C:\Users\jf051e\Documents\Arduino\libraries" "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG\VM_DBG.cpp" -o "C:\Users\jf051e\AppData\Local\V.Micro\Arduino\Builds\Nano_Trials\nano_atmega328\VM_DBG\VM_DBG.cpp.o" -DVM_DEBUG -DVM_DEBUG_ENABLE=1 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_USB=3 -DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_UART=5 -DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_COSA=11 -DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -DVM_DEBUG_BREAKPAUSE
The system cannot find the file specified
    Process: "{runtime.tools.avr-gcc.path}\bin\avr-g++" -c -g -Os -Wall -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=106011 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Arduino\libraries" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries" -I"C:\Users\jf051e\Documents\Arduino\libraries" "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG\VM_DBG.cpp" -o "C:\Users\jf051e\AppData\Local\V.Micro\Arduino\Builds\Nano_Trials\nano_atmega328\VM_DBG\VM_DBG.cpp.o" -DVM_DEBUG -DVM_DEBUG_ENABLE=1 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_USB=3 -DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_UART=5 -DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_COSA=11 -DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -DVM_DEBUG_BREAKPAUSE
Error compiling libraries

```

I swear I didn't touch anything. i was working on a different sketch and when I hit compile, Visual Studio froze and said it was busy. i had to kill the process and try again. I did this like 8 times before i realized that I could do longer compile ANY sketch. I even restarted my PC to no avail. What the heck??

# Answer
So I seem to have fixed it. One way or another, I think VisualMicro suffered some type of problem with the installed boards. My first clue was that my sketches still compiled int the native Arduino IDE. So I went into the VisualMicro explorer and noticed that there was an update to 1.6.19 in the board manager (I was running 1.6.13). I don't know exactly what the problem was, but installing the update to 1.6.19 seems to have fixed it.
> 2 votes

# Answer
There are a few suggestions here, here and here:

1. Ensure you are using the latest Arduino software *that is compatible with Visual Micro* (this is not necessarily the latest Arduino software!)
2. Go to Visual Micro menu -\> Board pulldown -\> Find or install a board--\> Rescan. You should get "Toolchain reload complete". The Visual Micro forum administrator suggests that you do this twice.
3. Reset the User's Appdata Arduino folder

* Close all IDE's
* Delete the C:\Users\<USERNAME\>\AppData\Local\Arduino15 folder
* Start the Arduino IDE once. Close after it has fully started
* Then try Visual Micro again

4. Delete the preferences.txt file (if it exists) Goto C:\Users\<USERNAME\>\AppData\Roaming\Arduino and delete the preferences.txt file.
> 2 votes

---
Tags: compilation-errors
---


# Question
Title: How to convert numbers from Serial port input to HEX String?
I am trying to read digits (number from 0 to 255) from Serial port, convert them to HEX String and send them using SoftwareSerial as HEX.

For example: when I send '60' trough the serial port, the SoftwareSerial will send '3C'

currently I am using the following code:

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 4); // RX, TX

String inputString     = "";
boolean stringComplete = false;

int HexInt = 0;
String HexString = "00";

void setup() {
  Serial.begin(115200);
  mySerial.begin(38400);
  inputString.reserve(200);
  delay(500);
  Serial.println("");
  mySerial.println("");
}

void loop() {
  serialEvent();
  if(stringComplete) {
    HexInt = inputString.toInt();
    HexString = String(HexInt,HEX);
    if (HexInt<16) HexString = "0" + HexString ;
    HexString.toUpperCase();

    mySerial.println(HexString);

    Serial.println(inputString); //debug
    stringComplete = false;
    inputString = "";
  }

}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    if (inChar == '\n') continue;
    if (inChar == '\r') {
      stringComplete = true;
      if (inputString == "") inputString = "NULL";
      inputString.toUpperCase();
      continue;
    }
    inputString += inChar;
  }
}

```

My question is: Is there a more elegant / effective way to perform the same outcome?

# Answer
You have the number. It's made up of two nibbles, each representing 4 bits (1 hex character).

If you want to do a manual conversion take the first nibble (AND with 240) add it's value to "0" then do the same for the lower nibble (AND with 15).

### OR

What I would do is use:

```
char HexString[3];
sprintf(HexString,"%02X",HexInt);

```

since you're not dealing with floats, you're good to go.

### OR

edit: I recalled a `printf` function that we put together once before, I don't know if it would work with SoftwareSerial, so you might have to play around with it a bit, but as a 3rd option, you could try the following. I don't have access to an Arduino or compiler at the moment, otherwise I'd have a play with this right now.

Before your setup:

```
// Function that printf and related will use to print
int serial_putchar(char c, FILE* f) {
    if (c == '\n') serial_putchar('\r', f);
    return Serial.write(c) == 1? 0 : 1;
}

FILE serial_stdout;

```

In your setup, add:

```
// Set up stdout
fdev_setup_stream(&serial_stdout, serial_putchar, NULL, _FDEV_SETUP_WRITE);
stdout = &serial_stdout;

```

in your loop, change your assignment to:

```
HexString = printf("%02X",HexInt);

```

from: https://arduino.stackexchange.com/a/480/304
> 1 votes

---
Tags: serial, softwareserial
---


# Question
Title: Make arduino board controler for watering system with power bank
I am trying to build an off-grid automatic watering system, and I was thinking of many options and the most reliable one that I found is to use a power bank which is charged by a solar panel.

So, I have a solar panel that outputs 5V, and I can charge a standard power bank with it. In addition to this, I bought a USB pump which I can also power with the power bank and controlled using an Arduino board. The problem is that the power bank doesn't support charging and discharging at the same time, and I thought that I could use an Arduino board to control this, but I have no knowledge on this. Therefore, I need help.

Is it possible to have a system like the one sketched below, where the Arduino board controls the input/output of the power bank?

The black path is my current path, but I was wondering if I could do the red path so that I can have both chargings from the solar panel and discharge due to the pump and Arduino board.

# Answer
Is it possible? Yes. Is it easy? Maybe.

A relay shield or similar would allow you to break the power connection from the solar panel to the power bank input, wait 5 seconds and then connect the power bank output to the pump.
Once you are done with the pump you could disconnect power from it and reconnect the charging power.

That is all fairly straight forward, maybe a dozen lines of code and some very simple wiring.

The issue is where does the arduino get power from? Or more accurately how does the arduino maintain power during the transitions between different power sources. How much of an issue this is depends a lot on how quickly the power pack transitions from charging to outputting and back and how you want the system to behave overnight or other times when there pump is idle but there isn't much sun light.

Also have you done a power budget? How much power does your pump take and how much power does your solar panel output under normal usage? Based on those two how long per day can you run the pump for assuming an ~80% efficient battery pack.
> 1 votes

# Answer
You should be able to solve it with two diodes, preferably Schotty diodes, they have a low forward drop voltage.
> 1 votes

---
Tags: home-automation
---


# Question
Title: Arduino Uno + Sim808: Using HTTP client for GPRS GSM
My problem is that I do not want to use AT commands everywhere to get/post data to my web server because it is brainstorming with all the delay and anything. I want to use library like `gsm.h` or something similar. Is there simple libraries which I can use to do the HTTP/HTTPS request (get/post) to my web server?

This code is my attempt with `gsm.h`, but it does not work. I suppose it only works with `Arduino + Telefonica GSM/GPRS shield`, not `Sim808`:

```
/*
 Web client

This sketch connects to a website through a GSM shield. Specifically,
this example downloads the URL "http://www.arduino.cc/asciilogo.txt" and
prints it to the Serial monitor.

Circuit:
* GSM shield attached to an Arduino
* SIM card with a data plan

created 8 Mar 2012
by Tom Igoe

http://www.arduino.cc/en/Tutorial/GSMExamplesWebClient

*/

// libraries
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password

// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;

// URL, path & port (for example: arduino.cc)
char server[] = "arduino.cc";
char path[] = "/asciilogo.txt";
int port = 80; // port 80 is the default for HTTP

void setup() {
// initialize serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
    }

    Serial.println("Starting Arduino web client.");
    // connection state
    boolean notConnected = true;

    // After starting the modem with GSM.begin()
    // attach the shield to the GPRS network with the APN, login and password
    while (notConnected) {
       if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &
       (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
          notConnected = false;
       } else {
          Serial.println("Not connected");
          delay(1000);
       }
    }

    Serial.println("connecting...");

    // if you get a connection, report back via serial:
    if (client.connect(server, port)) {
       Serial.println("connected");
       // Make a HTTP request:
       client.print("GET ");
       client.print(path);
       client.println(" HTTP/1.1");
       client.print("Host: ");
       client.println(server);
       client.println("Connection: close");
       client.println();
    } else {
      // if you didn't get a connection to the server:
      Serial.println("connection failed");
    }
}

void loop() {
     // if there are incoming bytes available
     // from the server, read them and print them:
     if (client.available()) {
        char c = client.read();
        Serial.print(c);
     }

     // if the server's disconnected, stop the client:
     if (!client.available() && !client.connected()) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();

        // do nothing forevermore:
        for (;;)
        ;
     }
 }

```

**Is there GSM/GPRS library that I can use with Sim808?**

# Answer
> 0 votes
Start Arduino IDE, open the Library manager, search for SIM800 and there is 3 libraries available there that you can install. The advantage is that this libraries is kept up to date and when a new version is available you will get a notice to upgrade.

There is a HTTP PUT/GET library "HttpClient" that can be installed the same way as above.

**Or**

If you googlem using "sim800 library arduino" you will find several libraries like:

https://cristiansteib.github.io/Sim800l

or on github:

https://github.com/search?l=Arduino&q=sim800&type=Repositories&utf8=%E2%9C%93

And as I understand it the 808 is GSM/GPRS + GPS, so the GPS features isn't normally covered by these libraries.

---
Tags: arduino-uno
---


# Question
Title: How to send a number to Arduino via Python over serial?
I call an API in Python and it gives as output as a single digit and an Arduino program receives this number over serial and displays it on a 7-segment display.

I wrote a different program in which Arduino sends the data and a Python program receives it. That worked but the following program is not working. What is the problem?

I am using Python 3 and Arduino Uno.

Python program:

```
import serial ,requests, json, time
arduino = serial.Serial('COM1', 9600, timeout=.1)
time.sleep(1)
response = requests.get("https://traffic.cit.api.here.com/traffic/6.1/flow.json?bbox=12.9808%2C77.5759%3B12.9803%2C77.5767&app_id=zbvY0tdRs089c3ZTKqWR&app_code=pxAtGksNBgVD9V5XF5nEzA",)
#CALLING API
response.content.decode("utf-8")
data = response.json()
text = str(data) #CONVERSION TO STRING
l = len(text)
for i in range(0,l): #Taking out the number
    if text[i] == 'J':
        j = text[i + 5]
        print (j)
        arduino.write(j) #writing over serial
        break

```

Arduino program:

```
int a=2;
int b=3;
int c=4;
int d=5;
int e=6;
int f=7;
int g=8;
int h=9;
int rx_byte = 0;

void setup() {
  Serial.begin(9600);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(g, OUTPUT);
  pinMode(h, OUTPUT);
  digitalWrite(h, 0);  // start with the "dot" off
}

void loop() {
  if (Serial.available() > 0) {
    rx_byte = Serial.read(); //reading serial
    switch (rx_byte) {
    case 0:
      zero();
      break;
    case 1:
      one();
      break;
    case 2:
      two();
      break;
    case 3:
      three();
      break;
    case 4:
      four();
      break;
    case 5:
      five();
      break;
    case 6:
      six();
      break;
    case 7:
      seven();
      break;
    case 8:
      eight();
      break;
    case 9:
      nine();
      break;
    }
  }
}

// write '9'

void eight() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 1);
  digitalWrite(g, 1);

}
void seven() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 0);
  digitalWrite(g, 0);

}
void six() {
  digitalWrite(a, 1);
  digitalWrite(b, 0);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 1);
  digitalWrite(g, 1);
}
void five() {
  digitalWrite(a, 1);
  digitalWrite(b, 0);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 0);
  digitalWrite(f, 1);
  digitalWrite(g, 1);

}
void four() {
  digitalWrite(a, 0);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 1);
  digitalWrite(g, 1);
}
void three() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 0);
  digitalWrite(f, 0);
  digitalWrite(g, 1);

}
void two() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 0);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 0);
  digitalWrite(g, 1);
}
void one() {
  digitalWrite(a, 0);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 0);
  digitalWrite(g, 0);

}
void zero() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 1);
  digitalWrite(g, 0);

}
void nine() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 1);
  digitalWrite(g, 1);

}

```

I am quite new to programming. Please help.

# Answer
> 1 votes
The python code

```
j = text[i + 5]
print (j)
arduino.write(j)

```

Is sending a single text character between '0' and '9', ascii values 48 to 58.

The c code

```
rx_byte = Serial.read(); //reading serial
switch (rx_byte) {
  case 0:

```

is looking for absolute values between 0 and 9.

There are two easy options to fix this, option 1 change the case statement to look for the correct values:

```
rx_byte = Serial.read(); //reading serial
switch (rx_byte) {
  case '0':

```

or option 2, rely on the fact that the ascii for the numbers is always 48 more than the number represented and subtract that:

```
rx_byte = Serial.read() - '0'; //reading serial
switch (rx_byte) {
  case 0:

```

`-'0'` and `-48` would have exactly the same effect here only by using `'0'` it makes it clear we are offsetting by the ascii value of a 0 rather than by some other randomly created number. It also saves you having to remember what the correct value is for 0.

Generally since you are using the value in a case statement I'd recommend the first option, it's a little more intuitive and avoids an extra calculation that can look a little odd if you are new to programming. The reason I mentioned the second option is that this is the method you would use if you wanted to use the rx\_byte value as the index in an array for any reason.

# Answer
> 0 votes
I think you are sending ASCII values 0 - 9 over serial. This is a bad idea, because they can be interpreted as control codes, always send printable characters. So in this case send '0' to '9'.

Also you could make you code much smaller if you used arrays.

For instance

```
int pins[8] = {2,3,4,5,6,7,8,9};
int TheData [8][8] =
{
    {1,1,1,1,1,1,0,0}, // 0
    {0,1,1,0,0,0,0,0}, // 1
    // etc
};
void write (int number)
{
    for (int i = 0; i < 7; i++)
    {
       digitalWrite (pins[i], TheData[number][i]);
    }
}

```

I'll let you figure out how to reduce setup to less than 3 lines :)

---
Tags: arduino-uno, serial, python
---


title: Burning Arduinos one after another

text:
# Question
Title: Burning Arduinos one after another
I very accidentally caused a short-circuit to two completely different cheap (under 4$ each) Arduino Uno clones, rendering Windows sound alert for unplugged USB several times.

This subsequently led to a problem with uploading code and not blinking green light on reset on both the Arduinos. Now, I am aware what this means but I am unable to see why this happens. I thought it has protection against that.

Is it normal for them to react like that so easily? How can I prevent this happening AGAIN?

# Answer
> I thought it has protection against that.

Genuine Arduinos do have some protection, yes.

> Is it normal for them to react like that so easily?

Cheap rubbish? Sure. You get what you pay for.

> How can I prevent this happening AGAIN..

Buy a real one. Also *be more careful*.

But at the price you pay for cheap clones, do you really care if they end up broken? You can buy many clones for each genuine one, and while a genuine one may last longer, when you do manage to kill it (they aren't *that* much more rugged, but some components are more reliable, such as the USB interface chip), which you seem adept at, you would be far more upset than if you'd killed a clone.

So I would suggest invest in one Genuine one for *special* projects, and to support Arduino (if no one buys Genuine boards there will *be* no Arduino), and a pile of clones that you can experiment and learn with. Blow them up at will, and when you are happy with your project transfer it over to the genuine board for showing off to people.
> 16 votes

# Answer
Measurements to prevent breaking an Arduino (or AVR in general):

**Precautions**

* Always remove the USB or adapter plug when you make a change in the circuit.
* Check all wires before you switch it on.
* Remove or make sure (temporary) loose wires/jumpers do not touch other components or the Arduino (better take them out or 'park' them somewhere else in the breadboard.

**Preventing wanted changes resulting in shortcuts**

* Check again the wires/jumpers you just changed/added.
* Make sure no other components/wires/jumpers are touching the Arduino or the breadboard (components).
* Clean your desk (if you have space), so if something metal falls/moves, it does not hurt your Arduino.
* When changing a shield, always check all wiring to and from it, to your Arduino and the components on the shield itself if needed.

**Preventing component shortcuts or overpowering**

* If you have a wire from a pin to GND or a pin to VSS, always make sure there is either a resistor, or you know why a resistor is not needed. This can also damage directly your Arduino.
* Make sure that every component does not get more power than it can handle.
* More specific: If you have components using 3.3V, make sure they don't get 5V.
* If you have components using 3.3V, make sure they don't get 5V.

**Preventing too much heat**

* Do not just put an Arduino in some case/enclosure ... heat may destroy it, so check before there is enough cooling, add a fan, heatsink or make holes in the enclosure.
* If you connect any power source other than USB, check again if it does not generate unnecessary much heat. Unused voltage will generate much heat.

**Preventing static electricity**

* Do not touch components when not needed
* If you touch components, make sure you are discharged (touch a radiator, use a wrist band, use an ESD mat, touch grounded wire).

**Preventing trivial mistakes**

* Do not keep drinks next to your Arduino or breadboard (or if you, keep it on the other side).
* Watch out for heavy cables not dragging your Arduino from the table/desk ... a USB cable can easily drag an Arduino down.
* Watch out when you change cables, not to pull your Arduino from the table/desk.
* Keep animals (and people too, to your own judgement) away from your electronics project.
> 22 votes

# Answer
Always use a series resistor when connecting anything to your IO pins. In many cases you will need one anyway (like driving a LED or a BJT), and in other cases it will not hurt (like driving MOSFET gates or UART lines). A 100 Ohm resistor will limit the current to 50 mA (keeping it within the safe range), while having little effect on your circuit in most cases.
> 4 votes

# Answer
I have used a current limiter (a cheap LM317 will do) occasionally, though even 100mA will burn your devices. It is good practice to limit current.

Generally don't wire a live circuit. Pull caps from the breadboard as well. Eventually you can disregard this, as you become more adept. I burned 4 arduino clones in the first few months.
> 2 votes

---
Tags: hardware, clones
---


# Question
Title: USB and Arduino: Power Arduino, charge LiPo, and transfer data at the same time
I was hoping to design my own Arduino board for a recent project of mine, a portable project that was powered by a 3.7 LiPo battery. Most ideally, I wanted to replace the USB B port with a single USB Micro port that implements the following features:

1. Provides power to the Arduino while it is plugged in (just like a regular Arduino does).
2. Connect the D+ and D- pins of the USB to the Arduino somehow to allow for on-board programming (however the Arduino accomplishes this already, I'll refer to this as the "onboard usb/serial converter"). I want it to keep it programmable on-the-go.
3. Charges an on-board 3.7V LiPo Battery. I was hoping to use Adafruit's PowerBoost 500 Shield as a reference for my schematic.

However, I haven't been able to find a schematic or example that implements **all 3 features** above at the same time **from the same USB port**. I don't have much experience with charging circuits, so the following questions might sound dumb. Below are some solutions I was thinking of that probably won't work, but I wanted to make sure:

1. Connect the Output Voltage of the LiPo Battery to the V+/GND supply of the USB cable (probably not safe to connect all V+ sources together).
2. Just connect the D+/- data cables to the "onboard usb/serial converter" without connecting the Vbat/Vusb somehow, have the USB V+/GND connect to the LiPo charging circuit, and the Battery Voltage power the Arduino.

I know some devices have this charging/data-transfer functionality (e.g. my phone can transfer photos to my computer while being powered on and charging at the same time), but I'm wondering how it's possible to have similar functionality for an Arduino board. Any advice?

Absolute worst case, I'll just have 2 USB ports, one for charging the LiPo and one for Serial Communication/Programming

**EDIT:** The idea of using an ATMega32U4 seems appealing (despite the 3.3V vs 5V operating voltage), mainly because it has a pin for VBUS for USB and Vcc for main power. But I was wondering how to do this on say an ATMega328P that doesn't have a pin for VBUS.

# Answer
I'd recommend using the Arduino Leonardo as a reference for your circuit. Its pretty much the same as an Arduino UNO but has a built in USB interface so you don't need the USB-Serial converter.

I'd also recommend running the chip at 3.3V. That way you can use a linear regulator to regulate the 3.7V battery voltage down. Otherwise you'd need a boost converter to bump the voltage up to 5V which needs more parts.

If you follow those recommendations then all you will need is a LiPo charging IC to handle the charging. You'll need to add an ISCP header to flash the initial Leonardo bootloader, but after that you can use USB and the Arduino IDE to program it.

I did exactly this for a school project a while back. You can find the schematics here: https://github.com/seanwatson/ece4416-project/blob/master/hardware/rev2/sw-4416-project-v2-sch.pdf
> 2 votes

# Answer
Use a TP4056 1A LiPo charger board (it has overdischarge protection) and a boost converter, like the XL6009. It will run you at most 5$ if you are prudent. Overdischarge protection is important.

If you want a port for programming, add a micro-USB breakout board, and if necessary a pushbutton for bringing RST down to GND. I prefer just having GND, TX, RX pins on a 3 pin header, and plugging my cable into that.
> 2 votes

# Answer
Following on from Sean Watson's answer, I would probably use the Bare Conductive Touch Board as your reference. It's a Leonardo derivative with all the features you're asking for. Full disclosure - I work at Bare Conductive and worked on the design of the board.

Eagle schematic and board file are here. Also, since this board successfully passed CE and FCC radiated emissions and immunity testing, you know that the reference design is sound for this if you want to create a product to sell.

The design uses a boost converter to allow for 5V operation - if you run the Atmega32u4 (or Atmega328) at 3.3V, you don't get guaranteed correct operation with a 16 MHz clock (check the data sheet). Since the Arduino bootloader for the Leonardo is written for a 16 MHz clocked MCU, this saves you the task of modifying the bootloader - and gives you the full 16 MIPS maximum performance.
> 1 votes

---
Tags: usb, serial, lipo
---


title: Roadblock using template functions

text:
# Question
Title: Roadblock using template functions
As part of a larger project, I'm trying to create a simple template function that will take an array and a value, both of the same type, and fill the array with the value. I'm running into the error quoted below:

"specializing member '::Fill\_With' requires 'template\<\>' syntax"

Below is the offending code fragment:

```
// Simple function to fill an array with a specified value.
template <class T> void Fill_With(T target_array, T value){
    int Array_Size = sizeof(target_array) / sizeof(T);
    for(int l = 0; l < Array_Size; ++l){
        target_array[l] = value;
    }
}

int array1[4] = {1,2,3,4}, k = 0;
Fill_With<int>(array1, k);

```

I've read numerous other forum posts on the error message, but haven't quite been able to figure out what I'm missing. I've read that I need to include a blank "template\<\>" header before the function declaration but that didn't seem to solve the issue. What am I doing wrong? Thanks!

# Answer
Let's start by getting rid of the templates, as they make things more confusing. In the following, I replaced `T` with `int`.

```
void Fill_With(int target_array, int value){
    int Array_Size = sizeof(target_array) / sizeof(int);
    for(int l = 0; l < Array_Size; ++l){
        target_array[l] = value;
    }
}

```

Let's try it out! I pasted this into the Arduino IDE and compiled it. Here is the output:

```
sketch_aug01a/sketch_aug01a.ino: In function 'void Fill_With(int, int)':
sketch_aug01a:4: error: invalid types 'int[int]' for array subscript
         target_array[l] = value;
                       ^
exit status 1
invalid types 'int[int]' for array subscript

```

This is telling us that we're trying to subscript (that's the term for the `[]` syntax) a variable of type `int` with a variable of type `int`. In C++, a pointer to the start of an array has type `int *`, not `int`. Let's fix the type of `target_array` in the function signature:

```
void Fill_With(int *target_array, int value){

```

It compiles, but if you ran it you would quickly run into a bug:

* When given an expression, the `sizeof` operator will return the number of bytes in the type of the expression. The type of the expression `target_array` is `int *`, so `sizeof(target_array) == sizeof(int *)`. On 32-bit systems, `sizeof(int *) == 32/8 == 4`.
* When given a type, the `sizeof` operator returns the number of bytes in the type. So `sizeof(int)` gives the number of bytes in an `int`, which is guaranteed to be at least 2 bytes (16 bits), but is usually 4 or 8 (it depends on the system).

Together, this means that `Array_Size` ends up being some small number like 0 or 1, regardless of the contents of `target_array`. To fix this, you can instead pass in the length of the array as a parameter:

```
void Fill_With(int *target_array, int array_size, int value){
    for(int l = 0; l < array_size; ++l){
        target_array[l] = value;
    }
}

int array1[4] = {1,2,3,4}, k = 0;
Fill_With(array1, 4, k);

```

Now you can put the templates back in:

```
template <class T> void Fill_With(T *target_array, int array_size, T value){
    for(int l = 0; l < array_size; ++l){
        target_array[l] = value;
    }
}

int array1[4] = {1,2,3,4}, k = 0;
Fill_With<int>(array1, 4, k);

```

By the way, C++ already has this function built in. It's called `std::fill`. Here's how to use it:

```
#include <algorithm>

int array1[4] = {1,2,3,4}, k = 0;
std::fill(array1, array1 + 4, k);

```
> 0 votes

---
Tags: arduino-mega, programming, c++
---