# Question
Title: Servo doesn't work in 'for' loop running under 'if' loop
This is my first StackExchange question. I'm relatively new to Arduino and I am trying to tinker with the components and functionality.

I have a RGB LED coupled to my breadboard with a servo attached. The LED only shows Red and Orange for some reason(Why?), SO I mended my code as per the LED behaviour. The code prompts the user for a color, and depending on that, the Servo should rotate along with the LED lighting up. My servo functions well only in 25-165 degrees range. The code goes as,

Here's the code:

```
# include<Servo.h>
int i;
Servo n1;

String color;
void setup(){

Serial.begin(9600);
  n1.attach(6);
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(6,OUTPUT);

}

void loop(){

Serial.println("Enter color: ");

while(Serial.available()==0){
}
color=Serial.readString();

if (color=="red"){
  digitalWrite(2,HIGH);

  for (i=25;i<=165;i=i+5){
        n1.write(i);
        delayMicroseconds(250);
  //}
  n1.write(25);
  delay(2500);
  digitalWrite(2,LOW);
}

}else if (color=="orange"){
  digitalWrite(3,HIGH);

  for (i=165;i>=25;i=i-2){
    n1.write(i);
    delayMicroseconds(250);
  }
  n1.write(25);
  delay(2500);
  digitalWrite(3,LOW);
}
}

```

So basically when Red is in, I want the Servo to go from 25 to 165 & come back to 25, and vice versa for Orange. But the servo behaves in 2 ways;

1.When Red is entered first, it turns some angle(I guess 25) and stays there, the programme doesn't even loop for further input of color for a long period. Then whatever the input goes, Servo stops rotating, only LED works.

2.When Orange is entered first, it goes again to the same angle as red, and mildly buzzes, but input is accepted and Servo is motionless. I simulated the same setup and code in TinkerCad circuits, and the behaviour is the same, so no particular problem with the hardware there.

I'm relatively new to understanding the Arduino workings and Fundamentals, any help is appreciated. Also, the circuit setup is attached.

Any help will be appreciated.

Thanks!

# Answer
This section of code is never going to run. The for loop says that i starts at 175, and while i\>=25175 then execute the n1.write(i) and subtract 2 from i each time it does this.

```
for (i = 175; i >= 25175; i = i - 2) {
      n1.write(i);
    }

```

From the arduino servo example page, n1.write() should only ever be from 0 to 180, as it is the angle the servo is at. So you go from 175 to 180 and it wont move past that.

```
//angle: the value to write to the servo, from 0 to 180

#include <Servo.h>

Servo myservo;

void setup()
{
  myservo.attach(9);
  myservo.write(90);  // set servo to mid-point
}

void loop() {}

```
> 1 votes

---
Tags: servo
---


# Question
Title: Why are commands executing on their own?
This is the program I have used. It's working fine. But I don't known why sometimes it operates on its own. It is used to control a welding machine (Arduino is isolated from earthing). When there is a little vibration the code executes a command. This is the code:

```
int a = 9;  //right actuator forward relay 1
int b = 12; //right actuator reverse relay 2 (orange 10)
int c = 10; //left actuator forward relay 4
int d = 11; //left actuator reverse relay 3
int x = 0;
int y = 0;
const int stepPin = 8; // HIGH =DOWN; LOW == UP
const int dirPin = 7;

void setup() {
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  pinMode(4, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  Serial.begin(9600);
  digitalWrite(b, HIGH);
  digitalWrite(d, HIGH);
  delay(2000);
  digitalWrite(b, LOW);
  digitalWrite(d, LOW);
  delay(1000);
  Serial.println("press the foot swtich"); // Serial Monitor for Debugging
}

void loop() {
  int Val = digitalRead(5); //   Actuator 1 Clamping
  int ValR = digitalRead(6);//   Actuator 2 Clamping
  int ValS = digitalRead(4);//Stepper Motor anticlockwise
  int ValM = digitalRead(2);//Stepper Motor Clockwise
  if (Val == LOW && x == 0  ) {
    Serial.print("Val000=");
    Serial.println(Val);
    digitalWrite(c, HIGH);
    delay(1750);
    digitalWrite(c, LOW);
    x = 1;
    Val = digitalRead(5);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (Val == LOW && x == 1  ) {
    digitalWrite(d, HIGH);
    digitalWrite(b, HIGH);
    delay(2000);
    digitalWrite(d, LOW);
    digitalWrite(b, LOW);
    x = 0;
    Val = digitalRead(5);
    Serial.println("fwd");
    y = 0;
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValR == LOW && y == 0 ) {
    digitalWrite(a, HIGH);
    delay(1350);
    digitalWrite(a, LOW);
    y = 1;
    ValR = digitalRead(6);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValR == LOW && y == 1 ) {
    digitalWrite(b, HIGH);
    delay(1200);
    digitalWrite(b, LOW);
    y = 0;
    ValR = digitalRead(6);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValS == HIGH) {
    Serial.println(Val);
    Serial.println("up");
    digitalWrite(dirPin, HIGH);
    // Enables the motor to move in a particular direction
    // Makes 100 pulses for making half cycle rotation
    for (int x = 0; x < 100; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(1000);
    }
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
  }
  if (ValM == LOW) {
    Serial.println("down");
    Serial.println(ValR);
    digitalWrite(dirPin, LOW);
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
    for (int x = 0; x < 100; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(1000);
    }
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
  }
}

```

# Answer
Trying to write a proper answer...

According to your description, it looks like you are victim of inductive noise pickup. The circuit \[MCU → Arduino ground pin → foot pedal → Arduino digital input pin → MCU\] is a loop that can pick up magnetic flux. If this flux varies, either because the magnetic field varies (ambient electromagnetic noise) or because the geometry of the circuit changes (you move the wires), this will induce an electromagnetic force that can make your Arduino read `LOW` even when the button is not pressed.

There are two things you can try to overcome this effect:

1. Replace the weak internal pullup of the Arduino by a much stronger external pullup. Something around 1 kΩ should make it quite hard for the noise to pull the signal low.
2. Connect the pedal to the Arduino board using a twisted pair of wires, like the ones found in telephone or network cables. This kind of cable does a good job at minimizing inductive pickup.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to pause Arduino for 1 millisecond through MATLAB?
I have been able to connect MATLAB to my Uno with this line of code: `a = arduino('COM4');` through this package: Matlab support package for Arduino.

Right now, MATLAB is my main script that will synchronize all the components \[like the Arduino\].

I am able to send pulses to my stepper-motor just by using:

```
void loop() {
    digitalWrite(2, HIGH);
    delay(1);
    digitalWrite(2, LOW);
    delay(1);
}

```

This works fine, and will make the motor move about once every 2 milliseconds. My problem is that I cannot find a way to produce this same delay through MATLAB's interface. I do know that MATLAB has a `pause()` function, but when I set up a loop in MATLAB like this:

```
a = arduino('COM4');
for m = 1:400
    a.digitalWrite(2, 1);
    pause(0.001);
    a.digitalWrite(2, 0);
    pause(0.001);
end

```

Each step takes WAY longer - about 200 milliseconds each.

What are other options for creating the pause between digital High / Low being sent to the Arduino? It would be nice if I could control the outcome from Matlab, through Arduino.

# Answer
> 8 votes
The increased in observed delay is due to the time it takes to send the command from MATLAB to the Arduino have its code execute the requested command. In your case the a.digitalWrite. So actual time between pulses using MATLAB's delay is 0.001 pause plus the time of baud rate times the packet size and decoding then execution.

I would recommend not pursuing this solution of the MATLAB controlling the timing of Step Motors, remotely. As this latent coupling will be a frustrating limitation. Noting that for step motors the timing can not afford such latent execution. Hence all the 3D printers and many CNC with Step Motors use Arduino's which get G-Code (motor move commands with destinations) and the Real-time firmware handles the stepping, within tolerances.

I would suggest using something like grbl firmware with step motor shield and then have the MATLAB send the needed G-code. Where there are others with much more features but tailored to 3d Printing. grbl is simpler and straight to the point of moving motors.

# Answer
> 0 votes
It's not clear from your question whether you are trying to get real-time execution without latency or simply want to adjust the motor delay time from MATLAB. If the latter, a good way is to send delay data (e.g. a number that represents how long you want between pulses) vie serial, which your Arduino program will receive and update the motor delay as desired. Or, bearing in mind RAM limitations, you can send a whole sequence of delays that can run one after another with precise timing.

---
Tags: arduino-uno, matlab
---


# Question
Title: How do I configure a pin to be a bidirectional and open collector?
I want to communicate with a keyboard asynchronously through a single open collector, bidirectional data pin. As part of the protocol, the data pin is active low and is pulled low by either the host or connected device.

Some code examples configure the pin direction to switch input to output depending on wether the host want to input or output a signal. Constantly switching the pin directions seems a bit naive.

Are there better methods?

# Answer
> 2 votes
If the other end of the link has the same signal voltage as your Arduino, you can simulate an open collector with a single pin:

* `digitalWrite(pin, LOW); pinMode(pin, OUTPUT);` sets the pin to output an active low signal.
* `pinMode(pin, INPUT_PULLUP)` sets the pin to input mode, or output passive high which, in open-collector mode, is the same thing.

Note that in the first case the order of the commands is important: on AVR microcontrollers, if you set the mode to `OUTPUT` before writing `LOW`, the pin will for a short time output an active high, which is forbidden in open-collector mode. I don't know how other MCUs would behave in the same situation though.

**Edit** to address Ignacio Vazquez-Abrams’ comment: An open-collector bus needs a pullup resistor on each data line to function properly. If that pullup is already provided by your keyboard, or your cable, then you should use `pinMode(pin, INPUT)` to accurately emulate an open-collector output on the Arduino side. Otherwise you have to provide that pullup, either as an external component or by using the internal pullup of the MCU. Beware that the latter may be a little bit weak, depending on your data rate.

---
Tags: pins, port-mapping
---


# Question
Title: Sending multiple messages over the serial monitor in nodeMCU
I am trying to send multiple messages wirelessly from one ESP8266-12E NodeMCU to another. I have successfully established the connection and am able to send and receive single messages. The MAC addresses are solely for the verification that the data is going to the right client. My trouble is sending multiple messages which I should be able to observe in the serial monitor.

Here's my server code:

