texts:
I am really short of interrupt pins on my Arduino because I have a project that already uses a lot of Arduino pins and to read DMP data from MPU6050 you always have to use an interrupt pin. I searched A LOT in the internet and many people says it's impossible to retrieve DMP data without interrupt pin. Some people also said the only way to do that would be if I could reverse engineer the MPU6050 code (which I don't know how to do).

But today, playing with MPU6050 I could finally get all of its DMP data without the interrupt pin, you just have to connect 4 pins (VCC, GND, SCL and SDA). Upload the code below to your Arduino and see that it works!

#include "MPU6050_6Axis_MotionApps20.h"
MPU6050 mpu;
uint16_t packetSize;
uint16_t fifoCount;
uint8_t fifoBuffer[64];
Quaternion q;
VectorFloat gravity;
float ypr[3];

void setup() {
  Wire.begin();
  TWBR = 24;
  mpu.initialize();
  mpu.dmpInitialize();
  mpu.setXAccelOffset(-1343);
  mpu.setYAccelOffset(-1155);
  mpu.setZAccelOffset(1033);
  mpu.setXGyroOffset(19);
  mpu.setYGyroOffset(-27);
  mpu.setZGyroOffset(16);
  mpu.setDMPEnabled(true);
  packetSize = mpu.dmpGetFIFOPacketSize();
  fifoCount = mpu.getFIFOCount();

  Serial.begin(115200);
}

void loop() {
  while (fifoCount < packetSize) {
    fifoCount = mpu.getFIFOCount();
  }

  if (fifoCount == 1024) {
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));
  }
  else {
    if (fifoCount % packetSize != 0) {
      mpu.resetFIFO();
    }
    else {
      while (fifoCount >= packetSize) {
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        fifoCount -= packetSize;
      }

      mpu.dmpGetQuaternion(&q, fifoBuffer);
      mpu.dmpGetGravity(&gravity, &q);
      mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

      Serial.print("ypr\t");
      Serial.print(ypr[0] * 180 / PI);
      Serial.print("\t");
      Serial.print(ypr[1] * 180 / PI);
      Serial.print("\t");
      Serial.print(ypr[2] * 180 / PI);
      Serial.println();
    }
  }
}

There is only one problem: Intermittently the Arduino hangs in the getFIFOBytes function for no reason. I am pretty sure it's a bug because when you call too many times getFIFOBytes for some reason the Arduino freezes.


texts:
Here's come Arduino code.

#define M(x, y) x * y;
void setup() {
  Serial.begin(9600);
  Serial.println(M(3 + 2, 4 + 2));
}
void loop() {
}

Why is the result 13?


texts:
Proceeding is the relevant part of the code for the problem I'm asking assistance with.  I'm attempting to vary the speed of the robots motors with PWM. The left motor speed can be varied numerical. The right motor fails to move. Any ideas is appreciated. The motor speed code is at the end of the sketch.
Any assistance is greatly appreciated.

//Below are the symbolic constants. Instead of having to type in a non-sensical pin number each time we want to do something we can write an easy to understand name which represents the pin, the compiler will then replace the names with the numbers
 #define LeftMotorForward 8
 #define LeftMotorBackward 9
 #define LeftMotorSpeed 10
 #define RightMotorForward 6
 #define RightMotorBackward 7
 #define RightMotorSpeed 5
 #define USTrigger 3
 #define USEcho 2
 #define MaxDistance 100
 #define LED 13

//Here we have created two 'objects', one for the servo and one for the ultrasonic sensor
 Servo servo;
 NewPing sonar(USTrigger, USEcho, MaxDistance);

//Below we are creating unsigned integer variables which we will use later on in the code. They are unsigned as they will only have postive values
 unsigned int duration;
 unsigned int distance;
 unsigned int FrontDistance;
 unsigned int LeftDistance;
 unsigned int RightDistance;
 unsigned int Time;
 unsigned int CollisionCounter;

 void setup()                                            //This block happens once on startup
 {
  Serial.begin(9600);                              //I have included the serial initialize but commented it out, if you want to debug and print information to the serial monitor just uncomment

  //Here we are setting the pin modes. As we will sending out signals from the pins we set them as outputs
  pinMode(LeftMotorForward, OUTPUT);
  pinMode(LeftMotorBackward, OUTPUT);
  pinMode(LeftMotorSpeed, OUTPUT);
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorBackward, OUTPUT);
  pinMode(RightMotorSpeed, OUTPUT);
  pinMode(LED, OUTPUT);
  servo.attach(11);                                    //The servo is attached to pin 4
 }

 void loop()                                           //This block repeats itself while the Arduino is turned on
 {
  servo.write(90);                                    //Rotate the servo to face the front
  scan();                                             //Go to the scan function
  FrontDistance = distance;                           //Set the variable FrontDistance to the value of the distance returned from the scan function
  Serial.println("Front distance = ");
  Serial.print(distance);
  if(FrontDistance > 40 || FrontDistance == 0)        //If there is nothing infront of the robot within 40cm or the distance value is 0 (which for the newping libary means no ping was returned) then...
  {
   moveForward();                                     //Go to the moveForward function
  }
  else                                                //Else (if there is something infront of the robot within 40cm) then...
  {
    CollisionCounter = CollisionCounter + 1;
    moveStop();                                       //Go to the moveStop function
    navigate();
  }
 }

 void moveForward()                                    //This function tells the robot to go forward
 {

  Serial.println("");
  Serial.println("Moving forward");
  //Turn on left motor
  digitalWrite (LeftMotorBackward, LOW);
  digitalWrite(LeftMotorForward, HIGH);
  //set speed
  analogWrite(LeftMotorSpeed, 100);

 // turn on right motor
  digitalWrite(RightMotorBackward, LOW);
  digitalWrite(RightMotorForward, HIGH);
// set speed
   analogWrite (RightMotorSpeed, 75);


texts: Suddently, "avrdude: Device signature = 0x000000" with ArduinoISP. Is my chip dead?

texts:
I have some boards with the atmega32u4 that they were working perfectly before. I'm using an unnoficial UNO board to program them via ICSP. To power the uC I'm using two lithium batteries and a step-down converter to drop it to 5 V.

This started happening when I tried to upload code via ISCP when the target chip was not powered by mistake.

This is my error message:

Arduino: 1.8.5 (Windows 10), Placa:"Arduino Leonardo"

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

     Using Port                    : COM4
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     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  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 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.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

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.

What I've already tried:

Different programmer (another Uno board);
Uploading to a proper Leonardo board via ICSP, it worked;
Uploading to another of my boards via ICSP, it worked;
Running with the portable Arduino version;
Check if the chip is being powered with 5 V;
Changed wires and checked the connections;
The chip does not get hot;

I've been around this two days straight, any help would be much appreciated.


texts:
I'm looking for a low cost motorized water valve.  I've done a number of searches and have found nothing compelling.  Has anyone here used a motorized water valve with Arduino?  What would you recommend?

A fail-open solenoid might also work but I'd like to try my hand at a motorized valve.

The valves I found start at US$50.  I'm looking for something cheaper.  The purpose is tinkering and I'd like to make an "if water detected - then close valve" sketch.  Ir's simple, just more expensive than I expected.


texts: hexadecimal 1 to float 1 - Compare the float 1 with a predefined float 2 - If the float 1 and float 2 are the same - Print hexadecimal 2

texts:
I want to input a hexadecimal data from cool terminal say like (05 00 02 03 00 04 00 E5) And convert the data to a float value say 45.3. Now that I have to preassign a float value say 45.3 in my program so that I can compare the converted float value with the preassigned float value. If the two values match I need to print another hexadecimal value i.e( 05 03 00 01 00 02 04 4F).

I have managed to do the conversion of hexadecimal to float. Can someone please help me in comparing the two float values?


texts: How to use capactive touch on Adafruit board in Arduino mode?

texts:
I have a Trinket M0 which has three pins capable of capacitive touch, A0, A3, and A4. When using CircuitPython on these boards you can use the CapTouch Library. But as far as I can tell this does not exist for use in Arduino mode. Does anyone know how to get these pins to pick up capacitive touch? I've tried the Adafruit_FreeTouch library, but with zero documentation, it's not very user friendly. I thought I had it working with two pins, but whenever both pins detect capacity, the capacity is divided between them, so both pins report about the same capacity.
Any help would be greatly appreciated.
This question does seem like a duplicated of Built-in capacitive touch detection with SAMD21 development board (Arduino Zero Compatible) but there was never a solution.
Thanks!


texts:
I'm developing on the Arduino platform (ESP8266 with USB -> serial) and sometimes the USB port that is being used stops working and gets frozen. Then I need to plug the device into another USB port. It happens again and once all the USB ports stop working I have to restart the machine, which is really annoying.

As far as I remember there is a command that can restart the USB subsystem individually, but I can't remember. How to restart USBs without restarting the entire system? Thanks.

I'm using Mac OS X Sierra.


texts:
I am trying to control an RGB LED strip with an Arduino. I have followed the tutorials in both of these websites:
Using MOSFETs: https://learn.adafruit.com/rgb-led-strips?view=all

Using LED Amplifiers: http://www.instructables.com/id/LED-Strip-Controller-w-LED-Amp-Arduino/

I have tried both setups and none of them work for me. When I try the setup with the MOSFETs, I am able to control each color but the blue LEDs are dimmer than the red and green, and therefore I can't mix any colors with blue.

When I try the LED Amplifiers, I am not able to control any light at all. Only the blue LEDs light up but the red and green dont. Also the blue LEDs stay ON the whole time and the only way to turn them off is to disconnect them from the DC power source.
What am I doing wrong?


texts: I salvaged an old LCD from a calculator (Texas Instruments) and I want to interface it with a microcontroller (preferably an Arduino). I‘ve searched the whole internet but I simply can‘t find any information about this display and its driver. I am looking for a specialist who can identify this:


texts: problem using #define to substitute functions

texts:
This might be more a general programming question, but I am using the Arduino compiler, and I've created my own ISR driven version of millis(), which I simply call myMillis(). So let's say I'd like to use this addition to a working project. Rather than do a global search and replace, I got the idea to simply put this define near the top of the program...

#define millis myMillis

uint32_t myMillis()
  { // my code ...
  }

So when I compile, every instance of millis() does indeed compile as if I did a global search and replace. I like that, because it means I don't have to make the change permanent, and can easily comment out my defines to compare program operation.

My question is, if I do as I just explained, what if, for whatever reason, there is some place within the project where I actually WANT to call the original version. A simple example might be if I wanted to occasionally output a message via serial.println(), comparing the returned value of millis() and myMillis(). I think there is a way to specify such an exception to my #define MACRO, but I'm not sure how.


texts: How many bluetooth modules can be interfaced with Arduino UNO?

texts: At most how many bluetooth modules(HC-05) can be interfaced to Arduino UNO?


texts: Why does my stepper motor run when I open the Serial port?

texts:
For some reason my motor moves a certain amount every time I open the serial port without giving it any other instructions. It will move further by the same amount if I close and reopen the serial port. Please could someone tell me how to avoid this? I haven't had this problem before.
I am using two stepper motors with a A4988 driver each.
Here is my code so far
#include <AccelStepper.h>
#include <MultiStepper.h>

// Define pin connections
const int dirPin1 = 2;
const int stepPin1 = 3;
const int dirPin2 = 4;
const int stepPin2 = 5;

String incomingByte; // for incoming serial data

// Define motor interface type
#define motorInterfaceType 1

// Creates an instance
AccelStepper stepper1(motorInterfaceType, stepPin1, dirPin1);
AccelStepper stepper2(motorInterfaceType, stepPin2, dirPin2);

MultiStepper steppers;

void setup() {
  Serial.begin(9600);
  String excess1 = Serial.readString();
  // Configure each stepper
  stepper1.setCurrentPosition(0);
  stepper2.setCurrentPosition(0);
  stepper1.setMaxSpeed(100);
  stepper2.setMaxSpeed(100);
  stepper1.setAcceleration(10);
  stepper2.setAcceleration(10);
  // Then give them to MultiStepper to manage
  steppers.addStepper(stepper1);
  steppers.addStepper(stepper2);
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {
    // read the incoming byte:
    incomingByte = Serial.readString();

    // say what you got:
    Serial.print("I received: ");
    //Serial.println(incomingByte, DEC);
    Serial.println(incomingByte);

    int x = incomingByte.toInt();

    long positions[2];

    positions[0] = x;
    positions[1] = 0;
    steppers.moveTo(positions);
    steppers.runSpeedToPosition();
  }
}


texts: Bluetooth hc-06 and Standalone Atmega168(possible?)

texts:
I am making a project that requires bluetooth communication between a Raspberry Pi(equipped with a bluetooth dongle) and a standalone atmega168 circuit.

I want to be able to transfer information serially between the two devices over bluetooth.

I have selected the hc-06 for the arduino and some usb bluetooth dongle for the PI.

I would like to know if connecting the hc-06's TX and RX pins to the RX and TX (respectively) pins of my atmega will work or not. If not, I would like to know how to achieve that (bluetooth on a standalone arduino-powered microcontroller)


texts: How do I write an Arduino program to an AVR chip without the Arduino bootloader?

texts: Is it possible to write an Arduino program to an AVR chip that does not have teh Arduino bootloader installed?  What is the process to do so?


texts:
I am using two XBee Series 2 modules (Zigbee), an Arduino Uno, and a HC-SR04 Ultrasonic sensor to send distance readings from the coordinator XBee on the Arduino to the XBee connected to my computer. I configured the ArduinoXBee as "Zigbee coordinator AT" and the ComputerXBee as "Zigbee end device AT" with the following networking settings:

Coordinator:
PanID: 1234
DH: 0
DL: FFFF

End Device:
PanID: 1234
DH: 0
DL: 0 (so it can only talk to the coordinator)

The problem I am facing is that when I open the End Device terminal on X-CTU, the distance readings I get are accurate yet very unstable. Like it receives the correct readings but the transmission is unsynchronized as it sometimes receives 5 numbers in one transmission and lags for 10 seconds then receives the next bunch and lags for another 10 seconds and so on...

The arduino code is:

#include <SoftwareSerial.h>
const int trigPin = 13;
const int echoPin = 9;

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

void setup()  {
   xbee.begin( 9600 );
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
}
void loop()  {
long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  xbee.println( distance );
  delay(500);
}

Can anyone help me?


texts:
Actually I am facing a big problem while programming my atmega328p using an arduino uno as ISP.
I followed a video on youtube  "Arduino as ISP" by Notes and Volts. Which look doing the same steps that the majority followed. For the blinking LED sketch the µC worked very well and it did not show any troubles.
So I  decided to carry on , and at this point I needed to upload a new program but this i wanted to upload my program using "avrdude" command line because my code was written with MikroC pro for avr, and here is the command line :

"avrdude -p atmega328p -b 19200 -C arduino -P COM7 -U lfuse:w:0xf7:m -U
 hfuse:w:0xc9:m -U efuse:w:0xff:m -U flash:w:LED.hex:i "

But unfortunately it did not work well and I have got the following error :

avrdude : invalid byte value <ff> specified for immediate mode
 avrdude : write to file 'ff' failed
 avrdude : safemode : Fuses OK

Seeing that error paniced me , that's why I decided to retry the programmation with an arduino sketch and then happened the big issue when the arduino generate an error message about finding a bad microcontroller [error about the device signature] []2.
My last try to find out if I ruined my µC is with switching the µCs; the arduino original and the one that I had to program and unfortunately It was not a good result :
"avrdude : stk500_recv() : programmer is not responding
 avrdude : stk500_getsync() attempt 1 of 10 : not in sync : resp=0x85"
Looking for more than day on the internet and I could not find a valid solution , except the possibility that I really BURNT my µC and I have to buy another one. And this is specifically why I am asking for your help; I need  to know if SO could figure this trouble out.Otherwise, could somebode confirm to me that there is no hope with my µC and it's gone and I have to stop trying to make it works .
Thank you
Regards


texts:
I was working with Arduino and Xbee with LED, circuit LED  + Servomotor
and doing testing for 5 hours (not continuously).

Then once I omitted the Servomotor circuit and I connected flex sensor, which required connecting 10k Resistor and connect it the laptop as usual, smoke came out of the board (from USB side).  I disconnected it immediately, but now the board doesn't light up and the 5V gives 1.5V.

Is there any chance to fix the board?

I discovered that the B2 diode cracked in the middle, the picture is showing a  good Arduino Nano.

I found a very similar in this post about dead NANO


texts:
I have a bluetooth module HC-06 and want to pair it to my Arduino UNO. The thing is when I researched how to do so, I got different answers. What pairing should I use? Thank you in advance. I have highlighted the differences.

First version:
https://www.instructables.com/id/Add-bluetooth-to-your-Arduino-project-ArduinoHC-06/

HC-06>>>Arduino

VCC>>>>3.3v

GND>>>>GND

TXD>>>>RXD

RXD>>>>TXD

Second version:
http://42bots.com/tutorials/hc-06-bluetooth-module-datasheet-and-configuration-with-arduino/

HC-06            <<>> Arduino

HC-06 Ground GND <<>> GND

HC-06 VCC pin  <<>> 5v

HC-06 TX/TXD pin <<>> Arduino RX

HC-06 RX/RXD pin << resistors >> Arduino TX

[![enter image description here][1]][1]

[![enter image description here][2]][2]


texts: How to export RSSI values from arduino ide to Excel (REAL TIME UPDATE)

texts:
i am using esp32 for getting the rssi values from esp 32 using Arduino IDE.
MY CODE
#include "WiFi.h"

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

  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.println("Setup done");
}

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

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

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

