texts: High precision timing on Arduino for serial communication

texts:
I am using an Arduino Uno to send time and voltage information over the serial port to Python to plot. However the interval timings between successive time stamps appears to be increasing over time, affecting my plotting. This is especially true when the baud rate is set to 9600, where my initial time differences maybe 1320 and increases to 16400 after a relatively short period of time. When this rate is put to maximum of 115200 bps the change is slower and less noticeable, from around 1340 to 1500 even after a relatively long run of sending. All times are given in microseconds.

I would like to know if I can reduce or eliminate this effect, and if not understand why it exists. I have read things about interrupts and delays causing this, but I do not fully appreciate the complexity of the electronics at hand and would like to know:

Can I get greater precision in the timing?
What causes this change in timing?

Here is what I currently have:

#include <eHealth.h>

extern volatile unsigned long timer0_overflow_count;
float fanalog0;
int analog0;
unsigned long time;

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

void loop() {
  while (Serial.available()>0){
    serialByte=Serial.read();
    if (serialByte=='S'){
      while(1){
        fanalog0=eHealth.getECG();
        // Use the timer0 => 1 tick every 4 us
        time=(timer0_overflow_count << 8) + TCNT0;
        // Microseconds conversion.
        time=(time*4);
        //Print in a file for simulation
        //Serial.print(time);
        //Serial.print(" ");
        Serial.print(fanalog0,5);
        Serial.print("\n");

        if (Serial.available()>0){
          serialByte=Serial.read();
          if (serialByte=='F')  break;
        }
      }
    }
  }
}


texts: Customize FTDI driver for custom PID and VID

texts:
I have changed PID and VID of my FTDI board for  arduino program because i wanted to rename the com port name.
The ic is  FT232R a USB to serial UART interface IC. I have store new vid and pid to EEPROM.
Now It is showing in unknown devices. I am not able to update driver of it.
I have followed this article http://forum.arduino.cc/index.php?topic=6929.0.

Can anyone tell how to make cutmoize driver for it.
Any suggestions will be very helpful.


texts: How can i make my MLX90614ESF scan temperature after the MFRC522 scans the RFID tag?

texts:
//THIS IS THE RFID CODE

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

//*****************************************************************************************//
void setup() {
  Serial.begin(9600);                                           // Initialize serial communications with the PC
  SPI.begin();                                                  // Init SPI bus
  mfrc522.PCD_Init();                                              // Init MFRC522 card
    //shows in serial that it is ready to read
}
//*****************************************************************************************//
void loop() {
  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;
  //some variables we need
  byte block;
  byte len;
  MFRC522::StatusCode status;
  //-------------------------------------------

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  byte buffer1[18];

  block = 4;
  len = 18;

  //------------------------------------------- GET FIRST NAME
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer1, &len);
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  //PRINT FIRST NAME
  for (uint8_t i = 0; i < 16; i++)
  {
    if (buffer1[i] != 32)
    {
      Serial.write(buffer1[i]);
    }
  }
  Serial.print(" ");

  //---------------------------------------- GET LAST NAME

  byte buffer2[18];
  block = 1;

  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid)); //line 834
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer2, &len);
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  //PRINT LAST NAME
  for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i] );
  }

  //----------------------------------------

  delay(1000); //change value if you want to read cards faster

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}
//*****************************************************************************************//

// AND THIS IS THE MLX90614 CODE
#include <Wire.h>
#include <Adafruit_MLX90614.h>

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

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

  mlx.begin();
}

void loop() {

  Serial.print("*\Body Temperature = "); Serial.print(mlx.readObjectTempC()); Serial.println("*C");

  Serial.println();
  delay(500);
}


texts: ESP8266 only executes Sketch after switching on/off CH_PD pin

texts:
I started a new project with an ESP8266-01 module. I want to use it as stand-alone circuit to send an Email at the press of a button.

The wiring is:

VCC    -  3.3v VCC
CH_PD  -  3.3v VCC
GND    -  GND
GPIO_2 -  Push down button (internal pullup)

I've the sketch (Arduino IDE), I've upload it and it essentially works. However:

If I call the sendEmail(); method inside the void setup(){}, it works like a charm.
If I add an push down button on Pin #2 (GPIO_2) it only works if I previously have removed VCC from the CH_PD pin and reattached it again shortly after.

Now, I would bet I read something regarding (or similar) this situation a couple of days back, but I am unable to find it again, now that I need it.

Is there a solution for this or am I missing something?

Any help will be greatly appreciate it!

Thanks in advance!


texts: ESP12e pin 13 won't set to output/won't work

texts:
I have an ESP12e and running a basic blink code on it. The problem is that GPIO13 of esp12e wont turn on. I have noticed that this has happened from time to time. Earlier I thought that the ESP was faulty so i just changed them. But now I have a lot of 10 ESPs and all of them have the same problem. Pin 13 wont turn on setting to HIGH.

What could be going wrong? Is there something that I am missing?

EDIT:
However, on the same piece of esp12, for some test, i tried putting the gpio12 to input and that worked.

Code:

void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(2000);
}


texts: Why can't I include a library in another one?

texts:
I am trying to create a new library that uses another existing library.

The original library declares a way to create an object called Multiserial that can be created in the main file and the program is correctly compiled.

However, when I include this library in a second one and I try to build the program, then the IDE returns an error that says:

  In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:27:0,
                   from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Stream.h:26,
                   from MultiSerial.h:17,
                   from maqMODBUSmst.h:5,
                   from maqMODBUSmst.c:1:
  C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Printable.h:25:1: error: unknown type name 'class'
   class Print;

Even if the library only contains the include of the first one.


texts:
Im using AsyncUDP in an ESP32 project, where I initialize AsyncUDP udpSender and call udpSender.write(sendbuffer, sendbuffer_size) from both cores, with different buffers on each core.
One core is continually collecting GY-91 (accel/gyro/magnet) sensor data many times a second and sending it via UDP multiple times a second (after every collection), and the other one is collecting some other data like temperature once a second, as well as responding to commands a server sends.
So I'm basically using one sender on both cores and wondering if this is "thread-safe", if that terminology even applies to this scenario.
Can this cause problems? Is there a specific way this should be done? Like using semaphores?


texts:
recently bought an UNIROI Smart Car kit.
(UNIROI Smart Robot Car Kit Arduino Robot Kit with 4 Wheel Drive, Arduino UNO R3 Board, Ultrasonic Sensor, Infrared Tracking Module (No Welding Required) https://www.amazon.co.uk/dp/B07CWS344R/ref=cm_sw_r_cp_tai_wQExCbHT0YM8K)

I bought some extra things with it to make it more interesting, but the problem is is that I need to connect more pins to the Arduino but they are all taken up by the car. What I have noticed is that there are these extra pins along the side of the Arduino board as you can see here: https://imgur.com/a/j1Q8QVu

I know you guys don’t have it in hand, but I thought I’d give it a shot to see if any of you know I can use those pins.
The description of the car also quotes
“Extended Pin Interface. The chassis is designed with
extended pin interface for Arduino UNO, only need to solder pins for using, more convenient to develop
and build your own robot car kit”

Appreciate any help you guys got.


texts:
I have made a class called subjects and I have then made a subject called math. I am trying to set a classroom for math but it is giving me the error 'math' doesn't name a type.

Code for the class

class subject {
public:
  char subjectname[];
  char classroom[];

};

Code for the classroom and math

subject math;
math.classroom = "A1";

How can I set the classroom of math to A1?


texts: redefining delay and delaymicros as personal function

texts:
Is it possible to redefine delay and delaymicros function with #define ?
I want to use timer2 interrupt instead of these.

Something like this:

#define delay(unisgned long ms) countMicros(uint16_t top, uint16_t storageVar)

setup(){}

loop(){
 delay();// function countMicros is called instead.
 }
void countMicros(uint16_t top, uint16_t storageVar){
//...}


texts: Trying to determine the phase difference between two square signals

texts:
I have been looking for the phase difference between two square signals and this is the code:

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

void setup() {
  //Serial.begin(9600);
  pinMode(2, INPUT);    //set pins 2 and 3 as inputs and 11 as output
  pinMode(3, INPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

  cli();           // disable all interrupts
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);  //set up timer2 to generate a PWM
  TCCR2B = _BV(CS20);    //set prescalar value to 1
  //TCCR1A = 0;
  //TCCR1B = _BV(CS20);
  //TCCR1B |= (1 << CS12); //256 values
  TCNT2  = 0;
  sei();             //enable all interrupts

  attachInterrupt(digitalPinToInterrupt(2), t1_ISR, RISING);     //enable interrupt service routines on pins 2 and 3
  attachInterrupt(digitalPinToInterrupt(3), t2_ISR, RISING);

  //Serial.print(OCR2A);
  //Serial.print(OCR1A);

}

volatile uint8_t t1, t2;

void loop() {
  if (t2 == t1)
  {
    OCR2A = 0;
    OCR2B = 0;
  }
  //compare time that one signal goes high to time the other signal goes high
  else if (t2 > t1)
  {
    OCR2A = (t2 - t1); //output PWM based on phase difference on pin 11
    OCR2B = 0;
  }
  else if (t2 < t1)
  {
    OCR2B = (t1 - t2);  //output PWM on pin 11
    OCR2A = 0;
  }
}
}

void t1_ISR() {         //interrupt if signal on pin 2 goes high and store counter
  t1 = TCNT2;           //value to variable t1
}

void t2_ISR() {         //interrupt if signal on pin 3 goes high and store counter
  t2 = TCNT2;           //value to variable t2
}

I want to operate the input pulses at 40 kHz, how can I do this and read the difference of phase? I am using the Arduino Mega2560


texts: Enabling pins of Arduino Due with direct port manipulation

texts:
I want to enable pin 13 on my SAM3X8E using direct port manipulation. On this chip the pin is bit 27 in port B, so I used PIOB->PIO_PER = 1<<27; to enable this pin, but it doesn't work. This pin keeps at 3.08V, the default value of non-initialized pins.

Here's my complete code:

#include <asf.h>

int main (void) {
  // Insert system clock initialization code here (sysclk_init()).
  board_init();
  sysclk_init();
  delay_init(sysclk_get_cpu_hz());
  PIOB->PIO_PER = 1<<27;
  PIOB->PIO_OER = 1<<27;
  while(1) {
    REG_PIOB_ODSR = 1<<27;
    delay_ms(1000);
    REG_PIOB_ODSR = 0<<27;
    delay_ms(1000);
  }
}

Can anyone tell me how I can get this to work?


texts:
I want to reclaim the space reserved for the bootloader on my ATMega32u4 (Leonardo chip).
But the lowest boot flash size I can see is BOOTSZ=11 which is 256 words (512 bytes). Is it not possible to completely disable it?
Basing this off of this: http://www.engbedded.com/fusecalc


texts: Motor controller for 24v motor, Arduino Uno

texts:
I need a motor controller for a 24v motor and I want to control it using än Arduino Uno. Suggestions?

The motor needs to run both directions and is going to draw about 5A


texts: Java NetBeans sending value and receiving value from Arduino

texts:
This is my Java code to send a value to Arduino and a receiving value from Arduino. Can anyone tell where I made a mistake? I am able to send the value but can't receive a value from Arduino.

package hell;

import com.panamahitek.ArduinoException;
import com.panamahitek.PanamaHitek_Arduino;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class led extends javax.swing.JFrame
{
    PanamaHitek_Arduino Arduino  = new PanamaHitek_Arduino();
    private BufferedReader input;
    SerialPort serialPort;

    public led(){
        initComponents();
        try {
            Arduino.arduinoTX("com3", 115200);
        }
        catch (ArduinoException ex) {
            Logger.getLogger(led.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    public synchronized void serialEvent(SerialPortEvent oEvent)
    {
        System.out.println("lol 31");
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                System.out.println("lol 1.1");
                Scanner s = new Scanner(serialPort.getInputStream());
                int mes =Integer.parseInt( s.nextLine());
                System.out.println(mes);
                System.out.println("lol 1");
            } catch (Exception e) {
                System.err.println(e.toString());
                System.out.println("Syncronice ");
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            Arduino.sendByte(0);
        }
        catch(Exception ex){
            Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
        }
        System.out.println("led is off");
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try{
            Arduino.sendByte(1);
        }
        catch(Exception ex){
            Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
        }
        System.out.println("led is on");
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new led().setVisible(true);
            }
        });
    }

    private javax.swing.JButton jButton1;

    try{
        Arduino.sendByte(1);
    }
    catch(Exception ex){
        Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
    }

    System.out.println("led is on");

    private javax.swing.JButton jButton2;
}

