# Question
Title: Sending arduino sensor data via WiFi to a MySQL server
I'm aware this question has probably been asked many times but I'm pulling my hair out.

I'm trying to get sensor data from an arduino to a MySQL server. I've checked the apache access log and the request is there. But it just isn't being inserted into the database. Manually adding the data using the browser works so the php code seems fine. I've allowed apache through the firewall and updated the permissions all to no avail. Code below:

Arduino Main Code:

```
#include "thingProperties.h"
#include <Arduino_MKRENV.h>
#include <WiFi.h>

WiFiClient client;

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500);

  //Connect to WiFi network
  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED){
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(SSID);
    status = WiFi.begin(SSID, PASS);
    delay(10000);
  }
  Serial.println("This is connected.");

  if (!ENV.begin()) {
  Serial.println("Failed to initialize MKR ENV shield!");
  while(1);
  }
  pinMode(2, INPUT);
}

void loop() {
 relativeHumidity = int(ENV.readHumidity());
 lightIntensity = (ENV.readIlluminance());
 airPressure = int(ENV.readPressure(MILLIBAR));
 temperature = int(ENV.readTemperature());
 if(digitalRead(2) == LOW){
   rain = 1;
 }else if(digitalRead(2) == HIGH){
   rain = 0;
 }
 Serial.println("httpRequest");
 httpRequest();
 delay(10000);
}

void httpRequest(){
  // if there's a successful connection:
  if (client.connect(SERVER, 80)) {
    Serial.println("Connecting to server...");
    // send the HTTP PUT request:
    client.print("GET /weather_data.php?temp=");
    Serial.println("GET /weather_data.php?);
    client.print(temperature);
    client.print("&pressure=");
    client.print(airPressure);
    client.print("&humidity=");
    client.print(relativeHumidity);
    client.print("&illumination=");
    client.print(lightIntensity);
    client.print("&rain=");
    client.print(rain);
    client.print(" ");
    client.println("HTTP/1.1");
    client.print(" Host: ");
    client.println(SERVER);
    client.println();
    Serial.println("Added.");
  } else {
    Serial.println("Not connected.");
  }
  if (client.connected()){
    client.stop();
  }
}

```

thingProperties.h:

```
#include <WiFi.h>
#include <SPI.h>

const char THING_ID[] = "c942a18f-7696-4431-952c-76eaea3214ea";

const char SSID[]     = SECRET_SSID;    // Network SSID (name)
const char PASS[]     = SECRET_PASS;    // Network password (use for WPA, or use as key for WEP)
const char SERVER[]   = SECRET_IP;      // Server IP Address

int airPressure;
float lightIntensity;
float relativeHumidity;
bool rain;
float temperature;

```

# Answer
> 2 votes
So I don't quite know why, but I started from scratch and it works now. I've put the new code below in case it helps someone in my situation.

```
// Arduino Low Power - Version: Latest
//#include <ArduinoLowPower.h>
//#include <ArduinoIoTCloud.h>
#include "thingProperties.h"
#include <Arduino_MKRENV.h>
/*
  Repeating Wifi Web Client

  This sketch connects to a a web server and makes a request
  using a WiFi equipped Arduino board.

  created 23 April 2012
  modified 31 May 2012
  by Tom Igoe
  modified 13 Jan 2014
  by Federico Vanzati

  http://www.arduino.cc/en/Tutorial/WifiWebClientRepeating
  This code is in the public domain.
*/

#include <SPI.h>
#include <WiFiNINA.h>

int status = WL_IDLE_STATUS;

// Initialize the Wifi client library
WiFiClient client;

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

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    //Serial.print("Attempting to connect to SSID: ");
    //Serial.println(SSID);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(SSID, PASS);

    // wait 10 seconds for connection:
    delay(10000);
  }
  // you're connected now, so print out the status:
  //printWifiStatus();
  //Start arduino cloud.
  //ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  //Begin ENV shield.
  if (!ENV.begin()) {
    Serial.println("Failed to initialize MKR ENV shield!");
    while (1);
  }
}

void loop() {
  //ArduinoCloud.update();
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }
    //Serial.println("Start reading sensors.");
    relativeHumidity = int(ENV.readHumidity());
    //Serial.println(relativeHumidity);
    lightIntensity = int(ENV.readIlluminance());
    //Serial.println(lightIntensity);
    airPressure = int(ENV.readPressure(MILLIBAR));
    //Serial.println(airPressure);
    temperature = int(ENV.readTemperature());
    //Serial.println(temperature);
    UV_Index = int(ENV.readUVIndex());
    //Serial.println(UV_Index);
    if (digitalRead(2) == LOW) {
      rain = 1;
    } else if (digitalRead(2) == HIGH) {
      rain = 0;
    }
    //Serial.println(rain);
    //Serial.println("Sensor data read.");
    //Serial.println("Start http request.");
    httpRequest();
    //Serial.println("Stop http request");
    delay(60000);
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the Nina module
  client.stop();

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    //Serial.println("connecting...");
    // send the HTTP PUT request:
    client.print("GET /weather_data.php?temp=");
    client.print(temperature);
    client.print("&pressure=");
    client.print(airPressure);
    client.print("&humidity=");
    client.print(relativeHumidity);
    client.print("&illumination=");
    client.print(lightIntensity);
    client.print("&UV_Index=");
    client.print(UV_Index);
    client.print("&rain=");
    client.print(rain);
    client.print(" ");
    client.println("HTTP/1.1");
    client.println("Host: 192.168.0.29");
    client.println("User-Agent: ArduinoWiFi/1.1");
    client.println("Connection: close");
    client.println();
  } else {
    // if you couldn't make a connection:
    //Serial.println("connection failed");
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

```

# Answer
> 0 votes
WiFi.h is for Arduino WiFi shield. Use the WiFiNINA library for MKR1010

---
Tags: wifi, mkr1010
---


# Question
Title: Binary to decimal using bitwise operators
I am trying to convert some binary data to decimal numbers. I succeeded to convert binary to hex, but now I want to do the same with binary to decimal. I want to use bitwise operators and NO array.

See my code from binairy to hex. The incoming data is 8 bits. This code first calculates the most significant number, and then, the least significant number. This works good, but I cannot figure it out for bin to dec

The function `console_print_char` is sort of the printf function of my program.

```
    void console_print_hex_char(unsigned char data){
    unsigned char temp;

    if(data){
        temp = (data >> 4);
        if(temp){
            if(temp> 9) console_print_char(temp + ('A'- 10));
            else console_print_char(temp + '0');
        }
        temp = data & 0x0F;
        if(temp> 9) console_print_char(temp + ('A'- 10));
        else console_print_char(temp + '0');
    }
    else{
        console_print_char('0');
    }
}

```

# Answer
You cannot do what you are trying to do. There is no direct correspondence between some number of bits and a decimal digit.

With hexadecimal, every 4 bits corresponds to exactly 1 hex digit. That is why hex is used for computers.

One hex digit represents exactly 4 bits. Every time you add another hex digit, you add 4 bits.

Two hex digits corresponds to exactly a byte. 00h to FFh represents a value from 0 to 255.

There is no such direct correspondence between binary and decimal. If you have 4 bits, it takes 1 or 2 decimal digits to represent it (0-15) If you have 8 bits, it takes 1, 2, or 3 decimal digits to represent it, but there are 3 digit decimal values (values \> 255) that you can't represent with 8 bits.

```
Binary  Hex Decimal
0000    0   0
0001    1   1
0010    2   2
0011    3   3
0100    4   4
0101    5   5
0110    6   6
0111    7   7
1000    8   8
1001    9   9
1010    A   10
1011    B   11
1100    C   12
1101    D   13
1110    E   14
1111    F   15

```

You simply cannot convert a binary number to decimal using bit shifting and masking.

As @Kwasmich says in their answer, the closest you're likely to come would be to convert your binary value to BCD (Binary coded decimal) where each 4 bits holds a decimal digit. You could convert THAT to decimal character output using masking and shifting.
> 1 votes

# Answer
here's the c++ code

```
    vector<int> b={1,0,1,0,1,0,1};
        int sum=0;
        for(int i=b.size()-1, j=0; i>=0; i--, j++){
            sum+=b[j]*(1<<i);
        }
        return sum;

```
> 0 votes

---
Tags: serial, programming, communication, analogread, uart
---


title: SPI Slave Programming for Arduino

text:
# Question
Title: SPI Slave Programming for Arduino
In my application Arduino Due is configured as master and instead of the actual slave device I am making use of Arduino Uno as Slave.I will share the Master code which I have worked out. Can Anyone please help me with respect to slave code of Arduino Uno to display the data in serial monitor at slave side. Any Help With respect to this aspect will be greatly greatly appreciated.

```
#include <SPI.h>

SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
const uint8_t ss = 10;

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

  SPI.begin();

  digitalWrite(ss, LOW);
  SPI.beginTransaction(mySettting);
  SPI.transfer(0x00);
  SPI.transfer(0x25);
  SPI.transfer(0x1C);
  SPI.endTransaction();
  digitalWrite(ss, HIGH);
}

void loop() {
}

```

---

Thanks for the reply. Referring to the code attached below at the slave side as you have mentioned that HEX to be displayed in serial monitor window, Do I need to add the HEX at the master side I mean Do I need to load the Hexadecimal data (0x00251C) into HEX buffer??

Thanks in Advance

```
#include <SPI.h>

SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
const uint8_t ss = 10;

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

  SPI.begin();

  digitalWrite(ss, LOW);
  SPI.beginTransaction(mySettting);
  SPI.transfer(0x00);
  SPI.transfer(0x25);
  SPI.transfer(0x1C);
  SPI.endTransaction();
  digitalWrite(ss, HIGH);
}

void loop() {
}

```

# Answer
> 4 votes
SPI.h library by default only support Master mode, the `SPI.begin()` will automatically set slave select (ss) pin to HIGH whether you have `pinMode(ss, OUTPUT)` in your setup() code or not and set the Arduino as an SPI master. This can be see on SPI library source code.

As the SPI library does not contain the functionality for slave mode, in order to use Arduino as a Slave, you will need to do some customised setup, mainly on 1) setting MISO as OUTPUT for slave to send data; 2) enable slave mode by setting the SPCR register; 3) enable interrupt when data is received. Here is an example for an SPI slave on Arduino.