```
#include <ESP8266WiFi.h>

extern "C" {
  #include <user_interface.h>
}

int32_t freq = 10000;

WiFiServer server(80);                            //Initialize the server on Port 80

void setup() {
  pinMode(D1,OUTPUT);
  pinMode(D2,OUTPUT);
  pinMode(D3,OUTPUT);

  Serial.begin(9600);                             //Start communication between the ESP8266-12E and the monitor window

  analogWriteFreq(freq);

  WiFi.mode(WIFI_AP);                             //This ESP8266-12E is an AccessPoint
  WiFi.softAP("NodeMCU_js", "12345678");          //Provide the (SSID, password)

  IPAddress HTTPS_ServerIP = WiFi.softAPIP();      //Obtain the IP of the Server
  Serial.println("Server IP is: ");                 //Print the IP to the monitor window
  Serial.println(HTTPS_ServerIP);
  server.begin();                                 //Start the HTTP Server

}

void loop() {
  WiFiClient client = server.available();         //Check if a client has connected to the server

  struct station_info *stat_info;
  struct ip_addr *IPaddress;
  IPAddress address;

  if (client) {
    Serial.println("Somebody has connected :)");

    stat_info = wifi_softap_get_station_info();

    while (stat_info != NULL){
      IPaddress = &stat_info->ip;
      address = IPaddress->addr;
      Serial.println();

      Serial.print("Client IP Address = ");
      Serial.print(address);
      Serial.println();

      Serial.print("Client MAC Address = ");
      Serial.print(stat_info->bssid[0],HEX);
      Serial.print(":");
      Serial.print(stat_info->bssid[1],HEX);
      Serial.print(":");
      Serial.print(stat_info->bssid[2],HEX);
      Serial.print(":");
      Serial.print(stat_info->bssid[3],HEX);
      Serial.print(":");
      Serial.print(stat_info->bssid[4],HEX);
      Serial.print(":");
      Serial.print(stat_info->bssid[5],HEX);
      Serial.println();

      if (stat_info->bssid[0] == 0xDC && stat_info->bssid[1] == 0x4F && stat_info->bssid[2] == 0x22 && stat_info->bssid[3] == 0x17 && stat_info->bssid[4] == 0xEE && stat_info->bssid[5] == 0x95){
          int duty1 = 150;
          int duty2 = 200;
          int duty3 = 250;
          Serial.println("Duty - 1 : "+String(duty1));
          Serial.println("Duty - 2 : "+String(duty2));
          Serial.println("Duty - 3 : "+String(duty3));

          analogWrite(D1,duty1);
          analogWrite(D2,duty2);
          analogWrite(D3,duty3);

          client.println(String(duty1)+"\r");                          //Server's response to the client
          client.println(String(duty2)+"\r");
          client.println(String(duty3)+"\r");
       }
      else {
        Serial.println();
        Serial.println("Client not recognized.");
      }
     stat_info = STAILQ_NEXT(stat_info, next);
    }
  }
}

```

Here's my client code:

```
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

char ssid[] = "NodeMCU_js";
char password[] = "12345678";

IPAddress server(192,168,4,1);       // the fix IP address of the server

WiFiClient client;                // Creates a client that can connect to to a specified internet IP address and port as defined in client.connect()

void setup() {
  pinMode(D4,OUTPUT);

  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);

  Serial.begin(9600);                 //Serial connection
  WiFi.begin(ssid,password);          //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {         //Wait for the WiFI connection completion
    delay(500);
    Serial.println("Connecting...");
  }
  Serial.println("Connected.");
  client.connect(server,80);
}

void loop() {
  if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status
    String answer1 = client.readStringUntil('\r');
    Serial.println();
    Serial.print("From Server(1): ");
    Serial.print(answer1);
    client.flush();

    String answer2 = client.readStringUntil('\r');
    Serial.println();
    Serial.print("From Server(2): ");
    Serial.print(answer2);
    client.flush();

    String answer3 = client.readStringUntil('\r');
    Serial.println();
    Serial.print("From Server(3): ");
    Serial.print(answer3);
    client.flush();

  }
  else{
    Serial.println("Error in WiFi connection");
  }
}

```

It would be helpful if I could get the correct way of doing this.

Thanks in advance.

# Answer
> 0 votes
from server you send at the end of line \r\r\n. first \r is in the string and \r\n is added by println. then at the client you read until \r the first line, the you read an empty line until next \r.

---
Tags: esp8266, arduino-ide, nodemcu, wireless
---


title: Programming an ATtiny85

text:
# Question
Title: Programming an ATtiny85
Recently I ordered some ATtiny85's from Jameco, and I've been trying to upload code to them through an Arduino Uno, following the instructions from this video on YouTube. I've been getting a lot of unexpected errors and I am now wondering if the chips I bought are the problem. Here are the specs from the Jameco website:

> Flash (Kbytes): 8 Kbytes
>
> Pin Count: 8
>
> Max. Operating Frequency: 20 MHz
>
> Power Supply: 2.7 - 5.5V
>
> Operational Range: Industrial (A) (-40°C to 85°C)
>
> CPU: 8-bit AVR
>
> Number of Touch Channels: 3
>
> Hardware QTouch Acquisition: No
>
> Max I/O Pins: 6
>
> Ext Interrupts: 6
>
> USB Speed: No
>
> USB Interface: No

Does the "USB Speed: No; USB Interface: No" mean these aren't programmable by my set up? Or is there is anything else I should know about these chips? Do I need to get new ones that are different?

# Answer
> 2 votes
Before you panic (try not to panic) and buy new chips, test the existing ones. See my page about detecting chip signatures which has links to code on Github for a sketch you can run on your Uno, to test the ATtiny85.

---

You can also upload code from a .hex file (which the IDE produces) by using a different sketch (same code link) from this page about a hex uploader and wiring like this (you also need an SD card adapter):

---

The first sketch and wiring should at least confirm your chips are OK. The second one is an alternative way of programming them.

# Answer
> -1 votes
I would suggest you to take a look at this video which explains step by step how to program the ATtiny85. https://www.youtube.com/watch?v=i9WOwDrpRKs

From my early days trying to program the ATtiny, i have watched this video.

---
Tags: attiny, avr
---


# Question
Title: How to use control a 48 000 motor with Arduino
I am new to Arduino and I am just playing with it, I wanna control a 48,000rpm motor with 9v voltage via Arduino the plobrem is how could I make that motor slow down, slowly. Any ideas? I am using Arduino mega

# Answer
So far you haven't added any information about the motor so I am going to assume it is a standard DC motor.

With this type of motor, you can change the speed by varying the voltage. So at 9V it will go full speed (theoretically 48,000 RPM). At 4.5V it should go at about (roughly) half. Of course this varies with the load you are applying to the motor.

You can control the motor speed using the PWM output of the Arduino. If you would like to read more about Pulse-width Modulation (PWM) I highly recommend that you read the Sparkfun article here.

This presents 2 problems.

1. The Arduino Mega PWM only gives you an adjustable voltage between 0V to 5V.
2. The current provided on these pins is only small and would not be able to power the motor fully.

To overcome both you need to add a MOSFET. I suggest a N-Channel MOSFET that switches on the low side.

simulate this circuit – Schematic created using CircuitLab
> 1 votes

---
Tags: arduino-uno, arduino-mega
---


# Question
Title: "Active LOW" relay board Pin configuration
I bought a 5 V Relay Board: LINK (Aliexpress) and just realised it's "Active LOW". I want to control a water pump via a Arduino Micro.

I tested it and as far as i understand the workings of this relay, putting the pin to LOW activates the little LED on the Relay Board and switches to the NC position where I connected the water pumps ground wire.

I don't feel very comfortable with that because normally those relays are activated by setting the pin to HIGH. I tried to connect the ground wire of the pump to the normally open position but than, if I disconnect the Arduino to simulate a malfunction the pump keeps running.... this doesn't happen with the first configuration.

So my Question: Is it a problem to use the Relay Board in the way described above (Pin to LOW switches Coil to NC Postion). Is there a way I'm not seeing to get the Board to switch the Coil if a pin is set to high.

# Answer
That relay module is driven by optocouplers. You are just driving and LED, and that is connected though a resistor to VCC.

In the past it was common to use active low for driving things since an N channel MOSFET could typically sink more current than a P channel one could source. Also in the days before CMOS there was really only low-side (sinking) switching, so active low was the norm.

These days it's not necessary, but it's still common because that is how it's always been.

So yes, active low is both common and accepted.
> 1 votes

---
Tags: relay, arduino-micro
---


# Question
Title: 8Ω speaker, what resistor values to use?
I want to connect 2 speakers of 8 ohm to 2 (different) pins of the Arduino. However, for this example one speaker is enough.

I came across a lot of circuits without or with a single resistor which on other foras was not adviced, where one pin directly controls the speaker. This way (assuming 0,02A is the max recommended output for a pin), the resulting power is like 0.02A * 5V = 0.1W.

My speaker is 0.5W (8 ohm) and I want to hear how hard that is :-)

But it seems I have to use something with a transistor to isolate the path. I came across this circuit:

However, when I would calculate the values or R1 and R2 myself I would get:

1. R2: Afaik, the recommended output for a pin is 0.02 A. This means: V = I * R \<=\> 5 = 0.02 * R \<=\> R = 5 / 0.02 = 250Ω -\> 270Ω (nearest higher value)
2. R1: my speaker is 0.5W, 8Ω. P = V * I \<=\> 0.5 = 5 * I \<=\> I = 0.1A V = I * R \<=\> 5 = 0.1 * R =\> R = 50Ω, which is Rtotal below: Rtotal = Rspeaker + R1 \<=\> R1 = Rtotal - Rspeaker = 50 - 8 = 42Ω =\> 47Ω (nearest higher value)

This result in V = I * R \<=\> 5 = I * (R1 + Rspeaker) \<=\> I = 5 / (47 + 8) = 5 / 55 = 0.0909 A P = V * I = 5 * 0.0909 = 0.4545 W (so I lose 'just' 10%)

Are my calculations correct, and I assume the +5V pin of the Arduino will not have trouble giving 90.9 mA ?

Update:

I have some more questions regarding the accepted answer:

1. Would it mean if I use 7 transistors, all my voltages will be used for transistors and nothing is left (7 times 0.7 V which is approx. 5 V?) \**** Answer = No, a transistor will add Voltage so 7\*0.7= 4.9Volt added \***
2. I assume I can better use as less as possible to 'switch' a transistor? *** Answer = No, 0.7-Volt required, 5V is fine depending on the rating of the transducer**  *(but enough to be able to switch it) ? You say R2 can be smaller, but I can better make it higher not to waist voltage?*  **Answer = Changing the resistor will change the volume, look at the wattage rating for the speaker ***
3. I already built the circuit below (but with a BC547 transistor) ... using a 0,25W R1 resistor. I guess I was lucky (?) *** Answer = No, luck has no part, that transistor would work fine within the parameters used, look at the datasheet ***
4. Regarding the base pin of the transistor ... by making the resistor higher (see item 2 above) ... that would help also not to burn the transistor pin? *** Answer = No... please view the datasheet and ratings for the hw ***
5. Again about the transistor, so I should make the resistor R2 in such a way that the gain times the mA is driving the speaker? (need to calculate this again) *** Answer No, and I think you are thinking of "Gain" the wrong way, "Gain" is a "DB" measure and is for how well AC is transferred between antenna. ***
6. You say to remove R1 completely ... but than I expect V = I * R \<=\> 5 = I * 8 =\> I = 0.625A ... P = V * I = 5 * 0,625 = 3.1W which blows the speaker? *** Answer = Wrong way of looking at the 8-Ohm Impedance rating, Impedance is AC ***

# Answer
Basically you are right and it should work.

But if you want to go to details, it would be better look on AVR328 documentation, as nothing is as easy as it looks in Arduino tutorials.

* maximum (really maximum) current on pin is 40mA for one DC pin and 200mA for all pins together (otherwise destruction of the processor is possible - never ever try to reach it), also datasheet states:

> Although each I/O port can source more than the test conditions (20mA at V CC = 5V, 10mA at V CC = 3V) under steady state conditions (non-transient), the following must be observed: ATmega48A/PA/88A/PA/168A/PA/328/P: 1\] The sum of all I OH , for ports C0 - C5, D0- D4, ADC7, RESET should not exceed 150mA. 2\] The sum of all I OH , for ports B0 - B5, D5 - D7, ADC6, XTAL1, XTAL2 should not exceed 150mA. If II OH exceeds the test condition, V OH may exceed the related specification. Pins are not guaranteed to source current greater than the listed test condition.