Here is my Arduino code, which receives a value from Java and prints it accordingly:

int val = 0;
int led = 8;

void setup() {
  Serial.begin(112500);
  pinMode(led, OUTPUT);
}

void loop() {
  if (Serial.available()>0) {
    val = Serial.parseInt();
    if(val == 1) {
      //Switch on the LED, if the received value is 1.
      digitalWrite(led, HIGH);
      Serial.println("Succesfully received.");
    } else if(val == 0) {
      //Switch off the LED, if the received value is 1.
      digitalWrite(led, LOW);
    }
  }
}

EDIT:
There is no problem to controlling arduino via Java code, the problem is that I can't received message from Arduino to display in a Java.


texts: Why is my code only reading the change of the encoder's pin A?

texts:
I am writing code for reading in a quadrature encoder. I used attachInterrupt on pin 2 and 3, but by using the same ISR.

    int encAPin= 2;
    int encBPin= 3;
    volatile int encAValue= 0;
    volatile int encBValue= 0;
    volatile int encCount= 0;

    void setup() {
      // put your setup code here, to run once:
      pinMode(encAPin, INPUT);
      pinMode(encBPin, INPUT);
      attachInterrupt(digitalPinToInterrupt(encAPin),encUpdate, CHANGE);
      attachInterrupt(digitalPinToInterrupt(encBPin),encUpdate, CHANGE);
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.println(encCount);
    }

    void encUpdate() {
      if(digitalRead(encAPin)==RISING){
        if(digitalRead(encBPin)==LOW){
          encCount++;
        }else if(digitalRead(encBPin)==HIGH){
          encCount--;
        }
      }
      if(digitalRead(encAPin)==HIGH){
        if(digitalRead(encBPin)==RISING){
          encCount++;
        }else if(digitalRead(encBPin)==FALLING){
          encCount--;
        }
      }
      if(digitalRead(encAPin)==FALLING){
        if(digitalRead(encBPin)==HIGH){
          encCount++;
        }else if(digitalRead(encBPin)==LOW){
          encCount--;
        }
      }
      if(digitalRead(encAPin)==LOW){
        if(digitalRead(encBPin)==FALLING){
          encCount++;
        }else if(digitalRead(encBPin)==RISING){
          encCount--;
        }
      }
    }

When I tried Serial.print to check whether or not the pin A's and B's inputs were changing, I noticed that only pin A's (pin 2) input was changing. I made sure that the circuit and the wiring were all correct. Is there something about my code that is not reading pin B's input properly?


texts:
I purchased a pack of esp8266 (https://www.amazon.com/gp/product/B00PA3UQNI/) and a usb to serial converter (https://www.amazon.com/gp/product/B01FUA2BBU/) from amazon. I hooked them up and attempted to use the Arduino serial monitor to communicate with the esp8266. Here are the commands I used and the responses I got:
    AT

OK
AT+GMR

+GMR: 7.80.5.0

OK
AT+RST

ERROR

My current setup is (RX on serial -> TX on esp) and (TX on serial-> RX on esp), although I have also tried them swapped. I have tried running the serial monitor at 115200, 57600, and 9600 baud and they all put out the same response. I have tried with both boards. I am currently running the esp8266 off of two AA batteries. All grounds are connected, CH_PD is connected to Vsupply with a 10k resistor, RST is connected to ground with a 3k resistor.

I have not done anything with the firmware and I have not tried any other serial monitor.

Please let me know if there is anything else I can try to get these to work.


texts: Buzzer interfere with thermistor reading

texts:
This is how i wired the thermistor and buzzer:

simulate this circuit – Schematic created using CircuitLab

And the code:

#define RT0 10000
#define B 3977
#define R 10000
float RT, VR, ln, TX, T0, VRT;

void setup() {
  T0 = 25 + 273.15;
}

void loop() {
  VRT = analogRead(A3);
  VRT = (5.00 / 1023.00) * VRT;
  VR = 3.3 - VRT;
  RT = VRT / (VR / R);
  ln = log(RT / RT0);
  TX = (1 / ((ln / B) + (1 / T0)));
  TX = TX - 273.15;
}

When i connect the buzzer it causes a bit of voltage drop which messes with temperature reading, How can i get a steady temperature reading while having a buzzer in the circuit?


texts: Can you use an Arduino EtherMega's 3.3v and 5v pins with two sensors, one requiring 3.3v and the other 5v and a sketch that combines both?


texts:
I have an unknown RFID tag and tried to read its value. I bought two readers, RDM6300 125KHZ and RC522 13.56MHz. Each of the readers connected to Arduino works well with the purchased corresponding tags, but not with this tag. According to my information, the tag should be 125kHz tag, but RDM6300 foes not read it. The tag is simply not detected. I am sure that the tag works, I use it to open the door.

So my question is: Is there any other RFID reader for Arduino, which is different than the two that I have, and could work?

Thank you.


texts: How to use Ultrasonic Sensor's trig pin, and why it is needed?

texts:
I have HC-SR04 Ultrasonic Sensor with me. I couldn't understand the "Trig" pin's working structure and the working technic. Do we really need it while we use?

(With Arduino examples, I generally use Echo pin more than trig pin.)


texts: Can wifi shield connect to local network without internet?

texts:
I have an Arduino Uno and a Texas Instruments CC3000 WiFi shield. I need to connect the Arduino to a local network which has no Internet access so that it can send information to a computer also connected to the same local network. I am using a Linksys WRT120N for the local network.

I can't use the Internet access WiFi because it is WPA2 Enterprise which is why I created the local network. Currently the computer is connected to the local network via WiFi.

I have downloaded and installed the correct library but when I run the connection test, it searches for Internet access which doesn't exist and sends back errors.

How do I verify that it is connecting to the local network?

Btw, I have almost no experience coding an Arduino but I have access to people who are proficient; However, they have no experience with a WiFi shield.


texts: Will Intel Atom Processor laptops support cloned a Arduino with CH340 driver?

texts:
I am planning to buy a low cost and low weight laptop with an Atom Processor.

I only have cloned Arduinos - will the Arduino drivers and IDE work on laptops which come with Atom Processors?


texts: Arduino R3 Uno with EasyVR 3.0 Shield fails to connect to COM port

texts:
I have an Arduino Uno R3, an EasyVR 3.0 Shield (for voice recognition) Sketch 1.6.7 and Windows 7. Unfortunately I failed early on in the process of uploading the EasyVR example code to Arduino (EasyVRBrdige and EasyVRTest).

When I remove the EasyVR shield the code upload works perfectly (and fail when it is mounted).

So I uploaded the EasyVRTest code when the EasyVR was unmounted Then mounted the EasyVR shield with its jumper at SW - but there is no response from the Serial monitor (also tried PC and HW with same results)

In fact seems like the 'COM' port disappears in some cases from the Device Manager or in other only the Arduino 1.6.7 does not see it (not listed under Tools->Port:) although USB is connected and device manager list it.

I got the following messages in verbos mode: “Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions. Board at COM12 is not available”

Using EasyVR Commander at both SW and PC jumper modes say COM port cannot be opened. The Arduino drivers are installed and up-to-date (Automatically detected by Windows 7). Using the USB power (no external power)

Any ideas?

I saw a hint in the post below that if Pin0 is connect that may cause such symptoms; how can I tell if EasyVR uses this Pin0? http://www.instructables.com/id/A-solution-to-avrdude-stk500getsync-not-in-syn/


texts:
I have the MKR 1010 and am working on a circuit that needs realtime GPS positioning.  I bought the MKR GPS Shield, and am using it on the I2C bus (attached via cable to the 1010 board), and am using the Arduino_MKRGPS library in my sketch.

I am attempting VERY basic interaction with the board at the moment, and basically just want to print out the GPS coordinates to the serial.

I am using the GPSLocation sample from the Arduino_MKRGPS library (see here):

  /*
  GPS Location

  This sketch uses the GPS to determine the location of the board
  and prints it to the Serial monitor.

  Circuit:
   - MKR board
   - MKR GPS attached via I2C cable

  This example code is in the public domain.
*/

#include <Arduino_MKRGPS.h>

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

  // If you are using the MKR GPS as shield, change the next line to pass
  // the GPS_MODE_SHIELD parameter to the GPS.begin(...)
  if (!GPS.begin()) {
    Serial.println("Failed to initialize GPS!");
    while (1);
  }
}

void loop() {
  // check if there is new GPS data available
  if (GPS.available()) {
    // read GPS values
    float latitude   = GPS.latitude();
    float longitude  = GPS.longitude();
    float altitude   = GPS.altitude();
    float speed      = GPS.speed();
    int   satellites = GPS.satellites();

    // print GPS values
    Serial.print("Location: ");
    Serial.print(latitude, 7);
    Serial.print(", ");
    Serial.println(longitude, 7);

    Serial.print("Altitude: ");
    Serial.print(altitude);
    Serial.println("m");

    Serial.print("Ground speed: ");
    Serial.print(speed);
    Serial.println(" km/h");

    Serial.print("Number of satellites: ");
    Serial.println(satellites);

    Serial.println();
  }

  delay(100);
}

What I'm seeing is that the GPS takes on the order of 30-90 secs to initialize, and then only provides new updated coords every 20-30 secs.  This is all with a clear view of the sky.

Is that really what to expect from this module?  I was under the impression that it could provide several samples per second.  Documentation seems to be very lacking for the Arduino_MKRGPS library.  Anyone else have insights or experience with this module?

Thanks!


texts: Arduino Analog Input: why the weird fluctuation?