```
#include<SPI.h>

volatile boolean received;
volatile byte receivedData;

ISR (SPI_STC_vect)        //Inerrrput routine function
{
  receivedData = SPDR;   // Get the received data from SPDR register
  received = true;       // Sets received as True
}

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

  pinMode(MISO,OUTPUT);   //Sets MISO as OUTPUT
  SPCR |= _BV(SPE);       //Turn on SPI in Slave Mode
  received = false;
  SPI.attachInterrupt();  //Activate SPI Interuupt
}

void loop()
{
  if(received) {
    SPDR = receivedData;    // send back the received data, this is not necessary, only for demo purpose
    received = false;
    Serial.print(receivedData, HEX);
  }
}

```

---
Tags: arduino-uno, arduino-due, spi
---


# Question
Title: Industrializing Arduino - 24V io? (Electronics)
I would like to make an arduino board that is capable of handling 24V i/o.

Powering the Arduino would be done through either a linear or switching regulator of some sort. Low amperages, so efficiency isn't the main problem.

For input: 24v to 5v input scaling could be created with a voltage divider.

As far as I know, there will never run a high current into the arduino? So the power loss is minimal?

For output: 5v to 24v can be easily achieved using a MOSFET? Since this will ramp up the possible load (higher amperages) given that I'm using a 24v supply/separate line.

So I could choose to make half the I/O only input and half only output.

1. Could I combine the MOSFET and voltage divider, and in what way?
2. Are my "assumptions" about the I/O correct, or are there beter ways of handling it?
3. What other things should I think of? Over voltage protection? Polarity inversion? Protection against too high currents?

# Answer
You mentioned 2 items: the supply voltage to the Arduino and scaling up to 24V output.

If the supply voltage you have available is 24V, then I would suggest you look for a DC-DC converter that scales down to 12V. Or, if you are looking to design your own PCB then perhaps use a 78xx voltage regulator. The 78xx are 3 pin devices and only require 2 caps to operate - I suppose a heat sink will not be needed.

To scale up the outputs to 24V I would suggest one of the following options:

a) Relay board / These will take the 5V from your Arduino and close a mechanical switch. If the relays are good quality they will go on for ages. And you can switch loads from 0 to 240V and more, DC or AC. Plus of the relays are sturdiness and that they are quite forgiving for short current overloads. Minus are that relays are " slow" when compared to semiconductors and they can arce when the contacts open - especially when driving inductive loads and that. Arcing will wear down your contacts and in extreme cases generate EMI that might interfere with your electronics. Arcing can be remediated in AC with a capacitor accross the contacts or in DC with a flyback diode.

If you will make your own PCB don't forget the flyback diode on pins connecting to the relay coils or you will possibly fry the Arduino due to a voltage spike!

Many of these boards are available on the web, so it's a quick solution.

b) Optocouplers / Also a good option. Functionally they act as a relay. They are a bit less forgiving to current overloads, so chose them wisely. They are silent and fast acting. Available for AC or DC and up to 600V. Minus side is that the tend to be a bit more expensive than relay boards. I'm talking about industrial grade devices and not some el-cheapo web site :-)

c) MOSFETS or Bipolar transistors / If you are designing your PCB then this could be an option. Here you can use a MOSFET or a PNP transistor of the adequate ratings and you would be done. Though maybe considering yur time investment the options above could be less expensive in the end. I this case you get complete control of PCB layout which might be a consideration. If you go this way, don't forget to add a flyback diode to the output of these devices to protect from spikes when switching inductive loads (= motors, solenoids).

A big advantage of Relays and Optocouplers is the galvanic isolation they provide, both from the load to the board as between the loads themselves.

If you could supply more detailed specs of the loads, environments etc I can help you narrow down your choices.
> 3 votes

# Answer
24 VDC industrial circuits are typically based around 4-20mA measurement (AI) transmitters and outputs (AO) to valves and other actuators. There are also 24 VDC DI & DO's. I believe that you should investigate Analog Devices and Texas Instruments chips for 4-20 mA interfacing. They have a number of chips for reading in and outputting 4-20 mA. You can get started if you Google "analog devices 4-20ma application note" or "texas instruments 4-20ma application note." If you Google "4-20mA application note," you will find that there are any number of people that make these chips and lots of people that provide application notes for 4-20mA loops.

Any information provided here is on a Caveat Emptor basis.
> 1 votes

# Answer
This is a pretty old post but I'm sure people still search this topic from time to time. If what you are after is making an arduino into the plc replacement of sorts, look at these links. I've done these tasks and they worked pretty easyily for me. When you compare the cost of a plc to these alternatives, you won't find a new plc for the same price:

https://www.universal-solder.ca/product/canaduino-plc-mega328-programmable-logic-controller-electronics-diy-kit-for-arduino-nano-included/

and

https://www.visuino.com/ \- A visual ide
> 0 votes

---
Tags: electronics, input
---


