texts:
I'm rather new to Arduino programming. I have a problem compiling the following bit of code:

const int relay1 = 10;  //Power Relay 1
const int relay2 = 11;  //Power Relay 2
const int relay3 = 12;  //Toggle Relay
const int button1 = 3;
const int button2 = 4;
const int button3 = 5;

//---Button States---\\
int button1State;   //Current state of Button 1
int button2State;   //Current state of Button 2
int button3State;   //Current state of Button 3
int button1State_prev = LOW;  //Previous state of Button 1
int button2State_prev = LOW;  //Previous state of Button 2
int button3State_prev = LOW;  //Previous state of Button 3

//---General Variables---\\
int userSelection = 0;
int interlockState = 0;
int platformState = 0;

//---Interval-Tracking Variables---\\
unsigned long lastTime_Debounce1 = 0;   //Button 1 debounce time
unsigned long lastTime_Debounce2 = 0;   //Button 2 debounce time

//---Activity Delays---\\
const unsigned int relayDelay = 10;           //Delay between relay actions (ms)
const unsigned int debounceDelay = 60;        //Delay for button de-bouncing (ms)

void setup() {
  //Configure Pins
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);

  digitalWrite(relay1, LOW);
  digitalWrite(relay2, LOW);
  digitalWrite(relay3, LOW);
}