texts:
I am using an Arduino Uno. analogRead(A0) (or whichever channel I use) returns 0 when it is grounded with Arduino Gnd, and 1023 when connected to Arduino 5v. But when I connect it to a current sensor (ACS712) it is always fluctuating like this:

  0, 0, 0, 0, 0, 0, 1023, 1023, 1023, 1023, 1023, 441, 446, 0, 0, 0, 0, 1023, 1023...

I also tried it with a potentiometer (10K) and analog joystick: the results are the same. I tried changing different power supplies (both Arduino's and the sensor's (ACS712, potentiometer, joystick)). I even tested it on an Arduino Mega, but no luck. Such extreme fluctuation are making no sense to me. Kindly help me what could be the issue.

My wiring diagram is attached to this post. And I use an external supply to the ACS712. Is it possible that Static electricity is causing this issue?

Code:

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

void loop() {
  float value = analogRead(A0);
  Serial.print("Raw:");
  Serial.println(value);
  delay(500);
}

Thanks.


texts: Using Arduino Wifi Shield to Receive Signal

texts: I am trying to use an Arduino Uno with Arduino Wifi Shield 101 to receive a signal from phone or webpage over wifi so it will "initiate" my circuit. I was able to connect the board to wifi but am unsure on how I should continue. My main goal is to be able to send it two different commands that would run different parts of code in my arduino script. I am very new to this stuff! Thanks :)


texts: Commander volet roulant avec esp8266 et sinric

texts: Comment programmer un nodemcu pour contrôler un volet roulant avec sinric à distance


texts:
Hi I was wondering if a digitalRead state change detection could be saved in a variable like counter++, just like you can do with an interrupt function.

arent these two operations almost the same?

like have an external circuit with a  reed closed by a magnet, to take the place of a momentary push button,


texts: Can't test for equality with string received from bluetooth module

texts:
I am trying to keep the program within a loop until the user inputs "ok" on the Bluefruit Connect App. I use the readString() function on the bluetooth object (ble) to read from it. Before this loop, my String command variable is initialized to be empty. Here is my code:
while(!command.equalsIgnoreCase("ok"))
{
  while(ble.available())
    command = ble.readString()
}

I have confirmed that I can receive data as I can output the command variable to the Serial monitor.
Why does the condition for this loop always return true (i.e. why is the String command variable never equal to the string literal "ok", while ignoring case)?


texts: Use ISRs inside a library more elegantly

texts: At the moment I try to make a library which uses attachInterrupt(?,?,RISING) to read a sensor. The article of Nick Gammon on Calling an ISR from a class helped me a lot, but his "Glue routines" get pretty ugly with more than 30 potential Interrupt Pins on the ESP32, which all need their own static void. Has anyone got a more elegant idea how to do this "Gluing"?


texts: Cannot flash Arduino Bootloader on SAMD21G with STLink via SWD programming and openOCD

texts:
I'm trying to flash the Arduino Bootloader on a bare ATSAMD21G with STLink via SWD programming and OpenOCD.

These are the steps that I took:

Create *.hex file to flash with ArduinoCore-samd repository
Connect SWD pins from ST-Link to the ATSAMD21G pins

Execute OpenOCD command

openocd -f interface/stlink-v2.cfg -c "set CHIPNAME at91samd21g18; set ENDIAN little; set CPUTAPID 0x0bc11477; source [find target/at91samdXX.cfg]" -c "init" -c "reset init" -c "load_image {/Path/To/ArduinoCore-samd/bootloaders/zero/samd21_sam_ba.hex} 0 ihex" -c "verify_image {/Path/To/ArduinoCore-samd/bootloaders/zero/samd21_sam_ba.hex} 0 ihex" -c "reset run" -c "exit"

Command Line output:

Open On-Chip Debugger 0.10.0
Licensed under GNU GPL v2

For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
Info : auto-selecting first available session transport "hla_swd". To override use 'transport select <transport>'.
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
none separate
adapter speed: 400 kHz
Info : Unable to match requested speed 400 kHz, using 240 kHz
Info : Unable to match requested speed 400 kHz, using 240 kHz
Info : clock speed 240 kHz
Info : STLINK v2 JTAG v17 API v2 SWIM v0 VID 0x0483 PID 0x3748
Info : using stlink api v2
Info : Target voltage: 2.922730
Info : at91samd21g18.cpu: hardware has 4 breakpoints, 2 watchpoints
target halted due to debug-request, current mode: Thread
xPSR: 0x61000000 pc: 0x00000f10 msp: 0x20007ffc
in procedure 'reset'
in procedure 'ocd_bouncer'
in procedure 'ocd_process_reset'
in procedure 'ocd_process_reset_inner' called at file "embedded:startup.tcl", line 248
in procedure 'at91samd21g18.cpu' called at file "embedded:startup.tcl", line 331
in procedure 'ocd_bouncer'

5824 bytes written at address 0x00000000
downloaded 5824 bytes in 0.132341s (42.976 KiB/s)
target halted due to breakpoint, current mode: Thread
xPSR: 0x61000000 pc: 0x2000002e msp: 0x20007ffc
verified 5824 bytes in 0.481737s (11.806 KiB/s)
in procedure 'reset'
in procedure 'ocd_bouncer'
in procedure 'ocd_process_reset'
in procedure 'ocd_process_reset_inner' called at file "embedded:startup.tcl", line 248
in procedure 'at91samd21g18.cpu' called at file "embedded:startup.tcl", line 331
in procedure 'ocd_bouncer'

Really unsure what steps I am missing as it does not seem to flash the bootloader at all. I cannot detect M0 on the USB port after trying to execute the OpenOCD command. Thanks!


texts: I'm using an Arduino and DS1307 for creating RTC but my code has some issue

texts:
I'm not getting any errors but the values that are supposed be displayed in the RTC_read are not being displayed for some reason.Initially i thought this was maybe due to the code being caught somewhere in the loop but that's not the case. Strangely when i'm using Serial.print() of some value the entire value is not being displayed

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

void i2c_init()
{
  TWSR=0x00;
  TWBR=0x47;
  TWCR=(1<<TWEN);
}

void i2c_start()
{
  TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while(!(TWCR&(1<<TWINT)));
}

void i2c_end()
{
  TWCR=(1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
  while(!(TWCR&(1<<TWSTO)));
}

void i2c_write(uint8_t data)
{
  TWDR=data;
  TWCR=(1<<TWINT)|(1<<TWEN);
  while(!(TWCR&(1<<TWINT)));
}

uint8_t i2c_read(int ack_val)
{
  TWCR=(1<<TWINT)|(1<<TWEN)|(ack_val<<TWEA);
  while(!(TWCR&(1<<TWINT)));
  return TWDR;
}

void RTC_init()
{
  i2c_init();
  i2c_start();
  i2c_write(11010000);
  i2c_write(00000111);
  i2c_write(00000000);
  i2c_end();
}

void RTC_set_time_date(uint8_t second,uint8_t minute,uint8_t hour,uint8_t day,uint8_t month,uint8_t year)
{
  i2c_start();
  i2c_write(11010000);
  i2c_write(00000000);
  i2c_write(second);
  i2c_write(minute);
  i2c_write(hour);
  i2c_write(day);
  i2c_write(month);
  i2c_write(year);
  i2c_end();
}

void RTC_read()
{
  char second,minute,hour,day,month,year;
  i2c_start();
  i2c_write(11010000);
  i2c_write(00000000);
  i2c_end();

  i2c_start();
  i2c_write(11010001);
  second=i2c_read(1);
  minute=i2c_read(1);
  hour=i2c_read(1);
  day=i2c_read(1);
  month=i2c_read(1);
  year=i2c_read(0);
  i2c_end();
  Serial.println(second);
  Serial.println(minute);
  Serial.println(hour);
  Serial.println(day);
  Serial.println(month);
  Serial.println(year);
  Serial.println("Recieving data");
}

int main()
{
  Serial.begin(9600);
  uint8_t second,minute,hour,day,month,year;
  second=00000000;
  minute=01000000;
  hour=00100011;
  day=00000011;
  month=00000111;
  year=00011001;
  Serial.write("abcd");
  RTC_init();
  RTC_set_time_date(second,minute,hour,day,month,year);
  RTC_read();
  return 0;
}


texts: My counting function is not working with the text on my lcd

texts:
I want the bottom row of my LCD to display the counting function and include text:

lcd.setCursor(0, 1);
lcd.print("Launch in"millis()/1000);

But it comes out with an error, what part is wrong?


texts: Making the speaker play a certain frequency of sound

texts:
I'm trying to make the piezo speaker play a sound of certain frequency. However, although I think the code is fine, the sound plays with a frequency between 130 ~160 only, and the frequency actually drops when it should be going up.

The code is as below:

digitalWrite(buzzer, LOW);
delayMicroseconds(1000000 / frequency);
digitalWrite(buzzer, HIGH);
delayMicroseconds(1);

What could be the problem?


texts:
I posted this also at Stack Overflow. I have tested the Johnny Five LED example on my Arduino Uno, and it worked fine. Now I need to test Johnny Five LCD. I connected all wires correctly.

The code:

var five = require("johnny-five"), board, lcd;

board = new five.Board();
board.on("ready", function() {
  lcd = new five.LCD({
    // LCD pin name  RS  EN  DB4 DB5 DB6 DB7
    // Arduino pin # 7    8   9   10  11  12
    pins: [7, 8, 9, 10, 11, 12],
    backlight: 6,
    rows: 2,
    cols: 20
    // Options:
    // bitMode: 4 or 8, defaults to 4
    // lines: number of lines, defaults to 2
    // dots: matrix dimensions, defaults to "5x8"
  });

  // Tell the LCD you will use these characters:
  lcd.useChar("check");
  lcd.useChar("heart");
  lcd.useChar("duck");

  // Line 1: Hi rmurphey & hgstrp!
  lcd.clear().print("rmurphey, hgstrp");
  lcd.cursor(1, 0);

  // Line 2: I <3 johnny-five
  // lcd.print("I").write(7).print(" johnny-five");
  // can now be written as:
  lcd.print("I :heart: johnny-five");

  this.wait(3000, function() {
    lcd.clear().cursor(0, 0).print("I :check::heart: 2 :duck: :)");
  });

  this.repl.inject({
    lcd: lcd
  });
});

But it doesn't output as expected. It is showing one row of black boxes only. what have I missed?


texts: How to identify connection lost on HC-06?

texts:
I am making an RC car on Arduino Uno. I have connected an L298N motor driver to an Arduino Uno to control 2 DC motors. I also connected an HC-06 to the Uno to receive commands from an Android smartphone. Everything is working fine. But if a connection is lost (because of low battery or disconnected on Android application), when the RC car is moving it is not stopping. It stops only when there is connection and "s"(stop) command is received via Bluetooth.

int in1 = 4;
int in2 = 5;
int in3 = 6;
int in4 = 7;

void setup() {
  Serial.begin(9600);
  pinMode (in1, OUTPUT);
  pinMode (in2, OUTPUT);
  pinMode (in3, OUTPUT);
  pinMode (in4, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    int command = Serial.read();
    move(command);
  }
}

void move(int command) {
    if (command == 'f') forward();
    else if (command == 'b') backward();
    else if (command == 'l') left();
    else if (command == 'L') leftback();
    else if (command == 'r') right();
    else if (command == 'R') rightback();
    else if (command == 's') stop();
}

Now what I want is to identify whether there is connection or it is lost. For example:

if(Serial.connectionLost()) stop();

Is there such a function to identify the connection state? If not, is it possible to implement this function in another way?


texts: Arduino IDE gives error a1 is not declared

texts:
#include <LiquidCrystal.h>
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);