# Question
Title: Connecting microSD reader and e-paper display to Nano at the same time?
Pretty much as the question states, I'm wondering if it's possible to connect (this: https://www.waveshare.com/7.5inch-HD-e-Paper-HAT.htm ) 7.5" e-paper display that has raspberry pi HAT and an SD card reader to Arduino nano/micro for reading images off SD and displaying on the screen. I'm an novice and a not sure if i can use the same pins for multipurpose

Thanks!

# Answer
No. Even the e-Paper alone is not usable by an Arduino Nano.
> 0 votes

---
Tags: arduino-nano, sd-card, display, arduino-micro
---


# Question
Title: Motor does not work for a specific case when programming with L293D motor driver shield
I tried to make a car that moves using a 4x4 keypad. Pressing "12" unlocks the car and sets the motors to move forward. After that, if I press 4, the speed of the left motor is reduced to half allowing the motor to turn left, and vice versa for right wheel when key 6 is pressed.

Here is the code:

```
#include <Key.h>
#include <Keypad.h>

char* startCar = "12";
int position = 0, state = 0;

/*
 * state 0: off
 * state 1: forward
 * state 2: backward
 *
 */

const byte rows = 3;
const byte cols = 3;
char keys[rows][cols] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'}
};

byte rowPins[rows] = {2,3,4};
byte colPins[cols] = {PD7, PD6, PD5};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, rows, cols);

int a=12,b=11,c=10,d=9;
void setup()
{
  pinMode(a,OUTPUT);
  pinMode(b,OUTPUT);
  pinMode(c,OUTPUT);
  pinMode(d,OUTPUT);
  Serial.begin(9600);
  setLocked(true);
}

void loop()
{
  char key = keypad.getKey();
  Serial.print(key);
  if (key == '9')
  {
    position = 0;
    setLocked(true);
  }
  if (key == startCar[position])
  {
    position ++;
  }
  if (position == 2)
  {
    setLocked(false);
  }
  if(state)
  {
    if(key=='2')
     {
      //Move forward
        state = 1;
        runmotors(255,0,0,255);
     }
     if(key=='8')
     {
      //Move backward
        state = 2;
        runmotors(0,255,255,0);
     }
    if(key == '4')
    {
      if(state == 1)
      {
        runmotors(127.5,0,0,255);
      }

      else if(state==2)
        runmotors(0,127.5,255,0);
    }
    if(key == '6')
    {
      if(state == 1)
        runmotors(255,0,0,127.5);
      else if(state==2)
        runmotors(0,255,127.5,0);

    }
  }
  delay(100);
}

void setLocked(int locked)
{
  if (locked)
  {
    state = 0;
    runmotors(0,0,0,0);
  }
  else
  {
    state = 1; // Moves forward
    runmotors(127.5,0,0,255);
  }
}
void runmotors(int s1,int s2,int s3,int s4)
{
  analogWrite(a,s1);
  analogWrite(b,s2);
  analogWrite(c,s3);
  analogWrite(d,s4);
}

```

Everything works perfectly, except for the fact that when the state is 1, i.e. car is running forward, and I press 4 the left motor completely stops instead of reduced speed. The LED on the motor driver shield which shows whether a motor is running or not also goes off. It is not a fault of the motor shield or the arduino as it worked when I test it individually with the motors (i.e. without the keypad etc).

Here is a photo of the shield:

Although my problem is not quite visible in this, but here is a video of the car: https://www.youtube.com/watch?v=bq19gNOL8Pg

# Answer
> 1 votes
On an UNO only certain pins are capable of PWM. Pin 12 is not one of them. When you try to call analogWrite with pin 12 it will recognize this and will simply call digitalRead for you with HIGH or LOW depending on whether your input is greater than 127.

With most motor controllers you can use one pin as a direction pin and the other as a PWM pin. So to go one direction you set pin 12 HIGH and do inverted PWM on 11 (if those indeed go to the same motor I didn't look at your shield). To go the other direction you write LOW on 12 and PWM on 11.

The motor turns when one pin is HIGH and the other is LOW. When you set pin 12 high then PWM pin 11, whenever 11 is LOW in the PWM cycle it is turning the motor on and when it is HIGH it is turning it off. So to make it run you might have to PWM 0 for go and 255 for stop. Sometimes your PWM is on the enable line and then you still use 255 for go and 0 for stop. It just depends on how things are wired.

When pin 12 is set to LOW then the motor is on when 11 is at the high part of the PWM cycle and off when it's low so you use 255 for go and 0 for stop. But the whole time pin 12 doesn't have to change.

Now I am not 100% sure that this is the case with your particular motor controller, I'm more of a coder than a hardware guy. But I've written enough code for motor controllers to know that you usually either need two direction lines and one PWM line or one direction and one PWM. If that's not the case here then we can let someone else work on why.

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


title: How to get data out of loop?

text:
# Question
Title: How to get data out of loop?
hi i wrote a code(i modified it actually, please forgive me, im in a mess please help me if you can) for my esp8266 to serial communicate with at tiny 85 ,it will monitor switch state and publish accordingly. now i want to write a code where it wont publish but whenever the serial is available i want it to directly take it and digital write in void callback.

```
//ItKindaWorks - Creative Commons 2016
//github.com/ItKindaWorks
//
//Requires PubSubClient found here: https://github.com/knolleary/pubsubclient
//
//ESP8266 Simple MQTT light controller

#include <PubSubClient.h>
#include <ESP8266WiFi.h>

int LED3 = 12;
int LED4 = 14;
int LED2 = 13;
int LED1 = 15;

bool switch1;
bool switch2;
bool switch3;
bool switch4;
char data ;
// the number of the pushbutton pin

//EDIT THESE LINES TO MATCH YOUR SETUP

#define MQTT_SERVER "192.168.0.223"
const char* ssid = "TACHYON_HOME";
const char* password = "qwertyui";

//LED on ESP8266 GPIO2

char* lightTopic = "/test/light1";
char* lightTopic1 = "/test/light2";
char* lightTopic2 = "/test/light3";
char* lightTopic3 = "/test/light4";

WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int length);
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void setup() {
  //initialize the light as an output and set to LOW (off)
  Serial.begin(9600);
  pinMode(LED3 , OUTPUT);
  pinMode(LED4 , OUTPUT);
  pinMode(LED1 , OUTPUT);
  pinMode(LED2 , OUTPUT);

    delay(100);

    // We start by connecting to a WiFi network

    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());

}

void loop(){
  //reconnect if connection is lost
  if (!client.connected() && WiFi.status() == 3) {reconnect();}

  //maintain MQTT connection
  client.loop();

  //MUST delay to allow ESP8266 WIFI functions to run
  delay(10);
   if (Serial.available()>0) /* If data available at serial port, enter if loop */
  {
    data = Serial.read(); /* Read data present at serial port */
    /* Print string with \r\n */
    Serial.print(data); /* Print data received */
    if (data == 'q') {
      client.publish(lightTopic,"1");

    }
else  if (data == 'w') {
      client.publish(lightTopic,"0");
    }
 else  if (data == 'e') {
      client.publish(lightTopic1,"1");
    }
    else if (data == 'r') {
      client.publish(lightTopic1,"0");

    }
     else if (data == 't') {
      client.publish(lightTopic2,"1");

    }
     else if  (data == 'y') {
      client.publish(lightTopic2,"0");

    }
     else if (data == 'u') {
      client.publish(lightTopic3,"1");

    }
     else if  (data == 'i') {
      client.publish(lightTopic3,"0");

    }

  }
}

void callback(char* topic, byte* payload, unsigned int length)
{
  //convert topic to string to make it easier to work with
  String topicStr = topic;

  //Print out some debugging info
  Serial.println("Callback update.");
  Serial.print("Topic: ");
  Serial.println(topicStr);

 if(topicStr.equals(lightTopic)){

   if(payload[0] == '1'){
      digitalWrite(LED1 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED1 , LOW);
    }
 }
 if(topicStr.equals(lightTopic1)){

   if(payload[0] == '1'){
      digitalWrite(LED2 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED2 , LOW);
    }
 }
 if(topicStr.equals(lightTopic2)){

   if(payload[0] == '1'){
      digitalWrite(LED3 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED3 , LOW);
    }
 }
  if(topicStr.equals(lightTopic3)){

   if(payload[0] == '1'){
      digitalWrite(LED4 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED4 , LOW);
    }
  }

}

void reconnect() {

  //attempt to connect to the wifi if connection is lost
  if(WiFi.status() != WL_CONNECTED){
    //debug printing
    Serial.print("Connecting to ");
    Serial.println(ssid);

    //loop while we wait for connection
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }

    //print out some more debug once connected
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
  }

  //make sure we are connected to WIFI before attemping to reconnect to MQTT
  if(WiFi.status() == WL_CONNECTED){
  // Loop until we're reconnected to the MQTT server
    while (!client.connected()) {
      Serial.print("Attempting MQTT connection...");

      // Generate client name based on MAC address and last 8 bits of microsecond counter
      String clientName;
      clientName += "esp8266-";
      uint8_t mac[6];
      WiFi.macAddress(mac);
      clientName += macToStr(mac);

      //if connected, subscribe to the topic(s) we want to be notified about
      if (client.connect((char*) clientName.c_str())) {
        Serial.print("\tMTQQ Connected");
        client.subscribe(lightTopic);
        client.subscribe(lightTopic1);
        client.subscribe(lightTopic2);
        client.subscribe(lightTopic3);

      }

      //otherwise print failed for debugging
      else{Serial.println("\tFailed."); abort();}
    }
  }
}

//generate unique name from MAC addr
String macToStr(const uint8_t* mac){

  String result;

  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);

    if (i < 5){
      result += ':';
    }
  }

  return result;
}

//////////////////i want to write some thing like///////////////////////////////////////
////////////////////////////////
if(topicStr.equals(lightTopic1)||Serial.available()>0){

   if(payload[0] == '1'|| data =q){
      digitalWrite(LED2 , HIGH);
    }

    else if (payload[0] == '0'|| data = w){
      digitalWrite(LED2 , LOW);
    }
/////////////////////////////////////////

```

# Answer
So you want your program to react to both MQTT and serial messages. You wrote this snippet:

```
if (topicStr.equals(lightTopic1) || Serial.available() > 0) {
    if (payload[0] == '1' || data = q) {
        digitalWrite(LED2, HIGH);
    }
    else if (payload[0] == '0' || data = w) {
        digitalWrite(LED2 , LOW);
    }
    // ...
}

```

Other than a couple of syntactic problems (you mean `data == 'q'`, not `data = q`), the logic is not appropriate. This is because:

* The test `payload[0] == '1'` only makes sense in the context of parsing an MQTT message, otherwise `payload` cannot be meaningfully defined.
* For the same reason, the test `data == 'q'` only makes sense in the context of parsing a serial command.

Since MQTT and serial use completely different commands, you will have to handle them independently. You can keep the MQTT callback as is, and implement the parser for the serial commands. Maybe something like:

```
if (Serial.available()) {
    char command = Serial.read();
    Serial.print(command);  // echo to the serial port
    switch (command) {
        case 'q':
            digitalWrite(LED1, HIGH);
            break;
        case 'w':
            digitalWrite(LED1, LOW);
            break;
        // ...
    }
}

```

Alternatively, use an `if ... else if ...` chain if you are not comfortable with the `switch` syntax.

I personally would rather store the topic names, LED pins and serial commands in an array of structs, and loop through the array in both the MQTT callback and the serial parser. But I assume that may be too advanced for your current programming level, so maybe just stick with the simple, albeit verbose solution.
> 0 votes

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


title: Arduino Trinket and CCS811 sensor

text:
# Question
Title: Arduino Trinket and CCS811 sensor
I have connected trinket and CCS811 I am trying to build and upload sketch to the module:

```
  /******************************************************************************
  Read basic CO2 and TVOCs

  Marshall Taylor @ SparkFun Electronics
  Nathan Seidle @ SparkFun Electronics

  April 4, 2017

  https://github.com/sparkfun/CCS811_Air_Quality_Breakout
  https://github.com/sparkfun/SparkFun_CCS811_Arduino_Library

  Read the TVOC and CO2 values from the SparkFun CSS811 breakout board

  A new sensor requires at 48-burn in. Once burned in a sensor requires
  20 minutes of run in before readings are considered good.

  Hardware Connections (Breakoutboard to Arduino):
  3.3V to 3.3V pin
  GND to GND pin
  SDA to A4
  SCL to A5

******************************************************************************/
#include <Wire.h>

#include "SparkFunCCS811.h" //Click here to get the library: http://librarymanager/All#SparkFun_CCS811

#define CCS811_ADDR 0x5B //Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address

CCS811 mySensor(CCS811_ADDR);

#include <SoftwareSerial.h>
const int rx = 0; //3
const int tx = 2; //4
const int alarmPin = 4;
SoftwareSerial mySerial(rx, tx);

void setup()
{
  mySerial.begin(9600);
  mySerial.println("CCS811 Basic Example");

  Wire.begin(); //Inialize I2C Hardware

  pinMode(alarmPin, OUTPUT);
}

void loop()
{
  //Check to see if data is ready with .dataAvailable()
  if (mySensor.dataAvailable())
  {
    //If so, have the sensor read and calculate the results.
    //Get them later
    mySensor.readAlgorithmResults();

    mySerial.print("CO2[");
    //Returns calculated CO2 reading
    double val = mySensor.getCO2();
    mySerial.print(val);
    if(val>=2000){
      digitalWrite(alarmPin, HIGH);
    }
    //Serial.print("] tVOC[");
    //Returns calculated TVOC reading
    //Serial.print(mySensor.getTVOC());
    //Serial.print("] millis[");
    //Display the time since program start
    //Serial.print(millis());
    //Serial.print("]");
    //Serial.println();
  }

  delay(10); //Don't spam the I2C bus
}

```

However when I verify the sketch I get following errors:

```
In file included from C:\Users\Nitin\Desktop\co2\co2.ino:26:0:

C:\Users\Nitin\Documents\Arduino\libraries\SparkFun_CCS811_Arduino_Library\src/SparkFunCCS811.h:77:28: error: 'TwoWire' has not been declared

  CCS811_Status_e beginCore(TwoWire &wirePort);

                            ^~~~~~~

C:\Users\Nitin\Documents\Arduino\libraries\SparkFun_CCS811_Arduino_Library\src/SparkFunCCS811.h:97:2: error: 'TwoWire' does not name a type; did you mean 'Wire'?

  TwoWire *_i2cPort; //The generic connection to user's chosen I2C hardware

  ^~~~~~~

  Wire

C:\Users\Nitin\Documents\Arduino\libraries\SparkFun_CCS811_Arduino_Library\src/SparkFunCCS811.h:112:13: error: 'TwoWire' has not been declared

  bool begin(TwoWire &wirePort = Wire);         //Use the Wire hardware by default

             ^~~~~~~

C:\Users\Nitin\Documents\Arduino\libraries\SparkFun_CCS811_Arduino_Library\src/SparkFunCCS811.h:113:34: error: 'TwoWire' has not been declared

  CCS811_Status_e beginWithStatus(TwoWire &wirePort = Wire);    //Use the Wire hardware by default

                                  ^~~~~~~

C:\Users\Nitin\Documents\Arduino\libraries\SparkFun_CCS811_Arduino_Library\src/SparkFunCCS811.h:112:33: error: could not convert 'Wire' from 'TinyM_USI_TWI' to 'int&'

  bool begin(TwoWire &wirePort = Wire);         //Use the Wire hardware by default

                                 ^~~~

C:\Users\Nitin\Documents\Arduino\libraries\SparkFun_CCS811_Arduino_Library\src/SparkFunCCS811.h:113:54: error: could not convert 'Wire' from 'TinyM_USI_TWI' to 'int&'

  CCS811_Status_e beginWithStatus(TwoWire &wirePort = Wire);    //Use the Wire hardware by default

                                                      ^~~~

Multiple libraries were found for "Wire.h"
 Used: C:\Users\Nitin\AppData\Local\Arduino15\packages\adafruit\hardware\avr\1.4.13\libraries\Wire
 Not used: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire
Multiple libraries were found for "SparkFunCCS811.h"
 Used: C:\Users\Nitin\Documents\Arduino\libraries\SparkFun_CCS811_Arduino_Library
 Not used: C:\Users\Nitin\Documents\Arduino\libraries\arduino_613982
Using library Wire at version 1.0 in folder: C:\Users\Nitin\AppData\Local\Arduino15\packages\adafruit\hardware\avr\1.4.13\libraries\Wire
Using library SparkFun_CCS811_Arduino_Library at version 2.0.1 in folder: C:\Users\Nitin\Documents\Arduino\libraries\SparkFun_CCS811_Arduino_Library
Using library SoftwareSerial at version 1.0 in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial
exit status 1
Error compiling for board Adafruit Gemma (ATtiny85 @ 8MHz).

```

I see that this library - SparkFun\_CCS811\_Arduino\_Library is not compatible with trinket https://github.com/sparkfun/SparkFun\_CCS811\_Arduino\_Library/issues/19

can anyone give me pointer to write sketch for trinket connected to CCS811 sensor?

# Answer
> 1 votes
Looks like you have two choices

* Use a different controller that is compatible with the normal Arduino Wire library - maybe something like the Nano?
* Modify SparkFunCCS811.h to #include TinyWireM.h instead of Wire.h. This is actually not hard at all - just takes a bit of patience and the knowledge that "there is no magic".

Frank

---
Tags: arduino-ide, library
---


title: Changes to user included library

text:
# Question
Title: Changes to user included library
I've been putting a small helper library together which I'm just including manually via the libraries sub-directory. I've just made some changes to the library in the filesystem however when trying to compile a previous sketch referencing it (after making the appropriate changes), the compiler is complaining and it appears to still be using the old version of the library. What's going on here and what is the correct way to update such a library?

I have tried completely reloading the Arduino IDE to flush out any caches etc. but that didn't help

# Answer
Whatever compiler you are using (Arduino IDE?) should have a 'verbose' setting that you can activate. This will give you a HUGE amount of output, but will also show you exactly what file is being accessed for the library in question.

When I do this, I copy/paste the entire output into Notepad++ and use its search capabilities to sort through all the chaff.

Frank
> 1 votes

---
Tags: library, compile
---


# Question
Title: Dragino lg01-p problem with serial monitor
i have a dragino lg01-p lora gateway to which i successfully communivate through lora with an arduino and i can program it through network as expected and seen in its manual with the demo client-server code. However, when i try to open the serial monitor on the side of the dragino, i get this:

Unable to connect: retrying (1)...

Unable to connect: retrying (2)...

Unable to connect: retrying (3)...

Unable to connect: retrying (4)...

Unable to connect: is the sketch using the bridge?

I need to have the serial communication cause i made a little app in C# which gets the data from a COM port. I also tried with Console instead of serial, but still didn't get any results back. This is the code, exactly as is in the examples no the manual

```
#include <SPI.h>
#include <RH_RF95.h>

// Singleton instance of the radio driver
RH_RF95 rf95;

int led = A2;
float frequency = 868.0;

void setup()
{
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  while (!Serial) ; // Wait for serial port to be available
  Serial.println("Start Sketch");
  if (!rf95.init())
    Serial.println("init failed");
  // Setup ISM frequency
  rf95.setFrequency(frequency);
  // Setup Power,dBm
  rf95.setTxPower(13);
  // Defaults BW Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on
  Serial.print("Listening on frequency: ");
  Serial.println(frequency);
}

void loop()
{
  if (rf95.available())
  {
    // Should be a message for us now
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    uint8_t len = sizeof(buf);
    if (rf95.recv(buf, &len))
    {
      digitalWrite(led, HIGH);
      RH_RF95::printBuffer("request: ", buf, len);
      Serial.print("got request: ");
      Serial.println((char*)buf);
      Serial.print("RSSI: ");
      Serial.println(rf95.lastRssi(), DEC);

      // Send a reply
      uint8_t data[] = "And hello back to you";
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent a reply");
      digitalWrite(led, LOW);
    }
    else
    {
      Serial.println("recv failed");
    }
  }
}

```

# Answer
Found it so i will share my problem here to help someone else!

Apparently `Bridge` funcions work better for this device if you include `Process.h` rather than `Bridge.h`.
> 1 votes

---
Tags: serial
---


title: Circuit not working with 9 volt battery

text:
# Question
Title: Circuit not working with 9 volt battery
I have made a simple circuit having an IR receiver and a Servo motor. Here is the diagram:

Red wire: power

Black wire: ground

Orange wire: digital signal

And here's the code:

```
#include <Servo.h>
#include <IRremote.h>
int receiver = 13;
IRrecv irrecv(receiver);
decode_results results;
Servo myServo;
int pos = 0;
void setup() {
  // put your setup code here, to run once:
  myServo.attach(9);
  Serial.begin(9600);
  irrecv.enableIRIn();
  myServo.write(0);
  delay(200);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (irrecv.decode(&results)){

    if (results.value== 0xC0000C){
      for (pos = 0; pos <= 90; pos += 10) {
        // in steps of 1 degree
        myServo.write(pos);
        delay(15);
      }
      for (pos = 90; pos >= 0; pos -= 10) {
        myServo.write(pos);
        delay(15);
      }
    }
  }
  irrecv.resume();
  delay(100);
}

```

It rotates the motor 90 degree and back when a button on a remote is clicked.

Here comes the problem: This is working perfectly when connected to my PC, but it doesn't when I connect it with my 9-volt (cuboid shaped) battery. The lights on the Arduino board still light up, but the circuit does nothing when I press the remote button.

I have also observed that the servo vibrates a little bit, but doesn't move.

Is this a problem in my circuit, or is it just that my battery power is low?

# Answer
> 1 votes
A 9V battery has both low peak current and low total power (low mAh rating). It is not a good choice for any circuit that draws more than ≈100 mA. (I pulled that number out of thin air, but it's probably a decent guess)

Build a battery pack from 6 AA alkaline cells instead. That will provide enough peak current. Or for much longer run-time, use 6 D sized cells.

---
Tags: power, servo, ir
---


# Question
Title: Problem on interfacing 3 flame sensors and servo to Arduino Fire Fighter
I had been trying to make Arduino Fire Fighter Robot but facing several problems in interfacing 3 flame sensors and servo together. When I upload the following code( Which I had posted at the end of my writing) my robot goes backward and detects flame at the front sensor and displays " Flame on Front" on 16x2 LCD display and the 5v pump pumps out water and the red LED blinks. But I want that my robot will work in the following way- Initially, my robot will be at rest. There are 3 sensors attached at the front part of the robot. And there is a SG90 servo for rotating the water tank( in this tank there is a 5v pump motor and the pump motor will pump out water from this tank). When any one of the three flame sensors will detect flame then the servo will rotate in that direction and when the front flame sensor detects fire , the servo will be in 90-degree angle and water will be pumped out. LCD will display the status of the flame sensors. But the robot is not working properly. I am not able to interface 3 flame sensors and servo together. My robot is not working according to my expectation as I had said before.

```
int pos = 0;
boolean fire = false;

#include <LiquidCrystal.h>
int Contrast=20;// for adjusting the brightness of the LCD , 20 is selected for the contrast of LCD
LiquidCrystal lcd(30,31,32,33,34,35);
int buzz= 38; //for led or buzzer
#define Left_S 9 // left sensor
#define Right_S 8     // right sensor
#define Forward_S 23  //forward sensor
#define LM1 52 //for pump motor
#define LM2 53 //for pump motor
#define IN1 5   //for motor
#define IN2 4  // for motor
#define IN3 3      //for motor
#define IN4 22     // for motor
//int flame_pin1 = HIGH ;
int LEDR= 36; // for danger signal
int LEDB=37;// for safe signal

void setup ( )  {
   analogWrite(6,Contrast);
     lcd.begin(16, 2);
      pinMode(Left_S, INPUT);
  pinMode(Left_S, INPUT);
  pinMode(Right_S, INPUT);
     pinMode (Forward_S,OUTPUT);
     pinMode (LEDB,OUTPUT);
 pinMode(LM1, OUTPUT);
 pinMode(LM2, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode( buzz,OUTPUT );
  pinMode(LEDR,OUTPUT);
  pinMode(LEDB, OUTPUT);
 // pinMode ( flame_sensor_pinM , INPUT );
  //Serial.begin ( 9600 );
   myservo.attach(25);
  myservo.write(90);
}
 void put_off_fire()
{
    delay (500);

    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, HIGH);

   digitalWrite(LM1, HIGH);
   digitalWrite(LM2, LOW);
   delay(500);

    for (pos = 50; pos <= 130; pos += 1) {
    myservo.write(pos);
    delay(10);
  }
  for (pos = 130; pos >= 50; pos -= 1) {
    myservo.write(pos);
    delay(10);
  }

  digitalWrite(LM1,LOW);
  digitalWrite(LM2,LOW);
  myservo.write(90);

  fire=false;
}

void loop ( ){
   myservo.write(90); //Sweep_Servo();

    if (digitalRead(Left_S) ==1 && digitalRead(Right_S)==1 && digitalRead(Forward_S) ==1) //If Fire not detected all sensors are zero
    {
    //Do not move the robot
    lcd.setCursor(0, 1);
      lcd.print("No flame");
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, HIGH);
    digitalWrite(LEDR,LOW);
    digitalWrite(LEDB,HIGH);
    digitalWrite(buzz,LOW);
    }

    else if (digitalRead(Left_S) ==0) //If Fire is straight ahead
    {
    //Move the robot forward
    lcd.setCursor(0, 1);
      lcd.print("Flame on Left");
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, LOW);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN2, LOW);
    digitalWrite(LEDR,HIGH);
    digitalWrite(LEDB,LOW);
    digitalWrite(buzz,HIGH);
    fire = true;

    }
    else if (digitalRead(Forward_S) ==0) //If Fire is straight ahead
    {
    //Move the robot forward
    lcd.setCursor(0, 1);
      lcd.print("Flame on front");
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, LOW);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN2, LOW);
    digitalWrite(LEDR,HIGH);
    digitalWrite(LEDB,LOW);
    digitalWrite(buzz,HIGH);
    fire = true;

    }

    else if (digitalRead(Right_S) ==0) //If Fire is to the right
    {
    //Move the robot right
    lcd.setCursor(0, 1);
      lcd.print("Flame on Right");
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, LOW);
    digitalWrite(LEDR,HIGH);
    digitalWrite(LEDB,LOW);
    digitalWrite(buzz,HIGH);
    fire= true;
    }

     delay(300); //Slow down the speed of robot

     while (fire == true)
     {
      put_off_fire();
     }
}

```

# Answer
If you format your code correctly, the code becomes less cluttered and the problem becomes more visible.

Also, if you think about the `if` statements, there is no need to check for `no fire` for all three sensors at the same time. If none of the three sensors see fire, then the only possibility that is left, is `no fire`.

Another thing, you have no `digitalWrite(IN1, LOW);` and no `digitalWrite(IN3, LOW);` in your code. You could put `digitalWrite(IN1, HIGH);` and `digitalWrite(IN3, HIGH);` in `setup()`

Here is your code rewritten and formatted.

Couple of unnecessary duplications are tagged.

There is no reason to use `while (fire == true)` because `put_off_fire()` clears the `fire` flag

Also, for future programs, `while (fire == true)` is a redundant form because it is same as `while (fire)`

Have a really close look at the `if` statement blocks.

You used copy&paste when writing the code, but you forgot to make changes.

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(30, 31, 32, 33, 34, 35);

#define Left_S       9                       // left    sensor
#define Right_S      8                       // right   sensor
#define Forward_S   23                       // forward sensor

#define LM1         52                       // for pump motor
#define LM2         53                       // for pump motor

#define IN1          5                       // for motor
#define IN2          4                       // for motor
#define IN3          3                       // for motor
#define IN4         22                       // for motor

//int flame_pin1 = HIGH ;

int LEDR     = 36;                           // for danger signal
int LEDB     = 37;                           // for safe signal
int buzz     = 38;                           // for led or buzzer
int pos      =  0;
int Contrast = 20;                           // for adjusting the brightness of the LCD , 20 is selected for the contrast of LCD

boolean fire = false;

void setup() {

    analogWrite(6, Contrast);

    lcd.begin(16, 2);

    pinMode( Left_S            , INPUT  );
    pinMode( Left_S            , INPUT  );
    pinMode( Right_S           , INPUT  );

    pinMode( Forward_S         , OUTPUT );
    pinMode( LEDB              , OUTPUT );   // xxxxxxxxxxxxx        duplicate

    pinMode( LM1               , OUTPUT );
    pinMode( LM2               , OUTPUT );

    pinMode( IN1               , OUTPUT );
    pinMode( IN2               , OUTPUT );
    pinMode( IN3               , OUTPUT );
    pinMode( IN4               , OUTPUT );

    pinMode( buzz              , OUTPUT );

    pinMode( LEDR              , OUTPUT );
    pinMode( LEDB              , OUTPUT );   // xxxxxxxxxxxxx        duplicate

//  pinMode( flame_sensor_pinM , INPUT  );

//  Serial.begin ( 9600 );

    myservo.attach(25);
    myservo.write(90);
}

void put_off_fire() {

    delay (500);

    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, HIGH);

    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW );
    delay(500);

    for (pos = 50; pos <= 130; pos += 1) {
        myservo.write(pos);
        delay(10);
    }

    for (pos = 130; pos >= 50; pos -= 1) {
        myservo.write(pos);
        delay(10);
    }

    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);

    myservo.write(90);                       // xxxxxxxxxxxxx        duplicate

    fire = false;                            // xxxxxxxxxxxxx        not needed
}