void loop() {
  //Read value of each input pin
  int button1Reading = digitalRead(button1);  //Current reading of Button 1
  int button2Reading = digitalRead(button2);  //Current reading of Button 2
  int button3Reading = digitalRead(button3);  //Current reading of Button 3

  //Debounce Button1
  if (button1Reading != button1State_prev) {
    lastTime_Debounce1 = millis();
  }
  button1State_prev = button1Reading;
  if ((millis() - lastTime_Debounce1) > debounceDelay) {
    if (button1Reading != button1State) {
      button1State = button1Reading;
    }
  }

  //Debounce Button2
  if (button2Reading != button2State_prev) {
    lastTime_Debounce2 = millis();
  }
  button2State_prev = button2Reading;
  if ((millis() - lastTime_Debounce2) > debounceDelay) {
    if (button2Reading != button2State) {
      button2State = button2Reading;
    }
  }

For some reason, the compiler is convinced that the variable lastTime_Debounce1 in the second IF-statement, on Line 54, has not been declared in-scope. I don't understand how this is possible, since the variable in question is a defined and initialized global.

If I comment-out the first trio of IF-statements (handling Button 1), the second trio (handling button 2) has no problem compiling, even though it does exactly the same thing in exactly the same way.

I checked all the usual suspects: spelling, braces, semicolons, even commented-out blocks of code one at a time, but I can't find the source of the problem. I'm using the Arduino 1.8.2 IDE.

Can someone please point out the mistake I'm missing?


texts:
I have a concern about the library port handling. I have used direct port direction manipulation successfully in previous projects but there seems to be a problem here.

// This code mostly taken from the example
#include "LedControl.h"

LedControl lc=LedControl(11,13,10,1);
//LedControl lc=LedControl(12,11,10,1); // original
// pin 12 is connected to the DIN pin (now MOSI 11)
// pin 11 is connected to the CLK pin (now SCK 13)
// pin 10 is connected to the CS pin  (now SS 10)
// 1 as we are only using 1 MAX7219

// I am actually using all arduino pins except 12 for my project
#define PD_MSK  B11111100 // Data pins PD2..7 (pins2..7)
#define PB_MSK  B00000011 // Data pins PB0,1 (pins8,9)
#define PC_MSK  B00001111 // Data pins PC0..3 (pins 14..17)

void setup()
{
// set pins 2..9 as inputs
  DDRD = DDRD & !PD_MSK; // this works OK
  DDRB = DDRB & !PB_MSK; // configure ports D,B inputs *** doesnt work with this
 // pinMode(8, INPUT); //*** does work with this
  //pinMode(9, INPUT); //*** does work with this

  DDRC = DDRC | PC_MSK; // configure PortC0..3 as outputs
  PORTC |= 0x0F; // set PortC0..3 high (default)

  // the zero refers to the MAX7219 number, it is zero for 1 chip
  lc.shutdown(0,false);// turn off power saving, enables display
  lc.setIntensity(0,8);// sets brightness (0~15 possible values)
  lc.clearDisplay(0);// clear screen

}
void loop()
{
  //numbers 7 to 0
  for (int a=0; a<8; a++)
  {
    lc.setDigit(0,a,a,false);
  }

  delay(1000);

  //display number 8 on all segments
  for (int a=0; a<8; a++)
  {
    lc.setDigit(0,a,8,false);
  }
  delay(1000);

  // numbers 7 to 0 reverse order
  for (int a=8; a>=0; a--)
  {
    lc.setDigit(0,a,a,false);
    //delay(100);
  }
  delay(1000);

}

The direct port direction setting does not seem to allow the library to work while the pinMode commands doing the same job do. I note that the library uses software SPI but I would like to use hardware if possible. I have certainly used hardware SPI with frequent port direction changes on the remaining pins for other projects.
Any insight as to why this problem occurs?

Thanks.


texts: How do I make my Arduino do a specific action when the computer is locked/unlocked?

texts:
I have a windows computer connected to my Arduino Uno. I work in a area with a bunch of cubicles and we leave our desk fairly regularly to go and troubleshoot other computers (I'm a service desk technician).
When we leave we are instructed to raise and lower a small flag so management can see whether or not we are sitting at our desk. I've attached my arduino to a servo motor with the following code.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
#define servoPin 3 //~
#define pushButtonPin 2

int angle =0;    // initial angle  for servo
int angleStep =20;
const int minAngle = 0;
const int maxAngle = 90;

int buttonPushed =0;

void setup() {
  // Servo button demo by Robojax.com
  Serial.begin(9600);          //  setup serial
  myservo.attach(servoPin);  // attaches the servo on pin 3 to the servo object
  pinMode(pushButtonPin,INPUT_PULLUP);
   Serial.println("Nathan's Status flag");
}

void loop() {
  if(digitalRead(pushButtonPin) == LOW){
    buttonPushed = 1;
  }
   if( buttonPushed ){
  // change the angle for next time through the loop:
  angle = angle + angleStep;

    // reverse the direction of the moving at the ends of the angle:
    if (angle <= minAngle || angle >= maxAngle) {
      angleStep = -angleStep;
       buttonPushed = 0;
    }
    myservo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
  delay(100); // waits for the servo to get there
   }
}

We also have a policy that we need to keep our computers locked for obvious reasons. I learned my lesson with that early on. I would like to edit my code so that when I lock my computer the flag goes down, then when my computer is unlocked it goes back up. That way as long as I remember to keep my computer locked when I'm away I don't have to worry about the flag. Here is my breadboard/arduino layout.

I also have processing on my computer and am planning on using that. (https://processing.org/)
Any help is greatly appreciated.


texts: Adjust time calculation after Timer0 frequency change

texts:
I have an Arduino Nano with an 328P and need all 6 PWM pins.

Thus, I had to adjust the prescaler and WGM Mode of Timer0.

It is now in phase correct PWM mode with a prescaler of 1.

TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
TCCR0B = _BV(CS00);

Now I need a working time calculation for other libraries, but since
Timer0 had that duty everything is out of order now.

I tried adjusting the wiring.c

// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

to this

#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 510))

But it's like I didn't change anything.
(tested other settings that were changed so it was compiled anew )

Whole Code:

void setup() {

  // Set Timer 0, 1 and 2
  // Register A: Output A and B to non-inverted PWM and PWM mode to phase correct.
  // Register B: Pre Scaler to 1.
  TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
  TCCR0B = _BV(CS00);

  TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
  TCCR1B = _BV(CS10);

  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
  TCCR2B = _BV(CS20);

  pinMode(8, OUTPUT);

}
void loop() {

  digitalWrite(8, LOW);
  delay(65000);
  digitalWrite(8, HIGH);
  delay(65000);

}


texts: How to get a stable LED lighting without scintillation over I2C bus

texts:
I built an 8x8 led matrix using white 5mm LEDs. I drive the LEDs using the MCP23017 connected to an Arduino over the I2C bus. The wiring of the LEDs in the matrix is such that a row is made up of 8 LEDs whose cathodes are wired together, and a column is made up of 8 LEDs whose anodes are wired together. The end of each row and each column is connected to a GPIO pin of the MCP23017.
The size of the pixel is 4cmx4cm which means that a row is 32 cm long (the same for a column).
I cannot get the light to be "stable", it keeps scintillating. I increased the clock frequency of the I2C bus from 100kHz to 400kHz, the light is more stable now, but not enough since the scintillation persists. Before that, I set the I2C clock frequency to 1700kH and the lighting became even slower..., I tried increasing the values of the pullup resistors of the GPIO pins of the MCP23017 to have a quicker response on its GPIO pins, but it had no effects.

I am thinking of 2 potential reasons:

The wires are too long for the I2C protocol to handle (a side of the led matrix is 32cm long).
the current reaching every column (the anodes) is not enough since there are so many leds to light up.

What do you think is causing this bad lighting? should I change the MCP23017 with another type of expander/protocol?
Here's the code:
#include <Wire.h>
#include <Adafruit_MCP23017.h>

bool four[3][5] = {{1, 1, 1, 0, 0}, {0, 0, 1, 0, 0}, {1, 1, 1, 1, 1}};
Adafruit_MCP23017 mcp;

void setup() {
  mcp.begin();
  for(int i=0; i<16; i++){
    mcp.pinMode(i, OUTPUT);
    }
}

void set_column(uint8_t col_idx, bool pixels[]){

  for(uint8_t i=0; i<8; i++)
    mcp.digitalWrite(i, HIGH);

  for(uint8_t i=8; i<16; i++) //Anodes are connected to Bank B of the MCP23O17
    if(i!=col_idx+8)
      mcp.digitalWrite(i, LOW);
    else
      mcp.digitalWrite(i, HIGH);

  for(uint8_t i=0; i<8; i++) //Cathodes are connected to Bank A of the MCP23O17
    if(pixels[i])
      mcp.digitalWrite(i, LOW);
}

void display_character(bool character[3][5]){
  bool pixels[8] = {0, 0, 0, 0, 0, 0, 0, 0};
  for(int col=0; col<3; col++){
    for(int i=0; i<5; i++){
      pixels[i+3] = character[col][i];
      }
    set_column(7-col, pixels);
    }
}

void loop() {

  uint32_t time = millis();
  while(millis() - time < 1000)
    display_character(four);
}


texts:
I am trying to use Arduino Nano with ESP8266 (01). I tried to follow a lot of online tutorial with no result.

In particular this one http://www.martyncurrey.com/arduino-to-esp8266-serial-commincation/.
I think connections between Arduino Nano and ESP8266 are fine, when I upload the code on Arduino the red led on the ESP8266 turns on, I set the Arduino Monitor to 9600 BAUD and try to send command like "AT" but I got not reply from ESP8266. I also tried to switch to 115200 BAUD with no result too.

I don't if is something wrong or ESP8266 is damaged. Is there any tutorial that you may suggest?

Thank you.


texts: ESP8266-01 connected to Arduino Mega - Current output?

texts:
I was thinking of powering my arduino with an external 9 V power source, but I am still trying to figure out the best way to get the right amount of current for the Wi-Fi module. Should I use an external power supply for the ESP8266-01 module that can output about 500mA or amplify the output from the arduino pins using a transistor?

If there is an easier way to do this I am all ears. I will be using Arduino Mega, not uno as shown in the picture.

EDIT: Voltage divider will be used on the RX pin and I might go for a logic level converter instead of the voltage regulator


texts: Arduino due dying after connection, gets hot

texts:
I have an Arduino Due (made in Italy) which suddenly (after working nicely for some time) started a new behavior: If I connect it to my computer via USB it is recognized and connects. The "On"-led is turned on but gets darker within seconds until it's off and the connection breaks. This happens with both USB ports. The area around the usb ports gets hot and especially the "504L" next to the reset buttons. (I just have my finger to measure the temperature, so it could also be something else in this corner).

What could have happened to the board? And is there anything I can try to revive it?

Update:
@GuitarPicker: It's the object labelled "0105" in your image, so it's probably the F1 fuse. If I connect the top USB, F1 gets hot, if I use the lower usb, F2 is activated.

There is nothing connected to the board. Before that, I used it to send SPI commands where I might have connected some of the SPI pins in the 6 pin group.
The board is placed on wood, so there should be no external connection
No smoke or visible damage.


texts: Arduino long message is cutoff in serial.read

texts:
My setup is like this, I have an arduino and an esp8266 esp-01 connected thru serial.
I have programmed my esp8266 esp-01 to read from a JSON Source and I am returning a sample json like this.
{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

My code in my ESP8266 ESP-01
void sendData(String payload){
  String dataToSend = "<";
  dataToSend += payload;
  dataToSend += ">";
  Serial.write(dataToSend.c_str());

}

Noticed that I am sending back a Message with a start and end marker
I copied the code from this Arduino Forum Post on how to read the message sent by my esp-01 to my Arduino https://forum.arduino.cc/index.php?topic=396450.0
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); // RX, TX

const int numChars = 1024;
char receivedChars[numChars];

boolean newData = false;

void setup() {
    Serial.begin(115200);
    mySerial.begin(115200);
    Serial.println("<Arduino is ready>");
}

void loop() {
    recvWithStartEndMarkers();
    showNewData();
}

void recvWithStartEndMarkers() {

    static boolean recvInProgress = false;
    static int ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (mySerial.available() > 0 && newData == false) {
        rc = mySerial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(receivedChars);
        newData = false;
    }
}

But I am receiving garbled message, only the first few lines are readable...
{
    "glossary": {
        "title": "example glossary",
        "wasasad+": {
            "eaSeta" tci ei,i"u c"7 : :9 n3
         p -x
        s"i,p

I tried editing my received code in my arduino like this
    String resultString="";
    boolean isReady= false;

    while (mySerial.available()){
     resultString=mySerial.readString();
     isReady= true;
    }

    if (isReady){
      Serial.println("Received String: " + resultString);

    }

But the output is still the same.  Any hints how can I receive the whole string?


texts:
I think I broke my Arduino Uno as I was playing with it. I connected an ultrasonic range finder to it and uploaded a sketch to it. It was working fine until I accidentally touched the ICSP headers for the USB interface (the pins near the USB port). Now,everything is still working but my computer cannot detect it and it does not show up in the device manager or the IDE. Please tell me if it is broken and how to fix it.

BTW, I just bought it and just started using it after another Arduino had the same problem.


texts:
I planed a 6x6 matrix with a Arduino Nano as controller.
Its only possible to let one LED in the matrix lighten up.
Any idea how I get the Code smaller? (Im a C Noobie ^^)

~Nico

Circuit diagram:

Code:

void setup() {
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(14, INPUT);
  pinMode(15, INPUT);
  pinMode(16, INPUT);
  pinMode(17, INPUT);
}

void loop() {
  int value1 = digitalRead(14);
  int value2 = digitalRead(15);
  int value3 = digitalRead(16);
  int test = digitalRead(17);
  int x1 = 2;
  int x2 = 3;
  int x3 = 4;
  int x4 = 5;
  int x5 = 6;
  int x6 = 7;
  int y1 = 8;
  int y2 = 9;
  int y3 = 10;
  int y4 = 11;
  int y5 = 12;
  int y6 = 13;

  // put your main code here, to run repeatedly:

  if (test == HIGH) {
    digitalWrite(x1, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x1, LOW);
    digitalWrite(x2, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x2, LOW);
    digitalWrite(x3, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x3, LOW);
    digitalWrite(x4, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x4, LOW);
    digitalWrite(x5, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x5, LOW);
    digitalWrite(x6, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x6, LOW);

  }
}


texts:
I'm trying to send data from my ESP8266 to a NodeJS TCP server, the connection and basic charakters (48-90) are working fine, but if I use others like ASCII-Code (0,1,2,3...)  I don't get any usefull data out of it. So what I was thinking about that there are some character which aren't allowed to send over TCP/IP.

By the way,
I'm using this to write to the server, and I work with the standard WiFi Client library

char arr[255]
for(int i = 0; i < 255; i++){
   arr[i] = (char)i;
}
client.print(arr);

Nodejs File:

// Load the TCP Library
net = require('net');

var mysql = require('mysql');

// Keep track of the chat clients
var clients = [];
var uploadCounter = 0;

initMySQLConnection();

// Start a TCP Server
net.createServer(function (socket) {

    // Identify this client
    socket.name = socket.remoteAddress + ":" + socket.remotePort

    // Put this new client in the list
    clients.push(socket);

    // Send a nice welcome message and announce
    socket.write("Welcome " + socket.name + "\n");
    broadcast(socket.name + " connected\n", socket);

    // Handle incoming messages from clients.
    socket.on('data', function (data) {
        broadcast(">> " + data, socket);

        uploadData(data);
    });

    // Remove the client from the list when it leaves
    socket.on('end', function () {
        clients.splice(clients.indexOf(socket), 1);
        broadcast(socket.name + " disconnected.\n\n");
    });

    // Send a message to all clients
    function broadcast(message, sender) {
        clients.forEach(function (client) {
            // Don't want to send it to sender
            if (client === sender) return;
            //client.write(message);
        });
        // Log it to the server output too
        process.stdout.write(message)
    }

}).listen(10101);

// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 10101\n");

var connection;
function initMySQLConnection() {
    connection = mysql.createConnection({
        host: "host",
        user: "user",
        password: "pass",
        database: "database"
    });

    connection.connect(function (err) {
        if (err) {
            console.log('error when connecting to db:', err);
        }
    });

    connection.on('error', function (err) {
        console.log('db error', err);
        if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
                                    // lost due to either server restart, or a
        } else {                                      // connnection idle timeout (the wait_timeout
            throw err;                                  // server variable configures this)
        }
    });

    setInterval(function () {
        connection.query('SELECT 1');
    }, 60000);
}

function uploadData(data) {
    data = String(data);

    console.log("Package Length: " + data.length);
    console.log("GOT ASCII CODE: ");
    for (var i = 0; i < 255; i++) {
        console.log(data.charCodeAt(i));
    }

    //upload Code
}


texts: Arduino Pro Mini interrupts timer not working

texts:
i am trying to make an arduino pro mini sd card serial logger.The arduino should log the data that comes over the uart and write it to an sd card and if it is no data on the serial for 25 seconds to save automatically the data into the file.Each file are named diffrent every time they are saved(for example datalog0.txt, datalog1.txt and so on).I am creating also at the start of the sketch an config(config.txt) file where the number of the file present of the sd are stored and if the file already exist than a new one will be created, this option works good.Now, after the 25 seconds past and it is no more  data over the serial the arduino dont close the datalog.txt file , so the next data will be saved in the same file, this is the problem i have, even in the config file the file number will be increased.I will attach the sketch and expect patient from you, ai am still newbie.I forgot to mention that it was working good for some time but not anymore, the only thing i did was to upload the bootloader from ide and since than is not working anymore.

Regards.

//#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>
#include <SoftwareSerial.h>

            int i;
            int incomingByte = 0;
//int data[512];
            File myFile;
            unsigned char bytes,flag_again;
            unsigned int fileNo,timer_count;
            String s_fileNo,filename,filename_master;
            char comanda;

            void Timer1_InIt()
        {
            TCCR1A = 0;
            TCCR1B = 0;
            TCNT1  = 0;
            OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
            TCCR1B |= (1 << WGM12);
                TCCR1B |= (1 << CS12) | (1 << CS10);
                //TIMSK1 |= (1 << OCIE1A);
            }

ISR(TIMER1_COMPA_vect)
{
    timer_count++;
    if(timer_count > 25)
    {
        timer_count = 0;
        TIMSK1 &= ~(1 << OCIE1A);
        myFile.close();
        fileNo++;
        myFile = SD.open("config.txt",FILE_WRITE);
        myFile.seek(0);
        myFile.print(fileNo);
        myFile.close();
        //software_Reset() ;    //reset the sketch
    }
}
SoftwareSerial mySerial(4, 5); // RX, TX

void setup()
{
    cli();
    Timer1_InIt();
    sei();

    mySerial.begin(9600);
    Serial.begin(10752,SERIAL_8E2);
    //mySerial.print("Initializing SD card...");

    if (!SD.begin(10))
    {
        //mySerial.println("initialization failed!");
        return;
    }
    Serial.println("initialization done.");

    myFile = SD.open("config.txt",FILE_READ);
// mySerial.println("Config file created");
    if(!myFile.available())
        bytes = 0;
    else
    {
        bytes = myFile.available();
        for(i = 0; i< bytes ; i++)
            s_fileNo += (char)myFile.read();
    }
    myFile.close();
    fileNo = s_fileNo.toInt();
// mySerial.print("file no:");
    //mySerial.println(fileNo);

    filename = "datalog";
    filename += fileNo;
    filename += ".txt";

    myFile = SD.open(filename,FILE_WRITE);
    if (myFile)
    {
        //mySerial.print(filename);
        //mySerial.println(" File Open...");
    }
}

void loop()
{

    if(!myFile)
        myFile = SD.open(filename, FILE_WRITE);

    while(Serial.available())
    {
        incomingByte = Serial.read();
        /*if(incomingByte == 0 || incomingByte < 15 )
        {
          Serial.print('0');
          myFile.print(0,HEX);
        }*/
        //mySerial.println(incomingByte,HEX);
        myFile.println(incomingByte,HEX);
        // myFile.println(incomingByte);
        timer_count = 0;
        flag_again = 1;
    }
    if(!Serial.available() && flag_again)
    {
        TIMSK1 |= (1 << OCIE1A);
        flag_again = 0;
    }

}


texts:
I want to make a wifi-enabled temperature sensor and place it inside my HVAC system to measure and push the temperature to a central server, every minute or so.

I have a LoLin NodeMcu v3 unit laying around, and I am wondering if it is possible to use this one - and have it last for many years inside the HVAC system?

I realize the LoLin unit has a onboard wifi chip, I also realize LoLin takes 3v input. Aside from that, I am pretty blank.

Yesterday I tested the LoLin board by programming it with the following code, which lists networks in the vicinity. It worked great:

#include "ESP8266WiFi.h"

void setup() {
  Serial.begin(9600);
  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(2000);
  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  int n = WiFi.scanNetworks();// WiFi.scanNetworks will return the number of networks found
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}

The actual question

Is the LoLin board a feasible board for making a low power wifi enabled temperature sensor? Or should I rather make board that communicates with a wall-connected parent unit via radio?


texts: GSM and Bluetooth modules on 1 Arduino Uno board

texts:
I couldn't find anything on this topic.

Task: to connect sensors to Arduino board via Bluetooth module, process the received data and then send the data to server via GSM module.

Question: Is it possible to connect both of these modules to 1 Arduino board? If I'm not wrong, Arduino Uno has only one pair of Rx Tx pins, while for these two modules each has its own pairs on Rx Tx pins.

I need to know this before ordering them. So, please help


texts: How to generate Analog Signal (Voice) to the microphone

texts:
I have question about microphone and generating sound signal. I have microphone in my intercom at home. It is simple analog microphone, not digital.

What I want is to connect arduino analog output to the microphone and generate some signal that will be heard like a voice at least few words.

Is it possible to do this ? Or it would be quite hard ?

Please suggest the easiest way to implement this.


texts: Why impedance between I/O pin and ground drops when Arduino is not powered

texts:
I have a 4KHz 5V pulsed signal connected to Arduino UNO pin2 (ISR).

When the board is powered, the pulse is attached to ISR rising edge, and is working as intended.

I don't know the output impedance of the pulsed signal, but when the board is not powered, the pulse drops to 2V.

The resistance between pin2 and ground is about 500K when not powered. The resistance is infinite when powered.

The pulsed signal does NOT drop when connected to a 500K resistor.

Question:

What is the cause of the signal drop?
How to prevent it ? (It's not practical to disconnected the signal from Arduino, but I can make sure Arduino is always powered. How to deal with transient situations like reset ?)

Thanks in advance !


texts: Compiling Assembly Script in External EEPROM to Arduino Code

texts:
I'm working on a simple game console, and I'm planning to use a cartridge system using an EEPROM. I know that you can read and write data from an EEPROM, but can you compile the data into executable Arduino code, and vice versa? If the Arduino can do it, we can probably too, right?
Thanks in advance!


texts:
I try to make a variable that can be modified from the server, using and ESP8266.

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

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

ESP8266WebServer server(80);

const int led = 13;

void handleRoot() {
    digitalWrite(led, 1);
    server.send(200, "text/plain", "hello from esp8266!");
    digitalWrite(led, 0);
}

void handleNotFound() {
    digitalWrite(led, 1);
    String message = "File Not Found\n\n";
    message += "URI: ";
    message += server.uri();
    message += "\nMethod: ";
    message += (server.method() == HTTP_GET)?"GET":"POST";
    message += "\nArguments: ";
    message += server.args();
    message += "\n";

    for (uint8_t i=0; i<server.args(); i++){
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
    }

    server.send(404, "text/plain", message);
        digitalWrite(led, 0);
    }
}

void setup(void) {
    pinMode(led, OUTPUT);
    digitalWrite(led, 0);
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    Serial.println("");

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

    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

    if (MDNS.begin("esp8266")) {
        Serial.println("MDNS responder started");
    }

    String content = "Basic";
    content += "<form action='action_page.php' method='POST'>
";
    content += "User:<input type='text' name='USERNAME' placeholder='user name'>
";
    content += "<input type='submit' name='SUBMIT' value='Submit'></form>
";

    server.on("/led", [](){
        server.send(200, "text/html", content);
        Serial.println(USERNAME);
    }

    server.on("/", handleRoot);

    server.on("/inline", [](){
        server.send(200, "text/plain", "this works as well");
    });

    server.onNotFound(handleNotFound);
    server.begin();
    Serial.println("HTTP server started");
}

void loop(void){
    server.handleClient();
}

When I compile it, it says

  'content' is not captured

I thought it may be from the input, and I tried to name it "Basic" for the start, but it still failed.


texts: Can I use notepad++ for writing sketches?

texts: Before I install the Arduino IDE, I was just wondering whether I could just use notepad++ to write the files and move them into correct location. I assume notepad++ doesn't support Arduino code, but I suspect there will be a mod for it, even though sketches are a low-end version of C++, which is supported.


texts:
I'm trying to establish a wireless connection between two Arduino's(M0) using xbee s2c, one Arduino as the sender and other as the receiver. But I am not able to receive the message what the Arduino is sending.

The two radio modules are configured as:

Sender

pan id- 1234
CE- enable
DH- 13A200
DL- 40F8D876
AP- Transparent mode

Receiver

pan id- 1234
CE- Disable
JV- Enable
DH- 13A200
DL- 40F8D874
AP- Transparent mode

SENDER CODE

void setup() {
  // Begin the Serial at 9600 Baud
  Serial1.begin(9600);
  SerialUSB.begin(9600);
}

void loop() {
  SerialUSB.print(int(Serial1.write("1")));
  delay(1000);
}

RECEIVER CODE

void setup() {
  // Begin the Serial at 9600 Baud
  Serial1.begin(9600);
  SerialUSB.begin(9600);
}

void loop() {
  if (Serial1.available()){
  SerialUSB.print(int(Serial1.read()));
  delay(1000);
}}


texts:
Recently I have been attempting to make my Arduino Uno a PIC16F877A programmer. Looking at the schematic to do this, I see that there is no JP1 pin on the Arduino as specified on the diagram on the top-left.

As I am new to electrical engineering I may just be simply overlooking it yet this is unlikely because I have been puzzled by this for two days.


texts: why am I losing data over serial communication between arduino and pc

texts:
I'm working on a project for school. I'm trying to rotate a servo by writing the letter that identify the servo and then the angle.

the problem is that sometimes the last number of the angle is lost or the whole angle all together. for example i want to rotate servo "a" 50 degrees. i enter a50 this works most of the time but sometimes i only get a 5 without the zero and sometimes i just get a zero. can anyone help, thanks.

please keep in mind i only did computer science in high school and intro to c++ in college. go easy on me please.

attached is the code and an image illustrating my problem.

#include <Servo.h>

Servo servo1;
Servo servo2;
Servo servo3;

String angle1="";
String angle2="";

char serialbuffer[4];
int index=0;
int charcount=0;

int lastangle;
int dif;

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

  Serial.begin(9600);

  serialbuffer[0]='0';
  serialbuffer[1]='0';
  serialbuffer[2]='0';
  serialbuffer[3]='0';
}

void loop() {

       charcount=0;
       index=0;
       serialbuffer[0]=99;

   while (Serial.available() > 0) {

      char charbuffer = Serial.read();
       if(charbuffer=='\n'){
          index=0;
        }
        else{

           serialbuffer[index]=charbuffer;
           index++;
           charcount++;
          }

      }

  angle1="";
  if(serialbuffer[0]=='a'){

      for(int i=1;i<charcount;i++){
         angle1+=serialbuffer[i];
      }
      move_servo3(angle1);
      index=0;
      serialbuffer[0]=99;
    }
  delay(15);
}

void move_servo3(String angle2){

   Serial.println(angle2.toInt());
   servo3.write(angle2.toInt());

  }


texts: ESP8266 send TCP HEX packet with 4 chars

texts:
I'm building a remote for my WiFi-RGB Lights. I have an ESP8266, which should send one TCP packet with 4 chars.

My code:

#include <ESP8266WiFi.h>

const char* ssid     = "Wifi";
const char* password = "wifikey";

void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);
}

void setup() {
  Serial.begin(115200);
  WiFi.disconnect(true);
  delay(1000);
  WiFi.onEvent(WiFiEvent);
  WiFi.begin(ssid, password);
}

void loop() {
  delay(1000);
  const uint16_t port = 5577;
  const char * host = "192.168.178.150";
  WiFiClient client;
  client.connect(host, port);
  client.print(char(0x71));
  client.print(char(0x24));
  client.print(char(0x0f));
  client.print(char(0xa4));
  client.flush();
  client.stop();
  delay(5000);
}

The problem: I send 4 TCP packets, while I should send 1 TCP packet with all 4 chars.

Thanks for your help.


texts: A library for interfacing TMS9918 with Arduino

texts:
I want to make a personal computer that includes using the ATMEGA8 acting as the CPU, and using an easy to interface DIP IC as video chip. I am considering to interface an Arduino with a TMS 9918 video chip,a chip used a lot in 1980s home computers, to an Arduino-this  seems like a good choice because it uses it own video RAM (instead of the Arduino's which cannot be expanded).
So,my question is, where is the link to a library for interfacing the Arduino Uno  and TMS9918?


texts: How to generate 4 square signals using Arduino Mega 2560 below 30hz using timers

texts:
I would like to generate 4 square signals of different frequencies below 30 hz using timers of Arduino Mega.

I was able to generate 30.6hz signals but I have no idea how to generate lower frequencies.

Any help would be appreciated.


texts: Using Browser window to display sensor values in realtime

texts:
The title pretty much says it all:

What would be the most obvious way to setup the Arduino (shields?), the Sketch (libraries?) and PC (webserver, ajax, plain html?) so that I get the following system working:

I open some page in a browser. The page has some labels/fields/values;
I power up Arduino, which is connected to some sensors (or even potentiometers);
The sensor values display keep being constantly updated in the page, with a sensible refresh rate (the fastest as possible, as to control some browser-based game for example);

The fundamental idea here is to use the Browser, and not some other GUI toolkit, or Processing, or the command line.


texts:
I am working with 8 dual color LED's and 2 shift registers. My connections are in place. But I do not understand how to work with 2 shift registers.

So I am trying to make this: turn the first led on, turn the first led of, go to the next led, turn it on, turn in off, etc...

I do not know how to jump from the first shift register to the second shift register when the last LED of the first shift register is turned off.


texts: ESP8266httpUpdate library built-in led blinking time

texts:
I have been working with the ESP8266httpUpdate library for a while now, I want to change the frequency of the blinking built-in led of the esp8266, I couldn't figure out how this library is commanding the led though, only private variables and a function to assign them to a local one, also, I intend to integrate the same functionality in another library so I need to know how it works, thanks!
library: ESP8266httpupdate
library function:
void setLedPin(int ledPin = -1, uint8_t ledOn = HIGH)
{
    _ledPin = ledPin;
    _ledOn = ledOn;
}

using the private variables _ledPin and _ledOn


texts:
I'm trying to send a button press over RF (performing a closed circuit operation on the receiving end).

I have a controller with an UP and DOWN button. Unfortunately I am limited to the cable length, and would like to extend it with radio frequency. The controller has one cable for GND and one each for the corresponding UP and DOWN buttons.

The RF units is the typical 433mhz bought online (ebay).

Can I in someway send the signal over RF (directly on the data pin of the transmitter) without hooking it up to a microcontroller (Arduino)?


texts:
I want to integrate Pololu's vl53l0x Time of Flight distance sensor into a project of mine. They created a library to interface with the vl53l0x over I2C, which works great on my Uno. The only problem is that Wire.h doesn't work on the ATtiny85.

TinyWireM is a replacement library for Wire that I think would be compatible. My question is this: how can I go about replacing all the calls to the Wire library with calls to the TinyWireM library? Is it as simple as replacing all instances of Wire with TinyWireM? Is there anything else I need to do to make the library ATtiny85 compatible?

Thanks!


texts:
I am trying to communicate Pc - Arduino Uno.

My Arduino code is here: (It is working as below)

int ndx = 0;
char pack[12];
void setup() {
Serial.begin(9600);
while(!Serial){;}
}

  void loop() {

   while(Serial.available() ){
    char rb = Serial.read();
    pack[ndx] = rb;
    ndx++;
    Serial.write(rb);
    if(ndx == 12){
        ndx=0;
      }
    }
    }

If I try in

Serial.write(rb);

Like that:

Serial.write(pack[ndx]);

Program is acting weird, I mean sending weird bytes. I do not know what is the reason. Can you help me, please? What is going on in code?
My python code:
https://github.com/mucahitkayadan/Python


texts:
I am running my Arduino based from the ATMEGA328P-PU chip from a 4v battery with this setup:

Everything works great and now I will like to make my project permanent building a custom PCB from easyeda.com. Anyways this question is not about how to create the custom PCB I have already made one and it works great. This is the PCB that I created:

Because I liked it so much now I want to build it even better. For example now I will like to combine the crystal with the 22pf ceramic capacitors into one small part.

Question

Can I use ----THIS---- part instead of the basic 22pf capacitor and the big 16Mhz crystal? In other words I want to replace the left picture with the right picture:

If its possible to use part 7325-1600A2210-00 then where can I find information on what pins to connect to the atmega328 chip and what pins to connect to ground? 7325-1600A2210-00 has 4 pins. To me it makes sense to connect 2 of the pins to pins 9 and 10 and the other 2 pins to ground. Will this work?


texts:
Yesterday when I was trying to reset my Tinyscreen+ by using a needle to flick its power switch (because the case made it hard to do it with my fingers). It was a bit clumsy and I may had shorted some connections in the process. After that, the text on the bottom part of the screen become scrambled as shown in the attached image.

Does anyone have an idea on what caused that and if it's fixable?

Thanks for any help


texts: SD Card shield and TCRT5000 sensor aren't working together on arduino uno

texts:
I need to work with SD card and TCRT5000 sensor (Reflective Optical Sensor with Transistor Output) and save data from sensor to file. So I select Arduino Uno and added to it a SD card shield(from LC STUDIO) and a TCRT5000 sensor but it isn't working.
My circuit and code is here:

#include <SPI.h>
#include <SD.h>

const int chipSelect = 10;

void setup() {
  Serial.begin(9600);
  pinMode(chipSelect, OUTPUT);
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    while(true);
  }
  Serial.println("card initialized.");
  File dataFile = SD.open("test.txt", FILE_WRITE);
  dataFile.close();
  dataFile = SD.open("test.txt", FILE_WRITE);
  if(dataFile){
    dataFile.println("Start:");
  }else{
    Serial.println("Error in creating file.");
    while(true);
  }
}

void loop() {
  float value = analogRead(A3);
  File dataFile = SD.open("test.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println(value);
    Serial.println(value);
    dataFile.close();
  }else{
    Serial.println("Error in opening file.");
  }
  delay(5);
}

When TCRT5000 isn't connected SD card working without any problem.
I think it is related to current and supply current. Any idea?


texts: RESTful API with ESP8266 and arduino mega

texts:
Anybody had worked with ESP8266 to post data to RESTful web service? I was trying but it's not posting anything. Tried with a test server:

http://www.posttestserver.com/

Serial.println("\nSetting AT+CIPSTART");
String client_conn = "AT+CIPSTART=\"TCP\",\"";
client_conn += SERVER;
client_conn += "\",";
client_conn += PORT;
Serial.println(client_conn);
Serial2.println(client_conn);
delay(3000);
while (Serial2.available() > 0) {
    c = Serial2.read();
    Serial.print(c);
    if(c=='\n\r' || c == '\r\n')
    Serial.println('\n\r');
}

It showed me that it got connected
Now I created POST string

String data = "{JSONBODY}";
String post = "POST /post.php HTTP/1.0\r\n";
post += "Host: posttestserver.com\r\n";
post += "Content-Length: ";
post += data.length();
post += "\r\n";
post += data;

Transmitting data

Serial2.print("AT+CIPSEND=");
Serial2.println(post.length());
delay(1000);
if(Serial2.find(">")) {
    Serial2.println(post);
    while (Serial2.available() > 0) {
        c = Serial2.read();
        Serial.print(c);
        if(c=='\n\r' || c == '\r\n')
            Serial.println('\n\r');
    }
    delay(5000);
    Serial2.flush();
    delay(5000);
}

Returned nothing
Closing connection

delay(1000);
Serial2.println("AT+CIPCLOSE");
while (Serial2.available() > 0) {
    c = Serial2.read();
    Serial.print(c);
    if(c=='\n\r' || c == '\r\n')
        Serial.println('\n\r');
}
delay(5000);
Serial2.flush();

Connection closed

But It returned nothing. posttestserver returns data path where it stored.


texts: Where can i get touch sensitive buttons with RGB-LED like in Ableton Push

texts:
I am searching for this component: a touch sensitive button with LEDs like in the Ableton Push or in other Launchpads. Does anyone have an idea about where I can buy something like this? The best would be an RGB LED.

This is what I've found so far. It has no RGB LED though.

Thanks!


texts:
I have a 2 wire thermostat. R is +24VAC, W is Heater. I have no Ground wire (C), and I cannot open the thermostat.
When the heater goes on, the thermostat internal relay gets powered and connects R and W together.
How can I detect when the heater is on from those two wires?


texts: Arduino Micro Cannot get Interrupt 6 work on PIN 7

texts:
After finding out about the situation with pin7 from this tutorial:

https://forum.sparkfun.com/viewtopic.php?f=32&t=35847

    void setup(){

    EICRB |= (1<<ISC60)|(0<<ISC61); // sets the interrupt type for EICRB (INT6).
                                  // EICRA sets interrupt type for INT0...3

    /*
    ISCn0  ISCn1   Where n is the interrupt. 0 for 0, etc
      0      0   Triggers on low level
      1      0   Triggers on edge
      0      1   Triggers on falling edge
      1      1   Triggers on rising edge
    */
EIMSK |= (1<<INT6); // activates the interrupt. 6 for 6, etc

void loop(){
//do other things here
}

ISR(INT6_vect) {
  // interrupt code goes here
  }

I have set:

EICRB |= (0<<ISC60)|(0<<ISC61);

Because I need it to be triggered on LOW.

I could still not get it work on the micro. IF I use the pin as regular input pin I can clearly see LOW/HIGHs on pin 7 with digitalread.

I have a sensor attached there which goes LOW in case it is triggered.

I wonder if anybody knows what else can I try to get it work. I already hardwired everything in my circuit board, there are no more free interrupts and no way to change them.


texts: TIMER1 CTC Interrupts not working with avr-gcc

texts:
I am attempting to program my arduino in plain C, and I've come across some very strange behavior. If I load the following code from the Arduino IDE, it works as expected and toggles Pin 6 every 100ms. However, if I compile it with avr-gcc and then load it with avrdude, no interrupts are run.
Here is the C code:

#include <avr/io.h>
#include <avr/interrupt.h>

int main();
void timer1_init();

int main()
{
    // connect led to pin PD6
    DDRD |= (1 << 6);
    PORTD |= (1 << 6);

    // initialize timer
    timer1_init();

    // loop forever
    while(1)
    {
        // do nothing
        // whenever a match occurs, ISR is fired
        // toggle the led in the ISR itself
        // no need to keep track of any flag bits here
        // done!
    }
}

// initialize timer, interrupt and variable
void timer1_init()
{
    /*cli();*/
    /*TCCR1A = 0;*/
    /*TCCR1B = 0;*/
    /*TCNT1 = 0;*/
    OCR1A = 24999;
    TCCR1B |= _BV(WGM12) | _BV(CS11) | _BV(CS10);
    TIMSK1 |= _BV(OCIE1A);
    sei();
}

ISR (TIMER1_COMPA_vect)
{
    // toggle led here
    PORTD ^= (1 << 6);
}

And here is the Makefile I'm using to load it onto the arduino:

CC = avr-gcc
CFLAGS = -g -O0 -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106

SOURCE = test

all: load

$(SOURCE): $(SOURCE).o
    $(CC) $(SOURCE).o -o $(SOURCE)

hex: $(SOURCE)
    avr-objcopy -O ihex -R .eeprom $(SOURCE) $(SOURCE).hex

load: hex
    avrdude -F -V -c arduino -p ATMEGA328P -P /dev/tty.usbmodem1411 -b 115200 -U flash:w:$(SOURCE).hex

clean:
    rm -f *.o *.hex
    rm -f `find . -perm 755 | perl -pe 's/\.\n//g' | perl -pe 's/\.\/(\w+)\n/\1 /g'`

Is there something that the arduino ide automatically adds to it that makes it work? What am I missing?

Edit: Here is the make output:

avr-gcc -g -O0 -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106   -c -o test.o test.c
avr-gcc test.o -o test
avr-objcopy -O ihex -R .eeprom test test.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/tty.usbmodem1411 -b 115200 -U flash:w:test.hex

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
         avrdude: erasing chip
         avrdude: reading input file "test.hex"
         avrdude: input file test.hex auto detected as Intel Hex
         avrdude: writing flash (196 bytes):

         Writing | ################################################## | 100% 0.04s

         avrdude: 196 bytes of flash written

         avrdude: safemode: Fuses OK (E:00, H:00, L:00)

         avrdude done.  Thank you.


texts: My Arduino UNO turns LED ON forever when I connect it to my Laptop

texts:
My Arduino UNO Board keeps the LED light turned on forever whenever I connect it to my PC. And, when I try to upload even a sample sketch, it says avrdude: stk500_recv(): programmer is not responding.

How can I fix this error?


texts: Create PWM pulses by comparing the cosine wave with AnalogRead potenciometer

texts:
I need generate 4 pulses, for the digital outputs, for example 8,9 and 10,11, at this moment I am using an Arduino Mega.
The pulses have these characteristics:

1) 8 and 9 are the same pulses, but I need them to be each going through a digital output. In the same way, 10 and 11 are another equal pair of pulses but different from 8 and 9. Therefore, they are altogether two pulses, only that each one will duplicate it and send it independently in a digital output.

Here is the bulk of the matter with which I need your experiences:

2) The pulses that I need to generate are with the cut of an analog input of a potentiometer that is produced with a trigonometric wave that I generate with a sweep in degrees with the help of a for cycle.
That is to say that the signals Vc and Vd (trigonometric signals) I must compare them with a control signal (Potentiometer) called Vx. That is, for each signal Vc and Vd, it would have a pair of pulses associated each in this way, in 8,9 and 10,11.
I think that this comparison of the signals with respect to the signal status of the potentiometer can be done with an IF arrangement, so I ask for your help because I have already tried it and it has not worked correctly.

3) Something important is that I only need to generate a rising edge that is with the first cut with the cosine wave, the second one that would be the lowering flank is not important, I do not know how I could limit this.

float V1,V2;
float Vc,Vd,Vcc;
float Vx;

void setup() {

    Serial.begin(9600);
    pinMode(A0,INPUT);
}

void loop() {

    Vx = 2.0 * analogRead(A0)/1023.0;      // analog input from potentiometer, range 0 to 2.0

    for (float j = 0; j <= 360; j++) {
        V1 = 1.0 * cos(j * (PI / 180.0));  // cosine wave

        Vd = 1.0 + V1;                     // Signals Vd and Vc
        Vc = 1.0 - V1;

        Serial.print(Vx);
        Serial.print(" ");
        Serial.print(Vd);Serial.print(" "); Serial.println(Vc);
    }
}

Thanks


texts:
I am new to Arduino project. I used MQ7 flying fish sensor to sense the CO.

Ok now I connected everything as mentioned in various tutorials, such as Arduino CO Monitor Using MQ-7 Sensor.

Also wrote this code based on the following tutorial

const int mq7Pin=0;//the AOUT pin of the CO sensor goes into analog pin A0 of the arduino

int mq7value;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);//sets the baud rate
  pinMode(mq7Pin, INPUT);
}