PROBLEM
I want to export the values of RSSI from the serial monitor into excel. I have used PLX DAQ ( I found this as a frequent solution on the internet) but this does not work in my case it gives an error that port is unavailable or check your port. (I have checked COM it was correct) I tried using excel data streamer using the same Arduino script but nothing appear on the sheet. the data columns were empty do I have to change the script? if yes what change? the excel sheet should have three columns TIMESTAMP,SSID(WIFI NAME), RSSI.
THANKS IN ADVANCE.


texts:
I have a string,

"id,port,password,ssid,delay,flag,class,category"

Please tell me how can stringtok this and find out the "flag" value(0 or 1)?

Here is what I tried:

void setup()
{
    char input[] = {"id,port,password,ssid,delay,flag,class,category"};
    char *ptr;
    Serial.begin(115200);
    ptr = strtok(input, ",");
    Serial.println(ptr);
    while (ptr != NULL) {
        ptr = strtok(NULL, ",");
        Serial.println(ptr);
    }
}

void loop(){}


texts:
I recently purchased a Digispark for some of my smaller electronics projects. After it initially being a great little board, I soon found myself unable to flash the board in the same way I had done before i.e. according to the method described here. I am still unsure as to why the previous flashing method stopped working but have been unable to overcome the issue, nor have I found many other accounts of similar problems online.

After a period of frustration, unable to even find a way to reset the board, it dawned upon me that I may be able to use an Arduino to flash the board as seen here. However, the issue is that all the tutorials I could find online assumed that an Arduino Uno could be easily accessed, which is not the case for me. Despite this, I do have a few NodeMCUs hanging around and would love it if I could use them to flash the Digispark.

My question is: how exactly would I flash the Digispark using a NodeMCU (if it is even possible)?

P.S. Whilst I am aware that the Digispark board has a number of other components aside from the ATtiny85 chip, the pinouts (not the USB) of the board allow for direct interfacing with the chip.

Thank you in advance for any help,

Kind regards,
Rocco


texts:
So recently I started making a sonar out of ultrasonic HC-SR04 sensor and servo motor. The idea was to slowly rotate servo 180 degrees while measuring distance.

Soon after I noticed that regular pulseIn() command could wait 20ms while doing nothing. So I started learning interrupts. I came up with a code which sends TRIG signal and records sending time with micros() function. When an interrupt occurs on ECHO pin, we subtract current time with TRIG time and get time of round trip of the sound.

The code works as intended without servos connected, but it behaves interestingly ! I always get distance which is 8 cm bigger than actual distance. So I had to subtract 8 cm every time ! Also I noticed that max reliable range decreased , using pulseIn() I could measure distance of 400cm, and with mine code it starts to show weird numbers after 150cm...

So i thought that 150cm is enough for me, and tried to run the code with servos attached. everything ran as intended, until the servos started to move. Now I was getting distance along with pretty much random numbers, periodically positive and negative.

I could just use one the fancy libraries out there, but I am curious what am I doing wrong, why i need to subtract 8cm each time , why my reliable range decreased so much, and most importantly why am I getting weird values while servos are on ?

CODE :

#include <Servo.h>

#define ECHO 2
#define TRIG 7

 Servo servo;
 int distance;
 volatile long echoTime = 0;
 long trigTime = 0,sendTime = 0,timeServo = 0;
 bool scanning = false;
 byte servoDir = -1,servoAngle = 0;

void setup()
{
  servo.attach(12);
  Serial.begin(115200);
  pinMode(ECHO,INPUT);
  pinMode(TRIG,OUTPUT);
  attachInterrupt(digitalPinToInterrupt(ECHO), echo_interupt, FALLING);

}
void loop()
{
  // SERVO

   if((millis() - timeServo > 10)){
     if(servoAngle <= 0 || servoAngle >= 180)servoDir = -servoDir;
     servoAngle += servoDir;
     servo.write(servoAngle);
     timeServo = millis();
   }

  // GETTING RESULTS
  if(echoTime > 0){
    distance = echoTime - trigTime;
    distance /= 58;
    echoTime = 0;
    trigTime = 0;
    Serial.println(distance - 8);
  }
  // SENDING PULSE
  if(millis() - sendTime > 20){
  digitalWrite(TRIG,LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG,HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG,LOW);
  trigTime = micros();
  sendTime = millis();
  }
}

 // INTERUPT