void loop() {

    myservo.write(90);                       // xxxxxxxxxxxxx        duplicate
//  Sweep_Servo();

    lcd.setCursor(0, 1);

    fire = true;                             // preset the state (gets cleared when no fire is detected

    if (digitalRead(Left_S) == 0) {          // If Fire is straight ahead

        lcd.print("Flame on Left");

        digitalWrite(IN1 , HIGH);            // Move the robot forward
        digitalWrite(IN2 , LOW );
        digitalWrite(IN3 , HIGH);
        digitalWrite(IN2 , LOW );
    }

    else if (digitalRead(Forward_S) == 0) {  // If Fire is straight ahead

        lcd.print("Flame on front");

        digitalWrite(IN1 , HIGH);            // Move the robot forward
        digitalWrite(IN2 , LOW );
        digitalWrite(IN3 , HIGH);
        digitalWrite(IN2 , LOW );
    }

    else if (digitalRead(Right_S) == 0) {    // If Fire is to the right

        lcd.print("Flame on Right");

        digitalWrite(IN1 , HIGH);            // Move the robot right
        digitalWrite(IN2 , HIGH);
        digitalWrite(IN3 , HIGH);
        digitalWrite(IN4 , LOW );
    }

    else {                                   // fire was not detected by any of the sensors

        fire = false;

        lcd.print("No flame");

        digitalWrite(IN1 , HIGH);            // Do not move the robot
        digitalWrite(IN2 , HIGH);
        digitalWrite(IN3 , HIGH);
        digitalWrite(IN4 , HIGH);
    }

    delay(300);                              // Slow down the speed of robot

    if (fire) {

        digitalWrite(LEDR, HIGH);            // do fire lights
        digitalWrite(LEDB, LOW);
        digitalWrite(buzz, HIGH);

        put_off_fire();
    }

    else {

        digitalWrite(LEDR, LOW );            // do nofire lights
        digitalWrite(LEDB, HIGH);
        digitalWrite(buzz, LOW );

    }
}