void Heat(){
  Serial.println("Heating sensor");
  analogWrite(mq7Pin,255);
  delay(60000);
  Serial.println("Reducing the voltage");
  analogWrite(mq7Pin,71); //HIGH*1.4v/5v => 255*1400/5000
  delay(90000);
}

void Read(){
  mq7value=analogRead(mq7Pin);
}

void Print(){
  Serial.print("CO : ");
  Serial.println(mq7value);
}

void loop() {
  // put your main code here, to run repeatedly:
  Heat();
  Read();
  Print();
  delay(60000);
}

After this I got the following output:

Heating sensor

Reducing the voltage

CO : 82

Heating sensor

Reducing the voltage

CO : 246

I used the sensor in a hall and I got 82 in clean air.

After that I used smokes from incense sticks, and I got 246 as sensor value.

So my question is in what format did sensor returned these values? Are they in PPM format?

If not, how can I convert it?


texts:
Setup

Windows 7 Entreprise
MPU-6050 : GY-521 breakout
Arduino Nano (chinese) with CH340 FTDI driver
Arduino IDE 1.6.12
Library for the gyro

Problem

When I run my code, the MPU will detect the angles at a good enough accuracy, but when I leave it on the table, the MPU starts drifting. Its not anything major, yet, but on something like a rocket guidance system, these values can srew up many things.