in this code the error given by IDE is 'A1' was not declared in this scope.
So whats the problem please help


texts:
HW:
2 Arduino ProMini 16Mhz, 5V
Software serial directly connected using male jumpers on bredboard.

I have creates a software serial port for communication between two arduinos, Parent and child

as per the documentation
http://arduino.cc/en/Reference/SoftwareSerialAvailable

mySerial.available()

should return the number of bytes available in the buffer.
and

mySerial.read();

should give me the byte or return -1 (255) on error.
http://arduino.cc/en/Reference/SoftwareSerialRead

here is my code snippet where i read the values

if(child1.available() > 0){
    Serial.print("ParentReceived Something from child 1\n");
    while(child1.available()){
      recvBuffer1[i] = child1.read();
      Serial.print(recvBuffer1[i], DEC); Serial.print(" ");
      Serial.print(i, DEC); Serial.print(" ");
      i++;
      if(i == FRAME_SIZE) break;
    }
  }

the Serial outputs are for debugging,
The condition for while is true. we go inside.
Now what i receive with child1.read() is the following

ParentReceived Something from child 2
255 0 255 1 255 2 255 3 255 4 255 5 255 6 255 7

all i see is 255.

what i did:
     I first suspected the child of sending these data, but i used a TTL to USB converter to directly read the values being sent by the child and they are received correctly as they should be. even if i TAP the serial ports to another
TTL to USB converter i get 255 on my arduino Serial monitor and the correct data on the sniffer.


texts: Converting Arduino UNO's analog pins to digital I/O

texts:
I am working on an Arduino UNO Project and running out of digital pins.

Can I convert the six analog pins to digital I/O and use them to drive servos?

Please suggest me a method


texts: Upload Assembly to AVR on a breadboard using Arduino as ISP

texts:
I try to learn assembly and use an arduino uno R3 to act as a programmer. i have build a standalone circuit with an atmega328p, can upload usual sketches (written in c) and have also sucessfully burned the bootloader to the external chip with the arduino as an isp but i cant bring my assembly code onto the chip on the breadboard. i tried it with avrdude and the following command

avrdude -C avrdude.conf -p atmega328p -c avrisp -P /dev/ttyACM0 -b 115200 -D -U flash:w:test.hex:i

and also

avrdude -C avrdude.conf -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:test.hex:i

but the code is always uploaded to the chip on the arduino - not to the one on the breadboard. can anyone lead me how to upload my assembly programm to the standalone chip on the breadboard using the arduino as isp? is this possible anyway?

EDIT This command worked for me

avrdude -C avrdude.conf -v -v -v -v -p atmega328p -c stk500v1 -P /dev/ttyACM0 -b19200 -Uflash:w:test.hex:i


texts: Cannot convert 'int (*)[size]' to 'int**'

texts:
Analyzing this and this answers under Arduino, which should be the proper way to pass a 2D array into a function?

The function should be applicable to different sizes of 2D arrays.

// NOT COMPILING EXAMPLE
void f(int** x,const int m, const int n){
// access x as x[0][0], x[0][1], etc...
}

void main{}{
    int x1[16][128];
    f(x1,16,128);
    int x2[64][16];
    f(x2,64,16);
}


texts: I want to use a nodemcu to water my plants. I connected a pump with a 2N2222 transistor (I know i should add a diode and a pull down on the gate). The pump is DSL370 and when it is off i measure 4.4V on the Vin pin while using a 2A charger connected to the USB port. When the pump is active, the vin voltage drops to 4.1V and the LCD becomes hard to read. I measured the current the pump uses and it is 300mA. What is the reason for the voltage drop? I thought the charger should be able to handle it.


texts: What is an ICSP pin? I have read that it is an AVR and a tiny programming header for the Arduino, but what is an AVR and what does an ICSP pin do?


texts:
I'm trying to interface an Arduino Mega with an AD7714 ADC. This ADC requires a command to be sent to the communications register (in my case 0x5C) in order to begin a read from the data register.
My question is how do I receive the data that is transmitted from the Slave ADC to the Master Arduino on the MISO line?
At the moment I have this code in an interrupt that is activated when the DRDY goes low:
byte dataIn;
byte dataOut = 0;
adc_write_reg(0x5C); //tell ADC to read data from data register
dataIn = SPI.transfer(dataOut); //transmit data in order to recieve data??

Thanks!


texts: How do I (easily) power a 5 V 3-pin fan?

texts:
I have a 5 V 3-pin fan. I want to be able to:

power it from an Arduino Uno or a Seeeduino Lotus board, and, ideally;
be able to change its speed.

Most resources I can find on the web explain how to connect a standard 12 V fan and moreover complicate the thing by explaining how to get the speed of a fan or to control multiple fans. This is way too complex for me.

If my understanding is correct, I can't just connect a fan to analog output pins, because the absolute max power per pin is 40 mA (recommended: 20 mA), while the fan uses 100 mA.

Instead, I have to somehow connect two of the three pins of the fan to an external power, and use the third pin to control the speed. Am I supposed to use the ground and 5 V pins situated on the left side of the board above ANALOG IN?

If not, what are my other options? The board is powered by an USB cable, and I see no way to split the power at this level between the board and another device without running a risk of damaging the board.


texts: Super slow serial (UART) communication on Arduino

texts:
I am using this device for my Arduino that connects to the OBD-II port of my car to get various information such as speed, rpm, etc. I am using this for a digital Nixie tube speedometer using the smart Nixie tube from a Kickstarter project.

I pass the information to the Nixie tubes through serial and get information from the OBD-II through serial as well. I am getting speed updates about every 20 seconds and that is incredibly slow when the device can supposedly update up to 100 times per second.

I originally was using an Arduino Uno and using software serial for the tubes, but I figured the slowdown was due to interupts interfering with the hardware serial, so I switched to the Arduino Mega 2560 to use a second hardware serial pin to hopefully fix the problem, yet the same issue is occurring.

Here is my code... There must be something I'm doing wrong. Serial2 is for the Nixie tubes.

#import <Arduino.h>

#include <OBD.h>

int ones = 0;
int tens = 0;

int kphValue = 0;
int mphValue = 0;

int rpmValue = 0;

String onesString;
String tensString;
String payloadString;
String rpmString;
COBD obd;

void setup(){
    Serial2.begin(9600);
    obd.begin();

    //Initiate OBD-II connection until success
    while (!obd.init()){
        Serial2.print("$0,Y,Y,255,255,000,000$0,Y,Y,255,255,000,000!");
        delay(1000);
        Serial2.print("$0,Y,Y,000,000,000,000$0,Y,Y,000,000,000,000!");
        delay(1000);
    }
}

void loop(){
    onesString = String(ones);
    tensString = String(tens);
    payloadString;
    rpmString;

    if(obd.read(PID_RPM, rpmValue)){
        if (rpmValue < 3000){
            rpmString =",N,N,255,000,255,000";
        }
        else if (rpmValue >= 5000){
            rpmString = ",N,N,255,255,000,000";
        }
        else if (rpmValue >= 3000){
            rpmString = ",N,N,255,255,030,000";
        }
    }

    if (obd.read(PID_SPEED, kphValue)){
        kphToMPH();
        payloadString = "$" + onesString + rpmString + "$" + tensString + "rpmString" + "!";
        Serial2.print(payloadString);
    }
}

void splitDigits(int input_number)
{
    ones = (input_number%10);
    tens = ((input_number/10)%10);
}

void kphToMPH()
{
    mphValue = kphValue * 0.621371;
    splitDigits(mphValue);
}

EDIT:
I am using the following library: https://github.com/stanleyhuangyc/ArduinoOBD


texts:
It has already been asked how many clients can connect to an ESP32 AP, but the answer is far from clear; the best one is from a year and half ago (ESP32 AP max connections: 4 or 10?) :

  The answer is as clear as any other EspressIf configuration data, it is 4 or maybe 5, or 8, or 12, 16 or even 20 (the same as a ESP8266!)

As I'm trying to move a project from the ESP8266 because it does not have enough AP connections, two questions can be asked :

what is the maximum number of AP connections supported by the 4.0 ESP-IDF framework ?
can it be increased in any way ?

Thank you.


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

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

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

  SPI.begin();

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

void loop() {
}

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

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

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

  SPI.begin();

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

void loop() {
}


texts:
I have an assignment wherein we have 8 LEDs connected to an Arduino Uno which has a switch. These LEDs light up according to the johnson counter but every time I turn the switch off it should reset back to the start. An example is if I turned the switch off while the pin is at 8 going back to 1 , then when i turn it on it should be back to 1 again. I got the 1 to 8 reset part right but the 8 to 1, I'm having trouble solving.

Here is my code:

int pin;
int sw3 = 10;

void setup() {
  // put your setup code here, to run once:
  for (pin = 2; pin <= 9; pin++) {
    pinMode(pin, OUTPUT);
  }
  pinMode(sw3, INPUT);
}

void loop() {
  pin == 2;
  if (digitalRead(sw3) == HIGH) {
    for (pin = 2; pin <= 9; pin++) {
      digitalWrite(pin, HIGH);
      delay(200);
    }
  }
  else {
    digitalWrite(pin, LOW);
  }

  delay(200);

  for (pin = 2; pin <= 9; pin++)
  {
    digitalWrite(pin, LOW);
  }
  delay(200);

  if (digitalRead(sw3) == HIGH) {
    for (pin = 9; pin >= 2; pin--) {
      digitalWrite(pin, HIGH);
      delay(200);
    }
  }
  else {

    digitalWrite(pin, LOW);
  }

  delay(200);

  for (pin = 9; pin >= 2; pin--) {
    digitalWrite(pin, LOW);
  }
  delay(200);
  {
    if (digitalRead(sw3) == LOW) {
      digitalWrite(pin, LOW);
    }
    else {
      digitalWrite(pin, LOW);
    }
  }
}


texts:
Hey guys I'm getting an error that is im pretty sure to do with how i am initializing my variables. It is:
exit status 1
'threshold' does not name a type

Here's my code:

//Global Variables for moving max:

int analogValues[100];
int ir=0;
int maxA0=0;
int threshold = 0;
//Global variables for moving max ^^

//Global Variables for moving average ECG:
const int no_averages = 2;

unsigned long time = 0, peak1 = 0, peak2 = 0;
int binaryrange, bpm, i=0; //not sure what i does tbh
int readings[no_averages]; // the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average which we will display as ECG

void setup() {
// initialize serial communication with computer:
Serial.begin(115200);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < no_averages; thisReading++) {
readings[thisReading] = 0;
}