so 20mA is not `recomended` but is `maximum guaranteed to be provided under some more conditions met` \- if you can, you should use less (also even if it works for one module on one pin, it may fail mysteriously for mor modules on more pins).

* Even if 20mA is guaranteed for one pin, the voltage on it would drop more then 0.5V if you drain so much
* you cannot draw as much on too many pins together
* also the maximum you can draw is less if you want higher frequency (I think the sound is not usually in category, where it matter too much)

In your equation 1 you used 5V/20mA, you should use 4.4V/20mA also keep in mind, that there is usually like 0.7V on base of open transistor (depends of type) - so the R2 can be even smaller, if you use only few pins.

About R1 - if you open the transistor, there can be like 0.2V on the collector, so the current is like 4.8V/6.8Ohm = 0.7A - on UNO board v3.0 is used NCP1117 as stabiliser, which can support even 1A (if powered not from USB, but 7V and higher source (if such source can give as much) so it could work too, but beware as it is about 4.8V\*0.7A=3.4W so R1 should be able to stand at least as much if the pin is HIGH for any longer time. If the pin is oscilating, the SPKR adds it current to that, so the value can be even higher (I would not use anything under 5W for R1).

On the other hand - Q1 2N3904 can support Ic max 200mA, so you could burn it by setting the pin for HIGH (or for PWM with more like 20% HIGH or more - switching makes even more heat) so you should use othe transistor here.

And this Q1 have current gain over 30 even for such currents as 100mA, so you need just 1/30 of Ic go thru the base from pin (so you need supply only 3.3mA to have 100mA thru Q1, 6.6mA is able to force 200mA and burn the transistor, if not properly cooled. 20mA is clearly much more than needed anyway.)

I would suggest some darlington transistor here or something like that, if you want manipulate such currents.

If your speaker is 0.5W only, you will burn more power on the R1 than on the speaker - not good result. It would be better just manipulate the speaker directly (put it instead of R1 and leave the R1 and C1 out).

(but on usual Arduino setup the power source and all is usually so underrated, that there is a good chance, that it would not be able to supply enough power to burn your equipement out, just it would drop the voltage and maybe fail randomly. Who knows. Also breadboards and long thin wires with bad connection adds a lot of resistance and voltage drops and manufacturers publish as `maximal rating` what the product should survive, which is usually a lot les, than is needed to sure destroy it, so many `experiments` can survive even if they should burn on simple paper calculations - which is part of why Arduino is so popular - is cheap and usually does not burn even if managed out of specs.)
> 0 votes

# Answer
The speaker rating of 8 Ω is AC resistance, speaker impedance. Impedance (AC-Resistance) changes based on the frequency of the signal fed into it.

If you are worried about hurting the speaker and need to calculate power driving that particular "load", look at the speaker Wattage rating. Say it is 1 W for example, and you are providing 5 V d.c., the amperage required will be: 0.2 A.

```
V * A = W
0.2 * 5 = 1

```

So the DC resistance is actually:

```
V = I * R (0.2 / 5 = 0.04 Ω).

```

Give it a higher amplitude... say 5.7 V to account for a transistor no resistor, and you get about 0.175 A. and a change in DC resistance again to 0.0301 Ω.

If the power supply is AC, the impedance needs to be matched to the speaker impedance to get best energy efficiency, otherwise the amplifier can be damaged.

For that circuit I suggest you place a variable resistor where the resistor is in your circuit to allow for a volume change. Also a flyback diode maybe a good idea, that will protect the speaker but take down voltage 0.7 V d.c. keep in mind you have that transistor there adding 0.7 V d.c.! so it evens things out too using that diode.

That diode placed on the high (+) side of the circuit, before the speaker and after the variable resistor.
> 2 votes

---
Tags: arduino-uno, electronics, resistor, speaker
---


title: Digispark Serial Port Communication

text:
# Question
Title: Digispark Serial Port Communication
I am using Digispark ATTiny85 and i need to send and receive data through the serial port of my computer. Does anyone have an idea as to how do i proceed with sending STRINGS and NUMBERS through the serial port ??

I have read that the ATTINY 85 does not have a serial port. If that is the case is there any alternative ??

# Answer
> 3 votes
You may use `DigiCDC` to virtually create a serial device. It's slow but does the job as mentioned in this article.

A serial-echo program would look something like this:

```
#include <DigiCDC.h>

void setup() {
  SerialUSB.begin();
}

// the loop routine runs over and over again forever:
void loop() {

  if (SerialUSB.available()) {
    SerialUSB.write(SerialUSB.read());
  }

   //SerialUSB.delay(10);
   /*
   if you don't call a SerialUSB function (write, print, read, available, etc)
   every 10ms or less then you must throw in some SerialUSB.refresh();
   for the USB to keep alive - also replace your delays - ie. delay(100);
   with SerialUSB.delays ie. SerialUSB.delay(100);
   */
}

```

# Answer
> 1 votes
> have read that the ATTINY 85 does not have a serial port.

It depends on your definition of serial port.

From a hardware perspective it has a usi. That can be configured as a uart. Whether it fits your need or not is up to your application. Read the datasheet to be sure.

# Answer
> 0 votes
The ATTiny85 does not have a hardware serial port, but you can use the Arduino SoftSerial library to implement a serial port in software. Have a look at SoftSerial. Or for better performance, including full duplex operation (transmit and receive at the same time) this may be better.

# Answer
> 0 votes
You have a number of options.

1. Go the DigiCDC/SerialUSB path. Or whatever replaces it.
2. (harder), use an I2C to serial bridge, SC16IS750. This has a 64 byte buffer limit so input should be short, typically \[Esc\] or "U" (for firmware update), but basic menu control is possible.
3. Use SendOnlySoftwareSerial, on a free pin as Tx and hook up an FTDI cable or a serial to USB adapter. This is good for PuTTy, Screen, MiniCom etc.

NB. I have no issues with blowing away the bootloader and just using the usb for power to get option 3 to work.

# Answer
> -1 votes
Its quite simple, you need a program on your PC that will send data (that you type) to the serial port.

If you are on Windows then you want a 'Terminal Emulator' program, I don't know what its called on Linux but it will be along the same lines.

If you are using the Arduino IDE then there is already something built in, the Serial Monitor will do the job. You don't even need to be using the IDE for programming you should be able to use the monitor anyway.

Also you can write your own application to do it, but don't do that unless you really have to.

---
Tags: serial, arduino-ide, digispark, attiny85
---


# Question
Title: LCD display not working properly + inconsistent results
I have soldered the pins to my 20x4 LCD display. The soldering is not very good, but this is the best i can do. I have measured the resistance between each of the pins of the LCD with my multimeter to check if the pins are isolated. And they are! So the bad soldering is not the problem...

Last night, the display showed weird results and non-existent characters, all over the 20x4 display. This morning, it showed only full blocks. But now it is showing only 2 of the 4 rows. I think this is weird because i did not touch it in my sleep...

I should see the text 'Welcome', but i only see blocks now.

I dont have a potentiometer any more, so i used a for-loop with a PWM signal to check the contrast i need. This did work the last time for me.

I use the arduino MEGA. Below you see my code, and photo's of my little project.

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(9, 10, 48, 46, 44, 42);

const int contrastPin = 8;

void setup() {
  // put your setup code here, to run once:
  lcd.begin(20,4);
  pinMode(contrastPin,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  lcd.setCursor(0,0);
  lcd.print("Welcome");

  //LOOP TO CHECK TE CONTRAST
  for(int i = 0; i <= 255; i++){
    analogWrite(contrastPin,i);
    delay(30);
  }
}

```

# Answer
I re-soldered the pins. Also, I used a small resistor between my PWM signal and the VO port. Now it works perfectly.
> 0 votes

---
Tags: arduino-mega, lcd
---


title: Function Millis() Arduino

text:
# Question
Title: Function Millis() Arduino
I would like to make a countdown with arduino. To do this I'm using the millis () function, but I have a problem, I can not reset this. Reading on the internet I read that it is not possible to do this. So how can I find an alternative for this? In practice, when I pressed the button I started the countdown, while if I put it back, I went into the pause mode.

---

```
void inizio(){
  Serial.println("INIZIO");

  currentMillis1_general = millis();
  total_1 = currentMillis1_general - currentMillis_general;
  Serial.println(total_1);

  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH){
    step_funzione = 1;
    delay(200);
  }
}

void countdown(){
  Serial.println("COUNTDOWN");

  display.setBrightness(7);

  currentMillis_general = millis();
  total_general = currentMillis_general - total_1;

  if(total_general - previousMillis_general >= interval_general){
    previousMillis_general += interval_general;
    //previousMillis_general = currentMillis_general;
    m = new_tempo/60;
    s = new_tempo%60;
    new_tempo--;
  }

  display.showNumberDec(m, true,2,0);
  display.showNumberDec(s, true,2,2);

  Serial.println(total_general);

  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH){
    step_funzione = 0;
    delay(200);
  }
}

```

# Answer
> 1 votes
A way to accomplish "Reset" is to set your starting value equal to millis() again. To do the equivalent of "Pause", you need a pause counter. When you begin a pause, save millis() to `pauseTime`. When you resume running again, add `millis() - pauseTime` to your pauseCounter. Then your interval should not expire until `millis() - pauseCounter > Interval)`.

---
Tags: arduino-uno, timers, millis
---


# Question
Title: Serial communication between a single Android device and multiple Arduino boards
I am thinking about a project, but I will need let's say two Arduino Uno. I can see that we can just use different USB ports on a PC, but what about an Android device?

I want to "run commands" from it on both Uno boards. Is it possible to connect it as it is single board, just both in parallel? I do not need communication between the boards, just with the smartphone.

For example, let's say that one of the boards will control a green LED and the other a red LED. I want to send from my phone on the serial "toggle green" or "toggle red" and both the boards will change the state of the LED connected to it accordingly to the "command" received. Will both boards be able to receive the "command"?

Thank you!

EDIT: I see that I forgot to add that I may need to receive on the phone from any of the boards. Something like feedback.

# Answer
Use a third Arduino, which serves as a hub. It is connected to your Android and to all Arduino Uno devices you want to interface. It passes the commands to all Arduino devices, and the feedbacks to the Android device. You could use for instance an Arduino Mega, with the Android on Serial0, and the Arduino Uno devices on Serial1 and Serial2.
> 2 votes

---
Tags: serial, communication, android
---


# Question
Title: Arduino IDE giving a blow to battery back-up of PC
When I have *serial plotter* open in the Arduino IDE with serial communication going on, the fans of my PC go full speed. On checking I found that **Java(TM) Platform SE binary(32 bit)** is using about **29%** of the **CPU**.

This gives a big blow to the PC's battery back-up. Is there some way to reduce the CPU usage ?

> The IDE version I use is **Arduino 1.8.4**

```
OS : Microsoft Windows 10 Home (64 bit)

PC : HP Au620 TX (laptop)

processor : Intel i5 7th gen (7200)

RAM : 8GB