Actual questions

Is this a common problem?
Why is this happening?
What is the best way to solve it?

Note

I'll include the code if you guys really need it, but I doubt its the problem because multiple codes have had the same problem.

Please do not recommend any other gyros.


texts: problem controlling rgb led with one button

texts:
I'm trying to make a lamp which quality to change color by pressing a
button, pressing once turns on red, pressing again turns on blue and so on, but I also want it to have a light effect in which it smoothly switches between different colors, my code does, however when pressing the button and getting to the last function and keep pressing the button no longer does the light change, it just stays in that state, I have been trying to solve it and investigating for hours but I do not get the expected result, I hope you can help me, thanks.

I enclose the wiring diagram and the code used.

#define varfija 0

int ledR = 11;
int ledB = 10;
int ledG = 9;
int pinButton = 7;
int buttonValue;
int count = 0;
int brillo;
int button_old = 0;

void setup() {
    pinMode(ledR, OUTPUT);
    pinMode(ledG, OUTPUT);
    pinMode(ledB, OUTPUT);
    pinMode(pinButton, INPUT);
}

void loop() {
    buttonValue = digitalRead(pinButton);
    if (button_old == 0 && buttonValue == 1) {
        count++;
        button_old = 1;
    }
    if (button_old == 1 && buttonValue == 0)
        button_old = 0;
    if (count > 4)
        count = 0;

    if (count == 0) {
        analogWrite(ledR, 0);
        analogWrite(ledG, 0);
        analogWrite(ledB, 0);
    }
    else if (count == 1) {
        analogWrite(ledR, 255);
        analogWrite(ledG, 0);
        analogWrite(ledB, 0);
    }
    else if (count == 2) {
        analogWrite(ledR, 0);
        analogWrite(ledG, 255);
        analogWrite(ledB, 0);
    }
    else if (count == 3) {
        analogWrite(ledR, 0);
        analogWrite(ledG, 0);
        analogWrite(ledB, 0);
    }
    else if (count == 4) {
        for (int i = 1; i < 255; i++) {
            analogWrite(ledR, i);
            analogWrite(ledB, varfija);
            analogWrite(ledG, varfija);
            delay(5);
        }
        for (int i = 255; i > 0; i--) {
            analogWrite(ledR, varfija);
            analogWrite(ledB, i);
            analogWrite(ledG, varfija);
            delay(5);
        }
        for (int i = 0; i < 255; i++) {
            analogWrite(ledR, varfija);
            analogWrite(ledB, varfija);
            analogWrite(ledG, i);
            delay(5);
        }
    }
}