//set moving max shit to zero
  for (int is = 0; is < 100; is++) {
analogValues[is]=0;
  }
}

void loop() {
  //int maxA0=0; //Whether I intitate the variables here or globally, same error
  //int threshold = 0;
time = millis();

average=0;
readings[readIndex] = analogRead(A0);
readIndex++;
for (int ir=0; ir < no_averages; ir++) {
  average = average + readings[ir];
}
if (readIndex >= no_averages) {    // ...wrap around to the beginning of array if it has hit the end:
readIndex = 0;
}
average = average/no_averages;
if (average>1000) {
  average = 600;
}
Serial.print(average);

analogValues[ir]=average;
ir++;
if (ir>=100) {
  ir=0; } //This is to roll back to the start of the array if it surpasses the 100th array spot
for (int is = 0; is < 100; is++) {
 if (analogValues[is]>analogValues[is-1])
 analogValues[is]=maxA0;
  }
}

//**************************

//This line with error:

threshold=maxA0-40;

//**************************

if (average<threshold){
  binaryrange=0; }
if (average>threshold && binaryrange==0){
  peak1=peak2;
  peak2=time;
  bpm=60000/(peak2-peak1);
  binaryrange=1;
  }
   Serial.print(" ");
  Serial.println(bpm);
//BPM code ^^

delay(8); // delay in between reads for stability
i++;
}

THANKS!


texts: How to power both arduino and 1 color led strip from single power source

texts:
I'm trying to understand and adapt this tutorial:

https://learn.adafruit.com/rgb-led-strips/current-draw

to my own use. I am doing essentially the same thing, except I have this single color LED strip, and I don't fully understand how to power both the arduino and the led strip from the same power source.

I tried to wire it using the diagram above, and something started smoking (I think the IR transmitter). I don't know much about circuits, but I'm pretty sure that's not good.

In this diagram, the 9v represents DC power, the IR sensor on the left represents the transmitter, the IR on the right is the receiver, and the white LED is the LED strip, with two outputs (+ - )

In the fritzing diagram for that tutorial, they have the + from the LED strip going straight in to Vin on the uno, but they don't show how either the LED strip or the uno themselves are being powered.

Do I need two power sources?

Do I need a mosfet considering I'm only using a one color LED strip?

I've got the IR sensors working, so I don't need help with that, and I can connect one of these 12V switching power supplies to one of these DC power screw terminals to power the lights without any arduino control, so all I'm missing is how to turn the lights on and off with arduino, IE, how to go from the power supply to the arduino to the LED strip.

I don't need to PWM the LED strip - just shut it off and on.

If anyone can help me correct the fritzing diagram or explain what I'm doing wrong / what I should be doing instead, I'd greatly appreciate it.


texts:
I'm writing Arduino UNO (=ATMega328P-PU) programs in assembly to save memory, so I use avra.exe (same as atmel studio's avrasm32) to compile and avrdude to upload, and simple programs like blinking run fine. But now i tried to half-bright a LED with pwm. I checked up my code for errors but I didn't find any, and the LED just full brighs. I checked wiring too. I'm getting struck :c. Here's my pwm.asm code:

.nolist
.include "m328pdef.inc"
.list

.cseg
.org 0x00
     rjmp start
.org 0x34
 start: sbi ddrb, 5 ;pin 13
        sbi portb, 5 ;pin 13 on, just to compare with the PWMed led
        sbi ddrd, 5 ;pin 5 pwm
        ldi r16, 0b00100011 ;fast pwm mode, non inverted pwm at oc0b = pin 5 (right?)
        out tccr0a, r16 ;I'm using Timer0
        ldi r16, 0b00000001 ;no prescaler
        out tccr0b, r16
        ldi r16, 128 ; duty cycle = 50%
        out ocr0b, r16

  loop: rjmp loop


texts:
I'm trying to make a program that whenever a button is push, a different word will show on a lCD screen. However, it seems that the two buttons provide the same output ("Screen A"), it's like there is no difference between them, and I'm not sure what's the cause.

The code is very simple:

const int buttonPin1 = 13;     // the number of the pushbutton pin
const int buttonPin2 = 12;     // the number of the pushbutton pin

int buttonState = 0;

long randNumber;

void setup() {

  for(int x=0; x<2; x++)
  {
    pinMode(buttonPin[x], INPUT);
  }

}
    void loop() {

      for(int x=0; x<2; x++)
      {
        buttonState = digitalRead(buttonPin[x]);

        if (buttonState == HIGH && buttonPin[x] == 13) {
          lcd.print("  Screen A ");
        }
        if (buttonState == HIGH && buttonPin[x] == 12) {
          lcd.print("  Screen B ");
        }
      }

    }

Any help is appreciated


texts: How to access bootloader recovery mode (like the Micro) or equivalent on the Due?

texts:
I would eventually like to use a Due as a custom USB device PC-side (through programming port) while using it as a USB Host on the native port.
Adding the programming port endpoints (perhaps willingly removing the CDC endpoints) means I may break USB descriptors, or USB to PC communication generally speaking during development.
On the Micro that's not a problem because a double reset input lets me access the bootloader for 8s and reprogram the board even though I've removed CDC endpoints altogether. But on the Due, which I am not familiar with, I can see that a double reset input does not seem to have the same effect as my script starts right away. So I am quite scared to begin messing with the USB communications if I might just break my Due permanently (or rather, until I can recover it directly accessing the MCU).
Hence the question: is there some equivalent to the bootloader recovery of the Micro (& other older boards) on the Due ?


texts:
I executed the following steps in order to burn a bootloader into an  AVR328P-PU chip I acquired on ebay.

I have set up AVR328P-PU on a breadboard as described here: http://arduino.cc/en/main/standalone
I have uploaded the ArduinoISP sketch into Arduion Uno.
Connected the wires in a way described here http://arduino.cc/en/Tutorial/ArduinoToBreadboard ( the setup with external clock)
Chose "Tools -> Programmer -> Arduion as ISP" in the IDE.
Chose "Burn Bootloader" from the IDE.
Got and error avrdude: Yikes!  Invalid device signature., noticed that I connected the wires in the wrong order.
Fixed the wired, but still got the error:

avrdude: Version 6.0.1

     System wide configuration file is "C:\Program Files\Arduino/hardware/tools/avr/etc/avrdude.conf"

     Using Port                    : COM3
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.06s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.07s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

avrdude done.  Thank you.

My questions

I understand that this can be caused by poor breadboard quality. How can I test this hypothesis before buying new breadboard?
Could the wrong wiring from step 5 ruin the chip?


texts: How to copy files from Yun to local computer?

texts:
I would like to copy a file that is in the root folder of my Yun, to my Macbook. They are connected with an ethernet cable and I am logged into the Yun through ssh.
The Yun's IP is 192.168.2.16 while the Mac's is 192.168.2.1.

How can I copy a file from the Yun?

Once I tried to copy a file from the Macbook to the Yun using "scp" and it worked, but now I don't know how to do for the other direction


texts: Efficient periodic wake up for sensor reads

texts:
I've been tasked to do an initial design for an Arduino setup that needs to run very infrequently.

Basically, I'd like the system to wake up daily to take some sensor readings and report them back to a central site (the mesh network for this will be my next stage).

Since these things are going to be run on battery, I need it to be as insanely efficient as possible, with minimal power drain when not reading the sensor.

What facilities does Arduino have to do this?


texts:
I would like to generate vibration patterns using the SW-420 or something similar that is able to reproduce the same pattern on similar vibrations. So if a 10p coin was dropped on a table from 1m at a 90 degree angle then I would expect the second time it dropped to make the same vibration pattern.

The objective is for the software on the Arduino to keep a small database of recorded vibration patterns and alert the user when a similar pattern has been detected.


texts: trouble finding peaks from pitch using IMU BNO080, 'array' was not declared in this scope not displayed

texts:
{
  if (myIMU1.dataAvailable() == true)
  {
    float x1 = myIMU1.getGyroX();
    float y1 = myIMU1.getGyroY();
    float z1 = myIMU1.getGyroZ();
    Serial.print(x1, 2);
    Serial.print(F("  "));
    Serial.print(y1, 2);
    Serial.print(F("  "));
    Serial.print(z1, 2);
    Serial.print(F("  "));

    if (myIMU1.dataAvailable()==true)
    {
      q1 = myIMU1.getQuatI();
      q2 = myIMU1.getQuatJ();
      q3 = myIMU1.getQuatK();
      q0 = myIMU1.getQuatReal();
      float quatRadianAccuracy = myIMU1.getQuatRadianAccuracy();
      //toEulerAngle(quatReal,quatI,quatJ,quatK);

      ya= atan2((q1 * q2 + q0 * q3), ((q0 * q0 + q1 * q1) - 0.5f));
      r = -asin(2.0f * (q1 * q3 - q0 * q2));
      p = atan2((q0 * q1 + q2 * q3), ((q0 * q0 + q3 * q3) - 0.5f));
      ya *= 180 / PI;  p *= 180 / PI;  r *= 180 / PI;

      Serial.print(ya, 2);
      Serial.print(F("  "));
      Serial.print(r, 2);
      Serial.print(F("  "));
      Serial.print(p, 2);
      Serial.print(F("  "));
      Serial.println();
    }
  }
  delay(20);
  pitch=r;
   n=sizeof(pitch);
  float myArray[n]={pitch};
  for (i=1;i<n-1;i++)
  {
    if((myArray[i]>myArray[i-1]) && (myArray[i+1]<myArray[i]))
    {
      pitch_dir=1;
    }
    else if((myArray[i]<myArray[i-1]) && (myArray[i+1]>myArray[i]))
    {
      pitch_dir=-1;
    }
    else
    {
      pitch_dir=0;
    }
  }
  Serial.print(pitch_dir);
  delay(20);
    Serial.println();
Serial.println();


texts: Adafruit Feather M0 Basic update bootloader

texts:
I bought a Feather M0 Basic from a reseller Lawicel however I'm missing the
UF2 boot feature. When I press the reset button two times I just
get a serial and have to program circuitpython using Bossa. The UF2
FEATHERBOOT usb storage drive as described  here doesnt show up.

I have a ARM-ICE and wired up the Feather board via SWD. I
can re-program the bootloader (first setting fuse to NVMCTRL_BOOTPROT 0x7
as described here ) via ARM-ICE.

However it seems that the Arduino bootloader featherm0bootloader_160305.zip is an old one that doesnt support the UF2 usb storage device programming protocol.

Where can I download a more recent bootloader that supports UF2 ?


texts: Sending Float values from Python to Arduino via serial communication

texts:
I want to Control the current flowing through a circuit using an Arduino. I have trained a PID controller for this purpose. I am using a current sensor to determine the error. It runs successful on my Arduino.
In my next step I want build a system where I can send the Current setpoint (deter mined by my python code) value to the Arduino through serial communication. I am able to send integer values to Arduino. But I am unable to send and receive float values from Python to Arduino. I want to know the necessary code to be written in both sender and receiver.
I tried of converting float to string and then send it to Arduino. But I failed. Please help.

Arduino Code(edit- Sorry previous code was an old file. Here is the correct one):

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
//pinMode(13,OUTPUT);
}
float f;