```

# Answer
> 0 votes
Run Arduino IDE in a virtual machine which allows CPU allocation. Set a strict limit on CPU resources in that VM, like 200..500 MHz.

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


# Question
Title: Noise when running Arduino close to analogue audio circuit
**TL;DR: My Arduino is injecting a lot of noise into an analogue audio circuit, even when not physically connected.**

I'm experimenting with using an Arduino as a low-frequency oscillator in audio circuits (modular synths, guitar effects etc). I'm using an Arduino Uno powered with a USB + mains plug.

As a test I set up a simple circuit -- I don't believe the circuit matters much in this case but I'm including it here anyway:

simulate this circuit – Schematic created using CircuitLab

The Arduino is set up with one PWM pin supplying 0-5v, varying in a triangle wave (i.e. ramping slowly up, then slowly down again). This is connected to the JFET, which acts as a variable resistor. I have tested the analogue part of the circuit manually and it works as expected.

With the Arduino connected, however, the circuit produces a very loud "squishing" noise that swamps the audio signal passing through it, not unlike someone tuning an old short-wave radio. The noise "squishes" in time to the oscillation of the voltage. It's not unlike the sound in this video associated with the PC power supply: https://youtu.be/lXPJvSU8MwI?t=10m52s.

This happens even if I physically disconnect the PWM pin from the circuit -- the closer its wire is to the circuit, the louder the noise, but it's clearly audible even when they're separated by are a foot or more of air.

Things I've tried:

* Tying the Arduino ground to the analogue circuit ground, and also keeping them separate.
* Adding power filtering caps to both circuits.
* Putting the Arduino in an aluminium box, grounded to either its own ground or the analogue circuit's, or both.
* Powering the Arduino from my laptop instead of plugged directly into the mains.

The analogue circuit is on breadboard right now so some noise is expected, but this is far outside anything I've experienced before even with very badly-behaved circuits.

I'm FAR from knowledgeable about Arduino so my hope is that I'm doing something stupid and easily fixed. I would happily accept an answer that proposes an entirely different way to achieve the desired result.

# Answer
> 1 votes
Arduino PWM signal is about 500Hz, so it will be audible (read: noise) by itself. You could implement a low-pass filter between the PWM pin and your J-FET. A simple RC filter tuned to 5Hz would attenuate a 500Hz signal to -40dB, which probably won't be enough for high quality audio. There are filters with better rejection properties which usually require active components to build. One of the simplest of such filters is the Sallen-Key topology, which can practically double the rejection ratio using a signle active component (opamp).

Another option is to use a simple RC filter, but increase the the PWM frequency (as described here) to achieve high rejection ratio. Eventually, increasing the frequency past the audible range (about 16kHz) will ultimately resolve the noise problem, though I would still use an RC filter to keep the J-FET in linear mode. Apparently, the highest frequency you can achieve at full resolution is 62.5KHz, which is more than enough.

---
Tags: power, audio, analogwrite
---


# Question
Title: Due: Write to digital pin when ADC is running
I have a problem writing to a digital pin on Arduino Due while my ADC is running.

I have the following code:

```
 #undef HID_ENABLED

// Arduino Due ADC->DMA->USB 1MSPS
// by stimmer
// from http://forum.arduino.cc/index.php?topic=137635.msg1136315#msg1136315
// Input: Analog in A0
// Output: Raw stream of uint16_t in range 0-4095 on Native USB Serial/ACM

// on linux, to stop the OS cooking your data:
// stty -F /dev/ttyACM0 raw -iexten -echo -echoe -echok -echoctl -echoke -onlcr

// source: https://gist.github.com/pklaus/5921022
// applied patch 1 from: http://forum.arduino.cc/index.php?topic=137635.msg2526475#msg2526475
// applied patch 2 from:  https://gist.github.com/pklaus/5921022 comment on Apr 2, 2017 from borisbarbour

volatile int bufn,obufn;
uint16_t buf[4][256];    // 4 buffers of 256 readings

void ADC_Handler(){     // move DMA pointers to next buffer
  int f=ADC->ADC_ISR;
  if (f&(1<<27)){
   bufn=(bufn+1)&3;
   // patch 2 start
   //ADC->ADC_RNPR=(uint32_t)buf[bufn];
   ADC->ADC_RNPR=(uint32_t)buf[(bufn+1)&3];
   // patch 2 end
   ADC->ADC_RNCR=256;
  }
}

void setup() {
  SerialUSB.begin(0);
  while(!SerialUSB);

  pmc_enable_periph_clk(ID_ADC);
  adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST);
  ADC->ADC_MR |=0x80; // free running

  ADC->ADC_CHER=0x80;

  NVIC_EnableIRQ(ADC_IRQn);
  ADC->ADC_IDR=~(1<<27);
  ADC->ADC_IER=1<<27;
  ADC->ADC_RPR=(uint32_t)buf[0];   // DMA buffer
  ADC->ADC_RCR=256;
  ADC->ADC_RNPR=(uint32_t)buf[1]; // next DMA buffer
  ADC->ADC_RNCR=256;
  // patch 1.2 start
  //bufn=obufn=1;
  bufn=1;
  obufn=0;
  // patch 1.2 end
  ADC->ADC_PTCR=1;
  ADC->ADC_CR=2;

  // this doesn't work:
  pinMode(52, OUTPUT); //
  digitalWrite(52, HIGH); //
}

void loop(){
  // patch 1.1 start
  while((obufn + 1)%4==bufn);// wait for buffer to be full
  // patch 1.1 end
  SerialUSB.write((uint8_t *)buf[obufn],512); // send it - 512 bytes = 256 uint16_t
  obufn=(obufn+1)&3;
}

```

Pin 52 says 0 V.

With this function, I can pull the digital output voltage to 1.58 V:

```
void digitalWriteDirect(int pin, boolean val){
  if(val) g_APinDescription[pin].pPort -> PIO_SODR = g_APinDescription[pin].ulPin;
  else    g_APinDescription[pin].pPort -> PIO_CODR = g_APinDescription[pin].ulPin;
}

```

Any ideas?

# Answer
> 0 votes
I found the problem: The Arduino had been waiting for the `SerialUSB` Connection.

The Serial connection has not been established because I was running the Arduino without running the corresponding Python script. That script would have opened the Serial connection.

When running the Python script, the Arduino Due then works as expected.

---
Tags: adc
---


# Question
Title: Communicating with magnetic sensor - TLV493D-A1B6 over I2C
I'm using the TLV493D-A1B6 sensor connected to an Arduino Uno: I've attached all necessary documentation at the bottom.

This is a 3D magnetic field position sensor that detects the magnetic field strength of a nearby magnetic field in the X, Y, and Z directions. I am NOT using the 2GO evaluation board. The sensor uses I2C protocol for communication.

I have this sensor all wired up, soldered correctly to a PCB with pinheadings, and ready to go on my breadboard. Also, I am using a bidirectional logic level converter that is recommended for this sensor. I can confirm this as the I2C scanner sketch detects the sensor and prints out its expected defulat address.

Specifically, I am having trouble understanding the data sheets and how to setup Arduino using the 'Wire.h' library to communicate with the sensor over I2C to obtain the X, Y, Z RAW/decoded readings continuously.

I have tried code from this thread: https://forum.arduino.cc/index.php?topic=419380.0 I have tried code from this dedicated tutorial for this sensor: https://www.allaboutcircuits.com/technical-articles/tutorial-and-overview-of-infineons-3d-magnetic-2go-kit/

I have even tried code from Github for this sensor: https://github.com/IRNAS/TLV493D-3D-Magnetic-Sensor-Arduino-Library/blob/master/TLV493D/TLV493D.h

Using any of the above, I will get readings of "X=-1, Y=-1, Z=-1" or the sensor will output random readings of "255" and "0" when exposed to any magnet.

I've written my own code and have failed vigorously to get anything but random, clearly wrong readouts, this was my latest attempt, I chopped this code down for simplicity and clarity. I've also tried variations using the I2C.h master library, but no luck:

```
#include "Wire.h"

const int tlv_addr = 0x1F; // obtained by i2c scanner; all default address of tlv sensor - 0x1F, 0x5E, or 0x3E
const int config_reg = 0x00; // I have scene this in other examples of code for this sensor, I cannot find the "configure" or "command register" address on any of its datasheets
const int lp_mode = 0x05; //Have found this on the data sheet as the low power mode command
// Note: I switched from const byte to const int for HEX assignments because I get a warning when compiling the sketch about this and I found online that this is the solution?

void setup() {
  Wire.begin();   //join I2C bus
  Serial.begin(9600); //start Serial
  while(!Serial); //wait for Serial to be available

  Wire.beginTransmission(tlv_addr); //initiate communication with sensor
  Wire.write(config_reg); //set pointer/access configuration register
  Wire.write(lp_mode); //from what I read, the sensor defaults to power down mode on start up, so I send the low power mode command to the configure register to activate the sensor in low power mode which should cause it to start "sensing"
  Wire.endTransmission(); //end configurations
  delay(100); //delay to allow time for sensor the update
  Serial.print("Setup Complete\n\n");
}

void loop(){
  Wire.requestFrom(tlv_addr, 3); //request the 3 raw, UN-decoded bytes from the sensor's readings of X, Y, Z axes

  //---- Read in each byte of sensor data one by one for each axis ----//
  byte Bx = Wire.read(); //Have scene the "*" added to the beginning of the variable on a lot of code, not sure why this is necessary?
  byte By = Wire.read();
  byte Bz = Wire.read();

  //---- Print Out Sensor Axis Readings ----//
  Serial.println("X= ");
  Serial.print(Bx);       //Have also scene "&" added to the beginning of the variable on a lot of code like Serial.print(&Bx);?
  Serial.print("\tY= ");
  Serial.print(By);
  Serial.print("\tZ= ");
  Serial.print(Bz);

  //Expecting something like this: 01011011
  //Getting -1 or 255 or 0 randomly?

  delay(1000); //arbitrary delay
}

```

And furthermore, I understand that these values needed to be decoded to make sense of the actual data, I have no idea what is going on the register map sheet and why they are shifting different bits of segments of each byte, seemingly like totally picking the bytes apart then reordering them, and then casting them as integers to get real data?

I am very new to Arduino and especially to I2C. If you could please help me understand especially what I'm missing from the data sheet, or what I'm doing wrong in the simplest of terms, I want to intuitively understand whats going on at every step so I can do this again with another I2C sensor on my own. If anyone could please help me with this.

---

sensor: https://www.infineon.com/cms/en/product/sensor/magnetic-position-sensor/3d-magnetic-sensor/tlv493d-a1b6/

datasheet: https://www.infineon.com/dgdl/Infineon-TLV493D-A1B6-DS-v01\_00-EN.pdf?fileId=5546d462525dbac40152a6b85c760e80

Register Map: https://www.infineon.com/dgdl/Infineon-TLV493D-A1B6\_3DMagnetic-UM-v01\_03-EN.pdf?fileId=5546d46261d5e6820161e75721903ddd

# Answer
In your code you read only the 3 first registers and write them to the variables `Bx` to `Bz`. These registers correspond to the correct magnetic values, but only the highest parts of them. The sensor measures 12-bit values - due to the higher precision - , but one register can only hold 8 bits. So the big 12-bit values are splitted into two parts. You will have to read all parts and put them together correctly to get meaningful results. Also the format of the values is a signed 12-bit value in two's complement, meaning that the decimal value is calculated by multiplying the value of the 12th bit with `-1`. You will have to convert this to a 16-bit two's complement for using the `int` type.

In the following part I will use the bitwise AND ( `&` ), the bitwise OR ( `|` ) and the bit-shifting operators ( `<<` and `>>`). I will only shortly explain, how to use them. If you are not familiar with them, please refer to a proper C/C++ tutorial, which can explain this in more detail than this answer.

1. The bitwise AND will compair each bit of the left value with the corresponding bit of the right value. Only if both bits are `1`, the corresponding bit in the output will be `1`, `0` in every other case. I use it to mask some bits of the value away, effectively deleting these bits. Also note the different writing of literal values: In hexadecimal `0x0F` or binary `0b00001111`.
2. The bitwise OR will work as the bitwise AND, but will put a `1` into a bit, when at minimum one of the corresponding input bits is `1`, and outputs `0` to this bit, if the input bits are both `0`. I use this, to put all bytes of one value together into one variable.
3. The shifting operators `<<` and `>>` will shift the bit values to one side. The bits, that are getting out of the values range are lost. On the other side zeros get shifted into the value. I use it for the proper alignment in bytes of a bigger value.

This is the important figure from the user manual. It tells you, that you will find bits 11 to 4 of the Bx value in the first register (11 is the most significant bit). The rest of the Bx value is to be found in the 5th register in the 4 most significant bits (bits 3 to 0 of the Bx value). So to get the correct values, we first need to read all the data (I will include the temperature here):

```
// Request 7 bytes from the sensor and return, if it didn't send enough (do not read, if there is nothing to read)
if(Wire.requestFrom(tlv_addr, 7) < 7) return;
// Read all registers to variables
byte bx_high = Wire.read();
byte by_high = Wire.read();
byte bz_high = Wire.read();
byte temp_high = Wire.read();
byte bxy_low = Wire.read(); // This has to be read together. We will split the values later
byte bz_low = Wire.read();
byte temp_low = Wire.read();