void echo_interupt(){
  echoTime = micros();
}


texts: Programming a USB mouse connected to the Intel Edison Arduino expansion board

texts:
How can I programme a USB mouse connected to the standard USB port of the Intel Edison's Arduino expansion board?  I would like to measure the displacement of the mouse and also specify the frequency of image capture using the mouse's optical sensor.  I do not know much about programming so tutorials relating to my project would be very helpful.

Thanks


texts: Compatibility between Arduino and Arduino clones

texts:
In a project I am using a Seeeduino v3.0 as an Arduino clone. On the seeeduino website it says that

  It is based on the Duemilanove schematic, 100% compatible to its existing program, shield and IDEs.

In fact I never had any problems with shields or the IDE.

My question is now: Is the seeeduino and other clones really 100% compatible? The seeeduino board was considerable cheaper then an arduino.


texts: OTA framework update by GitHub server Connection fail error

texts:
I have tried to use some OTA programming method by website servers like this method which was not successful and asked here. So I have tried the own Arduino library shown below:
and changed the ESP OTA GitHub Library example code :

to this kind :
/*
  GitHub_Upgrade.ino - Example for ESP library for auto updating code from GitHub releases.
  Created by Gavin Smalley, November 13th 2019.
  Released under the LGPL v2.1.
  It is the author's intention that this work may be used freely for private
  and commercial use so long as any changes/improvements are freely shared with
  the community under the same terms.
*/

#include <ESP8266WiFi.h>
#include <FS.h>

#ifndef STASSID
#define STASSID "Adsl momo"
#define STAPSK  "xxxxxx"
#endif

// A single, global CertStore which can be used by all
// connections.  Needs to stay live the entire time any of
// the WiFiClientBearSSLs are present.
#include <CertStoreBearSSL.h>
BearSSL::CertStore certStore;

/* Set up values for your repository and binary names */
#define GHOTA_USER "soheilpaper" //"username"
#define GHOTA_REPO "ota_github_blink" //"repository"
#define GHOTA_CURRENT_TAG "2.0"
#define GHOTA_BIN_FILE "BlinkWithoutDelay_ino_esp8285.bin"//"sketchname.ino.d1_mini.bin"
#define GHOTA_ACCEPT_PRERELEASE 2

#include <ESP_OTA_GitHub.h>

void handle_upgade() {
    // Initialise Update Code
    //We do this locally so that the memory used is freed when the function exists.
    ESPOTAGitHub ESPOTAGitHub(&certStore, GHOTA_USER, GHOTA_REPO, GHOTA_CURRENT_TAG, GHOTA_BIN_FILE, GHOTA_ACCEPT_PRERELEASE);

    Serial.println("Checking for update...");
    if (ESPOTAGitHub.checkUpgrade()) {
        Serial.print("Upgrade found at: ");
        Serial.println(ESPOTAGitHub.getUpgradeURL());
        if (ESPOTAGitHub.doUpgrade()) {
            Serial.println("Upgrade complete."); //This should never be seen as the device should restart on successful upgrade.
        } else {
            Serial.print("Unable to upgrade: ");
            Serial.println(ESPOTAGitHub.getLastError());
        }
    } else {
        Serial.print("Not proceeding to upgrade: ");
        Serial.println(ESPOTAGitHub.getLastError());
    }
}

void setup() {
    // Start serial for debugging (not used by library, just this sketch).
    Serial.begin(115200);

    // Start SPIFFS and retrieve certificates.
    SPIFFS.begin();
    int numCerts = certStore.initCertStore(SPIFFS, PSTR("/certs.idx"), PSTR("/certs.ar"));
    Serial.print(F("Number of CA certs read: "));
    Serial.println(numCerts);
    if (numCerts == 0) {
        Serial.println(F("No certs found. Did you run certs-from-mozill.py and upload the SPIFFS directory before running?"));
        return; // Can't connect to anything w/o certs!
    }

    // Connect to WiFi
    Serial.print("Connecting to WiFi... ");
    WiFi.mode(WIFI_STA);
    WiFi.begin(STASSID, STAPSK);
    if ((WiFi.status() != WL_CONNECTED)) {
        Serial.print("... ");
    }
    Serial.println();

    /* This is the actual code to check and upgrade */
    handle_upgade();
    /* End of check and upgrade code */

    // Your setup code goes here

}

void loop () {
    // Your loop code goes here
Serial.println("main loop");
delay (1000);
Serial.println("handle_upgade starting: ...");

 handle_upgade();

 Serial.println("handle_upgade ednded: ...");

 delay (1000);

}

but I get the connection error:
checking for update...
Not proceeding to upgrade: Connection failed
handle_upgade ednded: ...

Again, I get some connection similar error like my previous question.
So I asked it to find some instruction for fixing it, if possible.
Thanks.


texts:
So I've been happily making away with these nodeMCU boards now for a while but I came across a strange issue when updating some code on my board.The problem was that I couldn't flash anymore with Arduino's IDE (OR the NodeFlasher tool)

The error I was getting in Arduino's IDE was:

warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

I tried flashing over all the memory with the flash tool but that didn't work, I also tried connecting D3 to 3.3v output, that did nothing. I've also tried holding the flash button down while flashing without any effect.


texts: NodeMCU ESP8266 Returns IP address, but cant open the web with IP address

texts:
I have used the below code with proper Wifi Address and password. The Nodemcu connects to WIfi, and displays IP address, But the IP address cannot be used to open a web page. It says "This site cant be reached". Can anyone help with this

#include <ESP8266WiFi.h>

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

int ledPin = D0;
WiFiServer server(80);