```
> 1 votes

---
Tags: sensors
---


# Question
Title: Junk values in EEPROM. while writing large values
Facing an issue while writing a large value *(like 2000-5000)* to EEPROM using `EEPROM.put().`
For example, While writing 2000 values to address 5 of EEPROM. Some junk values are written automatically to a nearby address (address 4, 6, 7...).

*Note : Not trying to write an array of 2000 elements*

Board Used : Arduino Uno (Atmega328P)

Q1 : What is the typical range of a each address by using `EEPROM.put()` . Like `EEPROM.write()` has range limit of 0-255.
Q2 : How to write large value EEPROM addresses without effecting the nearby address.

# Answer
> 1 votes
It depends on what type of variable you have. If you have single byte variables like byte or char then it is one value to one address. But if you have an int value like:

```
int x = 2000;

```

then try to store that in EEPROM that will take 2 bytes because an int is 2 bytes in size. So if you write that to address 5 it will take 5 and 6 to write it.

If you write a long or a float, they are 4 bytes, so they will take 4 address slots in the EEPROM each.

If you just write EEPROM.put(5, 2000); then the 2000 gets seen as either int or long depending on how the code is written. I don't remember. But you certainly can't fit 2000 into a byte so it's going to have to take more than one.

---
Tags: arduino-uno, atmega328, eeprom, memory
---


# Question
Title: How can I make my Arduino Uno press Space on my laptop keyboard?
So I wanna build something which, when it receives a remote signal, presses the spacebar on my laptop keyboard. I tried using the Keyboard.press() but it is available only for Leonardo. Is there any way I can use it in my Uno, without having to mess with the firmware?

If not, what else can I use to accomplish my goal?

# Answer
On Windows you can use a serial to keyboard redirector like this one

It can start with windows, Im using it for a long time without any issues.
> 2 votes

# Answer
if you have some knowledge in Java or Python you can interface your Arduino board to PC, through Arduino's SerialPort. When Arduino sends a byte, for example, 0xAB, your Java or Python script sends a fake key-press event. I hope this can help. Good luck!
> 2 votes

---
Tags: arduino-uno, keyboard
---


# Question
Title: Uno went in washer and when I shake I hear something shaking around. What do I hear?
My friends Uno went in washer. I gave it a week to dry and when i plug it in, it works. But when I shake I hear something shaking around inside it. What do I hear shaking around?

# Answer
> 0 votes
It could be the USB port, barrel jack port, or most likely the pin header. The pin headers are a plastic shell with a two-point prong thing that goes in it. the pin could have desoldered when in the washer. check the pin headers. It might also be the inside of capacitors but that is highly unlikely.

---
Tags: arduino-uno
---


title: Arduino Nano-combo NRF2401

text:
# Question
Title: Arduino Nano-combo NRF2401
I am using two nano-combo for a RC car and when the remote emitter battery is too down if the car was running and battery finally empty the car was still running...is there any way by programming to check communication between the two nanos and solve this problem??. Thanks.

here is the code: //Receiver program

#include \<SPI.h\>; #include "Mirf.h" #include "nRF24L01.h" #include "MirfHardwareSpiDriver.h" Nrf24l Mirf = Nrf24l(10, 9);

void setup() { Serial.begin(9600); Mirf.spi = &MirfHardwareSpi; Mirf.init(); Mirf.setRADDR((byte \*)"FGHIJ"); //Set your own address (receiver address) using 5 characters Mirf.payload = sizeof(datos); Mirf.channel = 90; //Set the used channel Mirf.config(); //Serial.println("Listening..."); //Start listening to received data

void loop() { if (Mirf.dataReady()) { //When the program is received, the received data is output from the serial port Mirf.getData(datos);
delay(5);

if (datos\[7\] \>= 150) { //motor forward

```
analogWrite(3,0);
analogWrite(5,255);

```

}

if (datos\[7\] \<= 90) { motor back

```
analogWrite(3,255);
analogWrite(5,0);

```

}

if (datos\[7\] \> 90 && datos\[7\] \< 150 or datos\[7\] == 0) { //motor stop

```
analogWrite(5,0);
analogWrite(3,0);

```

} } }

it works perfect I can control dc motor no problem but if remoto control battery is low or empty then no communication with NANO receiver and the motor spin itself non stop.

I try different things in the void loop like:

if (!Mirf.dataReady()) { analogWrite(5,0); analogWrite(3,0); }

but still the same problem. So that´s why must be something inside Rf library to check if remote control NANO comms is off I don\`t know...

Thanks

# Answer
> 0 votes
You can do somthing like:

```
while(radio.hasData()){
}

```

This works in the NRFLite library. I don't know about other libraries like RF24 etc.

---
Tags: arduino-nano, nrf24l01+
---


title: Communication between 2 arduino boards

text:
# Question
Title: Communication between 2 arduino boards
I am not really 100% too sure how to do this but I am trying to make my arduino UNO communicate with my arduino MEGA. The reason why I needed to do this was because I was using the RFID module along with a TFT display and the problem I faced is that on the arduino mega they both needed pin 53. Luckily I have an arduino UNO so I just went for that instead for the display. I am trying to use the `analogWrite()` function to send analog signals from my MEGA over to the UNO so that the TFT display on the UNO can display the results. The UNO would also read the analog inputs coming from the MEGA. This did not work very well. The analog inputs are being sent from the MEGA but the UNO is not reciving them. I am using a PWN pin on the MEGA to send the analog output to the UNO.

This diagram shows what I mean:

These are the 2 compotents I am using:

https://i.stack.imgur.com/CqXdB.png TFT display

RFID

This shows how the libary sets out the pins. I am only a beginner so I personally don't want to mess around with the libary.

# Answer
> 1 votes
You can use the I2C interface.

TX:

```
// Wire Master Writer
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  x++;
  delay(500);
}