void loop() {
 if(Serial.available())
      {f=Serial.parseFloat();
        Serial.println(f);
      }
    delay(1000);
   }
//count=count+1;
      //delay(1);
//}

Python Code (edit- Sorry, the previous code was from an old file. Here is the correct one):

import serial
import time
import struct

ser = serial.Serial('/dev/ttyACM0', 9600, timeout = 1) # ttyACM1 for Arduino board
data=5.7

while True:
        ser.write(str(data))
        time.sleep(1)
        ser.flush()

When I run this code I get the following output on the Arduino Serial Monitor. As shown in the figure below.

Thank you.


texts: PWM water pump flow control - should I use capacitor for MOSFET?

texts:
I want to control flow level on 12V water pump with PWM pin, I'm using IRF520N MOSFET for that (and dedicated 12V power supply).

Should I use some capacitor on MOSFET output to "smoothen" voltage? And what kind?


texts: Code is not running, servo does not even spin

texts:
I am trying to run a program which works as follows:
An LDR is integrated in a box. A block is placed on top. This box is able to be rotated by a servo. The program is supposed to make the box turn until the block slides and lifts off from the LDR.
At that point the servo angle is stored and used to calculate the friction coefficient. Finally the answer to this calculation is printed on an lcd and the program repeats by first returning the box to the original state. The entire programs runs on Arduino and an Arduino Lotus. Why doesn't the servo rotate?
//servo
#include <Servo.h>

Servo myservo;
int previous_angle = 0;
int angle = 0;

//lightsensor
int lightsensor = 0;
int LIGHT = 800;
int DARK = 940;

//LED screen
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

void setup() {
  Serial.begin(9600);
  myservo.attach(6);

  pinMode(lightsensor, INPUT);

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  delay(100);
}

void loop() {
  int i = previous_angle;
  int lightStatus = analogRead(lightsensor);

  if (lightStatus >= DARK) {
    delay(300);

    while (int i = previous_angle) {
      i<=90;
      i = i+1;
      myservo.write(i);
      delay(45);
    };
  } else if (lightStatus < DARK) {
    for (int i = previous_angle; i>0;) {
      delay(300);
      int angle = tan(i);
      display.clearDisplay();
      display.setTextSize(1.5);
      display.setTextColor(WHITE);
      display.setCursor(0,0);
      display.println(angle);
      display.display();
      delay(300);

      myservo.write(0);
      delay(45);
    };
  }
}


texts: Parse a large json response with ESP8266

texts:
I'm doing a project where my Arduino uses an external ESP8266 wifi module (with AT firmware) to send http requests and receive server response.

I'm trying to get an NBA scoreboard, and here's what my Arduino sends to ESP:

> AT+CIPSTART=0,"TCP","data.nba.net",80
0,CONNECT

OK

> AT+CIPSEND=0,103
SEND OK

> GET /data/10s/prod/v1/20190214/scoreboard.json HTTP/1.1
Host: data.nba.net
Connection: keep-alive

+IPD,0,1460:HTTP/1.1 200 OK..
.............................
...here comes the response...
.............................

Now the code works fine, and I'm able to get the json file needed. The problem is that the response is sometimes too long and the file gets truncated, thus the response is incomplete. The file itself is sometimes pretty large, but I only need a few numbers from it (current teams + current score). So my questions are:

I use readString() method (of SoftwareSerial object instance) to read the response. Is there a way to parse the response chunk by chunk without loading everything in my ESP memory?
Is there a way to limit the response?
Are there any alternatives to the method I'm using? Maybe parsing the website (nba.com or espn.com/nba) directly? If so, how can I do that?
Maybe there's a way to write a separate (free) online API to parse json, constraint the response and send the small version upon request?

PS. I tried doing the same without AT firmware, flashing the module with a code that used HTTPClient directly (with ESP8266WiFi.h and ESP8266HTTPClient.h libraries):

HTTPClient http;
http.begin(request);
if (http.GET() > 0) {
    response = http.getString();
}
http.end();

That didn't help much. I'm still running out of memory since I'm directly loading the response to memory with getString().

PPS. Just in case it matters, I'm using ATmega2560 and a small ESP-01 module (similar to this).


texts: How to solve this "xpected primary-expression before ',' token"

texts:
I'm new in this arduino world, and I'm having some trouble. I am programming something for a school assignment. The program gives an error, and my teacher also doesn't know how to solve it. Maybe someone can help me?

#include <CapacitiveSensor.h>
#define speaker

CapacitiveSensor   cs_2_3 = CapacitiveSensor(2,3);
CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4);
CapacitiveSensor   cs_2_5 = CapacitiveSensor(2,5);
CapacitiveSensor   cs_2_6 = CapacitiveSensor(2,6);
CapacitiveSensor   cs_2_7 = CapacitiveSensor(2,7);
CapacitiveSensor   cs_2_8 = CapacitiveSensor(2,8);
CapacitiveSensor   cs_2_9 = CapacitiveSensor(2,9);
CapacitiveSensor   cs_2_10 = CapacitiveSensor(2,10);

int s1;
int s2;
int s3;
int s4;
int s5;
int s6;
int s7;
int s8;

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

void loop()
{

  s1 =  cs_2_3.capacitiveSensor(3000);
  s2 =  cs_2_4.capacitiveSensor(3000);
  s3 =  cs_2_5.capacitiveSensor(3000);
  s4 =  cs_2_6.capacitiveSensor(3000);
  s5 =  cs_2_7.capacitiveSensor(3000);
  s6 =  cs_2_8.capacitiveSensor(3000);
  s7 =  cs_2_9.capacitiveSensor(3000);
  s8 =  cs_2_10.capacitiveSensor(3000);

  Serial.print("s1: ");
  Serial.println(s1);
  Serial.print("s2: ");
  Serial.println(s2);
  Serial.print("s3: ");
  Serial.println(s3);
  Serial.print("s4: ");
  Serial.println(s4);
  Serial.print("s5: ");
  Serial.println(s5);
  Serial.print("s6: ");
  Serial.println(s6);
  Serial.print("s7: ");
  Serial.println(s7);
  Serial.print("s8: ");
  Serial.println(s8);

  if (s1 > 500){
    tone(speaker,131);
   }
  else if (s2 > 500){
    tone(speaker,147);
   }
  else if (s3 > 500){
    tone(speaker,165);
   }
  else if (s4 > 500){
    tone(speaker,175);
   }
  else if (s5 > 500){
    tone(speaker,196);
   }
  else if (s6 > 500){
    tone(speaker,220);
   }
  else if (s7 > 500){
    tone(speaker,247);
   }
  else if (s8 > 500){
    tone(speaker,262);
   }

  if (s1<=500  &&  s2<=500  &&  s3<=500 && s4<=500  &&  s5<=500  &&  s6<=500 &&  s7<=500 &&  s8<=500){
    noTone(speaker);
  }
}


texts: Any reason to acquire more watts than really needed?

texts:
Basic question (again):

I have a LED-strip that requires 5V, and each LED (150 in total) requires about 60 milliamps.
Calculating everything, I need 3 of these LED-strips (450 LED in total). This in turn tells me that they require 27 000 milliamps (27 amps), which is about 135W.
Which means I need an external power supply to power them.
I think about buying a 5V 40A (200 W), which should be sufficient(?).

But, is there any reason that I should not buy anything with more watts (250 or 300)?

Thanks for any help!


texts:
I am using Neopixel Library and a Trinket Pro 5V Microcontroller to chase first three LEDs on a strip and then burst the last 2 (could be modified based on the number of LEDs).
The LEDs chase only once. See the code below. I am not sure why, even though the logic is inside the loop function, it only executes once. Any suggestions?

#include <Adafruit_NeoPixel.h>
#include "WS2812_Definitions.h"
#ifdef __AVR__
  #include <avr/power.h>
#endif

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1
#define PIN            6

// How many NeoPixels are attached to the Arduino? How many Neopixels do you want to chase (starting from the first in address 0. How many do you want to burst at the end?
#define NUMPIXELS      5
#define NUMPIXELSCHASE 3
#define NUMPIXELSBURST 2

// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
#if defined (__AVR_ATtiny85__)
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
  // End of trinket special code

  pixels.begin(); // This initializes the NeoPixel library.
  clearLEDs();
  pixels.show();
}

void loop() {

  // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
  for(int i=0;i<NUMPIXELSCHASE;i++){

   pixels.setPixelColor(i, INDIGO);
   pixels.show(); // This sends the updated pixel color to the hardware.
   delay (200);
  }

  for(int i=NUMPIXELS-NUMPIXELSBURST;i<NUMPIXELS;i++){

   pixels.setPixelColor(i, AQUA);
   pixels.show(); // This sends the updated pixel color to the hardware.
   delay(0);
  }
}

// Sets all LEDs to off, but DOES NOT update the display;
// call leds.show() to actually turn them off after this.
void clearLEDs()
{
  for (int i=0; i<NUMPIXELS; i++)
  {
    pixels.setPixelColor(i, 0);
  }
}

Thank you.


texts: How to connect a 240x320 37-pin TFT to an Arduino Nano?

texts:
I have an old TFT display (extracted from an MP5 player) and I can't figure out how to connect it with an arduino nano, pls help.
here's the datasheet of the TFT:
http://read.pudn.com/downloads137/sourcecode/embed/586271/Varitronix-2.8-lcd/vl-ps-cog-t280mbqi-041.pdf
Thank you.


texts: Unable to alter SPI speed on Arduino Micro

texts:
I am using SPI to communicate with a IMU device which is working perfectly, except the SPISpeed which is not being altered as it should:

unsigned int m_SPISpeed = 400000;
SPI.begin();
pinMode(m_SPISelect, OUTPUT);
m_SPISettings = SPISettings(m_SPISpeed, MSBFIRST, SPI_MODE0);
...
SPI.beginTransaction(m_SPISettings);
digitalWrite(m_SPISelect, LOW);
SPI.transfer(regAddr | 0x80);

Where m_SPISpeed is 400000. No matter what i set this value to it is always operating at 125000Hz.


texts:
I want to measure the conversion rate of an arduino DUE. I know I could just take it from the datasheet but I need to measure it because I am running the ADC in free running mode.
Hints are welcome, I really don't know where to start.


texts: Difficulty getting Arduino data via puTTY

texts:
I am working on a project with a simple particulate matter sensor hooked up to an Arduino Uno. I'm using puTTY to log the sensor's output. My Arduino program converts the data to a numerical format, then prints it to the serial monitor every 30 to 31 seconds. I want to use puTTY to log this data to a file over a period of weeks. My problem now is that when I run it using puTTY, it stops after about 30-90 mins and "Fatal error: error reading from serial device" pops up. The wires connecting my sensor to the Arduino, and the USB cable connecting the Arduino to my computer all appear fine. Here is the code on the Arduino:

int pin = 8;
unsigned long duration;
unsigned long starttime;
unsigned long sampletime_ms = 30000;
unsigned long lowpulseoccupancy = 0;
float ratio = 0;
float concentration = 0;