```

Now we put together the splitted values in one variable each. To avoid complications with types, I use `unsigned int` here, which is like `byte`, but containing 16 bit. For `Bx` we have to shift the high part 4 bits to the left, since the lower part needs 4 bits of space. Also we have to seperate the lower parts of Bx and By. Since the lower part of Bx lies in the highest 4 bits of the read value, we need to shift them right for alignment with the least significant bit. The rest works similar, but is a bit easier. The temperature value uses another alignment, but the principle is the same.

```
unsigned int bx_value = (bx_high << 4) | ((bxy_low & 0xF0)>>4);
unsigned int by_value = (by_high << 4) | (bxy_low & 0x0F);
unsigned int bz_value = (bz_high << 4) | (bz_low & 0x0F);
unsigned int temp_value = (temp_high >> 4) | temp_low;

```

Now we have packed the 12-bit values into 16-bit unsigned integers. We now have to convert them to 16-bit signed integers. But if we simply cast them, this would result in false values, since the complemented bit here is the 16th, not the 12th like in the sensor. For solving this we use the answer from this question:

```
int16_t Bx = (int16_t)(bx_value << 4) / 16 ;

```

There is one difference from the answer: We have a 12-bit two's complement, not a 14-bit one. So we have to shift 4 bits, not 2. This corresponds to dividing by 16 (a factor of 2 for each shifted bit).

Now you should have the correct measured values from the sensor.

---

You may have a second issue with your code. It read the registers every second, without regard to the state of the sensor. The datasheet says:

> This sensor does not incorporate shadow-buffers for readout. Thus, it is mandatory to read the sensor data not during a running conversion to avoid corrupted reads.

So you might also get garbled values because you sometimes read the registers during the sensor writes in them. This may be not a great issue here (maybe it only happens once in a while). But you can circumvent this problem by either using the INT pin of the sensor for triggering a I2C read operation (at best via an interrupt) or by configuring the sensor to run in the "Master Controlled Mode", where it only does a new measurement, when the old values have been read from the registers.
> 0 votes

---
Tags: arduino-uno, sensors, i2c, communication
---


title: What is xrotor micro 30A?

text:
# Question
Title: What is xrotor micro 30A?
I was watching a video on how to build your own drone and this is one of the items. I tried to understand what it actually does but I couldn´t find any simple information.

I would like to know: \- what it does and \- if it could be replaced by an arduino

Thanks !!

Here is the video: https://www.youtube.com/watch?v=bQib0sAhUc4

# Answer
> 0 votes
The XROTOR MICRO is an ESC, which means Electronic Speed Control. It is essentially the motor driver in a quadcopter. Most quadcopter use brushless motors, because they are more fitted for the fast speeds of the propeller. But brushless motors aren't as easy to drive as simple DC motors. The current through the different coils has to be commutated depending on the current speed of the motor. The ESC does this for you and takes a PWM wave as input, whose duty cycle marks the requested speed. 30A is the current specification for this ESC. For more information google brushless motor.

> if it could be replaced by an arduino

Short answer: No.

Long answer: An ESC is a highly specialized device, which is very fast and drives high currents. It may be possible to build something like an ESC with an Arduino in it's heart, but this would be a dumb way to waste your time. The Arduino would be busy controlling the motor, so that it would not be able to do anything else. If you look at how many different peripherals the Arduino embodies, this is a total waste. Also the Arduino cannot drive these high currents by itself. You would have to add extra components to do this. If you are able to build this, it would be much bigger than a normal ESC.

All in all: If you aren't a crack in electronics and want to try this just for achieving, then you should simply buy an ESC for your drone project. Mostly Arduinos have vanished from modern drones, because there are many boards, that are better fitted for this.

---
Tags: drone
---


# Question
Title: Traffic signal simulation: A minor doubt
I am trying to simulate a traffic signal with a provision of a pedestrian button, that when pressed, stops the traffic for a while. Here are the conditions I'm trying to meet,

One green LED (on pin 10) lit for 3 seconds (the first LED to light up). \- Then one orange LED (on pin 11) lit for 1 second \- Then finally one red LED (on pin 12) lit for 3 seconds.

Two-colour light (pedestrian) \- The pedestrian light is constantly red (red LED on pin 9) and only turns green (LED on pin 8) once the button (on pin 2) is pressed.

> **On button press** If the button is pressed while the car traffic light is green, the orange light is lit for 1 second, then the car lights turn red for 5 seconds during which the green pedestrian light is green.

After those 5 seconds, the pedestrian light turns red again and normal functioning resumes (car traffic light returns to green)

And here's my code for the same,

```
int status=0;    //mode:state of button pin
int buttonpin=2;//pin related to pushbutton
void setup(){
  pinMode(10,OUTPUT);   //Green LED to pin10
  pinMode(11,OUTPUT);   //Orange LED to pin11
  pinMode(12,OUTPUT);   //Red LED to pin12
  pinMode(9,OUTPUT);    //Pedestrian Red on pin 9
  pinMode(8,OUTPUT);    //Pedestrian Green on pin 8
}

void loop(){

  digitalWrite(9,HIGH);//Pedestrian Red is on
  status=digitalRead(buttonpin);

  if (status==HIGH){
    digitalWrite(9,LOW); //pedestrian red is off
    digitalWrite(8,HIGH); //Pedestrian Green is on
    digitalWrite(11,HIGH);//orange lights up
    delay(1000);//1second delay
    digitalWrite(11,LOW);//orange shut off);
    digitalWrite(12,HIGH);//red starts
    delay(5000);//5 second delay
    digitalWrite(12,LOW);
    digitalWrite(9,HIGH);
  }
  else{
    digitalWrite(10,HIGH);//green lights up
  delay(3000);//3 second delay
  digitalWrite(10,LOW);//green shuts off
  digitalWrite(11,HIGH);//orange lights up
  delay(1000);//1second delay
  digitalWrite(11,LOW);//orange shut off);
  digitalWrite(12,HIGH);//red starts
  delay(3000);
  digitalWrite(12,LOW);//red shuts off
 }
}

```

The problem is, the pedestrian button only works when it is already pressed at the time of Traffic Green starting(because of the if loop right there in code), but once Traffic green has already been green for say 1.5 seconds, it won't work as the if loop condition check has been already passed. How can I mend my code to make the "On button Press" sequence explained above work at any time of the Green LED HIGH?

Attached is the circuit if the need be.

Edited code is:

```
#include <TimerOne.h>

int status=0;    //mode:state of button pin
int buttonpin=2;//pin related to pushbutton

void setup(){

  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);

  Timer1.initialize(100000);
  Timer1.attachInterrupt( buttonCheck );

}

void loop(){

  digitalWrite(9,HIGH);
  status=digitalRead(buttonpin);

  digitalWrite(10,HIGH);//green lights up
  delay(3000);//3 second delay
  digitalWrite(10,LOW);//green shuts off
  digitalWrite(11,HIGH);//orange lights up
  delay(1000);//1second delay
  digitalWrite(11,LOW);//orange shut off);
  digitalWrite(12,HIGH);//red starts
  delay(3000);
  digitalWrite(12,LOW);//red shuts off

}

void buttonCheck(){

   if (status==HIGH){
    digitalWrite(9,LOW);
    digitalWrite(8,HIGH);
    digitalWrite(11,HIGH);//orange lights up
    delay(1000);//1second delay
    digitalWrite(11,LOW);//orange shut off);
    digitalWrite(12,HIGH);//red starts
    delay(5000);//5 second delay
    digitalWrite(12,LOW);
    digitalWrite(9,HIGH);
    return;
  }
}

```

Will this work?

# Answer
The cause of the issue, is the way you have implemented `delay()` in your sketch. It's true that `delay()` should be avoided 99.9% of the time, but it does have it's uses.

If you start with the BlinkWithoutDelay example that comes with the Arduino IDE, then add a counter variable and a switch statement, you can easily get the traffic lights "part" of your requirements working.

Adding the pedestrian button functionality using non-blocking code is more difficult (for me it's more difficult), but it's a problem easily solved using `delay()`.

But what if you ever want your sketch to do more? What happens if you add another button to it? `delay()` is "blocking" code, so using it will probably "bite" you again if you try to add functionality to this sketch.

```
const byte buttonPin = 2;
byte secondsCounter = 0;
byte trafficLightState = 0;
unsigned long oneSecond = 1000;
unsigned long previousMillis = 0;