```

RX:

```
// Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

```

Schematic:

Image by Dronebot Workshop; check out their tutorial for more info: https://dronebotworkshop.com/i2c-arduino-arduino/

# Answer
> 1 votes
Pin 53 is just the default "slave select" pin. There is nothing special about it. You can use any other pin as slave select, as long as the libraries for your devices allow it (check the documentation and tutorials for those libraries).

You cannot transmit information with `analogWrite()` since it isn't really analogue (it's PWM), and analogue doesn't have enough definition for reliably representing more than a handful of discrete values anyway.

---
Tags: arduino-uno, arduino-mega, communication, analogwrite
---


title: Problem using 2 motors

text:
# Question
Title: Problem using 2 motors
I would like both the motors to spin the attached wheels forward when I push the joystick forward and vice versa. When the joystick is still, the motors should stop spinning. At the moment, when I push the joystick on x-axis and my `x` variable increases both motors spin, but when I push it in the opposite direction and `x` decreases, only motor A spins. Additionaly when I connect the arduino to the power (usb cable to my pc), motor B spins for approx 1 second and then stops.

This is the circuit I have (sorry for a lack of schematic, let's hope this wonderful drawing is enough):

The code:

```
int MotorAA = 7;
int MotorAB = 8;

int MotorBA = 11;
int MotorBB = 12;

int x = 0;

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

  pinMode(MotorAA, OUTPUT);
  pinMode(MotorAB, OUTPUT);

  pinMode(MotorBA, OUTPUT);
  pinMode(MotorBB, OUTPUT);

  digitalWrite(MotorAA, LOW);
  digitalWrite(MotorAB, LOW);

  digitalWrite(MotorBA, LOW);
  digitalWrite(MotorBB, LOW);
}

void loop() {
  x = analogRead(A0);
  Move();
  Serial.println(x);
}

void Move() {
  if (x == 0){
    return;
  }

  if (x > 520)
  {
    digitalWrite(MotorAA, HIGH);
    digitalWrite(MotorAB, LOW);

    digitalWrite(MotorBA, HIGH);
    digitalWrite(MotorBB, LOW);
  }
  else if (x < 480)
  {
    digitalWrite(MotorAA, LOW);
    digitalWrite(MotorAB, HIGH);

    digitalWrite(MotorBA, LOW);
    digitalWrite(MotorBB, HIGH);
  }
  else{
    digitalWrite(MotorAA, LOW);
    digitalWrite(MotorAB, LOW);

    digitalWrite(MotorBA, LOW);
    digitalWrite(MotorBB, LOW);
  }
}

```

# Answer
The Arduino can definitely not power that many motors. The Arduino's max output current is 0.1A and you might be drawing around 0.5A. Use an external battery like a LiPo battery for the motor controller.

NOTE: Please watch out! Drawing that many amps from Arduino can kill it! So please use the LiPo or normal batteries!
> 1 votes

---
Tags: motor, joystick
---


# Question
Title: How to run my buzzer for few more seconds after switching off
This is a basic level lazer alarm project. When anyone crosed or kept their hands on the lazer. buzzer starts working but when they took their hand from lazer light buzzer stops. But i want even after taking hands my buzzer should work for few (15-30) seconds .so please help me by giving idea..

# Answer
> 1 votes
If you are using a digital buzzer, you can do:

```
digitalWrite(buzzerPin,HIGH);
delay(1000);
digitalWrite(buzzerPin,LOW);

```

---
Tags: buzzer
---


title: nRF24l01+ Outputting Garbage Values

text:
# Question
Title: nRF24l01+ Outputting Garbage Values
I just purchased a set of 10 nRF24l01+ modules with a breakout board that looks like this:

Note: This is the nRF24l01+ chip, not a clone Si24Ri. Also, I'm using an Arduino Mega.

I'm following the Sparkfun tutorial here:
https://learn.sparkfun.com/tutorials/nrf24l01-transceiver-hookup-guide

The wires are hooked up like so:

* 3.3V → VCC
* GND → GND
* PWM 8 → IRQ
* PWM 9 → CE
* PWM 10 → CSN
* PWM 11 → MOSI
* PWM 12 → MISO
* PWM 13 → SCK

I've verified the two modules are hooked up as they should be. I'm using the *GettingStarted* example program for both units. Whenever I go into the serial monitor when connected to the transmitter, I get garbage values like `<¯�SžRÖ` being output. Whenever I try to transmit a message by entering `t`, nothing gets returned. The same problem is happening on the receiver end.

As for troubleshooting:

* I've wiggled all of the jumper cables to verify a stable connection.
* I've swapped out the modules I was using with others from the package (twice) so the modules probably aren't bad.
* After reading that a capacitor is sometimes needed to provide a smoother voltage to the module, I upped the voltage from the 3.3V the Arduino was providing to a stable 3.5V from an external variable power supply to account for any small voltage dips. I don't have any capacitors available to me at the moment, so I figured this would be the next best option.

Unfortunately, my RF modules are still not correctly transmitting any data, and I don't know where to go from here.

# Answer
> 0 votes
Check these things first:

* Is your power supply give a constant 3.3V and a minimum of 0.5A(500mA)?
* Does your code work for others?
* Are you on the right serial baud rate?
* Is the path from the radio to the Arduino as short as possible?
* Are your MISO and MOSI wires twined into each other?

If none of these things help then, please tell me what library you are using. I had a lot of issues with the RF24 library so maybe try using the NRFLite library.

---
Tags: arduino-mega, nrf24l01+
---


# Question
Title: How to use Atmega328p-PU from an Uno, on a breadboard without a crystal
How do you use Atmega328p-PU from an Uno, on a breadboard without a crystal?

# Answer
If you buy your ATmega as supplied by Microchip, through one of the large electronic parts resellers, it will come with its default fuse configuration:

* clock source: internal 8 MHz RC oscillator
* clock prescaler enabled at ÷8, yielding a 1 MHz system clock
* bootloader disabled

You could use it in this configuration, but you will probably want to disable the prescaler. This can be done by changing the right fuse or, alternatively, by some code running early in `setup()`. Note that, with no bootloader, you will need an ISP programmer in order to load the code. If you want the convenience of serial downloading (i.e. you would use an FTDI cable rather than an ISP programmer), you will have to burn the bootloader using an ISP programmer, and adjust the fuses to enable it and set its size.

If you take the ATmega from an existing Uno board, or buy one preconfigured with the bootloader, the fuses will be set differently:

* clock source: external crystal
* clock prescaler disabled
* bootloader enabled and sized to 0.5 KiB

In this case you will have to change the clock source.

In any case, you would tell the IDE you are using an Arduino Fio, or a Pro or Pro Mini with a 328P clocked at 8 MHz. And you will need an ISP programmer to load either your program or the bootloader. You could use an Arduino running the “Arduino as ISP” firmware for this.

Check the datasheet for the details on configuring the fuses. You can also use one of the online fuse calculators, like this one or this one.
> 0 votes

# Answer
You can use another IC like the 555 timers as an external oscillator.
> 1 votes

---
Tags: arduino-uno, atmega328
---


# Question
Title: How to interpret Serial data received by Bluetooth module
I'm experimenting with a hc-05 knockoff the JDY-30 and am confused about the Serial data I'm getting from it. I downloaded an app called BlueUino to send commands from my Android to my Arduino Uno via Bluetooth. I then print the data I get via Serial port using the code below:

```
  if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = '1'; //Serial.read(); // Reads the data from the serial port0
    stateData = Serial.read();
    sprintf(data, "Data is %u", stateData);
    Serial.println(data);
    Serial.println();
 }

```

Here are some of the results I get in the log which I can't make sense of. For example, sending the string "def" doesn't contain the sequence of data from sending the command "e". Also, how does one convert these values to characters ?

Send Command "b"

```
Data is 128
Data is 0
Data is 248

```

Send Command "abc":

```
Data is 120 // doesn't contain the sequence of Data of "b"
Data is 120
Data is 120
Data is 0
Data is 120
Data is 0
Data is 248

```

# Answer
> 1 votes
Or just storing the inbound data in a char type and use single quotes when parsing incoming bytes so that the compiler knows your dealing with ASCII, print them out on serial and they should be familiar characters, of course with the baud rate mismatch fixed

# Answer
> 0 votes
This might be sending the data in bytes so convert it and then try. You can convert it by doing `String(data)`.

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


# Question
Title: How to program ATmega4809 from Raspbeery GPIO
From this tutorial I'm able to nicely program an ATmega328 using SPI raspberry GPIO pins. However, when I try the same steps with ATmega4809, `avrdude` seems not having instructions and outputs the following:

```
program enable instruction not defined for part "ATmega4809"