sorry for my english, I don't master it


texts: Help with my DHT22 sensor and using GET request

texts:
For some reason using my DHT22 sensor I keep getting "NaN". I have tried using older versions of the DHT22 sensor library as suggested by a few of my searches, but it still doesn't fix the issue.

Also I can't get it to work with the GET request portion. Any help would be greatly appreciated.

#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <ESP8266WiFi.h>
#include <Phant.h>
#include <ESP.h>

#define DHTPIN 2
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "Myyyyyyh";
const char* password = "Ixxxxx1";
const char* host = "script.google.com";

//*****example address
//https://script.google.com/macros/s/AKfycbyNsFc87GQmRP3GnWoTzK6/exec?tag=test&value=8
const String gardenchart = "/macros/s/AKfycbyNnWoTzK6/exec?";
const byte sleeptime = 1;
const byte NUM_FIELDS = 5;
const String fieldNames[NUM_FIELDS] = {"ghumidity", "gtemp", "light", "otemp", "wtemp"};
String fieldData[NUM_FIELDS];

void setup() {
  Serial.begin(115200);
  delay(10);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
  fieldData[0] = 1;
  postdata();
  ESP.deepSleep(sleeptime * 60 * 1000000, WAKE_RF_DEFAULT);
}

void loop() {
  delay(50);
}

void postdata() {
  fieldData[0] = dht.readHumidity();
  fieldData[1] = dht.readTemperature(true);
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect (host, httpPort)) {
    return;
  }
  for (int i=0; i<NUM_FIELDS; i++) {
    client.print("GET ");
    client.print(fieldNames[i]); client.print("&value=");
    client.print(fieldData[i]); client.print(" HTTP/1.1");
    client.println("Host:"); client.print(host);
    Serial.print(fieldNames[i] + fieldData[i]); delay(500);
  }
  client.println("Connection: close");
}


texts: library mixing log4Esp & Syslog for esp8266

texts:
has someone finaly made a new lib combining log4esp and syslog
cf :
SyslogAppender for log4esp
thanks:!


texts:
I tried to flash my ATmega328P-PU not over the Arduino but over a self-made programming board and an USBasp. The problem is, I made the board a while ago and didn't mark which direction the 10-pin connector has to go.

My question is, can I fry the ATmega if I connect the 10-pin connector the wrong way around? Also, can this harm the USBasp in any way?

Connecting it the wrong way around would give me the following connections:

USBasp  ---  ATmega

MOSI    -|
NC      -|-  GND
RST     -|
SCK     -|

MISO    ---  Vcc
Vcc     ---  MISO

         |-  MOSI
GND     -|-  NC
         |-  RST
         |-  SCK


texts: MatLab connection to Arduino using Bluetooth

texts:
I am attempting to send some information from MatLab to an Arduino Uno via Bluetooth with the following

MatLab program:

b=Bluetooth('HC-06',1);
fopen(b);
for i=1:1:15
  fprintf(b,i);
  out(i) = fscanf(b,'%d');
end
fclose(b)

and Arduino program

int matlabval=0;

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

void loop() {
  if (Serial.available() > 0) {
    matlabval = Serial.read();
    Serial.println(matlabval);
  }
}

the output  of arduino is

1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9
10
10
10
11
10
12
10
13
10
14
10
15
10

The number 10 appears after each number. Why is that so?

Thanks in advance!


texts: when i compile this code it always 'sendCommand' was not declare in this scope..plzz help

texts:
#include <SoftwareSerial.h>
#define DEBUG true

SoftwareSerial esp8266(10, 11); // RX, TX