void setup(){
  pinMode(10, OUTPUT);   // Green LED to pin 10
  pinMode(11, OUTPUT);   // Orange LED to pin 11
  pinMode(12, OUTPUT);   // Red LED to pin 12
  pinMode(9, OUTPUT);    // Pedestrian Red on pin 9
  pinMode(8, OUTPUT);    // Pedestrian Green on pin 8
  // I used a wire from GND to "buttonPin" as a switch.
  pinMode(buttonPin, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){

  // Get the current time.
  unsigned long currentMillis = millis();

  // If the button is pressed while the car traffic light is green,
  // the orange light is lit for 1 second, then the car lights turn
  // red for 5 seconds during which the green pedestrian light is green.
  if(trafficLightState == 0 && digitalRead(buttonPin) == LOW){
    digitalWrite(10, LOW);
    digitalWrite(11, HIGH);
    digitalWrite(12, LOW);
    digitalWrite(9, HIGH);
    digitalWrite(8, LOW);
    Serial.println("Button Pressed. Orange light ON for 1 second, Pedestrian red ON.");
    delay(1000);
    digitalWrite(11, LOW);
    digitalWrite(12, HIGH);
    digitalWrite(9, LOW);
    digitalWrite(8, HIGH);
    Serial.println("Red light ON for 5 seconds, Pedestrian green ON.");
    delay(5000);
    digitalWrite(11, HIGH);
    digitalWrite(12, LOW);
    digitalWrite(9, HIGH);
    digitalWrite(8, LOW);
    Serial.println("Pedestrian red ON.");
    trafficLightState = 0;
    secondsCounter = 0;
    currentMillis = millis();
  }

  // Update the traffic light state every second.
  if(oneSecondTimer(oneSecond, currentMillis) == 1){

    secondsCounter += 1;
    if(secondsCounter > 7){secondsCounter = 1;}

    // Green traffic light.
    if(secondsCounter == 1){
      trafficLightState = 0;
      Serial.println("Green traffic light ON for 3 seconds");
    }
    // Orange traffic light.
    else if(secondsCounter == 4){
      trafficLightState = 1;
      Serial.println("Orange traffic light ON for 1 second");
    }
    // Red traffic light.
    else if(secondsCounter == 5){
      trafficLightState = 2;
      Serial.println("Red traffic light ON for 3 seconds");
    }
  }

  // Turn the traffic lights on/off as required.
  switch(trafficLightState){

    // Turn the green traffic light ON, pedestrian red ON.
    case 0:
      digitalWrite(10, HIGH);
      digitalWrite(11, LOW);
      digitalWrite(12, LOW);
      digitalWrite(9, HIGH);
      digitalWrite(8, LOW);
      break;

    // Turn the orange traffic light ON, pedestrian red ON.
    case 1:
      digitalWrite(10, LOW);
      digitalWrite(11, HIGH);
      digitalWrite(12, LOW);
      digitalWrite(9, HIGH);
      digitalWrite(8, LOW);
      break;

    // Turn the red traffic light ON, pedestrian red ON.
    case 2:
      digitalWrite(10, LOW);
      digitalWrite(11, LOW);
      digitalWrite(12, HIGH);
      // Pedestrian green light ON ONLY if button was
      // pressed while the traffic light was green.
      // digitalWrite(9, LOW);
      // digitalWrite(8, HIGH);
      break;
  }
}

byte oneSecondTimer(unsigned long delayTime, unsigned long currentMillis){
  if(currentMillis - previousMillis >= delayTime){previousMillis = currentMillis;return 1;}
  else{return 0;}
}

```
> 0 votes

---
Tags: led
---


# Question
Title: How can I program an arduino in pure C/C++?
I am a beginner and I want to learn AVR C/C++. Can I do this using an Arduino? (I'm asking this because I already have one).

If so, could someone tell me using which IDE can I write code in pure C/C++ and then flash it to the Atmega328P on the Arduino? Or, should I get an AVR and a programmer instead?

I've searched all over the internet and I'm really confused by all the terminology. Could someone explain it to me?

# Answer
> 4 votes
Yes, get an AVR programmer instead.

1) You can flash your arduino board with **avrdude/avr-gcc**. Install these tools, find the datasheet of atmega328 (google it), use the board pinouts to connect to your programmer (stk500v2/ISP) and voila!

2) Keep in mind that by "manually" flashing your atmaga on arduino board you're removing bootloader that is needed to load your sketches from ARDUINO IDE.

3) Use your favourite C/C++ IDE

# Answer
> 3 votes
If you're a beginner, I suggest you write C in the Arduino IDE. The libraries are very useful and I think the Arduino/Wiring/Processing environment will cover all your needs.

Check out the Lightblue Bean (http://punchthrough.com/bean/) it is a good example of the power of that platform. Even experienced embedded programmers can use it, since the underlying register are still accessible.

I am now programming on the Ti MSP430, and while I can appreciate the possibilities, I miss the simplicity of Arduino; much easier to get started with Arduino.

Go to http://arduino.cc/en/main/software to download the 1.0.6. IDE software, plug your Arduino, go to Tools-\>Board to select your Arduino, select the appropriate "tty" port in the Tools-\>Serial\_Port. Then write in pure C and download. There are tons of examples included with the IDE.

# Answer
> 2 votes
An Arduino is programmed in C/C++. There is a common misconception that Arduino has its own language. See this link C++ vs. The Arduino Language? for a full discussion on Arduino being C/C++ and the simplifications Arduino offers. Further more, you can see the Arduino core code here.

### From the Arduino website:

> Can I program the Arduino board in C?
> In fact, you already are; the Arduino language is merely a set of C/C++ functions that can be called from your code. Your sketch undergoes minor changes (e.g. automatic generation of function prototypes) and then is passed directly to a C/C++ compiler (avr-g++). All standard C and C++ constructs supported by avr-g++ should work in Arduino. For more details, see the page on the Arduino build process.

Arduino offers an easy learning curve for beginners through to experts. So simply download the latest Arduino IDE, install it and enjoy.

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


# Question
Title: Input voltage from circuit drops despite Arduino turned off
I'm using an Arduino Uno to emulate an old Atari disk drive as described here: http://whizzosoftware.com/sio2arduino/

As both the Atari and the Arduino use 5V TTL serial communication, the hardware setup is pretty simple, RX and TX are crossed over, GND is connected an an additional line is used for status information.

All works fine when the Arduino is the only device connected to the Atari's serial port (called SIO). Since the SIO bus is a daisy-chain bus, I should be able to hook up serval devices after each other. However, once I connect an original floppy drive together with the Arduino, both the original floppy drive as well as the one emulated by the Arduino stop working.

What made me wonder is that the original drive couldn't be accessed even if the Arduino was turned off but the wiring left in place. Only after I removed the RX and TX pins from the connection, the original drive could be accessed.

I checked with a scope and realized that data transmission was still reaching both devices, however idle voltage was just around 2V instead of 5V. I then checked the resistance on the Arduino between the digital input pins as well as RX/TX in relation to GND and got (varying, depending on the scale I set my multimeter) values that probably have the effect of a voltage divider and thus reduced the voltage on the whole bus by about half.

I was thinking to add a resistor on the RX/TX lines coming from the SIO bus in order to maintain the voltage on the bus, but that would effectively mean that also less current reaches the Arduino RX/TX pins and might therefore render it useless if the voltage drops below the point where the Arduino can distinguish between logical high and low.

Or is there a way to circumvent these internal resitors between the digital inputs and GND? Does this have anything to do with the pull-up/pull-down resistors which I could probably only influence when the Arduino is on?

Thank you in advance for any pointers (other than adding another switch to physically remove RX/TX from the bus when the device is off ;) )!

# Answer
> 4 votes
To protect the internals of integrated circuits many contain diodes at most input and output pins to VCC. In normal operation where the voltage at these pins are not expected to become greater than VCC, these diodes are not in forward bias. However, should the unexpected happen and the voltage at these pins does become higher than VCC the diodes are in forward bias. That is to say, the diodes try to keep the voltage at the pin no higher than VCC.

When you removed the power from the Arduino you essentially lowered VCC to zero. This will likely forward biased the diodes inside the Arduino and drive the voltage at the pin toward zero.

There is a good discussion of this in this Electrical Engineering StackExchange question & answer.

# Answer
> 1 votes
Although st2000 already answered my question, I still wanted to add how I solved the problem in case someone else faces the same situation:

What in the end worked for me was to add a 560 Ohm resistor each at the entry points of the RX/TX lines. This was low enough that the Arduino was still be able to distinguish logical high and low, and high enough that the SIO bus is still working when the Arduino is powered off. 470 Ohms was already too low to shield the SIO bus, 680 Ohms was too high for the Arduino to function properly when in use. I don't know if there is a way to calculate these values properly, but at least they work for me.

---
Tags: arduino-uno, serial, voltage-level
---


# Question
Title: ADS1115 : measuring 5v voltages and powering with 3.3v
I have a project where I need to measure 0 - 5 V. I’m using a ADS1115 to have a better precision, connected to a ESP12. Since the ESP is only 3.3 V tolerant and the ADS powered by 5 V (because it needs to be powered a the same voltage as the measured voltage), I put the two pull-up resistor of the I2C bus on 3.3 V.

Is it safe to operate like this?

# Answer
Is your arrangement safe? Yes, perfectly.

Is your arrangement a good idea? No, it is not.

When the ADS1115 is run at 5V it needs at least 3.5V on the I2C bus to properly register a HIGH.

However you can pull up to 5v instead and you won't have a problem. Not only is the ESP8266 tolerant of 5v, but that 5v is severely limited in current by the pull-up resistors, so even non tolerant inputs would have a hard time complaining. Worst case scenario, the ESP8266 pulls the bus down to maybe 3.8v (3.3v plus an ESD diode drop) which is fine for a logic high on the ADS1115.

However, if you want to do things properly, you really should use a proper I2C level translator.
> 3 votes

---
Tags: esp8266, i2c
---


# Question
Title: Communication with Arduino and electronic device(for example tv or computer) through rs 232 cable
> Say some electronic device (TV OR Computer) has an inbuilt program. Depending on received data from Ardiuno, it displays some text based on requirement. For example, if it receives 1 it should display 'error', else if it receives 0 it should display 'ready'.
>
> I am working on only sending signals/bytes from Arduino Uno to some device which already has an inbuilt program. I just want to send 0 or 1 byte from the Ardiuno to the device using TTL to RS 232 COVERTER. this is the code

```
#include<SoftwareSerial.h>

 #define rxPin 0 //make pin o as rx pin

 #define txPin 1//make pin 1 as tx pin

 SoftwareSerial mySerial(rxPin ,txPin);//i donot undersatnd this line (i got
 the code from net//

 void setup()

 {

     pinMode(rxPin,INPUT);//making rx as input//
     pinMode(txPin,OUTPUT);//making tx as output//
     Serial.begin(9600);
     mySerial.begin(9600);
}

void loop() {
// put your main code here, to run repeatedly:
Serial.print(0x00);//i want to send 0 byte data from ardinuo to device //
delay(200);
}

```

> I am using RealTerm software to check if the signals I have sent from the Arduino Uno are received as they have to be (without any interference).
>
> I am sending continuously 0 from ardinuo to realterm in this case(for testing purpose). I am receiving in RealTerm in Hexadecimal format. Since I'm sending 0s continuously, I should be getting a continuous output of 0s on RealTerm as well. Instead, I am getting some random values initially (while uploading the sketch) and RealTerm stops displaying output soon after.
>
> Can someone please help me solve my issue.
>
> **Update 1:** i have modified my code as per @chrisl's suggestion. Now, whn i send 0 i am getting a correct ouput ,but whn i am sending 1 contineosly i am getting many 0's and random values

```
#include<SoftwareSerial.h>
#define rxPin 2
#define txPin 3
SoftwareSerial mySerial(rxPin ,txPin);
void setup()
 {
 pinMode(rxPin,INPUT);
  pinMode(txPin,OUTPUT);
  Serial.begin(9600);
  mySerial.begin(9600);
  }

  void loop() {
     // put your main code here, to run repeatedly:
  Serial.print(0x01);//i want to send 1 byte data from ardinuo to
  device(realterm)
  delay(200);
   }

```

# Answer
You have 2 problems:

1. You use the `Serial.print()` function, which outputs ASCII encoded characters. When sending "0" this way, actually the value `48` (or `30` in hex) will be send. RealTerm seems to display hexadecimal values, so you would get a long series of "30"'s. This is not really a big problem, you only shouldn't expect zeros to display there with this code. You can use the `Serial.write()` function to send direct byte values instead of ASCII codes.
2. You initiate the SoftwareSerial on the same pins, that are reserved for the Hardware Serial. This cannot work properly, because both libraries will try to use the same pins. Choose other pins for Rx and Tx of the SoftwareSerial interface.

---

EDIT:

Also you are setting pin modes for Rx and Tx of the SoftwareSerial. I don't know, if this can cause a problem, but at least you don't have to do this. The library will handle setting the pins correctly.

EDIT2: Further explanation about binary, hexadecimal and ASCII representation of the Serial byte stream

There are different methods to display a stream of byte data (like the stream from your Serial interface). Let's look at the decimal value (the one you are using when invoking arithmetic operations like `+`, `-`) `48`. These are the different representation of this number in different numeral system (The first two characters mark the numeral system; 0b for binary, 0x for hexadecimal):

* binary: 0b00110000
* hexadecimal: 0x30

There are more numeral systems, but these are the most important ones. But the byte stream can also be used to look like a sequence of characters. For this the ASCII standard was born long time ago. In simple ASCII every value from 0 to 127 got assigned to a character or control action. The terminal program reads the byte stream and shows the corresponding characters according to the ASCII table. There are expansions to this model, to display more possible characters, but this is the very basic principle. With it, you are able to actually send human readable text from your Arduino to another device.

The `Serial.print()` function is made for this human readable text, so it will send an ASCII representation of the input parameter. The ASCII value of the character "0" is 48, which corresponds to a hexadecimal value of 30.

Now I'm not sure, if your terminal program shows hexadecimal or ASCII values. I though of the first, because all characters in your first image are digits or characters from A to F, which is the range of hexadecimal values. It didn't seem likely to not get other characters, when you have ASCII encoded text with random values in it. But I'm currently not sure, if the `Serial.print()` function would automatically print a hexadecimal representation in form of ASCII text, if given a hexadecimal value (I don't think so, but it might be possible). Please try to use the `Serial.write()` function and try sending different value while watching the output of RealTerm.

And please search for a settings, that determines, how the received byte stream is interpreted. This would make clear, what RealTerm is doing here. Also make sure you understand the relation between binary value and ASCII character. If this is still not clear enough, you can google for in detail explanations. There are tons of tutorials on that.
> 0 votes

---
Tags: arduino-uno, rs232
---


# Question
Title: How can I set up a watchdog interrupt vector timer on the Arduino Redboard/Uno?
I'm trying to set up a watchdog timer interrupt to execute a routine in the WDT\_vec ISR at some recurring interval. I don't want the processor to reset, just to execute the code in the interrupt and return to "normal" operation. I have the following test jig appropriated from the 'net that claims to set that up:

```
#include <avr/wdt.h>

 void setup_WDT() {
      noInterrupts();  // disable all the interrupts
      MCUSR = 0;       // ensure that the reset vectors are off

      /* Disable and clear all Watchdog settings. */

      _WD_CONTROL_REG = (1 << WDCE) | (1 << WDE);
      _WD_CONTROL_REG = 0;

      /* Setup Watchdog for interrupt and not reset, and a approximately 500ms timeout */
      _WD_CONTROL_REG = (1 << WDIE) | (1 << WDP2) | (1 << WDP0);

      interrupts();  // re-enable interrupts
    }

void setup() {
  setup_WDT();
  Serial.begin(9600);
  Serial.println("Startup");
}

void loop() {
}

ISR(WDT_vec) {
  Serial.println("Watchdog Interrupt");
}

```

The output indicates that the processor is just resetting repeatedly and never reaching the ISR. Also I get the following warning on compilation from the IDE (Arduino 1.8.2):

> warning: 'WDT\_vec' appears to be a misspelled signal handler, missing \__vector prefix \[-Wmisspelled-isr\] ISR(WDT\_vec) {

# Answer
> 1 votes
Two errors:

1. The watchdog interrupt vector is named `WDT_vect`, not `WDT_vec`.
2. The statement `_WD_CONTROL_REG = 0;` serves no useful purpose, and will likely mess up with the timed sequence for changing the watchdog setting. Just remove it.

# Answer
> 0 votes
\_WD\_CONTROL\_REG = 0; serves an important purpose. If the Watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the Watchdog Timer will stay enabled. If the code is not set up to handle the Watchdog, this might lead to an eternal loop of timeout resets. To avoid this situation, the application software should always clear the Watchdog System Reset Flag (WDRF) and the WDE control bit in the initialization routine, even if the Watchdog is not in use. if you are using it in developing a product whose programme should never freeze than this is important to remember.

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


# Question
Title: Unable to obtain pulse train at 32Hz with 20us pulse width with Uno
I tried to obtain 32Hz pulse train(between 30Hz and 35Hz is also fine) with around 20us pulse width with Arduino Uno but couldn't succeed. The problem is:

If I do the following:

```
void setup() {

    TCCR1B = TCCR1B & B11111000 | B00000101;

    pinMode(pwmPin9, OUTPUT); // sets the pin as output

}

void loop() {

analogWrite(pwmPin9, 1)

}

```

I can set the freq. roughly at 30Hz but analogWrite(pwmPin9, 1) will give minimum 100us cannot go down to 20us.

digitalWrite method with delay on the other hand doesn't work to obtain frequencies below about 60Hz.

How can I obtain a pulse train output with between 30Hz to 35Hz and with around 20us pulse width?

# Answer
For this kind of problems, the first thing to do is convert the two relevant times (the signal period and the duration of the `HIGH` state) into a number of CPU cycles. With a 16 MHz clock that gives:

* HIGH time: 20 µs = 320 CPU cycles
* period: 31.25 ms = 500000 cycles (±7%)

Then divide those numbers by the available prescaler values, to get the corresponding number of prescaled clock cycles:

```
prescaler       1      8    64     256      ...
HIGH time     320     40     5       1.25   ...
period     500000  62500  7812.5  1953.125  ...

```

Ideally, you want a prescaler that gives you integer numbers, in order to avoid rounding errors. And since you are using a 16-bit timer, you want these numbers to be no larger than 216. Or twice that if you use a phase-correct PWM mode, but I prefer to avoid that complication if possible.

From the table above, it appears that a prescaler of 8 is ideal. 64 would be practically as good, with a frequency error of only 64 ppm, which is less than the frequency tolerance of the ceramic resonator clocking your Uno.

Then you use either `OCR1A` or `OCR1B` to set the high time, depending on whether you are outputting to pin OC1A (digital 9) or OC1B (digital 10). An you use either `OCR1A` or `ICR1` to set the period. Since you are outputting on pin 9, the `OCR1A` register will be used to set the high time, thus you have to use `ICR1` to set the period. Then you search the table of modes in the datasheet and find the one relevant to this mode of operation is mode 14: fast PWM with the TOP value defined by ICR1. This gives the following configuration:

```
void configure_timer_1()
{
    DDRB  |= _BV(PB1);    // set pin 9 = PB1 = OC1A as output
    TCCR1A = 0;           // reset timer
    TCCR1B = 0;           // ditto
    OCR1A  = 40 - 1;      // HIGH for 40 * 8 CPU cycles
    ICR1   = 62500 - 1;   // period = 62500 * 8 CPU cycles
    TCCR1A = _BV(COM1A1)  // non inverting PWM on pin OC1A
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS11);   // clock at F_CPU/8
}