void setup() {
  Serial.begin(9600);
  pinMode(8,INPUT);
  starttime = millis();
  Serial.print("Data is collected roughly every ");
  Serial.print(sampletime_ms/1000);
  Serial.println(" seconds.");
}

void loop() {
  duration = pulseIn(pin, LOW);
  lowpulseoccupancy = lowpulseoccupancy+duration;
  if ((millis()-starttime) >= sampletime_ms)
  {
    ratio = lowpulseoccupancy/(sampletime_ms);
    concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62;
    Serial.print("Concentration = ");
    Serial.print(concentration);
    Serial.print(" pcs/0.01cf at ");
    Serial.print(millis()/1000);
    Serial.println(" seconds.");
    lowpulseoccupancy = 0;
    starttime = millis();
  }
}

I'm using the shinyei PPD42 particulate matter sensor.
Can anyone tell me what's going on, and if there's any sort of workaround I can use? I don't necessarily need to use puTTY, I just need to log the serial output from my Arduino.
Thanks!


texts: Is SRAM erased when putting Arduino into sleep_mode_pwr_down?

texts:
Question
In the interest of reducing power consumption, I am putting the Arduino into sleep mode between taking sensor readings. However, the data from readings are stored in arrays, and must not be erased when the device enters sleep mode.
For clarity, I am using sleep_mode_pwr_down, and triggering an interrupt using the Watchdog Timer on the ATMega328 chip. See this post for a description of the different sleep modes: What are (or how do I use) the power saving options of the Arduino to extend battery life?
It would be possible to address this issue by writing data to the EEPROM, however, I am unsure whether this is necessary. The question is whether putting the device into sleep_mode_pwr_down erases the dynamic memory?

Specs / Context:
Arduino Uno (ATMega328 chip)


texts: RGB LED color control with a single value

texts:
Apps like Photoshop have a single slider to select color: .

I'd like to achieve the same using variable resistance knob as a slider to control color of RGB LED. Can anyone put me on the right track how to linearly map color values?


texts: Not output on serial monitor, sending string on serial.print

texts:
I get two 10-bit values from analog pins. These two values in a string, ";" combine with.
for ex:  515; 510
I am sending it to another arduino via Serial.print. I cannot display this string expression on other arduino's serial monitor. But when I press the reset button of Coordinator arduino, there are a few values. Can you help me?
My Coordinator Code:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
int deger3;
int deger4;
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);

void setup() {
  //Serial.begin(9600);
  xBeeSerial.begin(38400);
  }void loop() {

    deger3 = analogRead(A0);
    deger4 = analogRead(A2);

    String deger5 = " " + (String)deger3 + ";" + (String)deger4 ;

    Serial.println("string ifade: " + deger5);

    xBeeSerial.print(deger5);
  }

My Receiver Code:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);
String d1;

void setup() {
  xBeeSerial.begin(38400);
  Serial.begin(38400);
}
void loop() {
  if(xBeeSerial.available()){
    d1=xBeeSerial.readString();
    Serial.print(d1);
  }
}


texts: How to add numbers to a position when controlling a seven-segment display

texts:
I'm recently having a hard time with my Arduino project. I'm trying to control a seven-segment display (it has a microcontroller on it) with an encoder, and I'm trying so that everytime I rotate the encoder it adds 5 to the number on the display. What am I doing wrong here???

P.S: there are some parts that are for controlling relays, they are not related to the issue. I removed them on this thread on purpose.

Code (without any attempts to change the added amount to the display):

#include <RotaryEncoder.h>
#include <TM1637Display.h>

// Module connection pins (Digital Pins)
#define CLK 10
#define DIO 11

// Setup a RoraryEncoder for pins A2 and A3:
RotaryEncoder encoder(A2, A3);

// The amount of time (in milliseconds) between tests
#define TEST_DELAY   1000

TM1637Display display(CLK, DIO);

void setup()
{
    Serial.begin(57600);
    Serial.println("SimplePollRotator example for the RotaryEncoder
    library.");
}

// The Interrupt Service Routine for Pin Change Interrupt 1
// This routine will only be called on any signal change on A2 and A3:
//exactly where we need to check.
ISR(PCINT1_vect) {
    encoder.tick(); // just call tick() to check the state.
}

// Read the current position of the encoder and print out when changed.
void loop()
{
    static int pos = 0;
    int newPos = encoder.getPosition();
    if(newPos > -1)
    {
        if (pos != newPos) {
            Serial.print(newPos);
            Serial.println();
            pos = newPos + 4;
            display.setBrightness(0x0f);
            // All segments on
            // Show decimal numbers with/without leading zeros
            display.showNumberDec(newPos, true); // Expect: 1234
            delay(100);
        }
    } // if
} // loop ()
// The End


texts: I can't upload sketches to my Arduino 101

texts:
When connected to USB green Power LED on but doesn't upload sketch(that says press master reset therefore i've pressed several time but timeout). And main thing is device doesn't show in device manager.(I'm working on windows10).

Have I "bricked" it?
What steps can I take to work out what is wrong?
What can I do to fix it?

I've search in many sites but doesn't give me detail about hardware repairing guide for arduino 101.

I've checked working usb cable and another laptop but not work.I think hardware problem.Once arduino getting hot near usb.


texts: Need help figuring out the pinout of a seven segmented display

texts: A friend of mine gave me a 2in. 4 digit seven segment display. But when I sat down and looked at it, I found it has 7 pins on one side and 5 on the other and no indicators of its pinout on it. The only information I could gleam from it was the (presumably its model number) which said "PARA LIGHT A-5V4G-12-U1 H H0615". I searched online for it but only found ambiguous information that didn't help me. I have a feeling this is a fairly easy question, if so: sorry I am a noob.


texts: Which are the unused digital pins after L293D motor shield is installed on a Arduino Uno board?

texts:
I have just started my first project on Arduino. I have an Arduino Uno and an L293D motor shield.
I have installed the motor shield on the Arduino Uno board and the motor shield covers all pins of the Arduino Uno board. The motor shield is connected with four gear motors and one servo motor.
Can I use digital pins 2-13 to make some LED flashing circuit?
Which digital pins are used by the Motor shield and which pins are not used?

It is L293D motor shield. A0 and A5 are used in the code. Four DC motors and one servo motor is used.


texts: How to make data sent by Python (via serial connection) wait for Arduino to finish current task?

texts:
I am trying to make my Arduino micro-controller and my Mac talk together, and I have created a functional serial connection. My computer is sending data to my Arduino, and my Arduino is sending a 1 when it is ready to receive a new piece of data.

I have created an if-else statement (Python script below), which is either sending a new line of data to the Arduino or waiting for the Arduino to be ready for receiving a new line of data.

The problem is that ser.read() in the first part of the Python script always returns 1, which means that the script is sending the individual data lines faster than the Arduino connected stepper motors can possible react.

In the Arduino script you can see that I am sending the state-status in the first line of the serialEvent() function, which in my world should let the Arduino finish its job, before a new "task" is coming. However, it is for some reason not working. Can anybody help me out here?

Python script

import os
import time
import serial

# Name of csv file with drawing coordinates
csvFile = "scaled_coordinates.csv"

# Create serial connection
ser = serial.Serial(port='/dev/tty.usbserial-A9005bDh', baudrate=9600)

wd = os.getcwd()
myFile = open(wd + "/coordinates/" + csvFile)

state = '1'

while True: # Exits when there is no more lines to read
    print "test"

    if state == '0': # Wait for Arduino to be ready
        state = ser.read()

    elif state == '1': # Send one more line to Arduino
        line = myFile.readline()
        if not line:
            break
        print line
        ser.write(line)
        state = '0' # Wait for Arduino before reading next line

ser.close
myFile.close

Arduino loop function

void loop() {
  serialEvent(); // Call the serial function
  if (coord_complete) {
    // Steps to move from currrent to new point
    target1 = steps(x_current, y_current, x_new, y_new, 1);
    target2 = steps(x_current, y_current, x_new, y_new, 2);

    // Start moving
    stepper1.move(target1);
    stepper2.move(target2);

    // Update current position
    x_current = x_new;
    y_current = y_new;

    // Reset variables
    x_complete = false;
    y_complete = false;
    coord_complete = false;
  }

  // Stay in while loop until steppermotors is done
  while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
    stepper1.run();
    stepper2.run();
  }
}

Arduino serialEvent function

void serialEvent() {
  // EDIT : PUT SERIAL.WRITE INSIDE IF STATEMENT //
  if((stepper1.distanceToGo() == 0) && (stepper2.distanceToGo() == 0)){
    Serial.write('1'); // Tell Python that Arduino is ready for one more line
  }

  while (Serial.available() && coord_complete == false) {
    char ch = Serial.read(); // Get new character
    // EDIT : REMOVE THIS LINE //
    Serial.print(ch);

    // If digit; add it to coord_string
    if (isDigit(ch)) {
      coord_string[index++] = ch;

    // Else if ch is ","; then rename to x_new
    } else if (ch == ',') {
      coord_string[index++] = NULL;  // Finish coord_string
      x_new = atoi(coord_string);    // Convert to integer
      x_complete = true;             // Change x_complete to true
      index = 0;                     // Reset index
      memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string
    // Else if ch is a new line; then rename as y_new
    } else if (ch == ';') {
      //Serial.write('0');
      coord_string[index++] = NULL;
      y_new = atoi(coord_string);
      y_complete = true;
      index = 0;
      memset(coord_string, 0, sizeof(coord_string));
    }

    // Ends while-loop when true
    coord_complete = x_complete * y_complete;
  }
}

Edit

I have changed a bit in the first few lines of the serialEvent function (See comments).

Here is a sample of the text file I am reading from:

239,275;
1100,275;
300,400;
200,400;
200,300;


texts: Unknown USB Device (Device Descriptor Request Failed) - Win 10

texts:
I am posting a possible solution here for any online searches happening upon this exact issue.

So I have a third party board (Mega 2560) and I was plagued with my board intermittently working, on some rare occasions it worked but in most cases it just threw me the "USB device not recognized" after plugging it into my pc.

Upon closer inspection I have noticed the following

The one coupling capacitor (Blocks DC but allows AC and signal to pass) was poorly soldered, barely making contact!

So if your pc intermittently connects to your arduino, maybe check what the physical signal path looks like, you might find something like this.


texts: Trouble connecting Arduino Pro Mini (Atmega328, 3.3V) to nRF24L01 over SPI, receiving all 0 values when I use radio.printDetails();

texts:
I am trying to connect my Arduino Pro Mini 3.3V to an nRF24L01 transceiver and cannot see what I am doing wrong. I've checked my wiring a million times because the problem hints there is an invalid or no connection between the Arduino and the transceiver. I have the following pin connections:

  Arduino --------------- nRF24L01

  --GND ------------------- GND

  --VCC ------------------- VCC

  ---D9 --------------------- CE

  --D10 -------------------- CSN

  --D13 -------------------- SCK

  --D11 -------------------- MOSI

  --D12 -------------------- MISO