void setup() { // Open serial communications and wait for port to open:
  Serial.begin(9600); //for monitoring purposes

  sendCommand("AT+CIFS+RST\r\n", 2000, DEBUG); // reset module
  sendCommand("AT+IPR=115200\r\n", 1000, DEBUG);
  sendCommand("AT+CWMODE=1\r\n", 1000, DEBUG); // configure as access point
  sendCommand("AT+CWJAP=\"ABCDEFG\",\"12345678\"\r\n", 3000, DEBUG); //connect to a network with name ABCDEFG with password 12345678
  delay(1000);
  sendCommand("AT+CIFSR\r\n", 1000, DEBUG); // get ip address
  sendCommand("AT+CIPSTA=\"192.168.43.16\"\r\n", 1000, DEBUG);
  sendCommand("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple connections
  sendCommand("AT+CIPSERVER=1,6625\r\n", 1000, DEBUG); // turn on server on port 6625
  Serial.println("Server Ready");

}

void loop() { // run over and over
  if (esp8266.available()) {
    if (esp8266.find("+IPD,0,")) {
      delay(10);
      esp8266.find(":");
      delay(10);
      char letter = esp8266.read();
      Serial.print(letter); //for monitoring purposes
      //Gets the value/char from android app
    }

String sendCommand(String command, const int timeout, boolean debug) {
  String response = "";
  esp8266.print(command); // send the read character to the esp8266
  long int time = millis();
  while ((time + timeout) > millis()) {
    while (esp8266.available()) {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }

  if (debug) {
    Serial.print(response);
  }
  return response;
}


texts: Setting up I2C with HTU21D, no response after beginTransmission

texts:
I'm playing with the temperature/humidity sensor HTU21D. Datasheet: https://www.te.com/commerce/DocumentDelivery/DDEController?Action=showdoc&DocId=Data+Sheet%7FHPC199_6%7FA6%7Fpdf%7FEnglish%7FENG_DS_HPC199_6_A6.pdf%7FCAT-HSC0004

The sensor is properly wired and yields reasonable values if I use the library and example here: https://github.com/sparkfun/SparkFun_HTU21D_Breakout_Arduino_Library/blob/master/examples/SparkFun_HTU21D_Demo/SparkFun_HTU21D_Demo.ino

But I'm more interested in how I2C works, so I'm trying to write a small sketch from scratch to communicate with the sensor. Here is what I have right now:

#include <Wire.h>

#define SensorAddress 0x40
#define SoftReset 0xFE
#define TriggerTemperatureNoHold 0xF3
#define TriggerHumidityNoHold 0xF5

void setup(){

    Serial.begin(9600);
    Serial.println("HTU21D library");

    //delay(50);

    //Wire.beginTransmission(SensorAddress);
    //Wire.write(SoftReset);
    //Wire.endTransmission();

    //delay(50);
    Serial.println("init finished");

}

void loop(){

    Serial.println("entering");
    Wire.beginTransmission(0x40);
    Wire.write(0xF3);
    Wire.endTransmission();
    Serial.println("hello");

    //Hang out while measurement is taken. datasheet says 50ms, practice may call for more
    bool validResult;
    byte counter;
    for (counter = 0, validResult = 0 ; counter < 10 && !validResult ; counter++){
        delay(100);

        //Comes back in three bytes, data(MSB) / data(LSB) / Checksum
        validResult = (3 == Wire.requestFrom(0x40, 3));
        Serial.println(validResult);

    }
    Serial.println("here");
}

I'm in the middle of debugging the sketch. When the sketch is uploaded, I'm reading on the serial connection, and all I can see is:

HTU21D library
init finished
entering

It seems the program hangs on the first communication attempt, when I send the TriggerTemperatureNoHold command.

Could you give me a hand please? I don't understand why it's hanging there.


texts: Cant find Sdl and Sca pins in lcd display

texts:
My project is of non contact temperature sensor.I am using RG1602A lcd display and mlx90164 temperature sensor.
But the problem is, there's no sdl , sca pins in my lcd display.
Is there any way, to overcome?


texts:
I try to connect arduino with motor using DRV-8835. The problem I have - simply nothing happens. I used tutorial from http://www.instructables.com/id/The-SnapMobile-Start-Your-Physical-Computing-Engin/step6/Building-the-Prototype-Wiring-Up-the-Arduino-the-D/

Code for arduino:

void setup() {
    pinMode(7, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(8, OUTPUT);
}

void loop() {
  digitalWrite(8, HIGH);
  digitalWrite(7, HIGH);
  analogWrite(5, 255);
}

Maybe someone has scheme how to connect wires to motor. Now I'm not sure if I made a mistake or motor driver is broken.


texts: Sending minimal data between two Arduinos far away from each other

texts:
Problem: I need to send small integer numbers (single-digit numbers suffices) between two arduinos located approximately 50-60m away from each other.
The connection must be made through cables. I have read that the mentioned distance is too long for using serial communication. I do not care if the method is not fast, delays up to one or two seconds are ok for this. If it helps: the devices (Arduino UNO or similar) will run not  yet written codes for a simple alarm system (with no cameras/images).

Question: What is a good way to this?

My efforts: I thought a couple of alternatives to solve this problem. Both involve the use of PWM signals sent from a device A to another B.

One of them requires some DAC in A  and read the analog input in B. The values read are then mapped to the small integer lists. I found some disadvantages with this approach:

Increment of hardware complexity and cost. Although I have read that the digital to analog conversion can be made with cheap capacitors I would have many problems to acquire them because of the lock-down of my country.
Probably I will need to  do many test to set up the mapping procedure  due to voltage drop.

The second is just read the digital input in B many times during a fixed period (e.g. 0.1 or 1 second) and average the values that were read in that period. My bet is that the devices are not synchronized and then the average (times 1023) in such longs periods would be close to the value sent by analogWrite(somepin, value). Finally, the accepted value would be the closest value in alist of acceptable values.
Example: For passing one of the numbers 0,1,2 or 3 the A device will output 0, 341, 682 or 1023, respectively. Eg. for passing "1" A will do analogWrite(somepinA, 341). B will read int lecture = digitalRead(somepinB) and get the time average of lecture for some time period. After multiplication by 1023 it could return something like "312". Then, it must find the value in [0, 341, 682,1023] closest to 280 (341) and map to 1.

Even if they were synchronized some way, I think that I could send 0 or 1 using random numbers or digitalWrite(somepinA) (Is it possible? Advantages? Disadvantages?)

I'm a novice in this field so I do not known if there is something wrong with my approach. I would also appreciate if a better alternative is proposed.
Thanks in advance.


texts: Are my arrays stored in sram or in Flash?

texts:
I have the following memory allocation:

unsigned char g1[]={
  0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ....0x00 ,0x00 ,0x00 ,0x00 ,0x00 };
g2[]={
  0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ....0x00 ,0x00 ,0x00 ,0x00 ,0x00 };
...

 unsigned char* index[10] = {g1,g2,g3,g4,g5,g6,g7,g8,g9,g0};

This is accessed in the following way:

unsigned char* getMatch(int input){
  return index[input];
}

This is then futher acces using the method of

unsigned char store[1024]
unsigned char* temp = getMatch(n);
for(int i=0;i <50;i++){
 store[i]=temp[i];
}

and store is then modified and send to an external device.

As my program is randomly failing I think it might be running low on SRAM and was wondering if there is any way to force this memory to be placed in flash. Anybody got an idea?


texts:
Hello I have a method where when you press a button a string is compared with a substring to see if the string contains the substring. The problem is when I load in the string I call the check button press and substring comparing method. Which only ever happens once. I want to know how I can keep calling the method. It sounds simple but it isn't.

void loadPrograme(){
   file = SD.open("/classes/basic.txt", FILE_READ);
   Serial.print("Reading, Checking and Compiling \n\n\n");

   for (int i = 0; i < arraysize; i++) {
      while (file.available()) {
         character23 = file.read();
         if (character23 == '\n') break;
         if (character23 != '^') {
            content += character23;
         }
      }
      content.trim();
      if (content != "") {
         result[i] = content;
         content = "";
         delay(1000);
      }
   }
   for (int i = 0; i <arraysize; i++) {
      if(result[i].substring(0,5) == "print"){
         printlnMethod(result[i]);

      }else
         if(result[i].substring(0,5) == "delay"){
            delayMethod(result[i]);
         }else
            if(result[i].substring(0,11) == "buttonPress"){
               buttonMethod(result[i]);

            }

   }

   file.close();
}

void buttonMethod(String s){
   s = s.substring(s.indexOf('{') + 1);
   s = s.substring(0, s.lastIndexOf('}'));
   String btn =" ";
   String daction = " ";
   String indaction = " ";
   btn= s.substring(s.indexOf('"')+1 );
   btn= btn.substring(0, btn.lastIndexOf('"'));
   daction = s.substring(s.indexOf(',')+1);
   daction = daction.substring(0, daction.lastIndexOf('('));
   indaction = s.substring(s.indexOf('~')+1);
   indaction = indaction.substring(0, indaction.lastIndexOf('~'));
   int buttonpressed;
   if(btn == "BUTTON_PIN_ENTER"){
      buttonpressed = 2;
   }else if(btn == "BUTTON_PIN_LEFT"){
      buttonpressed = 3;
   }else if(btn == "BUTTON_PIN_RIGHT"){
      buttonpressed = 4;
   }else if(btn == "BUTTON_PIN_DOWN"){
      buttonpressed = 5;
   }else if(btn == "BUTTON_PIN_UP"){
      buttonpressed = 6;
   }else if(btn == "BUTTON_PIN_ACTION"){
      buttonpressed = 7;
   }

   int btncheck = digitalRead(buttonpressed);
   if(btncheck == LOW){
      if(daction.substring(0,5) == "print"){
         printlnMethod(indaction);

      }else if(daction.substring(0,5) == "delay"){
         delayMethod(indaction);
      }
   }
}

}

So basically it loads in the txt file into the string array and loops through it and reads each line. each line is executed. for example if it get the substring of buttonpressed it goes to the buttonmethod(). The problem is in the button method. I want to have the button method keep looping until the button is pressed but it only runs through that method once. How can I keep running threw this method until the button is pressed?


texts: problem with reading PS3 controller buttons

texts:
I'm working on a camera slider mount with an X stepper (to move along slider), Y stepper (pan left right) and Z stepper (tilt up down). All of this is being controlled by a PS3 controller (PS3BT library).

I've implemented a feature in which all three steppers move from one saved position to other and then back again.. this keeps repeating infinitely. It works fine - except I can't stop it - it's more of a programming issue I think. Here's the code in question

// MultiStepper instance - at the top somewhere
MultiStepper StepperControl;

void loop(){
    if(PS3.getButtonClick(START)){ // START to start movement between two POS's.
        Serial.print("\n Starting Movement between POS1 and POS2");
        while(!PS3.getButtonClick(CROSS)){
          StepperControl.moveTo(POS1); // go to POS1
          StepperControl.runSpeedToPosition();
          delay(200);
          StepperControl.moveTo(POS2); // go to POS2
          StepperControl.runSpeedToPosition();
          delay(200);
        }
      }
}

My issue is that pressed X (cross) on the keypad, doesn't quit out of the loop. What I feel is happening is that the loop is running too fast and all the moveTo() commands are stacking on top of each other. And so, even if I do press X, too many moveTo() commands have already happened and it just keeps running those "queued" commands.

I've also tried putting an if statement inside the while loop that breaks out of the loop when CROSS is pressed - no luck.

// This isn't the entire code, just the parts I think are relevant.


texts: Did I break my new Arduino Leonardo Eth by restarting it?

texts:
I just bought a new Arduino Leonardo Eth, and, it was working perfectly.

I probably uploaded about 30 different sketches, and it did everything as expected.

The basic sketch was using the fade demo on pin 9 to ground with a LED attached.

I was then curious on how long the unit takes to restart, so, I unplugged the USB and put it back in.

When it started back up, the LED was on solid. I then restarted it again, and I honestly can't remember the state of it.

When I plug it in, it gets detected in the Arduino application and I see the port, but, after about 20 seconds, I get a popup on Windows saying about a malfunctioning USB device.

Pressing reset on the Arduino or unplugging/plugging it back does the same - I get about 20 seconds, and then it "goes bad".

Even if I am real quick in the IDE, or press restart after compiling/before upload, it just hangs.

I'm really annoyed with myself if I did break it, but, I'm not really sure what else I could have done differently... after all, there isn't an off switch.

Does anyone know what I have done, and, is there anyway to fix it?


texts:
Hi I'm new at this and can't figure out why I get this error "void does not name a type" on lines 3,5,8,26

// _2-5 set Debounce Button
const int BUTTON=2;
const int LED=9;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean ledOn = false;

Void setup()
{
  pinMode (LED, OUTPUT);
  pinMode (BUTTON, INPUT);
}

boolean debounce(boolean last)

{
  boolean current = digitalRead(BUTTON);
  if (last != current)
  {
    delay(5);
    current = digitalRead(BUTTON);
  }
  return current;
}

Void loop()
{
  currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    ledOn = !ledOn;
  }

  lastButton = currentButton;
  digitalWrite(LED, ledOn);

}


texts:
I have the following circuit:

And I know it works and that the diode protects the negative voltage from flowing back into the transistor. This is essentially the circuit:

Could someone illustrate what happens when the motor stops? The current normally flows from 5V to GND (and the electrons from GND to 5V, but this doesn't matter (I think?)), and then it reverses when you switch it off, so current comes out of the top of M1, and then what? I don't get it here.


texts: Counter using Ultrasonic Sensor (self.arduino)

texts:
I am doing a pretty simple arduino project that uses a Parallax Ping Ultrasonic Sensor to increment a counter when an object moves past the desired distance. (object leaves, counter goes up, object comes back, this loops forever). My problem is now that every time i run this.. the serial monitor just shows me Count: 1 over and over again and does not increment.
Any help would be appreciated!

example of what i want the Serial Monitor to write:
Count:0
Count:1
Count:2 ....

What it is currently doing:
Count:0
Count:0
Count:0

const int pingPin = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm, count;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

    // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
// count = 1;

 if (inches > 5)
{
  Serial.print("Count: ");
  Serial.print(count);
  Serial.print('\n');
  delay(1000);
        count++;

}

}

long microsecondsToInches(long microseconds)
{
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{

  return microseconds / 29 / 2;
}


texts: Adrduino IDE doesn't show port for connected ESP32 module

texts:
When I go to select port there's no port for the connected ESP32 module. I am using Mac OS Mojave, mac mini.
The port I find is


texts: tinkercad arduino simulator integers being outputted as larger numbers than they are?

texts:
I am using an Arduino simulator on www.tinkercad.com (a seemingly nice free product from Autodesk).  Working on conversion of an integer to a 16 bit binary string for output to a DAC, but unfortunately even at the first step I am getting unexpected behavior.

void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  Serial.print("Sanity Check\n");
  uint16_t num = 12000;
  Serial.print("\nNumber: " + String(num) + "\n");
  delay(3000);
}

Surprisingly the above code gave the following output:

Sanity Check

Number: 12222

Is there something I am doing wrong, or something wrong with the simulator?   The error seems to crop up with any value over 10000.  10001, 10002, 10003 all print as 10000.  11000, 11001, 11002, 11003 all print as 11111.  etc, etc.  What could be going on?


texts: Is there any way to control current precisely with Arduino without using a DC-DC converter?

texts: I have a circuit that consists of a torquer. Its torque is directly proportional to the current in the circuit. I want to precisely control the torque provided by the torquer and hence need to control the current in the circuit. Which is the best technique you would prefer using Arduino?


texts:
I have been trying to get the button to work properly for over a day, but it just won't, can you help me.

The lcd display is for another part of this project, not important at the moment, but I can't take it away.

Also, the piezo plays the sound within else{}.

const int buttonPin = A0;

int buttonState = 0;

void setup() {

  Serial.begin(9600);

  pinMode(buttonPin, INPUT);
}

void loop() {

  if (buttonState == HIGH) {
    tone(8, 400);
  }else{
    tone(8, 300);
    delay(375);
    tone(8, 200);
    delay(375);
    tone(8, 100);
    delay(750);
    tone(8, 400);
    delay(250);
    noTone(8);
    delay(5000);
  }

}


texts: Voltage, current measurement from solar panel using INA219 and ESP-12F

texts:
I recently started tinkering with ESP-12F thus I am a novice here. As a standard novice project, I am making a standalone weather station for my living room. I want to use solar panels to charge the batteries which power up the ESP-12F via USB. I am using ESP-12F as a controller and sending data to Rpi using MQTT.
I am using the following items:

ESP-12 F powered by USB
2.5W 5V solar panel ( I want to connected two in parallel but for now using only one )
RPi 3B
INA219A to measure voltage and current generated by solar panel.
IN4001 diode as blocking
DHT11 sensor for temp and humidity values
Battery pack to charge 2 x 2500mAh batteries ( This is not done yet )

I am quite confused by the connections to INA219 and the data its providing. Thus, ESP-12F is still connected to independent usb power source and my goal is for now to understand and monitor the voltage and current generated by solar panel.
The INA219 Vcc, GND, SDA, SCL are connected to ESP-12F. I can read the values and observe them on serial monitor or mqtt panel.
1. Below is the breadboard connection when INA219 Vin+ is NOT connected.

The voltage measurement sent via MQTT is as below:
Ignore graph, I was pluging in/out Vin wire too many times thus very bizzare lines.

Current connections are as below:
Solar Panel (-) --> INA219 Vin (-) and breadboard to power LED
Solar Panel (+) --> Only to breadboard to power LED [INA219 Vin+ NOT connected]
ESP-12F 3V --> INA219 Vcc
ESP-12F GND --> INA219 GND
ESP-12F D1 --> INA219 SCL
ESP-12F D2 --> INA219 SDA
ESP-12F is powered by separated USB power source
Code using which the values are computed:
I have used Adafruit_INA219 library.
  shuntvoltage = ina219.getShuntVoltage_mV();
  busvoltage = ina219.getBusVoltage_V();
  current_mA = ina219.getCurrent_mA();
  power_mW = ina219.getPower_mW();
  loadvoltage = busvoltage + (shuntvoltage / 1000);

I dont understand the values sent by INA219 and have no idea how to interpret them. At this point, INA219 is connected to ESP-12F 3V power (Vcc) and GND. It does not have any Vin. Why there is a load voltage of -1.9 and current?
2. When INA219 has Vin(+) and Vin(-) connected

When I connect the Vin+ and Vin- of INA219 I dont have any voltage/current on the breadboard. You can see the LED if OFF. I dont understand why this happens. The whole circuit on breadboard is redundant once I connect INA219 Vin pins to solar panel output pins.
Current connections are as below:
Solar Panel (-) --> INA219 Vin (-) and breadboard to power LED
Solar Panel (+) --> INA219 Vin(+) and breadboard to power LED
ESP-12F 3V --> INA219 Vcc
ESP-12F GND --> INA219 GND
ESP-12F D1 --> INA219 SCL
ESP-12F D2 --> INA219 SDA
ESP-12F is powered by separated USB power source
The voltage and current values at this point is shown below:

The load voltage increases and the difference which is approx 2.1V.
This delta voltage matches the voltage values from solar panel when measured by multimeter at this point. Thus, I would assume load voltage = current voltage generated by solar panel. But, current is unchanged and LED on breadboard if OFF the moment I connect INA219 Vin. Thus, I assume I have done wrong connections.
It will be great if you can point out my mistakes and make suggestions!
Thank you!


texts:
I'm using  nfc 2 click (NT3H2111), I tried via arduino to send data to my mobile phone using this code :

#include <Wire.h>

int i = 0;
int j = 0;

uint8_t NDEF_DATA[] = { 0x03, // NDEF Message
15, // Message size
0xD1, // Record header
1, // Type Length - 1 byte
11, // Payload Length - 11 bytes
'U', // Type / URI
0x01, // Payload
'm', 'i', 'k', 'r', 'o', 'e', '.', 'c', 'o', 'm',
0xFE
}; // NDEF Message End Mark

void setup()
{

delay(5000);
Wire.begin();
// initialisation de la liaison I2C
Serial.begin(9600);
// initialisation de la liaison série vers la console

Wipe_Tag() ;

Wire.beginTransmission(0x55);
Wire.write(0x00);
Wire.endTransmission();
Wire.requestFrom(0x55, 7);
Serial.println("UUID:");
while(Wire.available())
{
Serial.print(Wire.read(),HEX);
}

delay(1000);
Serial.println();

Serial.println("Start wrting");
Wire.beginTransmission(0x55);
Wire.write(0x01);

for (i = 0; i < 16; i++)
{
Wire.write(NDEF_DATA[i]); //Fill Block with Data
}
Wire.endTransmission();
delay(50);

Wire.beginTransmission(0x55);
Wire.write(0x02);

for (i = 16; i < 32; i++)
{
Wire.write(NDEF_DATA[i]); //Fill Block with Data
}
Wire.endTransmission();
delay(50);

Serial.println("Start wrting");

}
void loop()
{

}

void Wipe_Tag()
{
for (i = 1; i < 50; i++)
{
Wire.beginTransmission(0x55);
Wire.write(i);
for (j = 0; j < 16; j++)
{
Wire.write(0x00); //Fill Block with Zeros
}
Wire.endTransmission();
delay(50); //Delay 50 ms

}
}

All I get is the right UUID than nothing happened, if I try to put my phone I can't read nothing ( it should send me to mikroe website).

As I'm using the nfc 2 click from mikroe.

Thanks for reading.


texts: Softserial - max speed - loosing characters

texts:
I have a Ublox-NEO6M gps module that I am trying to read using SoftwareSerial. The GPS sends a few NMEA sentences at 9600 baud each 5th second - totally a couple of hundred characters. My 3.3V atmega 328 on an arduino pro board seems not to be able to cope and is loosing characters. One set of NMEA sentences ends up looking like

$GPRMC,131953.00,A,5939.89405,N,01038.33769,E,0.399,,060316,,,A*79
$GPVTG,,T,,0,.K2$G335.50.6,745,0*
GA1,2,0,.1,2
G,5,12702,21214G,,1,,,84,81037$S,,26,55,09,17*
G41,12388,2*$L39,1.615,6

The first one is good, all the following are mangeled (they should always start with $G and never contain a $ within the string.

If I set the transmission speed to 4800 baud, the arduino reads it without problems. Connecting the GPS to the same Serial USB interface that I use for the pro, so it talks directly to the PC, everything works at 9600, so the problem must be at the arduino. Is is as expected that soft serial is not working at higher baudrates than 9600? are there any settings I could change?(I was looking for possible buffer values without finding anything) Or are there other soft-serial libraries that is faster than SoftwareSerial?

I may end up using the hardware serial interface if I need the speed, but as that makes development and debugging a bit harder, I would prefer to use some other serial interface.. (and now, it is not possible to use a mega, this is prototyping for a gpssystem that cannot be too large)


texts:
Does anybody know where to find an updated scematics of Arduino Nano V3? All the Nano drawings I found (even in the Arduino official site) are based on ATMEGA 168 , no one including ATMEGA 328!!!

Thanks

Mike


texts: Where can I find the Arduino Mega core code?

texts: I am looking to modify the receiving hardware serial buffer size for the Arduino Mega. To do so I need to redefine it in HardwareSerial.h in the core code. However, I can't seem to find a copy of the Arduino Mega core code. A search for HardwareSerial.h on my computer returns no results. I am using Windows 10.


texts:
I am attempting to connect and use an ESP8266 board with my Arduino nano v3.0 and I am not have much luck.

I have read a bunch of tutorials and articles, the most recent is http://elektro-blogger.blogspot.co.nz/2015/07/arduino-and-esp82666.html

Any help would be greatly appreciated.

I have connected it like below and am using some simple code to try and get it working.

Code:

#include <SoftwareSerial.h>

SoftwareSerial esp8266(10, 11);

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

  Serial.flush();

  esp8266.print("AT+RST\r\n"); // reset for esp8266
  delay(500);
  esp8266.flush();//clear serial1
  // Check AT
  esp8266.print("AT"); // reset for esp8266
  esp8266.print("AT+CIFSR\r\n");// learn the ip which token for esp8266
  delay(500);
  if (esp8266.find("ready"))
  {
    esp8266.flush();
    esp8266.print("AT+CIFSR\r\n");
    delay(500);
    Serial.println("CIHAZ IP ADRESI:" + esp8266.readString()); // print esp8266 ip

  }
  else
  {
    Serial.println("there is no internet connection");
  }
  esp8266.print("AT+CIPMUX=1\r\n");//ser mux 1 so we want to connect as multiple users
  delay(500);
  if (esp8266.find("OK"))
  {
    Serial.println("Mux ok");
  }
  else
  {
    Serial.println("MUX failed");
  }
  esp8266.print("AT+CIPSERVER=1,23\r\n");// set esp8266 as server
  delay(500);
  if (esp8266.find("OK"))
  {
    Serial.println("SERVER started");
  }
  else
  {
    Serial.println("SERVER failed");
  }

}
void loop()
{

  if (esp8266.available())
  {
    Serial.print(esp8266.readString()); // get message which comes from clients.
  }
}


texts: Arduino IDE compiling for non-arduino AVR boards

texts:
Using:

Arduino IDE 1.8.2
the board manager from https://mcudude.github.io/MiniCore/package_MCUdude_MiniCore_index.json
an ATmega168P MCU in TQFP

I was able to run my code successfully by modifying the file

[ardunoIDE]\hardware\arduino\avr\variants\standard\pins_arduino.h

building and then flashing the MCU with avrdude.

Is there any way to have Arduino IDE build system pick its pins_arduino.h file from somewhere else ?


texts: Making servo spin and able to detect angle

texts:
After researching other posts I can see how to make a servo spin continually and remove the ability to set to a specific angle.

What I'm trying to do is make a small project that has a spinning 'game wheel', each segment of the wheel has a prize on it (think almost wheel of fortune). The catch is when someone has landed on a prize once it cannot be landed on again so I want to manipulate the spin slightly so it doesn't stop on the same prize. Do do this I need to be able to get the spin AND know where the needle is pointing.

Is there a component that will allow both a full rotation AND the ability to control the location of the needle at the same time? I suspect servos can do one, or the either but not both.


texts: Why does this code show me a lot of space?

texts:
I want to make a 4hz reading of GSR and temperature, in the following format for every second:

697,20.8744
696,20.86521
695,20.8653
699,20.8777

The print, in python, would be print(GSR+","+Temp)
The tries in C are giving problem, here's my actual code:

#include <OneWire.h>

const int GSR=A0;
int threshold=0;
int sensorValue;
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
OneWire  ds(3);

void setup(){
  long sum=0;
  Serial.begin(115200);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
  }

void loop()
{
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius;
    if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        // Do your job, such as
        sensorValue=analogRead(GSR);
        Serial.print(sensorValue);
        Serial.print(",");
        if ( !ds.search(addr)) {
    ds.reset_search();
    return;
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
      return;
  }
  // the first ROM byte indicates which chip

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

   // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
  }

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  Serial.print(celsius);

    }
    Serial.println("\n");

}

How can I reach the upper format?


texts: How to control a DRV8266 motor controller with an ESP8266?

texts:
https://github.com/sparkfun/SparkFun_MiniMoto_Arduino_Library/tree/V_1.1.0

Will this library work on an esp8266?   If not is there any way I can get this driver to work on the ESP?


texts: Is the SIM900 3G? Or is the SIM900A able to connect to 3G?

texts:
I would like to state that I am not familiar with the whole cellular connection thing. But I was wondering if the SIM900/or/SIM900A is 3G and will work with PTel Mobile.

I need this Arduino to be able to travel and needs to connect to every PTel's tower. Will I be able to connect to 3G or only the 2G and the 1G networks?


texts: Can an ESP read from an micro-SD card module to display pictures via its Access Point?

texts:
It seems the normal use of a micro-SD card module with Arduino and ESP MCUs is to log data. Instead, is it possible to read from a micro-SD card module to display pictures from an ESP's Access Point?
The closest thing I could find was using internet (not the ESP's Access Point), here: Host Web Page Over the Internet on ESP32 Using SD Card.
I want the Access Point browser page to display pictures. (They take up too much flash, and I want to know if it's possible to do this without getting an ESP32 with 16 MB instead of the standard 4 MB.)


texts: Division with big constant number. Ideas to make it more efficient?

texts:
Im reading the voltage applied to my microcontroller using the internal voltage reference.
Here the topic is talked, and there are some working examples.
Im NOT using this examples, im using my own library to do this.

In short, works like this:

Microcontroller has fixed internal voltaje reference of 2.048v that can be read
Reading this value with the ADC will give a value from 0-255 (im using 8 bit ADC for efficiency)
Depending on the value read, you can calculate the voltage at the Vcc pin
Math is like this:

Vcc_voltage = ADC_MAX_VALUE * VREF_VOLTAGE / adc_value

Where:

Vcc_voltage: Voltage calculated at the VCC input of the microcontroller
ADC_MAX_VALUE: the maximum value that the ADC could give (CONSTANT: 255 in this case)
VREF_VOLTAGE: voltage of the internal fixed reference (CONSTANT: 2.048v in this case)
adc_value: value read by the ADC at the internal voltage reference (VARIABLE: from 0 to 255)

So the calculation result:

Vcc_voltage = 255 * 2.048 / adc_value

In order not to use floats, I multiply the VREF_VOLTAGE * 1000. New calculation:

Vcc_voltage = 255 * 2048 / adc_value

Or:

Vcc_voltage = 522240 / adc_value

And this is where im stuck. Im running out of flash, and im optimizing every part of the code. At the moment this is a "int32" division with a int16 result".

I think this could be reduced by some "binary trick", some wise programmer advice or approaching the formula from a different point of view.

Any suggestion?


texts: Does anyone know a library that can emulate 3 throttles?

texts: There is this library, but it emulates only one throttle and one rudder. The X Y Z axis don't work because they are addressed from -127 to 127 and I need 0 to 255. I just need one more throttle axis. If it helps, I'm using an ATmega328 and read analog values in the 0 to 1024 range to read Logitech g27 pedals, then dividing by about 4 to fit the read value into the 0 to 255 range.


texts:
I have an Arduino sketch that serves an HTML web page using the standard Ethernet library (https://github.com/arduino-libraries/Ethernet) and the Ethernet Web Server library (https://github.com/khoih-prog/EthernetWebServer). I am serving HTML stored directly in the Arduino memory. The processor is the ARM Cortex M0+. Here is an extract from the code I am using:
#include <Ethernet.h>
#include <EthernetWebServer.h>

#define webpage "Big HTML string"

EthernetWebServer webServer;
void setup()
{
  SerialUSB.begin(9600);

  Ethernet.begin(settings.macAddress, settings.ipAddress, settings.ipAddressDns, settings.ipAddressGateway, settings.ipAddressSubnet); // 'settings' is a struct declared elsewhere
  webServer = EthernetWebServer(settings.portHttp);

  webServer.on("/login", [&webServer]{ // /login handler
    webServer.send(200, "text/html", webpage);
  });
}

void loop()
{
  webServer.handleClient();
}

When I refresh the page (send GET request) more than 9 times or so the Arduino freezes. I have checked by placing SerialUSB.println() inside the code and it seems to stop before even entering the "/login handler" callback.
Does anyone know the cause or at least how to solve this?


texts: How do I fix the serial loader on my Pro Mini?

texts:
I have an Arduino Pro Mini, 3v3, 8Mhz. I have in the past successfully programmed it over the serial line. I have two others, I can program them over the serial line. I can program the first one using SPI. Once programmed, I can communicate both ways over its serial lines. So I'm certain that the serial port is good, the board is good, and my connections are good.

I suspect it may be a corrupt bootloader. I have burned the bootloader using IDE. It still does the same thing.

What else could it be?


texts:
I tried to make a 2 way communication between my Arduino and a PC(running linux mint) using NodeJS:
My Arduino code:

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

void loop() {
  if(Serial.available()) Serial.println(Serial.readString()+"\r");
}

My NodeJS code:

var SerialPort = require('serialport');
var port = new SerialPort('/dev/ttyUSB0',{
  baudRate: 9600,
  parity: 'none',
  stopBits: 1,
  flowControl: false,
  parser: SerialPort.parsers.readline('\r\n')
});

port.on('open',function(){
  setInterval(() => port.write('Test'),1000);
});

port.on('data',(data) => console.log(data.toString()));

There is possible encoding error, but I cannot seem to find and fix this. Thanks in advance