```

So, how do I program ATmega4809 chip from Raspberry?

# Answer
> 1 votes
The ATMega4809 uses UPDI (Unified Programming and Debugging Interface) for programming, not ICSP like the older ATMega328P. You need a UPDI programmer.

There is a project jtag2updi which you can run on an Uno that turns it into a JTAG to UPDI adaptor which is then compatible with `avrdude -c jtag2updi ...`.

---
Tags: spi, avrdude, raspberrypi
---


# Question
Title: What do you do when you finish a project?
I have just about completed my first Arduino project using an Arduino Uno board, but is that what I use inside the finished device? I figured I’d keep the Uno for future projects and have something else controlling the finished product. Are you supposed to just keep purchasing the Uno board every project?

I just got it a couple of days ago so I’m not very familiar with any of it. If that is the case do you use the batter for power since I can’t have it connected to my laptop once it’s done.

# Answer
> 1 votes
There are many options, so it all ends up depending on your personal preferences:

* You could indeed dedicate this Arduino to this project, and buy a new one for the next project. This may be the simplest solution, if not the cheapest. Just make sure you are not using a breadboard for the other parts. A “proto-shield” may be a good option for soldering the rest of your circuit in a permanent form.
* You may replace the Uno with a smaller Arduino, like the Micro (but beware it uses a different MCU) or a Pro Mini clone (same MCU). These smaller boards can then be soldered onto a PCB using standard 0.1” pin headers.
* You could buy a cheap clone, test it to make sure it works as intended on this particular project, and dedicate the real one for further prototyping.
* You could get a bare ATmega328P plus crystal and caps and put them, together with the rest of your circuit, onto a perf-board or a strip-board. C.f. Michel Keijzers’ answer. Note that if your program can run happily off a somewhat inaccurate 8 MHz clock, you can use the MCU's internal oscillator instead of a crystal.
* If your program is far from using all the resources of the Uno, you may consider a smaller MCU. The ATtiny85 is a popular “minimalistic” choice. Make sure an Arduino core is available for it, unless you want to program all low-level.
* For the most professional result, you could design and order a real PCB for your whole circuit, including the MCU.

# Answer
> 1 votes
What you can do is:

* Buy the main IC (Atmel 328P)
* Use some external components to get it working (like a crystal). Check this on a breadboard to see if it works (and check.
* Buy a case to put it in
* Buy some protoboard or PCB to solder it on (or use a footprint)
* For power, use some components (voltage regulator) or an adapter, or battery, whatever you need. Make sure you check this on a breadboard before you solder it.

If you want to read more about the subject, search for 'prototyping'.

---
Tags: arduino-uno
---


# Question
Title: Is it possible to send data from internet server to ESP8266 behind proxy or regular requests from ESP8266 are required?
It would be kind of push notification or something like that probably. I can first connect to server and send it any data for "registration"...

I found many examples with websockets but all of them was about ESP8266 is like "server". That's not this case...

# Answer
It seems evident that you don't want your ESP8266 running as a server of any kind. That's understandable given that server programs consume a fair amount of system resources (CPU, RAM, etc.) that are in short supply. That means you'll have to use your ESP8266 as a **client** and this means either

1. **Polling** \- where the ESP8266 repeatedly connects to your "internet server" to explicitly ask for information at frequent intervals. Your internet server would have to be able to collect information in batches and hang onto it until your ESP8266 connects again to request the information.
2. **Socket connections** \- where your ESP8266 maintains a consistent socket connection to your "internet server." Note that the HTTP protocol relies on socket connections, but clients open a socket connection, request a web page and its images, CSS, etc., then disconnects the socket. You can also use sockets at a more basic level as a bytestream. This programming can be tricky, but ESP8266 does have examples of TCP socket communication like WiFiClient and ethernet client.

Client approaches have a variety of headaches:

* server has to hang on to information until the client comes back to retrieve it
* you have to work up some kind of data structure to track which information has been handled and which work must still be done
* latency issues -- i.e., what happens when there's a delay in processing information.

Server approaches also have challenges:

* server programs can be tricky to write so that they keep running. a single exception or fatal error can crash the program
* server programs are vulnerable to DDoS or other attacks, and can easily overwhelm a small device like ESP8266
* firewall and networking issues -- depending on how this device connects to the internet, it may or may not have a consistent IP address where it can be found, the ISP that connects it may not allow incoming connections for the ports that it listens on, etc.
> 1 votes

---
Tags: esp8266, esp32
---


title: i2c high speed and pull-up resistors

text:
# Question
Title: i2c high speed and pull-up resistors
hello guys i want to ask about 2 things first one is i'm connecting and arduino uno attached to a usb host sheild and transferring data of a mouse coordinates to 10 arduino leonardo i'm using the standard speed 100 normal mode my wires is all about 10 cm long

1. i need to speed up the comm to fast mode how to make this ? and the line of code where to put it in the code and in the master or slave ?
2. what about the pull-up resistors ? does arduino uno includes built in pull-up resistors ? does it needs to disable it and put my own pull up resistors ? i’m using wire library

# Answer
> i need to speed up the comm to fast mode how to make this

```
Wire.setClock(400000);

```

> and the line of code where to put it in the code

Just after `Wire.begin()` in `setup()`. `Wire.begin()` sets the speed to 100,000 and you need to then override that afterwards to set it to 400,000 (or whatever speed you want to run at).

> and in the master or slave ?

In the master, since it's the master that generates the clock.

> what about the pull-up resistors ? does arduino uno includes built in pull-up resistors ?

Yes, but they're too high for reliable I2C operation. You should add your own resistors in the region of 1kΩ.

> does it needs to disable it and put my own pull up resistors ?

No, yours will just be in parallel with them, with the net result of a small reduction of overall resistance.
> 3 votes

---
Tags: i2c, resistor, pull-up
---


title: TX, RX, ON, L LEDs were red at all time

text:
# Question
Title: TX, RX, ON, L LEDs were red at all time
Before seeing this error I did a project with my Uno board using a Bluetooth module.

After that, when I powered the board to upload another program, 4 LEDs (L, TX, RX, ON) went red without blinking.

So now, every time when I power up my Uno board, without any connection with any of the pins previously mentioned, the 4 LEDs are red coloured all the time.

# Answer
If you can upload sketches, I don't think it is that big of a deal but if you can't, check the TX and RX pin tracks since if those tracks are shorted, they can keep the indicator lights on for ever due to the Serial code on the Arduino. To get further help, please tell me what happens if you try uploading code.
> 0 votes

---
Tags: arduino-uno, led, bluetooth, error, rx-pin
---


title: Arduino Compiling Error

text:
# Question
Title: Arduino Compiling Error
I recently format my Windows 8 and installed Windows 8.1 . In Windows 8, I was using Arduino IDE and there was no error in compiling.But then I installed Windows 8.1 and re-installed Arduino IDE.I tried various codes for motor drivers and everything but they didn't compile.So, I tried to compile blink LED example first and even it didn't compile.It shows the following error on UPLOADING BLINK LED Example-

```
Arduino: 1.8.2 (Windows 8.1), Board: "Arduino/Genuino Uno"

C:\Program Files\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files\Arduino\hardware -tools C:\Program Files\Arduino\tools-builder -tools C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files\Arduino\libraries -libraries C:\Users\Admin\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10802 -build-path C:\Users\Admin\AppData\Local\Temp\arduino_build_754363 -warnings=none -build-cache C:\Users\Admin\AppData\Local\Temp\arduino_cache_657645 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\Arduino\hardware\tools\avr -verbose C:\Program Files\Arduino\examples\01.Basics\Blink\Blink.ino
C:\Program Files\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files\Arduino\hardware -tools C:\Program Files\Arduino\tools-builder -tools C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files\Arduino\libraries -libraries C:\Users\Admin\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10802 -build-path C:\Users\Admin\AppData\Local\Temp\arduino_build_754363 -warnings=none -build-cache C:\Users\Admin\AppData\Local\Temp\arduino_cache_657645 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\Arduino\hardware\tools\avr -verbose C:\Program Files\Arduino\examples\01.Basics\Blink\Blink.ino
Using board 'uno' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Detecting libraries used...
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\sketch\Blink.ino.cpp" -o "nul"
Generating function prototypes...
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\sketch\Blink.ino.cpp" -o "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\preproc\ctags_target_for_gcc_minus_e.cpp"
exit status 1
Error compiling for board Arduino/Genuino Uno.

```

I tried RE-installing the software and drivers.It didn't work

Why is this happening?What is the Solution?

# Answer
> 1 votes
Right click on the Arduino icon, select properties. Under the compatibility tab, check "Run this program in compatibility mode" and select Windows XP. You might also want to run it as administrator.

This should hopefully solve the issue.

Source

# Answer
> 0 votes
Uninstall Arduino. Then find the Arduino folder in your Appdata folder and delete it. Then reinstall Arduino. This is happening because after a library import, there might have been a clash in the Appdata and since uninstalling doesn't delete Appdata, just reinstalling wouldn't help. This happened to me when a PPM and Servo library clashed!

Note: Do this only after you try uploading a blank sketch and it still fails! Also be careful while in the Appdata folder.

---
Tags: programming
---


# Question
Title: Continuous voltage on IO Pins while 5V is not Connected?
i have a small project where i just sucessfully destroyed my frist of 5 Digisparks (Attiny85).

In the Picture you see the Cirucit. I have 2 Liion cells connected in series to get high enough voltage to step it down to constant 5V. To these 5V some Neopixels and a Digispark controller are connected which will set the color for the Neopixels. A0 and A1 measure the Voltage of the Cells to signal the user if the Voltage is to low so it can manually be switched of. While prototyping it i didnt have the 10k resistors in there.

Now what happend: While connecting the cells after each other the Controllers LEDs already lit up with the Frist cell. I guess it was powered trough the A0 pin (again i didnt have the 10k resistor in there), so i guess the internal IO Protection diodes conductet the voltage trough and this way the controller got damanged. Since this happend it wont turn on Anymore.

The problem: since i have really small space i cant use a multiple pole switch to also remove the voltage from the IO pins and therefore i will always have voltage von A0 and A1 while there is no 5V Supplyvoltage. I would guess that the Series resistance on the pin would be enough to Limit the current trough them and this way protect the controller from damange. But i dont really have experience with that and hope that you guys can give me some hints what could also be a problem or what could help :) I really dont want to destroy a second one xD

Thanks in advance and have a nice day :)

# Answer
For this I would recommend isolating the power from the batteries with P-channel MOSFETs and only switching them on when you want to sample the voltage. This means that there is no power consumption at all (aside from an absolutely minuscule leakage current) when turned off.

The whole setup would require 4 MOSFETs - two P-channel and two N-channel. They don't need to be big, since the currents involved are very small, but they do need to have "logic level" thresholds, ideally \< 1.5V (-1.5V for the P-channel).

The basic circuit looks like this:

simulate this circuit – Schematic created using CircuitLab

The circuit is made up of two identical segments - M1+M3 and M2+M4. The operation is fairly straightforward:

* M1 (M2) is kept in the OFF state by R1 (R2) pulling the gate up to source.
* M3 (M4) can pull the gate of M1 (M2) LOW turning it on and allowing current to flow
* Any GPIO pin (D7 in this example) can control both M3 and M4 together
* R5 keeps M3 (M4) off when there is no power - otherwise it floats.
* R3/R4 are your existing voltage divider.

The purpose of M3 and M4 is to both turn the GPIO (D7) into "open drain" so that it's either pulling down or floating high (rather than driving high at 5V) and to isolate the two pullup gate voltages. The same effect could be achieved by two diodes and one MOSFET but it's simpler to just use two MOSFETs and not have to get diodes as well.
> 2 votes

# Answer
As a general rule, you should not apply a higher voltage to the logic pins of digital ICs than you do to their power pin. This means that if you disconnect power, you must also shut off voltage to the logic pins.

Failure to follow that rule will often destroy an IC.

I don't know about the specifics of the inputs on your DigiSpark. 10K resistors will certainly lower the current that is able to flow into those pins, but you would still be breaking the "don't put more voltage into an input pin than you put into the VIN pin" rule.
> 0 votes

# Answer
If all you are doing with A0/A1 is 'signalling the user that the voltage is too low for continued operation', then consider the following:

* remove the lead from the top of the lower battery entirely
* instead of the 1/1 voltage divider, use something like 10/1 (i.e. a 680K on top and a 68K on the bottom to provide a large series resistance (making the steady-state current drain on the battery negligible). This will also put the nominal full-charge voltage as measured at the ADC input well within the DC voltage range of the Digispark at a small cost in accuracy. The specs for the ATiny85 ADC input impedance is something like 100 MegOhms, so the accuracy drop from using a 680K series resistor shouldn't be more than a few percent. Use a variable power supply to calibrate the A/D setup so your controller will alert the user when the battery stack gets low. If you don't have a variable power supply, consider something like this

Frank
> 0 votes

---
Tags: digispark, voltage-protection, analog
---


# Question
Title: TI ADS7250 Read From SPI and SPI1 Simultaneously
I'm so confused by the ADS2750 datasheet here, I can't seem to figure the proper bit shift to read data from bits 15-27 properly. I'm not even sure what some of the acronyms mean on page 23 table 1. I get that the first 15 bits are empty while the ADC takes a reading and then the last 12 bits for the 12 bit ADC are the value from that ADC that matches the SPI A or B input. Would someone be willing to explain to me how you would read data based on this datasheet using information from table 2 page 24?

My hardware set up to ADC7250 VCC 5 Volts

* D5 SS fro Both SPI & SPI1
* D13 SCK for Both SPI & SPI1
* D11 MISO SPI\_A from ADC
* D4 MISO SPI\_B from ADC
* No MOSI connected

I'm not sure what to send in the `SPI.Transfer(0x00)`. I'm also not sure if I'm setting up the modes properly, `SPISettings settings(24*MHZ, MSBFIRST, SPI_MODE1);` as I not 100% on the clock speed. I also I'm confused if this is LSB or MSB as the datasheet has two conflicting notes, the transfer function used LSB and then two paragraphs say "MSBs of ADC\_A and ADC\_B are output"

I'd love some help decoding this data sheet and getting a script that can read data from this chip using both SPI and SPI1 simultaneously.

Working on only reading SPI first the will add SPI1.

```
unsigned int readRegister(byte thisRegister, int bytesToRead);