```

Note that `OCR1A` and `OCR1B` have to be set to desired number of cycles minus one.
> 1 votes

# Answer
`analogWrite` is 8-bit.

The reciprocal of 30Hz (the time per full period) is 0.0313.

0.0313 divided by 256 (28) is 0.000122, or 122uS.

At 8 bits that's the smallest time that the 30Hz waveform can be cut up into.

To get smaller slices you need a higher resolution PWM signal. This question and answer shows how it can be done, but it's limited to which pins can be used, since you need the PWM channels attached to the 16-bit timer.
> 0 votes

---
Tags: pwm, timers
---


# Question
Title: How to read OC0A when in CTC (toggle) mode?
I have this code, which puts the Arduino into CTC mode with interrupts, and outputs a square wave on `PD6` (`OC0A`):

```
void setup_timer(double p_ms, double duty){
  DDRD |= (1 << 6);  // set pin 3 as output
  TCCR0A = _BV(COM0A0); // toggle OC0A on Compare Match
  TCCR0B = _BV(WGM01); // set CTC mode WGM0[2,1,0] = 0b010
  TIMSK0 |= _BV(OCIE0A); // Enable CTC interrupt
  OCR0A = 128;  // set on and off time
  TCCR0B |= ( (0 << CS02) | (0 << CS01) | ( 1 << CS00)); // CS02:0 - No prescaling
  sei();
}

```

In the `ISR` (which is not shown) I want to be able to see whether `OC0A` (i.e. `PD6`) is `HIGH` or `LOW`.

I assumed that I could do a `digitalRead()`, but this post, Re: How to read the state of an output pin ? says:

> Looking at the code the digitalRead() function just does a read of the appropriate bit in the appropriate PINx register without modifying anything, so it should work.
>
> One catch, if it's a PWM pin the PWM will be stopped.

So, will the toggling of `OCR0A` be stopped?

This answer to How can I digitalRead a pin that is in pinMode OUTPUT? suggests reading PORTD directly, with

```
bitRead(PORTD,6);

```

However, will that work for PWM output or will PWM also be stopped by reading `PORTD`?

---

### Addendum

I plan to use this code either as (primarily) a stand alone AVR µController (48/88/168/328 IC), but maybe in a Nano/Uno (if it will work) for *testing purposes*. I understand that using `Timer0` will affect the operation of `millis()`, `delay()` etc., but the rest of the code will not rely on any of those functions... so I presume (maybe incorrectly) that the code will work as expected. Is that correct?

In addition, I don't intend on using a `setup()` & `loop()` program structure but rather `main()`. Just out of interest, would `loop()` work (i.e. is it reliant on `Timer0`)? I don't believe that it is.

# Answer
If you look into the Arduino Core, you'll find this code for the digital read:

```
int digitalRead(uint8_t pin)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

    // If the pin that support PWM output, we need to turn it off
    // before getting a digital reading.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    if (*portInputRegister(port) & bit) return HIGH;
    return LOW;
}

```

That means, disabling PWM is just weird feature in `digitalRead`.

For reading `bitRead(PORTB,3);` I'm not so sure if you'll get output value of `OC0A`, it might be different signal line internally. However you'll get logical level on the port pin by reading `bitRead(PINB,3);`.
> 2 votes

# Answer
**Preliminary note**: If you are using any of the ATmega48/88/168/328, then the OC0A pin is PD6, not PB3.

As four your idea of reading the PORT register (`PORTD`, not `PORTB`), it won't work either, as that will only tell you what was the last value that was written to the port with `digitalWrite()`. Here is a schematic showing how the timer controls the output pin. It's taken from the ATmega328P datasheet, but the other AVRs of that family behave identically in this respect:

As shown in the schematic, the value written to the port comes from a multiplexer and is controlled either:

* by the PORT flip-flop when the timer is *not* generating a PWM output
* or the OC0A flip-flop when it is.

Quite importantly, the timer does *not* write to the PORT register, it only overrides it.

Thus, it would look like you want to read the OC0A flip-flop in your ISR. Alas, this schematic also shows that, contrary to the PORT flip-flop, the OC0A flip-flop is *not* connected to the data bus. Thus you cannot read it, and it doesn't even have an address.

What I would recommend is to read the PIN register instead. This won't tell you what the timer is writing to the port, but what you can read back. However, unless the pin is loaded well beyond its absolute maximum rating, what you read back what has been written. There is a small delay between the write operation and the value been available to read back (a couple of CPU cycles IIRC), but this is way shorter than the execution time of an ISR prologue.
> 2 votes

---
Tags: pwm, avr
---


title: Cannot access SD card on WINC1500

text:
# Question
Title: Cannot access SD card on WINC1500
I have a WINC1500 shield and have the Wi-Fi side working fine. I want to do some datalogging to the SD card and am having trouble getting it running. I have bought a 16 GB Sandisk card and inserted it. I have added the SD library, `SD.h` is included. However `SD.begin()` fails. I have a Mega2560 card (from Elegoo) so should be able to run the SD and wifi at the same time? Do I need to pass a parameter to `SD.begin()`?

The code below always prints "Card failed to initialise, or not present".

```
if(!SD.begin())
{
    Serial.println("Card failed to initialise, or not present");
}
else
{
    Serial.println("Card initialised ok");
}