void setup() {

  pinMode(ledPin,OUTPUT);
  digitalWrite(ledPin,LOW);

  Serial.begin(115200);
  Serial.println();
  Serial.print("Wifi connecting to ");
  Serial.println( ssid );

  WiFi.begin(ssid,password);

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

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

  Serial.println();

  Serial.println("Wifi Connected Success!");
  Serial.print("NodeMCU IP Address : ");
  Serial.println(WiFi.localIP() );

  server.begin();
  Serial.println("NodeMCU Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {

    // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("Hello New client");
  while(!client.available()){
    delay(1);
  }

   // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

   // Match the request

  int value = LOW;
  if (request.indexOf("/LED=ON") != -1)  {
    digitalWrite(ledPin, HIGH);
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1)  {
    digitalWrite(ledPin, LOW);
    value = LOW;
  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("");

  client.print("Led pin is now: ");

  if(value == HIGH) {
    client.print("On");
  } else {
    client.print("Off");
  }
  client.println("

");
  client.println("<button>Turn On </button>");
  client.println("<button>Turn Off </button>
");
  client.println("");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}


texts: Making HTTPS requests using ESP8266 AT commands

texts:
I am trying to make HTTPS GET/POST requests to the following server using AT commands.
AT+CIPSTART="TCP","54.166.71.140 ",443

I get errors when i use port 443 but on port 80 the requests are successful.
How can i get around this issue ? what could be potential solutions ?


texts:
I have a microphone and I need as precise values as possible. I have been told by my teacher, that it is somehow possible to make a ADC timer interrupt, which would interrupt always when the value is ready, so that the reading itself would not slow the program down.
    I know, how to use timer interrupts to read the analog value every other ms or something and I even have a code that lets the ADC read automaticly and takes the value, but I need to make it take the value always when it's ready, so that I would have every value the ADC read. I tried to look into the datasheet, but it's too complicated for me.
   How can I achieve such thing? I am using arduino uno.

this is the code I have that sets up the ADC interrupt:

  ADCSRA = 0;
  ADCSRB = 0;
  ADMUX = 0;
  ADMUX |= (1 << REFS0) + (1 << REFS1);
  ADMUX |= (1 << ADLAR);

  ADCSRA |= (1 << ADATE); //enabble auto trigger
  ADCSRA |= (1 << ADIE); //enable interrupts when measurement complete
  ADCSRA |= (1 << ADEN); //enable ADC
  ADCSRA |= (1 << ADSC);
  ADCSRA |= 0b010;

ISR(ADC_vect) {//when new ADC value ready
  af = af + ADCH;
  aaf++;
}

I found this on the internet, but it didn't work as I expected.


texts:
I made a simple code for my Arduino Uno with a servo motor:

#include <Servo.h>

Servo myservo;

void setup()
{
  myservo.attach(10);
}
void loop()
{
    myservo.write(80);
  delay(10500);
  myservo.write(120);
  delay(1000);
  myservo.write(96);
  delay(60000);
}

I uploaded it to my Arduino Uno and it said that the upload was successful and the blink sequence happened. I waited a minute and the code did not run. I unplugged and replugged and reset multiple times yet it didn't run. are there errors in my code? with my motor?


texts:
Does the VCC Output pin always give out a consistent 5V Voltage supply? What is the current output?

This is the Chip I have. On the chip it says ProMini R160JAC6v. and When i program it. It programs under 5V 16MHz with ATmega 328

Here is the bluetooth chip I am powering:


texts: Arduino mini pro as ISP for Atmega329P-PU serial monitor failing

texts:
After trying a lot of tutorials and manuals around the web including at least 20 solutions here on StackExchange, I don't know what to try anymore.

My goal is to write a message in the serial monitor window of the Arduino IDE from my ATMEGA328P-PU.

I have written the Arduino bootloader (tried 8 and 16MHz) to the ATMEGA and I use a 'blink' sketch as follows:

void setup()  {
 Serial.begin(9600);
 delay(100);
 pinMode(9, OUTPUT);
}

void loop()
{
 digitalWrite(9, HIGH);
 Serial.print("high");
 delay(1000);
 digitalWrite(9, LOW);
 Serial.print("low");
 delay(1000);
}

The blinking works fine, the timing looks good, not overly fast or slow.

I connect PIN3 (PCINT17, PD1, TXD) directly to the RX on the Arduino (lower red wire) and the serial monitor responds by returning nonsense like ����������.

I have checked the baud rate. I have also tested with all other baud rates in combination with and without 8Mhz and 16MHz.

I have tested the entire setup with another ATMEGA328P-PU and using an entirely other PC. Same results.

It is not possible to upload a sketch while leaving the TXD -> RX connected, so I disconnect this cable when I upload a sketch. I have also tested with only power and TXD -> RX connected.

I have also tried a few types of resistor between the TXD and RX, one of many tutorials recommended this.

This is what I am trying:
http://www.instructables.com/id/Attiny-serial-monitor-using-arduino-walkthrough/

And this is my boards.txt:

##############################################################

atmega328bb.name=ATmega328 (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.f_cpu=16000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude


texts:
How to compare a string coming from serial monitor with some predefined text stored  as a local variable?
If I say:

int led = 2;
String a = " abcds";

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

void loop() {
  String b = Serial.read();
  Serial.println(b);

  if (b != a) {
    digitalWrite(2,LOW);
  }
  else
  {
    digitalWrite(2,HIGH);
  }
}

just as an example, this code will not compile because on the serial I receive bytes and I want to compare with a string.
So my question is...
how should be done?


texts:
I am designing a PCB using a 328P. As I understand it, I can either flash the chip via the ICSP header (without bootloader) or via Serial (if it has a bootloader already). But how does programming actually work?

According to my program running on the chip, it acts as master for SPI peripherals. If using ICSP, how does the chip know that it is supposed to act as SPI slave and receive a program?
Is there anything I must take into account with regards to what is connected to the SPI pins? i.e. does it harm in any way if I have other SPI slaves on the board connected to these same pins?
Same for serial programming: how does the chip know that it's supposed to receive a program on the serial interface, when my application uses this port for a different purpose?


texts: Problems uploading arduino zero bootloader to atsamd21g18a

texts:
I am trying to upload the arduino zero bootloader (https://github.com/arduino/ArduinoCore-samd/tree/master/bootloaders/zero) to an atsamd21g18 breakout board that I made. The breakout has a 32KHz oscillator hooked to pins 1 and 2 (with 22pF caps). I have successfully done this twice before with two other atsamd21g18's, Atmel Studio, and an Atmel ICE as the programmer. These are the steps I followed the first two times:

Create a new GCC C executable project in Atmel Studio and chose ATSAMD21G18A as the device
Go to Tools->Device Programming, chose Atmel-ICE as tool, and SWD as interface
Go to Fuses, set USER_WORD_0.NVMCTRL_BOOTPROT to 0 Bytes, and hit Program
Go to Memories, select the file ArduinoCore-samd-master\bootloaders\zero\samd21_sam_ba.bin under the Flash option, and hit Program
Go back to Fuses, set USER_WORD_0.NVMCTRL_BOOTPRT to 8192 Bytes and hit Program

Then, I went to the Arduino IDE and was able to upload any sketches with Arduino Zero (programming port) chosen as the board and Atmel SAM-ICE as the programmer.
I have followed these same steps with the third samd21 chip. Eventually, all of the commands will go through. About 30% of the time when I click Program (in steps 2-5) I will get one of two errors:
Could not activate interface
Unable to enter programming mode. Verify device selection, interface settings, target power, security bit, and connections to the target device.
or
Erasing device failed.
However, if I just retry clicking Program it will not give any errors.
After following those steps with no errors in Atmel Studio, I go to the Arduino IDE and try uploading a basic blink sketch (with the same board and programmer selection as before), and the upload goes through (it says Done Uploading). However, the code does not execute. This is the code I am trying to upload:
const int ledPin =  6;

void setup() {
  // put your setup code here, to run once:
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(ledPin, HIGH);
  delay(1000);
  digitalWrite(ledPin, LOW);
  delay(1000);
}

This is the output I get after uploading the code:
Sketch uses 11444 bytes (4%) of program storage space. Maximum is 262144 bytes.
Global variables use 2188 bytes (6%) of dynamic memory, leaving 30580 bytes for local variables. Maximum is 32768 bytes.
Open On-Chip Debugger 0.10.0+dev-gf0767a31 (2018-06-11-13:36)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
debug_level: 0
none separate
adapter speed: 400 kHz
cortex_m reset_config sysresetreq
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x0000060c msp: 0x20007ffc
** Programming Started **
auto erase enabled
wrote 11520 bytes from file C:\Users\Michaela\AppData\Local\Temp\arduino_build_379254/blinky_samd21.ino.bin in 1.021138s (11.017 KiB/s)
** Programming Finished **
** Verify Started **
target halted due to debug-request, current mode: Thread
xPSR: 0x21000000 pc: 0x00000694 msp: 0x20007fdc
Error: error executing cortex_m crc algorithm
verified 11444 bytes in 0.999887s (11.177 KiB/s)
** Verified OK **
** Resetting Target **
shutdown command invoked

I have tried switching out the oscillator and led, uploading the bootloader and arduino sketch with and without the oscillator, simply hitting the Burn Bootloader command from the Arduino IDE, and even tried using openocd directly in the command line.
I do not believe this is an error with the specific samd21 chip I am using, because before I started messing with the bootloader, I uploaded a C sketch from Atmel Studio to blink the led, and it worked fine.
If anyone has any insight as to what could be going wrong, I would greatly appreciate it!


texts: Sodaq Moja — Accessing SW2/SW3 user switches

texts:
I have a Sodaq Moja, from supporting the project on Kickstarter, and I didn't have much time until now to play with it. Unfortunately, the online documentation for the Moja has disappeared, and only the docs for the new version, the Mbili, is accessible. And nowhere can I see where to access the user switches. Which, to boot, have been reordered in the Mbili, can cut down from 3 to 2.

Would anyone have an idea?

Cheers,


texts: How to implement an alternating current using only two PWM pins on STM32 Nucleo L053R8?

texts:
I am an arduino rookie and definitely not an expert in electronics, even if I do know the physics that is behind it.
Before burning my object of experience, I prefer to ask my silly question to the community.

Context :

I do use a bare stm32 based Nucleo L053R8 board which is arduino compatible.
I want a 1 minute long loop during which I send a 1.5V@20mA impulsion during 1 second and a -1.5V@20mA impulsion 30 seconds later.

Question :

can I simply use and wire two arduino PWM-able pins only to implement that alternating polarity low current? Or will it fail because of unsinked current?


texts: I've salvaged a 4 Ohm, 1.5 Watt speaker from an old computer, and I was wondering how I'd go about getting it to work with my Arduino. I've heard of various amplifier circuits such as opamps, but I do not know which would be the best for my situation. I've also heard that using the speaker in certain ways (such as directly connected to a pin from the Arduino) could damage both the speaker and the output pin, so that is definitely something I'd like to avoid. I'm not looking for anything complicated; I'm just trying to get a feel for the general circuitry, programming, and speaker volume. Any suggestions?


texts: Pause running program using a pushbutton

texts:
I have a program that flashes three LED in sequence indefinitely. How can O program a pushbutton to pause the program in the middle of the code?

Also, can I modify the code so that pressing the button a second time would speed up the flashing of the LED?

Each time I try to use a pushbutton to pause the program, it only pauses it once the program loops back to the beginning.

Here's my code at the moment (sorry, it's not very clean):

int ledpins[]   = {4, 5, 6};
int buttonpin   = 3;
int buttonstate = 0;

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

  for (int pin = 6; pin > 3; pin--) {
    pinMode(ledpins[pin], OUTPUT);
  }
  pinMode(buttonpin, INPUT);
}

void loop() {
  buttonstate = digitalRead(buttonpin);
  if (buttonstate == HIGH) {
    digitalWrite(ledpins, HIGH);
  }
  if (buttonstate == LOW) {
    for (int pin = 4; pin < 7; pin++) {
      digitalWrite(pin, HIGH);
      delay(200);
      digitalWrite(pin, LOW);
    }
    for (int pin = 6; pin > 3; pin--) {
      digitalWrite(pin, HIGH);
      delay(200);
      digitalWrite(pin, LOW);
    }
  }
}


texts:
For the below code snippet
const char* fr_fbdb(char tag[30]) // fn for retrieving data
{
  char full_path[120];
  const char *_dt ;
  strcpy(full_path , base_path);
  strcat(full_path , tag);
  Serial.print( "retrieving from " );
  Serial.println(full_path) ;
  Firebase.get(firebaseData, full_path);
  _dt = firebaseData.cstrData();
//  Serial.print("while ext: ");
//  Serial.println(_dt);
  return _dt ;
}

void retreive_sch()
{
  int no_tag = strlen(*tag) ;
  //Serial.print("no. of tags in the DB: ");
  //Serial.println(no_tag);
  const char *_data[no_tag];

  Firebase.get(firebaseData, "/SCHEDULE DETAILS/SELECTED");
  sch_no = firebaseData.cstrData();

  Serial.print("extracting schedule");
  Serial.println(sch_no);

  strcat(base_path , sch_no); // base path w/ sch no.

  for (int i = 0 ; i < 6 ; i++)
  {
    _data[i] = fr_fbdb(tag[i]);
    Serial.print("while ext: ");
    Serial.println(_data[i]);

  }

  for(int i=0 ; i<6 ; i++)
  {
    Serial.print("after extraction:");
    Serial.println(_data[i]) ;
  }
}

This is the output:
retrieving  schedule changes -- setup
extracting schedule3
retrieving from /SCHEDULE DETAILS/SCHEDULE3/DATE
while ext: [1609612200000,\"inf\"]
retrieving from /SCHEDULE DETAILS/SCHEDULE3/FREQ FR
while ext: \"-2\"
retrieving from /SCHEDULE DETAILS/SCHEDULE3/FREQ TO
while ext: \"-2\"
retrieving from /SCHEDULE DETAILS/SCHEDULE3/WEIGHT
while ext: 29
retrieving from /SCHEDULE DETAILS/SCHEDULE3/TIME
while ext: \"6:30\"
retrieving from /SCHEDULE DETAILS/SCHEDULE3/frequency
while ext: \"-1\"
after extraction:"root":[]
after extraction:\"-1\"
after extraction:keep-alive
after extraction:\"-1\"
after extraction:"root":[]
after extraction:\"-1\"

As you can see, the output of the same variable _data[] inside that particular function changes.
Any idea why?


texts:
I am trying to simply send a digital output from the Raspberry Pi to trigger some code on an Arduino. I have setup the Pi with the digital output working fine (tested using LED) however, I cant seem to get the Arduino (Leonardo) to read this output. I mean, all the details about the Pull Up resistor and logic having to be low to be high is confusing me and I really dont want to use any other electronic components (ie transistors or switches, etc).

Is there a simple way of just reading the output and triggering the code on the Arduino?


texts: DT-06 WIFI. How to program with Arduino Uno

texts:
I have a DT-06 wireless WiFi. I can connect using my phone but I cannot access 192.168.4.1/status.html or /wifi_set.html like in the tutorial

I put this module in wiring with Arduino Uno on 5v. I notice that the LED is low lighting until I put pin state in GND. Then I get full power red led. I put RX module to TX Arduino and TX module to RX Arduino but i can not access it using Arduino.

How can I program this module or how can I access? Any tutorial links are welcome.

Thanka. Sorry for my English.

L.E.

Module RX - Arduino TX
Module TX - Arduino RX
Module VCC - Arduino 5v
Module GND - Arduino GND
Module STATE - GND

My module has a red led on it. This led is low lighting until i put pin STATE in GND. After that the red led is full lighting.

After i put VCC and GND i can "see" my module using my phone wireless connection


texts: Arduino Libraries: Declaring variables as public?

texts:
How come I never see any Arduino Library expose some of it's internal variables as public in the header file? I only see functions which are declared as public, while every variable is declared private.

Background: I want to write my first Arduino library. And I thought of making some variables of this library public, so that I don't have to call a function later on when I import the library.

E.g. I want:

#include MyLibrary
...
MyLibrary instance();
instance.avariable = 12345;

instead of:

#include MyLibrary
...
MyLibrary instance();
instance.setVariable(12345);


texts: Arduino starter kit example LEDS modification

texts:
I just begun with the Arduino starter kit, and in the second example I would like to test some changes to learn more.

The point is to have a green LED shining, and when pressing the button the two red LEDs blink.

This is the code:

int switchState = 0;

void setup()
{
  pinMode(2, INPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

  // the button is pressed
  digitalWrite(3, LOW);

  digitalWrite(4, LOW);
  digitalWrite(5, HIGH);
  delay(250); // wait for a quarter second
  // toggle the LEDs
  digitalWrite(4, HIGH);
  digitalWrite(5, LOW);
  delay(250); // wait fo a quarter second
}

void loop()
{
  switchState = digitalRead(2);
  // this is a comment
  if(switchState == LOW)
  {
    // the button is not pressed
    digitalWrite(3, HIGH); // green LED
    digitalWrite(4, LOW); // red LED
    digitalWrite(5, LOW); // red LED
  }
  else
  {
    // the button is pressed
    digitalWrite(3, LOW);

    digitalWrite(4, LOW);
    digitalWrite(5, HIGH);
    delay(250); // wait for a quarter second
    // toggle the LEDs
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
    delay(250); // wait fo a quarter second
  }
} // go back to the beginning of the loop

I added a modification into the schema (a fourth LED in parallel with the green), like this:

But the added LED is not shining. It's a long time ago I finish school and I forgot a lot of things. Am I wiring the fourth LED incorrectly?


texts: Cannot control servos through 32-servo-controller on Aurduino Duamilanove

texts:
I have servo (TowerPro sg90) connected to 32 servo controller (this one) through UART interface (RX-TX, GND-GND).
Seller provide documentation how to connect and control my servos, but it isn't work.

Servo work if I connect it indirectly to Arduino. Controller indicate that it is working too (photo below - red led).

I already try different servos. Also try use provided software to control servos from pc through Mac/PC. But it's interface is unreadable for me. I tried different options but servos not responding.

Sketch code below (from sellers examples):

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

void loop() {
  Serial.print("#3P500T2000\r\n");
  delay(2000);
  Serial.print("#3P1500T2000\r\n");
  delay(3000);
  Serial.print("#3P2500T2000\r\n");
  delay(2000);
  Serial.print("#3P1500T2000\r\n");
  delay(2000);
}

Photo of my connections:

Sorry if it post duplicate some, but I cannot google this problem.


texts:
The following question is based on the Arduino Pro Mini (8MHz, 3.3V)

I'm in process of developing (yet another) LED strip driver shield. For that I wrote a simple control loop, that adjusts the channel brightness (PWM duty cycle) to a given target value with a smooth transition.

For testing purposes I configured Timer1 with a 0.5Hz interval to randomly assign new target values. This works almost as intended. When watching the values you can see the constant value periods and completely random, fast changing periods in between (picture generated with Arduino built-in plot). The curved, rather smooth lines are the PWM outputs following the target value (that part is confirmed to work):

The relevant code responsible for the changing of the target value is

ISR(TIMER1_COMPA_vect) //timer1 interrupt 0.5Hz
{
  for(auto it = 0; it < 4; ++it)
        channel_target[it] = random(0, 255);  // assign a random value between 0..255 (max for pwm)
}

My assumption is, that the ISR is called very fast in the fuzzy intervals but since I havn't done much with arduinos yet, I'm not familiar on what kind of background functions might interfere with that.

For completeness the full code:

double          channel[4];
uint8_t         channel_target[4];
const double    channel_k_p[4]      = { 0.001, 0.001, 0.001, 0.001 };
const double    channel_k_i[4]      = { 0.01, 0.01, 0.01, 0.01 };
double          err;
const uint8_t   led_pins[4]         = { 3, 5, 6, 9 };
char            serial_buffer[100];

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

    for(auto it = 0; it < 4; ++it)
        channel[it] = 0;

    for(auto it = 0; it < 4; ++it)
    {
        pinMode(led_pins[it], OUTPUT);   // sets the pin as output
        analogWrite(led_pins[it], 0);
    }

    cli();//stop interrupts

    TCCR1A = 0;// set entire TCCR1A register to 0
    TCCR1B = 0;// same for TCCR1B
    TCNT1  = 0;//initialize counter value to 0
    // set compare match register for 1hz increments
    OCR1A = 15624;// = (8*10^6) / (0.5*1024) - 1 (must be <65536)
    // turn on CTC mode
    TCCR1B |= (1 << WGM12);
    // Set CS10 and CS12 bits for 1024 prescaler
    TCCR1B |= (1 << CS12) | (1 << CS10);
    // enable timer compare interrupt
    TIMSK1 |= (1 << OCIE1A);

    //set timer2 interrupt at 500Hz
    TCCR2A = 0;// set entire TCCR2A register to 0
    TCCR2B = 0;// same for TCCR2B
    TCNT2  = 0;//initialize counter value to 0
    // set compare match register for 8khz increments
    OCR2A = 248;// = (8*10^6) / (500*64) - 1 (must be <256)
    // turn on CTC mode
    TCCR2A |= (1 << WGM21);
    // Set CS21 bit for 64 prescaler
    TCCR2B |= (1 << CS21) | (1 << CS20);
    // enable timer compare interrupt
    TIMSK2 |= (1 << OCIE2A);

    sei();  // reactivate interrupts

    randomSeed(analogRead(0));
}

void loop()
{
    for(auto it = 0; it < 4; ++it)
    {
        sprintf(serial_buffer, "%d ",  channel_target[it]);
        Serial.write(serial_buffer);
    }

    for(auto it = 0; it < 4; ++it)
    {
        sprintf(serial_buffer, "%d ", round(channel[it]));
        Serial.write(serial_buffer);
  }
    Serial.write("\n");

    delay(100);
}

ISR(TIMER2_COMPA_vect)  // timer2 interrupt at 1kHz
{
    // ******************************
    // Channel brightness control loop
    for(auto it = 0; it < 4; ++it)
    {
        err = channel_target[it] - channel[it];

        channel[it] += err * channel_k_p[it];           // proportional
        channel[it] -= err * 0.002 * channel_k_p[it];   // integral

        if(channel[it] > 255)
            channel[it] = 255;
        analogWrite(led_pins[it], floor(channel[it]));
    }
}

ISR(TIMER1_COMPA_vect) //timer1 interrupt 0.5Hz
{
  for(auto it = 0; it < 4; ++it)
        channel_target[it] = random(0, 255);  // assign a random value between 0..255 (max for pwm)
}


texts:
I have two, three-wire load sensors (https://cdn.sparkfun.com//assets/parts/4/5/9/5/10245-01.jpg) hooked up in a half wheatstone bridge (I think), with two 1K resistors.  Using a multimeter, I am reading small voltage changes when applying pressure to either strain gauge, when measured on between the pins A+ and A- on the HX711 ADC amp, however my Arduino serial output shows all 0's when using a variety of code examples (for example, this one:  http://www.dfrobot.com/wiki/index.php/Weight_Sensor_Module_V1#Sample_code).

My concern is that my circuit is not setup correctly as I am fairly novice, however everything I have researched about wheatstone bridges, and half wheatstone bridges seems fairly straightforward, and seems to match my circuit.  Any guidance/advice on the attached breadboard circuit diagram would be extremely helpful.


texts:
#include <Arduino.h>

void setup()
 {
  pinMode(13, OUTPUT);
 }
void loop()
{
 digitalWrite(13, HIGH);
 delay(1);
 digitalWrite(13, LOW);
 delay(1);
}

I am trying to make an led glow for one second to glow and then go off but nothing happens


texts: Do all arducam need the "Arducam-F Shield"?

texts:
The information on this is so greatly lacking to the extent that no related youtube videos could be found, no internet material and the seller seems to be very important and not answer to my questions as he is supposed to.
Also he appears to be the only seller to offer such a variety of arduino cameras.

I want to choose colored arduino camera for my project, but I am unable to receive enough information so that I can choose the appropriate arduino camera.

The most important for me to know is does all arduino cameras need the arducam-f shield board in order to work properly (i.e be programmable, colored, with "decent" quality and be able to capture photos in less than 1~2 seconds)

This is "5MP Mega pixel OV5642 Sensor Camera Module w CS mount Lens" It costs US $29.99. The description doesn't mention the need of any other 3rd party hadware in order to work.

This bellow is "Arducam-F Shield V2 Camera module shield /w OV2640 for Arduino UNO MEGA2560 DUE" it costs US $29.99 and is a camera that evidently comes with this magical shield. We can see that the version is slightly older than that on the other cameras.

This is "2 Mega pixel Camera Module MT9D111 JPEG Out + HQ lens" for US $21.99 and also, like in any other description, the need of shields is not mentioned

And this is "2Megapixel MT9D111 Auto Focus lens camera flex module with Adpater board" that has autofocus, is 2MP like the one above, comes with .... ?Adapter board"? (nothing like that is shown in the pictures or described in the description) and costs only US $9.99. It looks ugly compared to other cameras.

These was the 4 example arduino cameras I would choose from and do all of them need arduino shields in order to do what a camera should do?
(Explaining differences, pros and cons will be very useful to everyone who are in the same boat as I am)


texts: Using the SD library with the ESP8266 DevKit

texts:
The situation is as follows, I've connected a SPI TFT screen to the ESP8266 DevKit, set my own MISO,MOSI, CD, SCK pins and it works fine, wanted to do the same for using the SD card reader, but then I realized that the SD library is using the pre-defined pins with no visible way override this.. There must be a way, no?

I did try editing the pins_xxx files:

static const uint8_t SS   = 10;
static const uint8_t MOSI = D7; //11;
static const uint8_t MISO = D5; //12;
static const uint8_t SCK  = D6; //13;

But it did not work, I'm not that well familiar about the build process..
So, is there a way to accomplish this? Maybe a different library?

P.S. I am using the Arduino IDE for the ESP.


texts: Square wave based on falling edge of alternative pulse of upcoming RPM square wave

texts:
In my recent project, I have RPM Square wave from vehicle. Now, based on that I want square wave based on falling edge but only alternative pulse of RPM square wave.

I think below image clear more properly.

Upper yellowish square wave which I need. And below pinkish square wave is RPM square wave.

I made a code for that and it's working fine but when RPM is stable. But when RPM change rapidly then it's not working fine.

const int kPinRPM = 3;        // RPM / Digital Pin 3
const int RPMInterrupt = 1;   // RPM's interrrupt pin
byte engineCylinders = 2;         // Engine cylinders = 4;
byte engineCycles = 4;            // Engine cycle = 2
int refreshInterval = 750;        // Milliseconds between sensor updates
unsigned long previousMillis = 0;
volatile int RPMpulses = 0;
int RPM, Final_RPM;

const int kPinInj = 12;

volatile uint32_t kInjTime = 0;

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

  pinMode(kPinRPM, INPUT_PULLUP); // Enable internal pullup
  attachInterrupt(RPMInterrupt, countRPM, FALLING); //Interrupt for RPM

  pinMode(kPinInj, OUTPUT);
}

void loop()
{
  if(millis() - previousMillis > refreshInterval)
  {
    previousMillis = millis();
    RPM =  getRPM();
  }

  Serial.println(RPM);

  if((kInjTime > 0) && ((millis() - kInjTime) >= 10))
  {
    kInjTime = 0;
    digitalWrite(kPinInj, LOW);
  }
}

void countRPM()
{
  RPMpulses++;

  if(RPMpulses % 2 == 0)           // Skip alternative pulse
  {
    kInjTime = millis();
    digitalWrite(kPinInj, HIGH);
  }
}

int getRPM()
{
  Final_RPM = int(RPMpulses * (60000.0 / float(refreshInterval)) * engineCycles / engineCylinders / 2.0);
  RPMpulses = 0;
  Final_RPM = min(99999, Final_RPM);
}

After SUGGESTION, updating my codes. But it output waveform has some problem. In white circle, you can see that problem.


texts: Can I use GSM and GPS modules at the same time?

texts:
In my project I want to retrieve the Latitude and longitude and then transmit to a cell phone through GSM module. But the GSM as well as GPS modules uses the same pins i.e. Tx and Rx, so is it possible to use both modules at the same time?

Link to products

GSM - http://www.ebay.co.uk/itm/SIM800L-GPRS-GSM-Module-SIM-Board-Quadband-PCB-Antenna-for-MCU-Arduino-/191611848583?hash=item2c9cf4c787

GPS-- http://www.ebay.co.uk/itm/New-1PC-Ublox-NEO6MV2-GPS-Module-Aircraft-Flight-Controller-For-Arduino-/400830328802?hash=item5d53596fe2

Thank you.


texts: I have a question about ussd code in sim800l and arduino project; How to send the amount of balance that is shown by running the code at + cusd in the monitor serial with SMS to my phone? In fact, how to check the balance of the sim800l SIM card with a mobile phone?


texts:
I am making a Smart Cart using RFID. The user will
have a RFID card. As soon as he swipes the card on
the RFID Reader it will identify the user and will create
a linked list for that particular user. The linked list will
contain the unique Rfid based Ids of the items purchased by the user. In my code
the problem is that after the detection of the user it is
not creating any linked list for the items/it is not detecting the items bought by the user. Both the user and items are identified by their unique ids (ie RFID tags).It is detecting the user but once the user is being detected it is not mapping the items bought with that user.

the code for the same is :

int count = 0; // count = 0
int i;
char input[12];                                   // character array of size 12
boolean flag = 0;
// flag =0

boolean comparetag(char x[12], char bb[12]) {
  boolean ff = false;
  int fg = 0;
  for (int cc = 0; cc < 12; cc++) {
    if (x[cc] == bb[cc]) {
      fg++;
    }
  }
  if (fg == 12) {
    ff = true;
  }
  return ff;
}

struct Node {
  char x[12];
  struct Node *next;
};

struct Node* X;
struct Node* point;

void printList(struct Node *n) {
  while (n != NULL) {
    Serial.print(n->x);
    n = n->next;
  }
}

struct Node* Shopping(char[]) {

  Serial.print(input);
  // Print RFID tag number
  Serial.print("Welcome User");
  Serial.println();

  Serial.print("Start Shopping ");

  struct Node* head = NULL;
  head = (struct Node*) malloc(sizeof(struct Node));

  return head;

}

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

void loop() {

  if (flag == 0) {
    if (Serial.available()) {
      count = 0;
      while (Serial.available() && count < 12) // Read 12 characters and store them in input array
      {
        input[count] = Serial.read();
        count++;
        delay(5);
      }

      if (comparetag(input, "1B006AFA9F14")) {
        flag = 1;

        point, X = Shopping(input);
      } else {
        Serial.println("not Registered User");
      }
    }
  } else {
    int c = 0;
    if (Serial.available()) {
      while (Serial.available() && c < 12) // Read 12 characters and store them in input array
      {
        Serial.print("Taking Input");
        X->x[c] = Serial.read();
        c++;
        delay(5);
      }
      struct Node* second = NULL;
      second = (struct Node*) malloc(sizeof(struct Node));
      second = NULL;

      X->next = second;
      X = second;

    }
  }
  printList(point);
}


texts:
I've read several other posts but I still couldn't solve the issue. I'm trying to connect to a website which is HTTP (not HTTPS) but I always get code -1 as response. If I open the link in the browser it works well. Not sure what I am missing? Here's my full code:

#include <ESP8266HTTPClient.h>
#include <esp8266wifi.h>

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

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);
    Serial.print("Connecting..");

  }
}

void loop() {

  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("www.francescosoave.com/blind/getTime.php");
    http.addHeader("Content-Type", "text/html");
    int httpCode = http.GET();

    Serial.print("HTTP CODE: ");
    Serial.println(httpCode);

    if(httpCode > 0){
      String payload = http.getString();
      Serial.print("PAYLOAD: ");
      Serial.println(payload);
    }

    http.end();
  }

  delay(2000);
}


texts: How to alter joystick values with Arduino Uno?

texts:
I'm trying to use an Arduino Uno to read values from a 2-axis joystick analogue input, and alter these values. Rather than the true joystick values, I arithmetically convert the values at neutral to range between 0 - 5, with 'neutral', i.e. when the joystick isn't being pushed, being at roughly 2.5 for each axis. These joystick values currently output to a live text file, to be graphed in real-time. One function I'm trying to implement is that when the joystick value is greater or less than a defined value (e.g. in the code, greater than 4.55, or less than 0.5)  that the Arduino sets that point to be the new 'neutral' position (i.e. 2.5), however my code at the moment isn't working and I'm not sure how to go about attempting this.

Any insight would be most appreciated!

Cheers

const int buttonPin = 2;
const int successPin = 13;

int buttonState = 0;

void setup()
{
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
pinMode (buttonPin, INPUT);
pinMode (successPin, OUTPUT);
while (digitalRead(buttonPin) == LOW) {};
}

void loop () {

int sensorValueY = analogRead(A0);
int sensorValueX = analogRead(A1);

//arithmetic operation that maps output values from 0 - 5 instead of 0 - 1023
float voltageX = sensorValueX * (5.0 / 1023.0);
float voltageY = sensorValueY * (5.0 / 1023.0);
Serial.print(voltageX);
Serial.print(" , ");
Serial.print(voltageY);

if (voltageX >= 4.55) {
  voltageX == 2.5;
  successPin==HIGH;
  delay(1);
  successPin==LOW;
}

if (voltageX <= 0.5) {
  voltageX ==2.5;
  successPin==HIGH;
  delay(1);
  successPin==LOW;
}

if (voltageY >=4.55) {
  voltageY == 2.5;
  successPin==HIGH;
  delay(1);
  successPin==LOW;
}

if (voltageY <= 0.5) {
  voltageY ==2.5;
  successPin==HIGH;
  delay(1);
  successPin==LOW;
}
Serial.println();

}


texts: Problem uploading code to Arduino Uno using stino

texts:
I am having problems uploading my code to my Arduino Uno. The code that's already up, is running normally. The error code I get is:

ioctl("TIOCMSET"): Connection timed out
avrdude: stk500_recv(): programmer is not responding
ioctl("TIOCMSET"): Connection timed out
[Stino - Error 1]


texts:
I am currently planning a battery-powered project, where one of the tasks involves reading Desfire EV1 tags. Since the cheap RC522 based NFC shields are reported not to work with the Desfire EV1 tags, I wanted to make an attempt with a PN532 based shield. Due to offering the fastest shipping option, I ordered an Aptotec PN532 shield, although there are many other, and likely cheaper options out there as well. The Aptotec shield seems identical to the Seeed NFC Shield V2.0.

Communicating with the Desfire EV1 tags works as expected, but I am not understanding the shield's power consumption. If I understand the PN532 datasheet correctly, the chip itself should only draw 45µA when in standby mode, some 30mA when active, but not transmitting and additionally up to 150mA more during actual transmission.

After sending an 'InRelease all targets' command to the PN532, the shield however still draws about 50mA, although the PN532 should be in stand by mode. Using the RFConfiguration command to turn the RF field off completely still does not decrease the shield's power consumption. Activating the RF field e.g. by issuing an InListPassiveTarget command, the current draw increases to about 80mA, which matches with my assumption that the PN532 now draws 30mA more than when idle. There seems however to be something else on the shield causing a 'base line' 50mA current draw, which is not caused by powering the PN532 chip.

Does someone know where this power is lost, if it is possible to software-based turn off whatever is causing the power draw or if other PN532 shields show the same behaviour? Since my project must run on a battery, the 50mA unexplained current draw is not acceptable.


texts: What does this notation stands for? Wire.read() <<8 | Wire.read()

texts:
I'm using the Arduino's site test code for getting raw values from a MPU-6050 accelerometer + gyro. In the loop, there are this lines for getting the next data from its registers:

Wire.requestFrom(MPU_addr, 14, true);  // request a total of 14 registers

AcX = Wire.read()<<8 | Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read()<<8 | Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read()<<8 | Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp = Wire.read()<<8 | Wire.read();  // 0x41 (TEMP_OUT_H)   & 0x42 (TEMP_OUT_L)

GyX = Wire.read()<<8 | Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read()<<8 | Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read()<<8 | Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

Hex numbers indicates, of course, the address of each register. However, I can't get how, if the first instruction only requests from the MPU_addr (constant), it changes to the consecutive registers. Is it that <<8| makes something like a sum or a logic OR to switch the register to read?

Regards!


texts: 2 sensors, add delay between each reading

texts:
I have two temperature sensors, an MCP9808 and a DS18B20, connected to an arduino and I've read that it could be advantageous to set a small delay between temperature readings. What I wonder is where I should set the delay, in the setup function:

tempsensor.begin();                           //initialize communication with mcp9808
sensors.begin();                              //initialize communication with dc18b20
readSensors();

or the readSensors function?:

temp = tempsensor.readTempC();              //read current temperature and save value inside "temp"
sensors.requestTemperatures();              // Send the command to get temperatures
temp2 = sensors.getTempCByIndex(0);

As you can probably tell I am very new to all of this, intuition tells me that I should set the delay within the readSensors function.

Any alternative suggestions about how I should be readings temperature data from two different sensors connected to one arduino would be appreciated.

EDIT
after re-reading question and based on first answer I haven't made it unequivocally clear my intention; I want to delay the time between the mcp9808 and the ds18b20 temperature readings, so that it waits X seconds between each. I have read that this may help to reduce noise.


texts:
I have been working on my project but I get an error and I need some advice or correction.

I use I2C method to communicate between master and slave. I've got two questions:

I send 7 inputs (from master) to the slave but only receives 6
Will my coding make an output like this video

Master Code

// Master Code
#include <Wire.h>
byte nChar =0;
char input[7];

void setup () {

  Serial.begin(9600);
  Wire.begin();
}

void loop()
{
  if (nChar < 7) {if (Serial.available()) { input[nChar++] = Serial.read();}}

    else {

      Wire.beginTransmission(1);

      //a
      Wire.write(input[0]);
      Serial.print("Drawer : ");
      Serial.println(input[0]);

      //x
      Wire.write(input[1]);
      Serial.print("Output : ");
      Serial.println(input[1]);

      //00
      Wire.write(input[2]);
      Wire.write(input[3]);
      Serial.print("Output : ");
      Serial.print(input[2]);
      Serial.println(input[3]);

      //y
      Wire.write(input[4]);
      Serial.print("Output : ");
      Serial.println(input[4]);

      //00
      Wire.write(input[5]);
      Wire.write(input[6]);
      Serial.print("Output : ");
      Serial.print(input[5]);
      Serial.println(input[6]);

      delay(15);

      while (Serial.available())
      {
        //Remove extra
        Serial.read();
      }
      Wire.endTransmission();
        nChar = 0;
    }
  }

Slave Code

#include <Wire.h>
byte ledPins[] = {12, 11, 10, 9, 8, 7, 6};
byte ledPins2[] = {12, 11, 10, 9, 8, 7, 6};
byte count;
byte nChar;
char c;
char input[8];
char data[30] = "";
int n;
#define nBits sizeof(ledPins)/sizeof(ledPins[0])
#define nBits sizeof(ledPins2)/sizeof(ledPins[0])

void setup()
{
  Wire.begin(1);
  Serial.begin(9600);
  for (byte i = 0; i < nBits; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
for (byte i = 0; i < nBits; i++) {
    pinMode(ledPins2[i], OUTPUT);
    }
  Serial.begin(9600);
}

void loop()
{
  if (nChar < 8) {                    //accumulate three characters
    if (Serial.available()) {
      c = Serial.read();
      input[nChar++] = c;
    }
  }
  else {
    input[8] = 1;                   //atoi() expects string terminator
    n = atoi(input);                //convert the input characters to integer
    dispBinary(n);
    delay(100);                     //wait for any additional characters
    while (Serial.available()) {    //ignore them
      c = Serial.read();
    }
    nChar = 1;
  }
}

void receiveEvent(int howMany)
{
  while (1 < Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }
}

void dispBinary(int n) //Vertical
{
  if (n >= 0 && n <= 5) {
    for (byte i = 0; i < nBits; i++) {
      digitalWrite (ledPins[i], n & 1);
      n /= 2;
    }
  }
}

void dispBinary2(int n) //Horizontal
{
  if (n >= 0 && n <= 5) {
    for (byte i = 0; i < nBits; i++) {
      digitalWrite (ledPins2[i], n & 1);
      n /= 2;
    }
  }

}

void b()
{
  if (data[0] != 'a')
  {
    dispBinary(atoi("00"));
    delay(100);
    dispBinary2(atoi("00"));
    delay(100);
    goto fin;
  }
  if (data[1] = 'x')
  {
    char xdata[2] = {data[2], data[3]};//(data[2], data[3]);
    dispBinary2(atoi(xdata));
    delay(100);
  }
  if (data[4] = 'y')
  {
    char ydata[2] = {data[5], data[6]};//(data[5], data[6]);
    dispBinary(atoi(ydata));
    delay(100);
  }

fin:;
}


texts: How to make an arduino button to forget his past purpose?

texts:
For my school project im making an arduino speedometer for a bicycle. I will be using a reed switch sensor to get the speed. There will also be an clock and a termometer, it will be on a 16x2 lcd screen. To get the speed I will need the user to type in his bike size, in zoll. I managed to let the user tap the button until his size and then double tap the button to confirm it. Alright, fine. Now I need the same button to FORGET his last purpose. Because I want to use the same button to change the screen between speed, clock and termometer. SPEED -> tap -> CLOCK -> tap -> TEMPERATURE -> tap -> SPEED ........

I hope you get the idea. After the user picks his size, if he keeps tapping the number it would just keep on growing. So, im trying to make the button forget, or make him go trough that loop only once.

Pick your size tap tap tap double tap, thank you. And stop! I want him to do that only once and never again. I will need the same principle when the user will adjust his clock, he will have to tap to set it, save the number but reset the buttons function.

#include <LiquidCrystal_I2C.h>
#include <LiquidCrystal.h>
LiquidCrystal_I2C lcd(0x27, 16,2);
#define buttonPin 7
int a = 16;
int b = 0;

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.print("RADGROESSE IN");
  lcd.setCursor(0, 1);
  lcd.print("ZOLL EINGEBEN");

   // Set button input pin
   pinMode(buttonPin, INPUT);
   digitalWrite(buttonPin, HIGH );
}
void loop() {
   int b = checkButton();
   if (b == 1) clickEvent();
   if (b == 2) doubleClickEvent();
}
void clickEvent() {

   lcd.setCursor(14, 1);
    lcd.print(a);
    delay(100);
    lcd.print(" ");
    delay(100);
    a++;
    delay(100);
    if(a >= 23){
      a = 16;
      }
}
void doubleClickEvent() {
      b = a - 1;
      Serial.println("Button was idle for one second or more");
      lcd.clear();
      lcd.print("ZOLL = ");
      lcd.setCursor(7, 0);
      lcd.print(b);

}

//=================================================
//  MULTI-CLICK:  One Button, Multiple Events

// Button timing variables
int debounce = 20;          // ms debounce period to prevent flickering when pressing or releasing the button
int DCgap = 420;            // max ms between clicks for a double click event
// Button variables
boolean buttonVal = HIGH;   // value read from button
boolean buttonLast = HIGH;  // buffered value of the button's previous state
boolean DCwaiting = false;  // whether we're waiting for a double click (down)
boolean DConUp = false;     // whether to register a double click on next release, or whether to wait and click
boolean singleOK = true;    // whether it's OK to do a single click
long downTime = -1;         // time the button was pressed down
long upTime = -1;           // time the button was released

int checkButton() {
   int event = 0;
   buttonVal = digitalRead(buttonPin);
   // Button pressed down
   if (buttonVal == LOW && buttonLast == HIGH && (millis() - upTime) > debounce)
   {
       downTime = millis();
       singleOK = true;
       if ((millis()-upTime) < DCgap && DConUp == false && DCwaiting == true)  DConUp = true;
       else  DConUp = false;
       DCwaiting = false;
   }
   // Button released
   else if (buttonVal == HIGH && buttonLast == LOW && (millis() - downTime) > debounce)
   {
           upTime = millis();
           if (DConUp == false) DCwaiting = true;
           else
           {
               event = 2;
               DConUp = false;
               DCwaiting = false;
               singleOK = false;
           }
   }
   // Test for normal click event: DCgap expired
   if ( buttonVal == HIGH && (millis()-upTime) >= DCgap && DCwaiting == true && DConUp == false && singleOK == true && event != 2)
   {
       event = 1;
       DCwaiting = false;
   }

   buttonLast = buttonVal;
   return event;
}

Thank you! I would really appreciate it!


texts:
I have a HMC5883L 3-axis magnetometer. I would like to add tilt compensation to my Arduino Uno project.

Since the IC has 3 axis that it measures (X,Y,Z) is it possible to add tilt compensation without an accelerometer? If yes would this how do I find an equation to do the calculation. Is this equation found from http://bluelemonlabs.blogspot.fi/2013/08/arduino-simple-compass-with-hmc5883l.html correct?


texts:
I am as new as new can be to the Arduino world and have been playing around with them.  I have a few "Arduino Uno" boards that I purchased and have successfully loaded sketches to them.  However I am having problems figuring out how to write code in a simple manner.

I am  using a LED strip of WS2812 LEDs (similar to this). Here is what I would like to achieve:

I would like to be able to light  "lets say"  LEDs  1, 3, 5, 7.  Then light LEDs 2, 4, 6, 8  or any other combination of "multiple LEDs", by that I mean maybe LEDs 0, 14, 15, 36, 37, 52, 54.  I am sure you get the idea.

Can I write a single line code to light these LEDs or do I have to write out each line.

Sorry if this is a simplistic question, but I have searched and have not seen anything that may accomplish this, or I just over looked it.

Thanks in advance for your help


texts: What programming practices should be adopted while coding sketches for Arduino?

texts:
What are some of the best programming practices that can be adopted while coding sketches for Arduino, so that it uses the least memory and performance should not suffer from memory outage, and still the code be robust?

From the link: https://www.arduino.cc/en/Products/Compare

I have learned that the Uno has 32 KB of Flash memory. The maximum available is in the MEGA with 256 KB. I think Uno and Mega are the most widely used by people.


texts:
I'm using an arduino uno and ESP8266 (esp01) with the WiFiEsp library to connect to WiFi and POST data, connecting to WiFi works just fine.

I need to send a POST request, but I can't get it to work as I want.

 #include "WiFiEsp.h"
 // Emulate Serial1 on pins 7/8 if not present
 #ifndef HAVE_HWSERIAL1
 #include "SoftwareSerial.h"
 SoftwareSerial Serial1(6, 7); // RX, TX
 #endif
 char ssid[] = "Innovating-Guest"; // your network SSID (name)
 char pass[] = "wireless"; // your network password
 int status = WL_IDLE_STATUS; // the Wifi radio's status

 char server[] = "10.66.240.66";//http://10.66.240.66:8000/loadimage
 WiFiEspClient client; // Initialize the Ethernet client object

 void setup()
 {
 // initialize serial for debugging
 Serial.begin(9600);
 // initialize serial for ESP module
 Serial1.begin(9600);
 // initialize ESP module
 WiFi.init(&Serial1);
 // check for the presence of the shield
 if (WiFi.status() == WL_NO_SHIELD)
 {
 Serial.println("WiFi shield not present");
 // don't continue
 while (true);
 }

 // attempt to connect to WiFi network
 while ( status != WL_CONNECTED) {
 Serial.print("Attempting to connect to WPA SSID: ");
 Serial.println(ssid);
 // Connect to WPA/WPA2 network
 status = WiFi.begin(ssid, pass);
 }
 // you're connected now, so print out the data
 Serial.println("You're connected to the network");
 printWifiStatus();
 Serial.println();
 Serial.println("Starting connection to server...");
 // if you get a connection, report back via serial
 if (client.connect(server, 8000)) {
 Serial.println("Connected to server");
 String temp= "12.22";
 String humd= "23.33";
 String batt= "100";

 String content ="{\"temperature\": + temp +,\"humidity\":+ humd +,\"batteryPer\": + batt + }";
 client.println("POST /loadimage HTTP/1.1");
 client.println("Host: 10.66.240.66:8000");
 client.println("Accept: */*");
 client.print("Content-Length: ");
 client.println(content.length());
 client.println("Content-Type: application/json");
 client.println();
 client.println(content);
 }
 }
 void loop()
 {

 while (client.available()) {
 char c = client.read();
 Serial.write(c);
 }
 // if the server's disconnected, stop the client
 if (!client.connected()) {
 Serial.println();
 Serial.println("Disconnecting from server...");
 client.stop();
 // do nothing forevermore
 while (true);
  }
 }

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

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

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

Can anyone help me to know that why this error is coming.

Thanks in advance.


texts:
I'm trying to figure out how you can work with multiple sketches using Visual Studio Code and the Arduino.

Let's say I have three projects that I want to actively develop.

Motors.ino
Motors_with_controls.ino
Motors_with_lights.ino

Each one is a different project, but I want to quickly be able to upload one, then upload another.

My folder for Visual Studio Code is set up as such:

ArduinoProjects
   .vscode
       arduino.json
       c_cpp_properties.json
   Motors
       Motors.ino
   Motors_with_controls
       Motors_with_controls.ino
   Motors_with_lights
       Motors_with_lights.ino

But it seems like the only way to upload a particular ino is to go into the arduino.json file and hand edit the "sketch" parameter.

"sketch": "Motors\\Motors.ino"

Is there a quicker way? Ideally I'd like it to upload the ino I am currently editing without having to go and edit the arduino.json file.


texts: Arduino GPRS (GSM) shield (SIM900) no long pins

texts:
I have bought a SIM900 shield for an ordinary Arduino Uno board. The problem is that it doesn't have long pins on the bottom side, making it impossible to click on mu Arduino Uno.
The shield I have is this:

As you can see, there are identical pin spaces next to the red and yellow plastic female pin things. Can I just solder new pins in the free spaces and will it work like that?
I notice that the yellow and red plastic female pin holders on my board are on the free spaces in this picture. I supposed I can just use the adjacent foles to solder long pins so I can use it for my Arduino?


texts: Can I make existing libraries use external SRAM for the Arduino

texts:
I am running out of memory on my Arduino due to the libraries I am using. After I have included all the libraries I need then there is very little in the way of free memory for my own code.

If hook up some external RAM to the Arduino, is there a way I can make existing libraries use the external RAM rather than the SRAM on the arduino or will I need to alter the code in the library to do it.

If I have to modify the code is that a relatively easy thing to do?


texts: Arduino Pro mini to CH340G Connection problem

texts:
I have worked with Arduino UNO but recently I bought a new Arduino Pro mini 5v 16M and a CH340G converter to work with. I have searched google to connect pins but I found examples that explains this way :
GND to GND
VCC to VCC
Converter RDX to Arduino Pro Mini TXO
Converter TDX to Arduino Pro Mini RXI
My problem is that my Arduino Pro Mini (328p) has pins TXD and RXD (not RXI , not TXO) or maybe I have no knowledge about TX,RX, IN and OUT.
Can someone please help me to connect these wires?


texts: Compile problem when using keyword 'new' on Raspberry Pi

texts:
I have the following line of code in my Arduino sketch:

static double *temps = new double[arraySize];  //Declare array to hold tempratures, place the array on the heap where it will not be deleted and keep the pointer as a static
//double temps[arraySize];

When I compile with the Arduino IDE on Ubuntu it compiles just fine. However, when I compile on the Raspberry Pi, it throws up the following error:

xxx.cpp.o: In function `last Function in file()':
xxx.cpp:[last line in file]: undefined referance to `operator new[] (unsigned int)'
collect2: error: ld returned 1 exit status

Is this a bug? If so, how do I report it? If not, why is it throwing this error or how else can I declare a static array of doubles (needs to be static, I calculate an average of some incoming data over several function calls)?


texts: Millis() does not back to zero after woke up from deep sleep mode

texts:
I am going to make a project that needs four boards of Arduino which synchronization in time is needed. The project is about capturing the timestamp (in ms resolution) whenever something is crossing ultrasonic proximity sensor. The following are the modules I am going to use:

Arduino Uno R3 4 units
Ultrasonic Proximity sensor 4 units
DS1302 RTC modules 4 units
Micro SD Card modules 4 units

The boards will be placed in 4 different places which it is quite far from each other that makes it is hard to make wired connection. The detecting object will move back and forth during a certain interval of time, so that is why the time synchronization is needed.

My idea is, by using the timestamp from RTC modules, I turn all the boards together into deep sleep mode at the time I have set in the code and wake them up together after 10 seconds. I don't have any problem with RTC modules, but my problem lies in the millis() function which did not back to zero after woke up from deep sleep mode. I need this function since the DS1302 RTC does not provide ms resolution, yet I can not achieve sync if the millis() function does not back to zero.

I tried the code (edited with millis() added in the loop) from here:
https://www.youtube.com/watch?v=8fiYvnBDsDE

Do you have any solutions? Or another RTC module which provides ms resolution instead. Thank you


texts: Inserting myself in serial communication

texts:
I am assigned on a project involving Arduino and Raspbery PI. I have plenty of experience with Arduino and 0 with Raspbery or Linux. Person working quit and there are some problems that need me to start debuging.

The project involves control of input and output by Arduino and a touch screen and SMS aplication in Raspbery. They comunicate with standard Serial port using USB.

I want to read that communication on my PC terminal. What would be the simplest way of inserting myself without modifying anything on Raspbery?


texts: Arduino Uno R3 and ESP8266(ESP-01) serial connection

texts:
I have done everything i found but just nothing works, or maybe i just dont understand why it wont work. Im only trying to pass data(String) from Arduino to Esp through serial comms. Please I need your help, I'm as dead as my deadlines.

Note: What I am trying to do is send data from arduino to esp and make esp send the data on a raspberry pi server through sockets. The rasp part is fine, i just need the data passed from arduino to esp.

Original Arduino code

volatile int flow_frequency; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor = 2; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;
void flow () // Interrupt function
{
   flow_frequency++;
}
void setup()
{
   pinMode(flowsensor, INPUT);
   digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
   Serial.begin(9600);
   attachInterrupt(0, flow, RISING); // Setup Interrupt
   sei(); // Enable interrupts
   currentTime = millis();
   cloopTime = currentTime;
}
void loop ()
{
   currentTime = millis();
   // Every second, calculate and print litres/hour
   if(currentTime >= (cloopTime + 1000))
   {
      cloopTime = currentTime; // Updates cloopTime
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency = 0; // Reset Counter
      Serial.print(l_hour, DEC); // Print litres/hour
      Serial.println(" L/hour");
   }
}

ESP

#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>

SoftwareSerial  ESPlease(3,1);

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

uint16_t port = 8090;
const char* host = "192.168.1.3";

void setup()
{

  Serial.begin(9600);
  ESPlease.begin(9600);
  pinMode(3,INPUT);
  pinMode(1,OUTPUT);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("...");
  }

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

}