const int CS_ADC_ISOLATOR = D5;
__SPISettings settings(24*MHZ, MSBFIRST, SPI_MODE0);
const int buffersize = 30;
unsigned char dataBuffer [buffersize];
const byte READ = 0x22;

// setup() runs once, when the device is first turned on.
void setup() {
  Serial.begin(115200);
  pinMode (CS_ADC_ISOLATOR, OUTPUT);
  digitalWrite (CS_ADC_ISOLATOR, HIGH);
  SPI.begin();
  SPI1.begin();
}

// loop() runs over and over again, as quickly as it can execute.
void loop() {
    digitalWrite (CS_ADC_ISOLATOR, LOW);
    SPI.beginTransaction(settings);
    for(unsigned char i = 0; i < buffersize; i ++)
    {
        dataBuffer[i] = SPI.transfer(0x00 << 14);
    }
    digitalWrite (CS_ADC_ISOLATOR, HIGH);
    SPI.endTransaction();
    for(unsigned char n = 0; n < buffersize; n ++)
    {
        Serial.print(dataBuffer[n]);
    }
    Serial.print("::");
}

```

# Answer
> 1 votes
You can't use the normal SPI library for communicating with this device properly. Well, you *can*, but you will only be able to use one channel - the other will be completely ignored.

SPI only works on one MISO pin - you need two. There are two other types of "SPI" that are used by devices, most notably SPI flash chips: DSPI and QSPI (dual SPI and quad SPI). You want DSPI.

Unfortunately the Arduino doesn't do DSPI, so you will have to "bit bang" it, which means manually manipulating the IO pins to create your own SPI signals in software.

Now... on to the datasheet:

The important part is the timing diagram on page 9. From that you can see that you just send 32 clock pulses and the chip responds, after 15 pulses, with the data.

So if you just do 4 8-bit transfers back-to-back then you get the data. It doesn't matter what you "send" in those transfers since the MOSI pin isn't connected to anything.

As far as speed goes, 24MHz is the *maximum* speed that it will run at. The actual speed is dictated by the Arduino and how fast you manipulate the SCK pin. That can be as slow as 1x10<sup>-1000</sup>Hz if you really want.

Data should be read on the falling edge of SCK.

So you could write a little routine that looks like:

```
uint32_t resa = 0;
uint32_t resb = 0;

pinMode(SCK, OUTPUT);
pinMode(SDI_A, INPUT);
pinMode(SDI_B, INPUT);
pinMode(CS, OUTPUT);
digitalWrite (CS, HIGH);

digitalWrite (CS, LOW);
for (int i = 0; i < 32; i++) {
    digitalWrite(SCK, HIGH);
    digitalWrite(SCK, LOW);
    resa <<= 1;
    resb <<= 1;
    resa |= digitalRead(SDI_A);
    resb |= digitalRead(SDI_B);
}
digitalWrite (CS, HIGH);

Serial.print("A: "); Serial.println(resa);
Serial.print("B: "); Serial.println(resb);

```

So for 32 iterations you pulse the clock HIGH then LOW, then shift each result 1 bit to the left, and then add in the newly read bit into the lowest bit position.

You could speed up operation by using direct port manipulation and avoiding the slow `digitalWrite()` and `digitalRead()` functions.

---
Tags: spi, adc
---


title: Add char at intervals in a String

text:
# Question
Title: Add char at intervals in a String
I'm trying to create a function that will take a String as an input, and at every 20 characters, it will instert "\n" so that the string doesn't go off the side of my screen (I'm using an oled with the SSD1306Ascii library).

This is my code so far, but when I run it nothing appears on the screen (I have another part of the code which passes the string to the funtion):

```
String message = "";
String newMessage = "";

void printMessage(String message) {
  oled.clear();
  if(message.length() > 20) {
    current = 20;
    while(current < message.length()) {
      newMessage = message.substring(current-20, current) + "\n";
      newMessage = newMessage + message.substring(current+1);
      current+20;
    }
    oled.println(newMessage);
  }
  else {
    oled.println(message);
  }
}

```

# Answer
> 0 votes
I think that your implementation is fundamentally flawed. In the while loop, when you assign `newMessage` to a `message.substring` you are discarding all the work done in the previous iterations.

Also I would recommend keeping the splitting and the printing separated. The `operator +=` also is very handy here. This code (untested) should implement your original idea in a correct way

```
String splitMessage( const String & message, const unsigned limit) {
  String newMessage = "";
  unsigned i = 0;
  while ( i+limit < message.length() ) {
    newMessage += message.substring(i, i+limit);
    newMessage += '\n';
    i += limit;
  }
  newMessage += message.substring(i);
  return newMessage;
}

```

Then you can do:

```
whatever.println(splitMessage(myMessage, 20));

```

---

Note that I retained the use of `String` from your original implementation, although, being in an embedded environment, it is likely better to avoid it in favor of stack-allocated c-strings.

I have found a substantial amount of pretty enlightening information in the various answers to this question: Is using malloc() and free() a really bad idea on Arduino?

# Answer
> 0 votes
One issue with both your failed implementation and the previous answer is that they do loads of dynamic allocations and copies. Every time you use the String’s `+` or `+=` operators you are allocating heap memory for a brand new String, copying the original character data into the newly allocated space, and eventually destroying the original Strings when you don’t need them anymore.

The simplest way to avoid all these copies and allocations is to *not* build the String you want. Instead, just `write()` the pieces one after the other on the display. Here is a zero-copy, zero-dynamic allocation solution:

```
void printMessage(const char *message) {
    size_t length = strlen(message);
    while (length > 20) {
        oled.write(message, 20);
        oled.write('\n');
        message += 20;  // point to the rest of the message
        length  -= 20;  // remaining length
    }
    oled.write(message);
}

```

Note that the method `Print::write(const char *, size_t)` is used here to print a slice of the message without ever building it as a string in memory.

On these memory-constrained devices it is always preferable to avoid heap allocation, and thus `String` objects. However, if for whatever reason you *really* need to print a `String` object, then you can use the following overload to print it’s internal buffer without making any extra copy:

```
void printMessage(const String &message) {
    printMessage(message.c_str());
}

```

---
Tags: c, string
---


# Question
Title: Make an Arduino board act as both a usb storage device and a keyboard?
I am making an interface project that, when plugged into a computer, shows up as both usb flash storage and can type like a keyboard when some physical buttons on the board are pressed.

I have seen projects that do one or the other, but not both at the same time.

I have gotten it to work using a usb hub and two chips that are sharing the same storage (since I want the hot-key buttons to type out information stored in the flash drive side as well), with one acting like a HID and one acting as usb storage, but this has a few problems. First, it feels redundant. Second it's difficult to program since every time I plug the mess in it randomly assigns a name to each chip with no easy way of telling which to send the HID code to and with to send the USB Drive code to. I have to plug them in one at a time which wont work once this project is all on the same board. The last problem is the buttons work inconsistently since, im assuming, the two chips are not doing a nice job of sharing access to the text file it's trying to read for the text to 'type out' on the computer.

Is there a nicer way of doing this that uses one arduino acting in both roles accessing the one flash storage? Thanks!

# Answer
The Leonardo can easily be used as a keyboard. There are also special codes to turn the USB-to-Serial chip on newe Unos into a keyboard (see here)

USB mass storage is another game all together. The Brondani EasyUSB is a simple chip that exposes 2MB of storage space on both the USB and microcontroller. They say they will be releasing larger capacities.

The easyUSB also has a serial link built into it from uC to computer.

If you really want, you can make your own USB stack to handle this on you own, but the pitifully small amount of ram on these chips would prohibit it.
> 2 votes

# Answer
You're looking to create a USB composite device. I don't see any examples within the arduino community, but I don't see a reason why you couldn't use the 16u2 as a composite device, it'll just require more effort than you'd normally put into an arduino project.
> 1 votes

# Answer
You can try using an Arduino Mega ADK. This is because it has a separate USB port for USB devices along with many serial ports for other serial device.
> 0 votes

---
Tags: serial, programming
---