I am using the following sketch

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"

RF24 radio(9, 10);

const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0C2LL };     //Addresses to send/receive

void setup()
{
  printf_begin();
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15, 15);
  radio.openReadingPipe(1, pipes[0]);
  radio.printDetails();
  radio.stopListening();
}

void loop()
{
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));

  delay(1000);
}

I have no clue where I am going wrong. This setup works well on my Uno, however I cannot replicate it on the Arduino Pro Mini. Can anyone tell me if I am doing something super wrong that would prevent this from working? I'm all out of ideas. Appreciate any help in advanced!

Update:

I forgot to copy and paste the output from printDetails():

STATUS  = 0x00
RX_DR=0
TX_DS=0
MAX_RT=0
RX_P_NO=0
TX_FULL=0
RX_ADDR_P0-1    = 0x0000000000 0x0000000000
RX_ADDR_P2-5    = 0x00 0x00 0x00 0x00
TX_ADDR = 0x0000000000
RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA   = 0x00
EN_RXADDR   = 0x00
RF_CH   = 0x00
RF_SETUP    = 0x00
CONFIG  = 0x00
DYNPD/FEATURE   = 0x00 0x00
Data Rate   = 1MBPS
Model   = nRF24L01
CRC Length  = Disabled
PA Power = PA_MIN


texts: I'm making a project with MQTT Arduino, but on publish messages i read that it's not possible to publish with qos 1 and 2? It is true? If is not, how can i put qos on publish messages?


texts: Controled in the led by Arduino UNO to Firebase through ESP8266-01+ MIT App Inventor

texts:
exchange community ,

help me community :(

I want to control led by MIT App Inventor with used Arduino UNO to Firebase through ESP8266-01

Notes :

1-The led connected pin 11 on Arduino-Uno

2-The esp8266-01 connected tx rx pin 2 pin 3 on Arduino-Uno

3- This circuit was designed by me, but I cannot control it through the Internet of Things

when I search on google i find this tutorial on YouTube but all video in google used dht sensor but i want controlled led  :

enter link description here

this is dht sensor code :

//
// Copyright 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

// FirebaseDemo_ESP8266 is a sample that demo the different functions
// of the FirebaseArduino API.

#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>

// Set these to run example.
#define FIREBASE_HOST "example.firebaseio.com"
#define FIREBASE_AUTH "token_or_secret"
#define WIFI_SSID "SSID"
#define WIFI_PASSWORD "PASSWORD"

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

// connect to wifi.
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
 Serial.print("connecting");
while (WiFi.status() != WL_CONNECTED) {
 Serial.print(".");
delay(500);
 }
 Serial.println();
 Serial.print("connected: ");
 Serial.println(WiFi.localIP());

Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
 }

int n = 0;

void loop() {
// set value
Firebase.setFloat("number", 42.0);
// handle error
if (Firebase.failed()) {
  Serial.print("setting /number failed:");
  Serial.println(Firebase.error());
  return;
 }
delay(1000);

// update value
Firebase.setFloat("number", 43.0);
// handle error
if (Firebase.failed()) {
  Serial.print("setting /number failed:");
  Serial.println(Firebase.error());
  return;
}
delay(1000);

// get value
 Serial.print("number: ");
 Serial.println(Firebase.getFloat("number"));
 delay(1000);

// remove value
Firebase.remove("number");
delay(1000);

// set string value
Firebase.setString("message", "hello world");
// handle error
if (Firebase.failed()) {
  Serial.print("setting /message failed:");
  Serial.println(Firebase.error());
  return;
 }
 delay(1000);

// set bool value
Firebase.setBool("truth", false);
// handle error
if (Firebase.failed()) {
  Serial.print("setting /truth failed:");
  Serial.println(Firebase.error());
  return;
}
delay(1000);

// append a new value to /logs
String name = Firebase.pushInt("logs", n++);
// handle error
 if (Firebase.failed()) {
  Serial.print("pushing /logs failed:");
  Serial.println(Firebase.error());
  return;
 }
 Serial.print("pushed: /logs/");
 Serial.println(name);
 delay(1000);
 }


texts: Arduino Mega 2560 multiple slave via SPI

texts:
I'm new to Arduino and microcontroller . I want to connect my Arduino Mega to three slaves which Arduino Unos. I know that these slaves will share MISO, MOSI, and SCK lines. However, SS is unique to each slave.

For single slave, the SS is pin 53. So, for three slaves, which other two pins can I use as SS?

Thank you for your help.


texts: Can i supply the AREF pin with an Analog pin from the same board?

texts:
I guess its a dumb question but couldnt find anything about it online. I know its possible to supply the AREF pin with 3.3 V to increase the ADC resolution.

For the project i am working on the analog voltage i will be reading will be between 0 and 2.2 and the increased resolution is a must.

I know i can use another board that has a 12 bit resolution but i really would like to make do with Uno. So i wonder if i can set an analog pin to output 2.3 V and feed it to the Aref pin.

If thats not possible please let me know why, so i can increase my knowledge


texts: Cannot get HC-12 to function with Arduino Pro Micro clone

texts:
[first time usage]

I'm checking this config out with a simple sketch derived from one @ https://www.allaboutcircuits.com/projects/understanding-and-implementing-the-hc-12-wireless-transceiver-module/.

The sketch acknowledges a command from the Serial Monitor and responds accordingly along with an "OK".  I have used this sketch countless times before with numerous HC-12 and UNO, and this particular HC-12 functions properly when connected to such.

For the Pro Micro, the command is echoed back instead, which, in my experience, indicates that the HC-12 is not receiving/responding.

The Pro Micro test config is very basic: Pro Micro, HC-12, USB connection, 5 direct jumper connections for vcc, gnd, pins 4-6. Vcc output reads 4.2 volts.

I specify:

const byte HC12RxdPin = 4; // "RXD" Pin on HC12
const byte HC12TxdPin = 5; // "TXD" Pin on HC12
const byte HC12SetPin = 6; // "SET" Pin on HC12

SoftwareSerial HC12(HC12TxdPin, HC12RxdPin)

I have also tested with an IN4007 in the power connect for the HC-12, but results are the same.

I've swapped HC-12s, and checked out the requisite pins by using another sketch that toggles an led on each.
The Arduino IDE is 1.8.2, and I am specifying a Leonardo board.  This is the suggestion I found whilst researching.

I have seen a few projects using the HC-12 with the Pro Micro and other small boards, but noticed no special considerations for such.

Have you any suggestions or solutions [even better]?


texts: Combining mysensors with SD card (on an Ethernet Shield v2)

texts:
I'm trying to combine a MySensors network with the usage of a SD card. Currently I'm working with the SD card reader on the EthernetShield v2.
The NRF24L01+ chip I'm using is also using SPI but we used Soft-SPI to change the pins that is uses so I'm not using pin 4 or 10 (that are used to select the SD card as far is I know).

To read from the SD card I'm using the SdFat library.
When I exclude the following part of code, the messages are getting send and I don't have any weird resets:

if (!SD.begin(SD_CS_PIN)) {
    Serial.println("initialization failed!");
    return;
  }

But the card keeps resetting after booting and it gives these logs:

0;255;3;0;9;!TSF:MSG:SEND,0-0-15-15,s=0,c=1,ne.
0;255;3;0;9;MCO:BGN:INIT OK,TSP=1
14;Gateway startup complete.
0;255;0;0;18;2.1.1
0;255;3;0;9;MCO:BGN:STP
initialization done.
0;255;3;0;9;MCO:BGN:INIT OK,TSP=1
0;255;3;0;9;MCO:BGN:INIT GW,CP=RNNGA--,VER=2.1.1
0;255;3;0;9;TSM:INIT
0;255;3;0;9;TSF:WUR:MS=0
0;255;3;0;9;TSM:INIT:TSP OK
0;255;3;0;9;TSM:INIT:GW MODE
0;255;3;0;9;TSM:READY:ID=0,PAR=0,DIS=0
0;255;3;0;9;MCO:REG:NOT NEEDED
0;255;3;0;14;Gateway startup complete.
0;255;0;0;18;2.1.1
0;255;3;0;9;MCO:BGN:STP
initialization done.
0;255;3;0;9;MCO:BGN:INIT OK,TSP=1
0;255;3;0;9;!TSF:MSG:SEND,0-0-15-        15,s=0,c=1,t=24,pt=0,l=25,sg=0,ft=0,st=NACK:Message Gateway -> Pongno
0;255;3;0;9;MCO:BGN:INIT GW,CP=RNNGA--,VER=2.1.1
0;255;3;0;9;TSM:INIT
0;255;3;0;9;TSF:WUR:MS=0
0;255;3;0;9;TSM:INIT:TSP OK
0;255;3;0;9;TSM:INIT:GW MODE
0;255;3;0;9;TSM:READY:ID=0,PAR=0,DIS=0
0;255;3;0;9;MCO:REG:NOT NEEDED
0;255;3;0;14;Gateway startup complete.
0;255;0;0;18;2.1.1
0;255;3;0;9;MCO:BGN:STP
initialization done.
0;255;3;0;9;MCO:BGN:INIT OK,TSP=1

The code:

#define MY_DEBUG

#define MY_SOFTSPI
#define MY_RF24_CE_PIN 11
#define MY_RF24_CS_PIN 6
#define MY_SOFT_SPI_SCK_PIN 8
#define MY_SOFT_SPI_MISO_PIN 9
#define MY_SOFT_SPI_MOSI_PIN 7

#define MY_RADIO_NRF24
#define MY_RF24_CHANNEL 69
#define MY_NODE_ID 0
#define MY_GATEWAY_SERIAL

#include <MySensors.h>
#include <SPI.h>
#include "SdFat.h"
SdFat SD;

#define SD_CS_PIN 4

File myFile;
#define PONGNODEID 15

MyMessage msg(MY_NODE_ID, V_VAR1);

void setup() {
  // Open serial communications and wait for port to open:

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  msg.setDestination(PONGNODEID);

  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);

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

}

void presentation() {}

long lastSent = 0;

void loop() {
  if (millis() - lastSent >= 3000) {
    lastSent = millis();
    send(msg.set("Message Gateway -> Pongnode"), true);
  }
}


texts: What device do I add in order to detect if my project is moved?

texts:
I seem to be going round in circles trying to find the answer to this question, so thought I'd ask the good folk here.

I have an Arduino pro mini 3.3v based project, using lowpower libraries. It wakes up every h hours and takes a reading.  I would now like it to still wake up every h hours but in the meantime know whether the item (the board, or its container) has actually physically been moved - like binary, did it move or not at all?

I don't need constant monitoring of position. Once triggered I'd turn off the interrupt until the next wake up event.

In my mind I see the solution as being an interrupt attached to low power device which when moved slightly triggers the event to be recorded.

pseudo code would be:

if ((hour == h_hour) && movementDetectedSinceLastWakeup){
  doStuff();
} else {
  goBackToSleep(2hrs);
}

My question is, what kind of sensor should I consider for this job?

3.3v
lowpower
can trigger interrupt

EDIT "move" as in it vibrated past some set level.