void loop()
{
    WiFiClient client;

    if (!client.connect(host, port)) {

        Serial.println("Connection to host failed");

        delay(1000);
        return;
    }
    String message = "";

    Serial.println("Connected to server successful!");
    while(Serial.available()) {
      message = Serial.readString();
     // messageReady = true;
    }
    String sensorValue = message;
    String sname = "flowRate-";
    String stringThree = sname + sensorValue;

    if(sensorValue != 0){
      client.print(stringThree);
    }

    Serial.println("Disconnecting...");
    client.stop();

    delay(10000);
}

please help me anyone :(


texts: WiFiServer Stops After Reconnection to WiFi

texts:
In the following code, the Arduino is reconnecting to the WiFi after several loops. The idea is to check and re-establish WiFi connection every 30 minutes or so.

However, the WiFiServer seems to stop working after the reconnecting to the WiFi network. At least I get a timeout, if I try to request data by calling the Arduino's IP address.

#include <SPI.h>
#include <WiFi101.h>

// the IP address for the shield:
IPAddress ip(12,34,56,78);

char ssid[] = "wifinetwork";
char pass[] = "correcthorsebatterystaple";

int status = WL_IDLE_STATUS;
int count = 0;
int retries;

WiFiServer server(80);

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

  connectToWiFi();

  server.begin();
  Serial.println("Server Started");
}