```

# Answer
> Do I need to pass a parameter to SD.begin()?

Yes, you need to pass the Chip-Select (CS/SS) pin number. What number depends on how you have it hooked up, the default is 10. (*yours might be 4*)

n.b. according to the docs a standard arduino can't use the WiFi, and the SD at the same time; presumably the mega has enough memory.
> 1 votes

---
Tags: sd-card
---


# Question
Title: Double Speed Operation for USART on Arduino Mega 2560
I happened to be looking through the HardwareSerial.cpp file that contains the functions used for Serial communication for Arduino. While looking through the HardwareSerial::begin(baud, config) function, I noticed that the ucsra register has its U2X0 bit set. When I looked through the datasheet, it says that the U2X0 bit is set to start Double Speed Operation. From what I'm reading, this means that the baud rate is doubled.
I've been using this Arduino on this computer for a while now with no complaints for the baud rate being at an incorrect speed. What is Double Speed Operation? Why does it seem to be set in the code by default? I attached the code and section in the manual below.

```
void HardwareSerial::begin(unsigned long baud, byte config)
{
  // Try u2x mode first
  uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;
  *_ucsra = 1 << U2X0;

  // hardcoded exception for 57600 for compatibility with the bootloader
  // shipped with the Duemilanove and previous boards and the firmware
  // on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot
  // be > 4095, so switch back to non-u2x mode if the baud rate is too
  // low.
  if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095))
  {
    *_ucsra = 0;
    baud_setting = (F_CPU / 8 / baud - 1) / 2;
  }

  // assign the baud_setting, a.k.a. ubrr (USART Baud Rate Register)
  *_ubrrh = baud_setting >> 8;
  *_ubrrl = baud_setting;

  _written = false;

  //set the data bits, parity, and stop bits
  #if defined(__AVR_ATmega8__)
    config |= 0x80; // select UCSRC register (shared with UBRRH)
  #endif
  *_ucsrc = config;

  sbi(*_ucsrb, RXEN0);
  sbi(*_ucsrb, TXEN0);
  sbi(*_ucsrb, RXCIE0);
  cbi(*_ucsrb, UDRIE0);
}

```

# Answer
When in double-speed mode, as noted in the manual, fewer samples are used. In Asynchronous serial communication, there is no clock signal, so the clock that keeps the two devices in sync is extrapolated from the data signal. Each end of the communication has it's own clock source (crystal oscillator, ceramic resonator, R-C oscillator, etc.), and you'll rarely find two that are calibrated identically.

The receiver samples the signal at a higher rate than the actual baud rate so that it can better determine where, relative to it's own clock, the data-signal edges go up or down and continually adjusts its offset to compensate for clock drift.

By operating in double-speed mode, the receiver has fewer samples to work with, and so if your transmitter has a clock source that is different enough than the receiver, or is not stable, or you have long or noisy wires or fluctuating temperatures (etc.) then you may experience less stable communication.

If your particular use-case works fine, then stick with it. But if you start to notice errors in communication, the first troubleshooting step would be to disable this mode, since the clock recover is less robust in this mode.
> 4 votes

# Answer
As explained in jose can u c’s answer, in double speed mode the UART has fewer samples for doing clock and data recovery. But this doesn't help answering the second question:

> Why does it seem to be set in the code by default?

Double speed mode has also an advantage: it enables higher resolution in setting the baud rate. In normal mode, the bit duration is constrained to be a multiple of 16 CPU clock cycles, whereas in double speed mode it is only constrained to a multiple of 8 cycles.

As an example, let's say you want 57600 bps on a 16 MHz Arduino. Then,

F\_CPU ÷ desired\_baud\_rate = 277.78 = 8 × 34.72 = 16 × 17.36

In single speed mode, this would be rounded to 16 × 17, and the rounding error would make the baud rate 2.1% too fast. In double speed mode, it is rounded to 8 × 35, and the baud rate is only 0.8% too slow. Thus you get better baud rate accuracy in double speed mode. Note that for some baud rates, like 9600 bps, single speed and double speed yield the exact same rate.

This is presumably the reason the Arduino core uses double speed mode, except for a documented compatibility exception and for extremely low baud rates (double speed cannot work below 488 bps).

It should be noted that this is not the only possible strategy. The avr-libc, for example, provides some helper macros for baud rate calculations. These macros give preference to single speed mode and revert to double speed only if the rounding error exceeds a specified tolerance, which defaults to 2%.
> 2 votes

---
Tags: serial, uart, baud-rate
---


title: ESP8266 Bad request error 400

text:
# Question
Title: ESP8266 Bad request error 400
```
#include <ESP8266WiFi.h>

const char* ssid     =  "Tonosh";
const char* password =  "a43056043";

const char* host     =  "192.168.8.107";

void setup()
{
  Serial.begin(115200);
  delay(10);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid,password);

  while(WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP Address: ");
  Serial.println(WiFi.localIP());

}

int value = 0;

void loop()
{
  delay(2000);
  ++value;

  Serial.print("Connecting to ");
  Serial.println(host);

  WiFiClient client;
  const int httpPort = 80;
  if(!client.connect(host,httpPort))
  {
    Serial.println("Connection failed");
    return;
  }

  String url = "http://192.168.8.107/prueba.php";

  String data = "serie=777&temp=33";

  Serial.print("Requesting URL:  ");
  Serial.println(url);

  client.print(String("POST ") + url + "HTTP/1.0 \r\n" +
               "Host: " + host + "\r\n" +
               "Accept: *" + "/" + "*\r\n" +
               "Content-Length: " + data.length() + "\r\n" +
               "Content-Type: aplication/x-www-form-urlencoded\r\n" +
               "\r\n" + data
              );
  delay(10);

  Serial.println("Respond:");

  while(client.available())
  {
    String line = client.readStringUntil('\r');
    Serial.print(line);

    Serial.println("Closing connection");
  }
}

```

Any idea? I tried different post here and nothing works.

# Answer
> 4 votes
HTTP status code 400 means that your request syntax is invalid.

Here's a good way to debug it: store the request in a string, print that, and then transmit it. You'd see very quickly at least one of the problems your code has.

```
String request = String("POST ") + url + "HTTP/1.0 \r\n" +
                 "Host: " + host + "\r\n" +
                 "Accept: *" + "/" + "*\r\n" +
                 "Content-Length: " + data.length() + "\r\n" +
                 "Content-Type: aplication/x-www-form-urlencoded\r\n" +
                 "\r\n" + data;
Serial.print(request);
client.print(request);

```

The request in the POST line needs to be just the pathname and any arguments. You also need a space before `HTTP/1.0`.

So right now you're transmitting:

```
POST http://192.168.8.107/prueba.phpHTTP/1.0

```

when you need to transmit

```
POST /prueba.php HTTP/1.0

```

---
Tags: esp8266, http
---


# Question
Title: Runtime Error when using array of structs of unknown size as variable within class - some kind of overflow issue?
I have a class defined as below, it's basically a simple ring buffer, with some methods for getting useful statistics from the data held in the buffer.

```
enum BalanceMsgType{
  BAL_MSG_NOT = 0,
  BAL_MSG_READING = 1,
  BAL_MSG_SPECIAL = 2,
  BAL_MSG_ERROR = 3
};

typedef struct MeasuredMass{
  float mg;
  unsigned long time;
  bool steady;
  BalanceMsgType type;
};

class RingBuffer{
  private:
  unsigned int _size = 0;
  unsigned int _pos = 0;
  MeasuredMass *_array;
  void LinearRegression(){
    //... left out for simplicity
  }
  public:
  float lin_reg_m = 0;
  float lin_reg_c = 0;
  float lin_reg_r = 0;
  float est_current_mg = 0;
  //methods
  RingBuffer(unsigned int size){
    _size = size; //forgetting to put this line ->div0-> >1hr debugging :(
    _array = new MeasuredMass[_size];
    for (int i = 0; i < _size; i++){
      _array[i].mg = 0.0;
    }
  }
  void Add(MeasuredMass in_element){
    _array[_pos] = in_element;
    _pos = (_pos + 1)%_size;
    LinearRegression();
    est_current_mg = lin_reg_m*(in_element.time+BALANCE_DELAY) + lin_reg_c;
  }
  void ReadInOrder(MeasuredMass *pdata){  //Call with
                                          //my_buffer.ReadInOrder(data)
    for(int i = 0; i < _size; i++){
      pdata[i]=_array[(_pos+i+1)%_size];
    }
  }
  float Sum(){
    //...
  }
  float Mean(){
    //...
  }
  float StdDev(){
    //...
  }
  bool SteadyEnough(float max_sd){
    //...
  }
};

```

It compiles fine, and runs nicely in test programs. However, if I include it in larger programs (something like progmem 117404 of 122880 bytes, global vars 13604 of 32768) I get a "Board at COM8 not available" warning when using the Arduino Serial Monitor after uploading to my Fubarino Mini. (Even without actually interacting with those programs beyond creating an instance of the class.) Recent experience tells me this is some kind of crash due to a runtime error.

Fiddling around with the code, I've found that the issue doesn't occur in a version of the library which holds an array of floats instead of my `MeasuredMass`. That my `MeasuredMass` struct is obviously much larger than a float suggests to me that this is due to some pointer/array overflowy behaviour.

I've also managed to show that if I alter the class such that it uses a fixed length array rather than a pointer to one, the issue disappears.

i.e. RingBuffer's private member `MeasuredMass *_array;` becomes `MeasuredMass _array[25];` and

```
RingBuffer(unsigned int size){
  _size = size; //forgetting to put this line -> div0 -> >1hr bugtracking
  _array = new MeasuredMass[_size];
  for (int i = 0; i < _size; i++){
    _array[i].mg = 0.0;
  }
}

```

becomes

```
RingBuffer(){
  for (int i = 0; i < _size; i++){
    _array[i].mg = 0.0;
  }
}

```

I'd rather maintain the ability to set the size of the ring buffer at runtime (in my case it's set based upon the number of seconds' worth of data requested), so can anyone help me in figuring out how I can achieve this without running into the overflow / memory problems I seem to be having?

Thanks

# Answer
The problem is most likely here:

```
_array = new MeasuredMass[_size];

```

You're allocating `_size * sizeof(MeasuredMass)` bytes in the heap. If `_size` is too big the amount of memory allocated becomes too great and it fails to allocate. You should check if `_array` is `NULL` or not after the `new`. If it's `NULL` then it failed to allocate.

The problem is that heap allocation is limited to 2kB. This is regardless of the amount of memory you actually have in the chip. This is a limit imposed by the compiler (actually the libraries bundled with the compiler) and is set by a value in the linker script. It's something I've been campaigning to have removed from the libraries for many years, but it's always fallen on deaf ears. So much so that I provide a "fixed" version of the compiler in UECIDE that removes this hard limit.

The best thing you can do is to not use dynamic allocation. Instead have a statically created array which you then pass to the constructor.

```
MeasuredMass massBuffer[25];
RingBuffer massRing(massBuffer, 25);

```

and:

```
RingBuffer(MeasuredMass *buf, unsigned int size){
  _size = size; //forgetting to put this line ->div0-> >1hr debugging :(
  _array = buf;
  for (int i = 0; i < _size; i++){
    _array[i].mg = 0.0;
  }
}

```
> 1 votes

---
Tags: array, memory-usage, memory, pointer, chipkit
---