void loop () {
  count++;
  Serial.println(count);
  WiFiClient client = server.available();

  if(client) {
    Serial.print("Connected to a client : ");

    if(client.connected()) {
        Serial.println("Response Sent to Client");
        client.println("Data");
    }

    delay(5);
    client.stop();
    Serial.println("Client is disconnected");
  }

  if (count > 10) {
    Serial.println("Reconnect to WiFi");
    connectToWiFi();
    server.begin();
    count = 0;
  }

  delay(2000); // Wait for 2 seconds before starting to listen again
}

void connectToWiFi(){
  WiFi.config(ip);
  retries = 0;

  // attempt to connect to Wifi network:
  do {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    retries++;
    delay(2000);
  } while(status != WL_CONNECTED && retries < 3);

  if (WiFi.status() == 3) {
    Serial.println("Connected");
  }
}


texts:
I am just interested, but I would like to run a webpage with php on my arduino ethernet. I would like to be able to store my webpage on the sd card as well.
does anyone know of a library that would let me do this?


texts: Atmel atmega32u4 not recognized when connected by usb after attempting to flash new bootloader

texts:
I am making a mechanical keyboard using Atmel's pro micro as the controller.  I decided I would try to replace it's bootloader, as the one it ships with doesn't seem compatible with QMK's RESET keycode (which is supposed to put the controller into DFU mode).

Clearly I didn't know what I was doing, as the controller no longer seems to be recognized when I plug it in via USB - MicroUSB.

If I recall correctly, this is the command I used to attempt to flash the bootloader:

"sudo avrdude -p atmega32u4 -P /dev/ttyACM0 -c avr109 -U flash:w:Caterina-promicro16.hex"

At this time, it seems likely to me that the issue is that I over-wrote the bootloader (or some portion of it) and failed to replace it with an appropriate alternative.  Is this correct?  Is there any way to correct my error through a USB-MicroUSB connection at this point, or will I need to buy some sort of programmer?  All the leds light up.


texts: Reading/writing to Arduino GPIO pins from raw C code

texts:
I'm interested in writing a C program without the Arduino IDE and related libraries and am trying to figure out how I can access the GPIO pins for read and write.

My assumption is that the GPIO pins are - at the hardware layer - just memory addresses, and so if I know what their address is I can send/receive data to and from them.

For writing to the digital pins, do I just send an int with a value of 0 or 1 to the pin's address? If so, what might that code look like? Can I then assume I could poll that address for a value, which would be either 0 or 1?
Can I assume the same for analog pins, but instead of binary values, I'd get an integral value between 0 and 1023?

And if I'm way off here, and pins are not accessed via memory addresses, then how?

Again, the solution I'm looking for wouldn't involve Arduino software, just the Arduino hardware (an AVR or ARM MCU). Bonus points for C pseudo-code examples! Thanks in advance!


texts: PCA on ESP32 - libraries and recommendations?

texts:
it would seem that this would be a commonly sought-after topic, however I cannot find straightforward libraries for this and it's taking too long, so please allow me the question:
Is there a good library for Arduino/ESP32 to run principal component analysis (PCA) on a 3D matrix? Any links etc welcome, EigenArduino is the 'only' library I could find but it's not exactly straight forward (no example code etc). I want to extract the first component of some data sized 3x3000.
Thanks